LLVM 24.0.0git
DwarfCompileUnit.cpp
Go to the documentation of this file.
1//===- llvm/CodeGen/DwarfCompileUnit.cpp - Dwarf Compile Units ------------===//
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// This file contains support for constructing a dwarf compile unit.
10//
11//===----------------------------------------------------------------------===//
12
13#include "DwarfCompileUnit.h"
14#include "AddressPool.h"
15#include "DwarfExpression.h"
16#include "llvm/ADT/STLExtras.h"
20#include "llvm/CodeGen/DIE.h"
26#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/DebugInfo.h"
29#include "llvm/MC/MCAsmInfo.h"
30#include "llvm/MC/MCSection.h"
31#include "llvm/MC/MCStreamer.h"
32#include "llvm/MC/MCSymbol.h"
38#include <optional>
39#include <string>
40#include <utility>
41
42using namespace llvm;
43
44/// Query value using AddLinkageNamesToDeclCallOriginsForTuning.
46 "add-linkage-names-to-declaration-call-origins", cl::Hidden,
47 cl::desc("Add DW_AT_linkage_name to function declaration DIEs "
48 "referenced by DW_AT_call_origin attributes. Enabled by default "
49 "for -gsce debugger tuning."));
50
52 "emit-func-debug-line-table-offsets", cl::Hidden,
53 cl::desc("Include line table offset in function's debug info and emit end "
54 "sequence after each function's line data."),
55 cl::init(false));
56
58 bool EnabledByDefault = DD->tuneForSCE();
59 if (EnabledByDefault)
62}
63
65
66 // According to DWARF Debugging Information Format Version 5,
67 // 3.1.2 Skeleton Compilation Unit Entries:
68 // "When generating a split DWARF object file (see Section 7.3.2
69 // on page 187), the compilation unit in the .debug_info section
70 // is a "skeleton" compilation unit with the tag DW_TAG_skeleton_unit"
71 if (DW->getDwarfVersion() >= 5 && Kind == UnitKind::Skeleton)
72 return dwarf::DW_TAG_skeleton_unit;
73
74 return dwarf::DW_TAG_compile_unit;
75}
76
79 DwarfFile *DWU, UnitKind Kind)
80 : DwarfUnit(GetCompileUnitType(Kind, DW), Node, A, DW, DWU, UID) {
82 MacroLabelBegin = Asm->createTempSymbol("cu_macro_begin");
84 for (auto *GVE : CUNode->getGlobalVariables())
85 if (auto *GV = GVE->getVariable())
86 GlobalVarScopes.insert(GV->getScope());
87}
88
89/// addLabelAddress - Add a dwarf label attribute data and value using
90/// DW_FORM_addr or DW_FORM_GNU_addr_index.
92 const MCSymbol *Label) {
93 if ((Skeleton || !DD->useSplitDwarf()) && Label)
94 DD->addArangeLabel(SymbolCU(this, Label));
95
96 // Don't use the address pool in non-fission or in the skeleton unit itself.
97 if ((!DD->useSplitDwarf() || !Skeleton) && DD->getDwarfVersion() < 5)
98 return addLocalLabelAddress(Die, Attribute, Label);
99
100 bool UseAddrOffsetFormOrExpressions =
101 DD->useAddrOffsetForm() || DD->useAddrOffsetExpressions();
102
103 const MCSymbol *Base = nullptr;
104 if (Label->isInSection() && UseAddrOffsetFormOrExpressions)
105 Base = DD->getSectionLabel(&Label->getSection());
106
107 if (!Base || Base == Label) {
108 unsigned idx = DD->getAddressPool().getIndex(Label);
110 DD->getDwarfVersion() >= 5 ? dwarf::DW_FORM_addrx
111 : dwarf::DW_FORM_GNU_addr_index,
112 DIEInteger(idx));
113 return;
114 }
115
116 // Could be extended to work with DWARFv4 Split DWARF if that's important for
117 // someone. In that case DW_FORM_data would be used.
118 assert(DD->getDwarfVersion() >= 5 &&
119 "Addr+offset expressions are only valuable when using debug_addr (to "
120 "reduce relocations) available in DWARFv5 or higher");
121 if (DD->useAddrOffsetExpressions()) {
122 auto *Loc = new (DIEValueAllocator) DIEBlock();
123 addPoolOpAddress(*Loc, Label);
124 addBlock(Die, Attribute, dwarf::DW_FORM_exprloc, Loc);
125 } else
126 addAttribute(Die, Attribute, dwarf::DW_FORM_LLVM_addrx_offset,
128 DD->getAddressPool().getIndex(Base), Label, Base));
129}
130
133 const MCSymbol *Label) {
134 if (Label)
135 addAttribute(Die, Attribute, dwarf::DW_FORM_addr, DIELabel(Label));
136 else
137 addAttribute(Die, Attribute, dwarf::DW_FORM_addr, DIEInteger(0));
138}
139
141 // If we print assembly, we can't separate .file entries according to
142 // compile units. Thus all files will belong to the default compile unit.
143
144 // FIXME: add a better feature test than hasRawTextSupport. Even better,
145 // extend .file to support this.
146 unsigned CUID = Asm->OutStreamer->hasRawTextSupport() ? 0 : getUniqueID();
147 if (!File)
148 return Asm->OutStreamer->emitDwarfFileDirective(0, "", "", std::nullopt,
149 std::nullopt, CUID);
150
151 if (LastFile != File) {
152 LastFile = File;
153 LastFileID = Asm->OutStreamer->emitDwarfFileDirective(
154 0, File->getDirectory(), File->getFilename(), DD->getMD5AsBytes(File),
155 File->getSource(), CUID);
156 }
157 return LastFileID;
158}
159
161 const DIGlobalVariable *GV, ArrayRef<GlobalExpr> GlobalExprs) {
162 // Check for pre-existence.
163 if (DIE *Die = getDIE(GV))
164 return Die;
165
166 assert(GV);
167
168 auto *GVContext = GV->getScope();
169 const DIType *GTy = GV->getType();
170
171 auto *CB = GVContext ? dyn_cast<DICommonBlock>(GVContext) : nullptr;
172 DIE *ContextDIE = CB ? getOrCreateCommonBlock(CB, GlobalExprs)
173 : getOrCreateContextDIE(GVContext);
174
175 // Add to map.
176 DIE *VariableDIE = &createAndAddDIE(GV->getTag(), *ContextDIE, GV);
178 if (auto *SDMDecl = GV->getStaticDataMemberDeclaration()) {
179 DeclContext = SDMDecl->getScope();
180 assert(SDMDecl->isStaticMember() && "Expected static member decl");
181 assert(GV->isDefinition());
182 // We need the declaration DIE that is in the static member's class.
183 DIE *VariableSpecDIE = getOrCreateStaticMemberDIE(SDMDecl);
184 addDIEEntry(*VariableDIE, dwarf::DW_AT_specification, *VariableSpecDIE);
185 // If the global variable's type is different from the one in the class
186 // member type, assume that it's more specific and also emit it.
187 if (GTy != SDMDecl->getBaseType())
188 addType(*VariableDIE, GTy);
189 } else {
190 DeclContext = GV->getScope();
191 // Add name and type.
192 StringRef DisplayName = GV->getDisplayName();
193 if (!DisplayName.empty())
194 addString(*VariableDIE, dwarf::DW_AT_name, GV->getDisplayName());
195 if (GTy)
196 addType(*VariableDIE, GTy);
197
198 // Add scoping info.
199 if (!GV->isLocalToUnit())
200 addFlag(*VariableDIE, dwarf::DW_AT_external);
201
202 // Add line number info.
203 addSourceLine(*VariableDIE, GV);
204 }
205
206 if (!GV->isDefinition())
207 addFlag(*VariableDIE, dwarf::DW_AT_declaration);
208 else
209 addGlobalName(GV->getName(), *VariableDIE, DeclContext);
210
211 addAnnotation(*VariableDIE, GV->getAnnotations());
212
213 if (uint32_t AlignInBytes = GV->getAlignInBytes())
214 addUInt(*VariableDIE, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
215 AlignInBytes);
216
217 if (MDTuple *TP = GV->getTemplateParams())
218 addTemplateParams(*VariableDIE, DINodeArray(TP));
219
220 // Add location.
221 addLocationAttribute(VariableDIE, GV, GlobalExprs);
222
223 return VariableDIE;
224}
225
227 DIE *VariableDIE, const DIGlobalVariable *GV, ArrayRef<GlobalExpr> GlobalExprs) {
228 bool addToAccelTable = false;
229 DIELoc *Loc = nullptr;
230 std::optional<unsigned> TargetAddrSpace;
231 std::unique_ptr<DIEDwarfExpression> DwarfExpr;
232 const GlobalVariable *LastGlobal = nullptr;
233 for (const auto &GE : GlobalExprs) {
234 const GlobalVariable *Global = GE.Var;
235 const DIExpression *Expr = GE.Expr;
236
237 // For compatibility with DWARF 3 and earlier,
238 // DW_AT_location(DW_OP_constu, X, DW_OP_stack_value) or
239 // DW_AT_location(DW_OP_consts, X, DW_OP_stack_value) becomes
240 // DW_AT_const_value(X).
241 if (GlobalExprs.size() == 1 && Expr && Expr->isConstant()) {
242 addToAccelTable = true;
244 *VariableDIE,
246 *Expr->isConstant(),
247 Expr->getElement(1));
248 break;
249 }
250
251 // We cannot describe the location of dllimport'd variables: the
252 // computation of their address requires loads from the IAT.
253 if (Global && Global->hasDLLImportStorageClass())
254 continue;
255
256 // Nothing to describe without address or constant.
257 if (!Global && (!Expr || !Expr->isConstant()))
258 continue;
259
260 if (Global && Global->isThreadLocal() &&
261 !Asm->getObjFileLowering().supportDebugThreadLocalLocation())
262 continue;
263
264 if (!Loc) {
265 addToAccelTable = true;
267 DwarfExpr = std::make_unique<DIEDwarfExpression>(*Asm, *this, *Loc);
268 }
269
270 if (Expr) {
271 Expr = DD->adjustExpressionForTarget(Expr, TargetAddrSpace);
272 DwarfExpr->addFragmentOffset(Expr);
273 }
274
275 if (Global) {
276 const MCSymbol *Sym = Asm->getSymbol(Global);
277 // 16-bit platforms like MSP430 and AVR take this path, so sink this
278 // assert to platforms that use it.
279 auto GetPointerSizedFormAndOp = [this]() {
280 unsigned PointerSize = Asm->MAI.getCodePointerSize();
281 assert((PointerSize == 4 || PointerSize == 8) &&
282 "Add support for other sizes if necessary");
283 struct FormAndOp {
284 dwarf::Form Form;
286 };
287 return PointerSize == 4
288 ? FormAndOp{dwarf::DW_FORM_data4, dwarf::DW_OP_const4u}
289 : FormAndOp{dwarf::DW_FORM_data8, dwarf::DW_OP_const8u};
290 };
291 if (Global->isThreadLocal()) {
292 if (Asm->TM.getTargetTriple().isWasm()) {
293 // FIXME This is not guaranteed, but in practice, in static linking,
294 // if present, __tls_base's index is 1. This doesn't hold for dynamic
295 // linking, so TLS variables used in dynamic linking won't have
296 // correct debug info for now. See
297 // https://github.com/llvm/llvm-project/blob/19afbfe33156d211fa959dadeea46cd17b9c723c/lld/wasm/Driver.cpp#L786-L823
298 addWasmRelocBaseGlobal(Loc, "__tls_base", 1);
299 addOpAddress(*Loc, Sym);
300 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
301 } else if (Asm->TM.useEmulatedTLS()) {
302 // TODO: add debug info for emulated thread local mode.
303 } else {
304 // FIXME: Make this work with -gsplit-dwarf.
305 // Based on GCC's support for TLS:
306 if (!DD->useSplitDwarf()) {
307 auto FormAndOp = GetPointerSizedFormAndOp();
308 // 1) Start with a constNu of the appropriate pointer size
309 addUInt(*Loc, dwarf::DW_FORM_data1, FormAndOp.Op);
310 // 2) containing the (relocated) offset of the TLS variable
311 // within the module's TLS block.
312 addExpr(*Loc, FormAndOp.Form,
313 Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym));
314 } else {
315 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
316 addUInt(*Loc, dwarf::DW_FORM_udata,
317 DD->getAddressPool().getIndex(Sym, /* TLS */ true));
318 }
319 // 3) followed by an OP to make the debugger do a TLS lookup.
320 addUInt(*Loc, dwarf::DW_FORM_data1,
321 DD->useGNUTLSOpcode() ? dwarf::DW_OP_GNU_push_tls_address
322 : dwarf::DW_OP_form_tls_address);
323 }
324 } else if (Asm->TM.getTargetTriple().isWasm() &&
325 Asm->TM.getRelocationModel() == Reloc::PIC_) {
326 // FIXME This is not guaranteed, but in practice, if present,
327 // __memory_base's index is 1. See
328 // https://github.com/llvm/llvm-project/blob/19afbfe33156d211fa959dadeea46cd17b9c723c/lld/wasm/Driver.cpp#L786-L823
329 addWasmRelocBaseGlobal(Loc, "__memory_base", 1);
330 addOpAddress(*Loc, Sym);
331 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
332 } else if ((Asm->TM.getRelocationModel() == Reloc::RWPI ||
333 Asm->TM.getRelocationModel() == Reloc::ROPI_RWPI) &&
334 !Asm->getObjFileLowering()
335 .getKindForGlobal(Global, Asm->TM)
336 .isReadOnly()) {
337 auto FormAndOp = GetPointerSizedFormAndOp();
338 // Constant
339 addUInt(*Loc, dwarf::DW_FORM_data1, FormAndOp.Op);
340 // Relocation offset
341 addExpr(*Loc, FormAndOp.Form,
342 Asm->getObjFileLowering().getIndirectSymViaRWPI(Sym));
343 // Base register
344 Register BaseReg = Asm->getObjFileLowering().getStaticBase();
345 unsigned DwarfBaseReg =
346 Asm->TM.getMCRegisterInfo().getDwarfRegNum(BaseReg, false);
347 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + DwarfBaseReg);
348 // Offset from base register
349 addSInt(*Loc, dwarf::DW_FORM_sdata, 0);
350 // Operation
351 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
352 } else {
353 DD->addArangeLabel(SymbolCU(this, Sym));
354 addOpAddress(*Loc, Sym);
355 }
356 LastGlobal = Global;
357 }
358 // Global variables attached to symbols are memory locations.
359 // It would be better if this were unconditional, but malformed input that
360 // mixes non-fragments and fragments for the same variable is too expensive
361 // to detect in the verifier.
362 if (DwarfExpr->isUnknownLocation())
363 DwarfExpr->setMemoryLocationKind();
364 DwarfExpr->addExpression(Expr);
365 }
366 DD->addTargetVariableAttributes(*this, *VariableDIE, TargetAddrSpace,
368 LastGlobal);
369 if (Loc)
370 addBlock(*VariableDIE, dwarf::DW_AT_location, DwarfExpr->finalize());
371
372 if (DD->useAllLinkageNames())
373 addLinkageName(*VariableDIE, GV->getLinkageName());
374
375 if (addToAccelTable) {
376 DD->addAccelName(*this, CUNode->getNameTableKind(), GV->getName(),
377 *VariableDIE);
378
379 // If the linkage name is different than the name, go ahead and output
380 // that as well into the name table.
381 if (GV->getLinkageName() != "" && GV->getName() != GV->getLinkageName() &&
382 DD->useAllLinkageNames())
383 DD->addAccelName(*this, CUNode->getNameTableKind(), GV->getLinkageName(),
384 *VariableDIE);
385 }
386}
387
389 const DICommonBlock *CB, ArrayRef<GlobalExpr> GlobalExprs) {
390 // Check for pre-existence.
391 if (DIE *NDie = getDIE(CB))
392 return NDie;
393 DIE *ContextDIE = getOrCreateContextDIE(CB->getScope());
394 DIE &NDie = createAndAddDIE(dwarf::DW_TAG_common_block, *ContextDIE, CB);
395 StringRef Name = CB->getName().empty() ? "_BLNK_" : CB->getName();
396 addString(NDie, dwarf::DW_AT_name, Name);
397 addGlobalName(Name, NDie, CB->getScope());
398 if (CB->getFile())
399 addSourceLine(NDie, CB->getLineNo(), /*Column*/ 0, CB->getFile());
400 if (DIGlobalVariable *V = CB->getDecl())
401 getCU().addLocationAttribute(&NDie, V, GlobalExprs);
402 return &NDie;
403}
404
406 DD->insertSectionLabel(Range.Begin);
407
408 auto *PrevCU = DD->getPrevCU();
409 bool SameAsPrevCU = this == PrevCU;
410 DD->setPrevCU(this);
411 // If we have no current ranges just add the range and return, otherwise,
412 // check the current section and CU against the previous section and CU we
413 // emitted into and the subprogram was contained within. If these are the
414 // same then extend our current range, otherwise add this as a new range.
415 if (CURanges.empty() || !SameAsPrevCU ||
416 (&CURanges.back().End->getSection() !=
417 &Range.End->getSection())) {
418 // Before a new range is added, always terminate the prior line table.
419 if (PrevCU)
420 DD->terminateLineTable(PrevCU);
421 CURanges.push_back(Range);
422 return;
423 }
424
425 CURanges.back().End = Range.End;
426}
427
429 if (CUNode->isDebugDirectivesOnly())
430 return;
431
432 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
433 if (DD->useSectionsAsReferences()) {
434 LineTableStartSym = TLOF.getDwarfLineSection()->getBeginSymbol();
435 } else {
436 LineTableStartSym =
437 Asm->OutStreamer->getDwarfLineTableSymbol(getUniqueID());
438 }
439
440 // DW_AT_stmt_list is a offset of line number information for this
441 // compile unit in debug_line section. For split dwarf this is
442 // left in the skeleton CU and so not included.
443 // The line table entries are not always emitted in assembly, so it
444 // is not okay to use line_table_start here.
445 addSectionLabel(getUnitDie(), dwarf::DW_AT_stmt_list, LineTableStartSym,
447}
448
450 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
451 addSectionLabel(D, dwarf::DW_AT_stmt_list, LineTableStartSym,
453}
454
456 const MCSymbol *End) {
457 assert(Begin && "Begin label should not be null!");
458 assert(End && "End label should not be null!");
459 assert(Begin->isDefined() && "Invalid starting label");
460 assert(End->isDefined() && "Invalid end label");
461
462 addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
463 if (DD->getDwarfVersion() >= 4 &&
464 (!isDwoUnit() || !llvm::isRangeRelaxable(Begin, End))) {
465 addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);
466 return;
467 }
468 addLabelAddress(D, dwarf::DW_AT_high_pc, End);
469}
470
471// Add info for Wasm-global-based relocation.
472// 'GlobalIndex' is used for split dwarf, which currently relies on a few
473// assumptions that are not guaranteed in a formal way but work in practice.
474void DwarfCompileUnit::addWasmRelocBaseGlobal(DIELoc *Loc, StringRef GlobalName,
475 uint64_t GlobalIndex) {
476 // FIXME: duplicated from Target/WebAssembly/WebAssembly.h
477 // don't want to depend on target specific headers in this code?
478 const unsigned TI_GLOBAL_RELOC = 3;
479 unsigned PointerSize = Asm->getDataLayout().getPointerSize();
480 auto *Sym =
481 static_cast<MCSymbolWasm *>(Asm->GetExternalSymbolSymbol(GlobalName));
482 // FIXME: this repeats what WebAssemblyMCInstLower::
483 // GetExternalSymbolSymbol does, since if there's no code that
484 // refers to this symbol, we have to set it here.
486 Sym->setGlobalType(wasm::WasmGlobalType{
487 static_cast<uint8_t>(PointerSize == 4 ? wasm::WASM_TYPE_I32
489 true});
490 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_WASM_location);
491 addSInt(*Loc, dwarf::DW_FORM_sdata, TI_GLOBAL_RELOC);
492 if (!isDwoUnit()) {
493 addLabel(*Loc, dwarf::DW_FORM_data4, Sym);
494 } else {
495 // FIXME: when writing dwo, we need to avoid relocations. Probably
496 // the "right" solution is to treat globals the way func and data
497 // symbols are (with entries in .debug_addr).
498 // For now we hardcode the indices in the callsites. Global indices are not
499 // fixed, but in practice a few are fixed; for example, __stack_pointer is
500 // always index 0.
501 addUInt(*Loc, dwarf::DW_FORM_data4, GlobalIndex);
502 }
503}
504
505// Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
506// and DW_AT_high_pc attributes. If there are global variables in this
507// scope then create and insert DIEs for these variables.
509 const Function &F,
510 MCSymbol *LineTableSym) {
513 // If basic block sections are on, ranges for each basic block section has
514 // to be emitted separately.
515 for (const auto &R : Asm->MBBSectionRanges)
516 BB_List.push_back({R.second.BeginLabel, R.second.EndLabel});
517
518 attachRangesOrLowHighPC(*SPDie, BB_List);
519
520 if (DD->useAppleExtensionAttributes() &&
521 !DD->getCurrentFunction()->disableFramePointerElim())
522 addFlag(*SPDie, dwarf::DW_AT_APPLE_omit_frame_ptr);
523
524 if (emitFuncLineTableOffsets() && LineTableSym) {
525 MCSymbol *Symbol =
526 Asm->getObjFileLowering().getDwarfLineSection()->getBeginSymbol();
527 addSectionLabel(*SPDie, dwarf::DW_AT_LLVM_stmt_sequence, LineTableSym,
528 Symbol);
529 }
530
531 // Only include DW_AT_frame_base in full debug info
533 const TargetFrameLowering *TFI = Asm->MF->getSubtarget().getFrameLowering();
535 TFI->getDwarfFrameBase(*Asm->MF);
536 switch (FrameBase.Kind) {
539 MachineLocation Location(FrameBase.Location.Reg);
540 addAddress(*SPDie, dwarf::DW_AT_frame_base, Location);
541 }
542 break;
543 }
546 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_call_frame_cfa);
547 if (FrameBase.Location.Offset != 0) {
548 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_consts);
549 addSInt(*Loc, dwarf::DW_FORM_sdata, FrameBase.Location.Offset);
550 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
551 }
552 addBlock(*SPDie, dwarf::DW_AT_frame_base, Loc);
553 break;
554 }
556 // FIXME: duplicated from Target/WebAssembly/WebAssembly.h
557 const unsigned TI_GLOBAL_RELOC = 3;
558 if (FrameBase.Location.WasmLoc.Kind == TI_GLOBAL_RELOC) {
559 // These need to be relocatable.
561 assert(FrameBase.Location.WasmLoc.Index == 0); // Only SP so far.
562 // For now, since we only ever use index 0, this should work as-is.
563 addWasmRelocBaseGlobal(Loc, "__stack_pointer",
564 FrameBase.Location.WasmLoc.Index);
565 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
566 addBlock(*SPDie, dwarf::DW_AT_frame_base, Loc);
567 } else {
569 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
570 DIExpressionCursor Cursor({});
571 DwarfExpr.addWasmLocation(FrameBase.Location.WasmLoc.Kind,
572 FrameBase.Location.WasmLoc.Index);
573 DwarfExpr.addExpression(std::move(Cursor));
574 addBlock(*SPDie, dwarf::DW_AT_frame_base, DwarfExpr.finalize());
575 }
576 break;
577 }
578 }
579 }
580
581 // Add name to the name table, we do this here because we're guaranteed
582 // to have concrete versions of our DW_TAG_subprogram nodes.
583 DD->addSubprogramNames(*this, CUNode->getNameTableKind(), SP, *SPDie);
584
585 return *SPDie;
586}
587
588// Construct a DIE for this scope.
590 DIE &ParentScopeDIE) {
591 if (!Scope || !Scope->getScopeNode())
592 return;
593
594 auto *DS = Scope->getScopeNode();
595
596 assert((Scope->getInlinedAt() || !isa<DISubprogram>(DS)) &&
597 "Only handle inlined subprograms here, use "
598 "constructSubprogramScopeDIE for non-inlined "
599 "subprograms");
600
601 // Emit inlined subprograms.
602 if (Scope->getParent() && isa<DISubprogram>(DS)) {
603 DIE *ScopeDIE = constructInlinedScopeDIE(Scope, ParentScopeDIE);
604 assert(ScopeDIE && "Scope DIE should not be null.");
605 createAndAddScopeChildren(Scope, *ScopeDIE);
606 return;
607 }
608
609 // Early exit when we know the scope DIE is going to be null.
610 if (DD->isLexicalScopeDIENull(Scope))
611 return;
612
613 // Emit lexical blocks.
614 DIE *ScopeDIE = getOrCreateLexicalBlockDIE(Scope, ParentScopeDIE);
615 assert(ScopeDIE && "Scope DIE should not be null.");
616
617 createAndAddScopeChildren(Scope, *ScopeDIE);
618}
619
622
623 HasRangeLists = true;
624
625 // Add the range list to the set of ranges to be emitted.
626 auto IndexAndList =
627 (DD->getDwarfVersion() < 5 && Skeleton ? Skeleton->DU : DU)
628 ->addRange(*(Skeleton ? Skeleton : this), std::move(Range));
629
630 uint32_t Index = IndexAndList.first;
631 auto &List = *IndexAndList.second;
632
633 // Under fission, ranges are specified by constant offsets relative to the
634 // CU's DW_AT_GNU_ranges_base.
635 // FIXME: For DWARF v5, do not generate the DW_AT_ranges attribute under
636 // fission until we support the forms using the .debug_addr section
637 // (DW_RLE_startx_endx etc.).
638 if (DD->getDwarfVersion() >= 5)
639 addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_rnglistx, Index);
640 else {
641 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
642 const MCSymbol *RangeSectionSym =
644 addSectionLabel(ScopeDIE, dwarf::DW_AT_ranges, List.Label, RangeSectionSym);
645 }
646}
647
649 DIE &Die, SmallVector<RangeSpan, 2> Ranges) {
650 assert(!Ranges.empty());
651 if (!DD->useRangesSection() ||
652 (Ranges.size() == 1 &&
653 (!DD->alwaysUseRanges(*this) ||
654 DD->getSectionLabel(&Ranges.front().Begin->getSection()) ==
655 Ranges.front().Begin))) {
656 const RangeSpan &Front = Ranges.front();
657 const RangeSpan &Back = Ranges.back();
658 attachLowHighPC(Die, Front.Begin, Back.End);
659 } else
660 addScopeRangeList(Die, std::move(Ranges));
661}
662
664 DIE &Die, const SmallVectorImpl<InsnRange> &Ranges) {
666 List.reserve(Ranges.size());
667 for (const InsnRange &R : Ranges) {
668 auto *BeginLabel = DD->getLabelBeforeInsn(R.first);
669 auto *EndLabel = DD->getLabelAfterInsn(R.second);
670
671 const auto *BeginMBB = R.first->getParent();
672 const auto *EndMBB = R.second->getParent();
673
674 const auto *MBB = BeginMBB;
675 // Basic block sections allows basic block subsets to be placed in unique
676 // sections. For each section, the begin and end label must be added to the
677 // list. If there is more than one range, debug ranges must be used.
678 // Otherwise, low/high PC can be used.
679 // FIXME: Debug Info Emission depends on block order and this assumes that
680 // the order of blocks will be frozen beyond this point.
681 do {
682 if (MBB->sameSection(EndMBB) || MBB->isEndSection()) {
683 auto MBBSectionRange = Asm->MBBSectionRanges[MBB->getSectionID()];
684 List.push_back(
685 {MBB->sameSection(BeginMBB) ? BeginLabel
686 : MBBSectionRange.BeginLabel,
687 MBB->sameSection(EndMBB) ? EndLabel : MBBSectionRange.EndLabel});
688 }
689 if (MBB->sameSection(EndMBB))
690 break;
691 MBB = MBB->getNextNode();
692 } while (true);
693 }
694 attachRangesOrLowHighPC(Die, std::move(List));
695}
696
698 DIE &ParentScopeDIE) {
699 assert(Scope->getScopeNode());
700 auto *DS = Scope->getScopeNode();
701 auto *InlinedSP = getDISubprogram(DS);
702 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
703 // was inlined from another compile unit.
704 DIE *OriginDIE = getAbstractScopeDIEs()[InlinedSP];
705 assert(OriginDIE && "Unable to find original DIE for an inlined subprogram.");
706
707 auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_inlined_subroutine);
708 ParentScopeDIE.addChild(ScopeDIE);
709 addDIEEntry(*ScopeDIE, dwarf::DW_AT_abstract_origin, *OriginDIE);
710
711 attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
712
713 // Add the call site information to the DIE.
714 const DILocation *IA = Scope->getInlinedAt();
715 addUInt(*ScopeDIE, dwarf::DW_AT_call_file, std::nullopt,
716 getOrCreateSourceID(IA->getFile()));
717 addUInt(*ScopeDIE, dwarf::DW_AT_call_line, std::nullopt, IA->getLine());
718 if (IA->getColumn())
719 addUInt(*ScopeDIE, dwarf::DW_AT_call_column, std::nullopt, IA->getColumn());
720 if (IA->getDiscriminator() && DD->getDwarfVersion() >= 4)
721 addUInt(*ScopeDIE, dwarf::DW_AT_GNU_discriminator, std::nullopt,
722 IA->getDiscriminator());
723
724 // Add name to the name table, we do this here because we're guaranteed
725 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
726 DD->addSubprogramNames(*this, CUNode->getNameTableKind(), InlinedSP,
727 *ScopeDIE);
728
729 return ScopeDIE;
730}
731
733 DIE &ParentScopeDIE) {
734 if (DD->isLexicalScopeDIENull(Scope))
735 return nullptr;
736 const auto *DS = Scope->getScopeNode();
737
738 auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_lexical_block);
739 ParentScopeDIE.addChild(ScopeDIE);
740
741 if (Scope->isAbstractScope()) {
742 assert(!getAbstractScopeDIEs().count(DS) &&
743 "Abstract DIE for this scope exists!");
744 getAbstractScopeDIEs()[DS] = ScopeDIE;
745 return ScopeDIE;
746 }
747 if (!Scope->getInlinedAt()) {
748 assert(!LexicalBlockDIEs.count(DS) &&
749 "Concrete out-of-line DIE for this scope exists!");
750 LexicalBlockDIEs[DS] = ScopeDIE;
751 } else {
752 InlinedLocalScopeDIEs[DS].push_back(ScopeDIE);
753 }
754
755 attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
756
757 return ScopeDIE;
758}
759
761 auto *VariableDie = DIE::get(DIEValueAllocator, DV.getTag());
762 insertDIE(DV.getVariable(), VariableDie);
763 DV.setDIE(*VariableDie);
764 // Abstract variables don't get common attributes later, so apply them now.
765 if (Abstract) {
766 applyCommonDbgVariableAttributes(DV, *VariableDie);
767 } else {
768 std::visit(
769 [&](const auto &V) {
770 applyConcreteDbgVariableAttributes(V, DV, *VariableDie);
771 },
772 DV.asVariant());
773 }
774 return VariableDie;
775}
776
777static const DIType *resolveTypeQualifiers(const DIType *Ty) {
778 while (const auto *DT = dyn_cast_or_null<DIDerivedType>(Ty)) {
779 switch (DT->getTag()) {
780 case dwarf::DW_TAG_typedef:
781 case dwarf::DW_TAG_const_type:
782 case dwarf::DW_TAG_volatile_type:
783 case dwarf::DW_TAG_restrict_type:
784 case dwarf::DW_TAG_atomic_type:
785 Ty = DT->getBaseType();
786 continue;
787 default:
788 return Ty;
789 }
790 }
791 return Ty;
792}
793
794bool DwarfCompileUnit::emitImplicitPointerLocation(const Loc::Single &Single,
795 const DbgVariable &DV,
796 DIE &VariableDie) {
797 const DIExpression *Expr = Single.getExpr();
798 if (!Expr)
799 return false;
800
801 // Only handle the simple case where DW_OP_LLVM_implicit_pointer is the
802 // sole operation (or followed only by DW_OP_LLVM_fragment).
803 //
804 // Multi-level implicit pointers (e.g., int **pp where both levels are
805 // optimized away) would require stacking multiple implicit_pointer ops
806 // in one expression and unwinding them into a chain of artificial DIEs.
807 // This is left for future work.
808 //
809 // Location list support (Loc::Multi) is not yet handled.
810 auto ExprOps = Expr->expr_ops();
811 auto FirstOp = ExprOps.begin();
812 if (FirstOp == ExprOps.end() ||
813 FirstOp->getOp() != dwarf::DW_OP_LLVM_implicit_pointer)
814 return false;
815
816 if (DD->getDwarfVersion() < 4)
817 return false;
818
819 const DbgValueLoc &DVal = Single.getValueLoc();
820 if (DVal.isVariadic())
821 return false;
822
823 assert(!DVal.getLocEntries().empty() &&
824 "Non-variadic value must have one entry");
825 const DbgValueLocEntry &Entry = DVal.getLocEntries()[0];
826
827 // Resolve the variable's type, stripping qualifiers and typedefs,
828 // to find the pointer or reference type underneath.
829 // The verifier rejects cyclic type references, so this loop terminates.
830 const DIDerivedType *PtrTy =
832 if (!PtrTy)
833 return false;
834
835 if (PtrTy->getTag() != dwarf::DW_TAG_pointer_type &&
836 PtrTy->getTag() != dwarf::DW_TAG_reference_type &&
837 PtrTy->getTag() != dwarf::DW_TAG_rvalue_reference_type)
838 return false;
839
840 const DIType *PointeeTy = PtrTy->getBaseType();
841
842 // Try to reuse an existing artificial DIE for constant integer values.
843 // This avoids duplicate DIEs when multiple pointer variables reference
844 // the same constant (e.g., after ArgumentPromotion promotes the same
845 // struct member for two different pointer parameters).
846 DIE *ArtificialDIEPtr = nullptr;
847 if (Entry.isInt() && PointeeTy) {
848 auto It = ImplicitPointerDIEs.find({PointeeTy, Entry.getInt()});
849 if (It != ImplicitPointerDIEs.end())
850 ArtificialDIEPtr = It->second;
851 }
852
853 if (!ArtificialDIEPtr) {
854 // Check that the value can be described before creating a DIE for it.
855 if (!Entry.isLocation() && !Entry.isInt() && !Entry.isConstantFP())
856 return false;
857
858 DIE &ProcDIE = createAndAddDIE(dwarf::DW_TAG_dwarf_procedure, getUnitDie());
859
860 if (Entry.isLocation()) {
861 addAddress(ProcDIE, dwarf::DW_AT_location, Entry.getLoc());
862 } else if (Entry.isInt()) {
863 if (PointeeTy)
864 addConstantValue(ProcDIE, Entry.getInt(), PointeeTy);
865 } else {
866 addConstantFPValue(ProcDIE, Entry.getConstantFP());
867 }
868
869 ArtificialDIEPtr = &ProcDIE;
870
871 // Cache constant entries for de-duplication.
872 if (Entry.isInt() && PointeeTy)
873 ImplicitPointerDIEs.insert(
874 {{PointeeTy, Entry.getInt()}, ArtificialDIEPtr});
875 }
876
877 auto *Loc = new (DIEValueAllocator) DIELoc;
878
879 const unsigned ImplicitPtrOp = DD->getDwarfVersion() >= 5
880 ? dwarf::DW_OP_implicit_pointer
881 : dwarf::DW_OP_GNU_implicit_pointer;
882 addUInt(*Loc, dwarf::DW_FORM_data1, ImplicitPtrOp);
883
884 Loc->addValue(DIEValueAllocator, static_cast<dwarf::Attribute>(0),
885 dwarf::DW_FORM_ref_addr, DIEEntry(*ArtificialDIEPtr));
886
887 addSInt(*Loc, dwarf::DW_FORM_sdata, 0);
888
889 addBlock(VariableDie, dwarf::DW_AT_location, Loc);
890 return true;
891}
892
893void DwarfCompileUnit::applyConcreteDbgVariableAttributes(
894 const Loc::Single &Single, const DbgVariable &DV, DIE &VariableDie) {
895 // Handle DW_OP_LLVM_implicit_pointer before normal location emission.
896 if (emitImplicitPointerLocation(Single, DV, VariableDie))
897 return;
898
899 const DbgValueLoc *DVal = &Single.getValueLoc();
900 if (!Single.getExpr())
901 DD->addTargetVariableAttributes(*this, VariableDie, std::nullopt,
903 if (!DVal->isVariadic()) {
904 const DbgValueLocEntry *Entry = DVal->getLocEntries().begin();
905 if (Entry->isLocation()) {
906 addVariableAddress(DV, VariableDie, Entry->getLoc());
907 } else if (Entry->isInt()) {
908 auto *Expr = Single.getExpr();
909 if (Expr && Expr->getNumElements()) {
910 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
911 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
912 // If there is an expression, emit raw unsigned bytes.
913 DwarfExpr.addFragmentOffset(Expr);
914 DwarfExpr.addUnsignedConstant(Entry->getInt());
915 DwarfExpr.addExpression(Expr);
916 addBlock(VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
917 if (DwarfExpr.TagOffset)
918 addUInt(VariableDie, dwarf::DW_AT_LLVM_tag_offset,
919 dwarf::DW_FORM_data1, *DwarfExpr.TagOffset);
920 } else
921 addConstantValue(VariableDie, Entry->getInt(), DV.getType());
922 } else if (Entry->isConstantFP()) {
923 addConstantFPValue(VariableDie, Entry->getConstantFP());
924 } else if (Entry->isConstantInt()) {
925 addConstantValue(VariableDie, Entry->getConstantInt(), DV.getType());
926 } else if (Entry->isGlobalAddress()) {
927 auto *Expr = Single.getExpr();
928 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
929 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
930 DwarfExpr.addFragmentOffset(Expr);
931 if (!DwarfExpr.addGlobalAddress(Entry->getGlobalAddress(),
932 Entry->getGlobalOffset()))
933 return;
934 // A rejected operation leaves the expression built so far in Loc, which
935 // describes some other location rather than none. Drop it instead.
936 if (!DwarfExpr.addExpression(Expr))
937 return;
938 addBlock(VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
939 if (DwarfExpr.TagOffset)
940 addUInt(VariableDie, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1,
941 *DwarfExpr.TagOffset);
942 } else if (Entry->isTargetIndexLocation()) {
943 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
944 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
945 const DIBasicType *BT = dyn_cast<DIBasicType>(
946 static_cast<const Metadata *>(DV.getVariable()->getType()));
947 DwarfDebug::emitDebugLocValue(*Asm, BT, *DVal, DwarfExpr);
948 addBlock(VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
949 }
950 return;
951 }
952 // If any of the location entries are registers with the value 0,
953 // then the location is undefined.
954 if (any_of(DVal->getLocEntries(), [](const DbgValueLocEntry &Entry) {
955 return Entry.isLocation() && !Entry.getLoc().getReg();
956 }))
957 return;
958 const DIExpression *Expr = Single.getExpr();
959 assert(Expr && "Variadic Debug Value must have an Expression.");
960 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
961 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
962 DwarfExpr.addFragmentOffset(Expr);
963 DIExpressionCursor Cursor(Expr);
964 const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo();
965
966 auto AddEntry = [&](const DbgValueLocEntry &Entry,
967 DIExpressionCursor &Cursor) {
968 if (Entry.isLocation()) {
969 if (!DwarfExpr.addMachineRegExpression(TRI, Cursor,
970 Entry.getLoc().getReg()))
971 return false;
972 } else if (Entry.isInt()) {
973 // If there is an expression, emit raw unsigned bytes.
974 DwarfExpr.addUnsignedConstant(Entry.getInt());
975 } else if (Entry.isConstantFP()) {
976 // DwarfExpression does not support arguments wider than 64 bits
977 // (see PR52584).
978 // TODO: Consider chunking expressions containing overly wide
979 // arguments into separate pointer-sized fragment expressions.
980 APInt RawBytes = Entry.getConstantFP()->getValueAPF().bitcastToAPInt();
981 if (RawBytes.getBitWidth() > 64)
982 return false;
983 DwarfExpr.addUnsignedConstant(RawBytes.getZExtValue());
984 } else if (Entry.isConstantInt()) {
985 APInt RawBytes = Entry.getConstantInt()->getValue();
986 if (RawBytes.getBitWidth() > 64)
987 return false;
988 DwarfExpr.addUnsignedConstant(RawBytes.getZExtValue());
989 } else if (Entry.isTargetIndexLocation()) {
990 TargetIndexLocation Loc = Entry.getTargetIndexLocation();
991 // TODO TargetIndexLocation is a target-independent. Currently
992 // only the WebAssembly-specific encoding is supported.
993 assert(Asm->TM.getTargetTriple().isWasm());
994 DwarfExpr.addWasmLocation(Loc.Index, static_cast<uint64_t>(Loc.Offset));
995 } else if (Entry.isGlobalAddress()) {
996 if (!DwarfExpr.addGlobalAddress(Entry.getGlobalAddress(),
997 Entry.getGlobalOffset()))
998 return false;
999 } else {
1000 llvm_unreachable("Unsupported Entry type.");
1001 }
1002 return true;
1003 };
1004
1005 if (!DwarfExpr.addExpression(
1006 std::move(Cursor),
1007 [&](unsigned Idx, DIExpressionCursor &Cursor) -> bool {
1008 return AddEntry(DVal->getLocEntries()[Idx], Cursor);
1009 }))
1010 return;
1011
1012 // Now attach the location information to the DIE.
1013 addBlock(VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
1014 if (DwarfExpr.TagOffset)
1015 addUInt(VariableDie, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1,
1016 *DwarfExpr.TagOffset);
1017}
1018
1019void DwarfCompileUnit::applyConcreteDbgVariableAttributes(
1020 const Loc::Multi &Multi, const DbgVariable &DV, DIE &VariableDie) {
1021 addLocationList(VariableDie, dwarf::DW_AT_location,
1022 Multi.getDebugLocListIndex());
1023 auto TagOffset = Multi.getDebugLocListTagOffset();
1024 if (TagOffset)
1025 addUInt(VariableDie, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1,
1026 *TagOffset);
1027}
1028
1029void DwarfCompileUnit::applyConcreteDbgVariableAttributes(const Loc::MMI &MMI,
1030 const DbgVariable &DV,
1031 DIE &VariableDie) {
1032 std::optional<unsigned> TargetAddrSpace;
1033 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
1034 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
1035 for (const auto &Fragment : MMI.getFrameIndexExprs()) {
1036 Register FrameReg;
1037 const DIExpression *Expr = Fragment.Expr;
1038 const TargetFrameLowering *TFI = Asm->MF->getSubtarget().getFrameLowering();
1039 StackOffset Offset =
1040 TFI->getFrameIndexReference(*Asm->MF, Fragment.FI, FrameReg);
1041 DwarfExpr.addFragmentOffset(Expr);
1042
1043 auto *TRI = Asm->MF->getSubtarget().getRegisterInfo();
1044 SmallVector<uint64_t, 8> Ops;
1045 TRI->getOffsetOpcodes(Offset, Ops);
1046
1047 Expr = DD->adjustExpressionForTarget(Expr, TargetAddrSpace);
1048 if (Expr)
1049 Ops.append(Expr->elements_begin(), Expr->elements_end());
1050 DIExpressionCursor Cursor(Ops);
1051 DwarfExpr.setMemoryLocationKind();
1052 if (const MCSymbol *FrameSymbol = Asm->getFunctionFrameSymbol())
1053 addOpAddress(*Loc, FrameSymbol);
1054 else
1055 DwarfExpr.addMachineRegExpression(
1056 *Asm->MF->getSubtarget().getRegisterInfo(), Cursor, FrameReg);
1057 DwarfExpr.addExpression(std::move(Cursor));
1058 }
1059 DD->addTargetVariableAttributes(*this, VariableDie, TargetAddrSpace,
1061 addBlock(VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
1062 if (DwarfExpr.TagOffset)
1063 addUInt(VariableDie, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1,
1064 *DwarfExpr.TagOffset);
1065}
1066
1067void DwarfCompileUnit::applyConcreteDbgVariableAttributes(
1068 const Loc::EntryValue &EntryValue, const DbgVariable &DV,
1069 DIE &VariableDie) {
1070 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
1071 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
1072 // Emit each expression as: EntryValue(Register) <other ops> <Fragment>.
1073 for (auto [Register, Expr] : EntryValue.EntryValues) {
1074 DwarfExpr.addFragmentOffset(&Expr);
1075 DIExpressionCursor Cursor(Expr.getElements());
1076 DwarfExpr.beginEntryValueExpression(Cursor);
1077 DwarfExpr.addMachineRegExpression(
1078 *Asm->MF->getSubtarget().getRegisterInfo(), Cursor, Register);
1079 DwarfExpr.addExpression(std::move(Cursor));
1080 }
1081 addBlock(VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
1082}
1083
1084void DwarfCompileUnit::applyConcreteDbgVariableAttributes(
1085 const std::monostate &, const DbgVariable &DV, DIE &VariableDie) {}
1086
1088 const LexicalScope &Scope,
1089 DIE *&ObjectPointer) {
1090 auto Var = constructVariableDIE(DV, Scope.isAbstractScope());
1091 if (DV.isObjectPointer())
1092 ObjectPointer = Var;
1093 return Var;
1094}
1095
1097 const LexicalScope &Scope) {
1098 auto LabelDie = DIE::get(DIEValueAllocator, DL.getTag());
1099 insertDIE(DL.getLabel(), LabelDie);
1100 DL.setDIE(*LabelDie);
1101
1102 if (Scope.isAbstractScope())
1103 applyLabelAttributes(DL, *LabelDie);
1104
1105 return LabelDie;
1106}
1107
1108/// Return all DIVariables that appear in count: expressions.
1111 auto *Array = dyn_cast<DICompositeType>(Var->getType());
1112 if (!Array || Array->getTag() != dwarf::DW_TAG_array_type)
1113 return Result;
1114 if (auto *DLVar = Array->getDataLocation())
1115 Result.push_back(DLVar);
1116 if (auto *AsVar = Array->getAssociated())
1117 Result.push_back(AsVar);
1118 if (auto *AlVar = Array->getAllocated())
1119 Result.push_back(AlVar);
1120 for (auto *El : Array->getElements()) {
1121 if (auto *Subrange = dyn_cast<DISubrange>(El)) {
1122 if (auto Count = Subrange->getCount())
1123 if (auto *Dependency = dyn_cast_if_present<DIVariable *>(Count))
1124 Result.push_back(Dependency);
1125 if (auto LB = Subrange->getLowerBound())
1126 if (auto *Dependency = dyn_cast_if_present<DIVariable *>(LB))
1127 Result.push_back(Dependency);
1128 if (auto UB = Subrange->getUpperBound())
1129 if (auto *Dependency = dyn_cast_if_present<DIVariable *>(UB))
1130 Result.push_back(Dependency);
1131 if (auto ST = Subrange->getStride())
1132 if (auto *Dependency = dyn_cast_if_present<DIVariable *>(ST))
1133 Result.push_back(Dependency);
1134 } else if (auto *GenericSubrange = dyn_cast<DIGenericSubrange>(El)) {
1135 if (auto Count = GenericSubrange->getCount())
1136 if (auto *Dependency = dyn_cast_if_present<DIVariable *>(Count))
1137 Result.push_back(Dependency);
1138 if (auto LB = GenericSubrange->getLowerBound())
1139 if (auto *Dependency = dyn_cast_if_present<DIVariable *>(LB))
1140 Result.push_back(Dependency);
1141 if (auto UB = GenericSubrange->getUpperBound())
1142 if (auto *Dependency = dyn_cast_if_present<DIVariable *>(UB))
1143 Result.push_back(Dependency);
1144 if (auto ST = GenericSubrange->getStride())
1145 if (auto *Dependency = dyn_cast_if_present<DIVariable *>(ST))
1146 Result.push_back(Dependency);
1147 }
1148 }
1149 return Result;
1150}
1151
1152/// Sort local variables so that variables appearing inside of helper
1153/// expressions come first.
1158 // Map back from a DIVariable to its containing DbgVariable.
1160 // Set of DbgVariables in Result.
1162 // For cycle detection.
1164
1165 // Initialize the worklist and the DIVariable lookup table.
1166 for (auto *Var : reverse(Input)) {
1167 DbgVar.insert({Var->getVariable(), Var});
1168 WorkList.push_back({Var, 0});
1169 }
1170
1171 // Perform a stable topological sort by doing a DFS.
1172 while (!WorkList.empty()) {
1173 auto Item = WorkList.back();
1174 DbgVariable *Var = Item.getPointer();
1175 bool visitedAllDependencies = Item.getInt();
1176 WorkList.pop_back();
1177
1178 assert(Var);
1179
1180 // Already handled.
1181 if (Visited.count(Var))
1182 continue;
1183
1184 // Add to Result if all dependencies are visited.
1185 if (visitedAllDependencies) {
1186 Visited.insert(Var);
1187 Result.push_back(Var);
1188 continue;
1189 }
1190
1191 // Detect cycles.
1192 auto Res = Visiting.insert(Var);
1193 if (!Res.second) {
1194 assert(false && "dependency cycle in local variables");
1195 return Result;
1196 }
1197
1198 // Push dependencies and this node onto the worklist, so that this node is
1199 // visited again after all of its dependencies are handled.
1200 WorkList.push_back({Var, 1});
1201 for (const auto *Dependency : dependencies(Var)) {
1202 // Don't add dependency if it is in a different lexical scope or a global.
1203 if (const auto *Dep = dyn_cast<const DILocalVariable>(Dependency))
1204 if (DbgVariable *Var = DbgVar.lookup(Dep))
1205 WorkList.push_back({Var, 0});
1206 }
1207 }
1208 return Result;
1209}
1210
1212 const Function &F,
1213 LexicalScope *Scope,
1214 MCSymbol *LineTableSym) {
1215 DIE &ScopeDIE = updateSubprogramScopeDIE(Sub, F, LineTableSym);
1216
1217 if (Scope) {
1218 assert(!Scope->getInlinedAt());
1219 assert(!Scope->isAbstractScope());
1220 // Collect lexical scope children first.
1221 // ObjectPointer might be a local (non-argument) local variable if it's a
1222 // block's synthetic this pointer.
1223 if (DIE *ObjectPointer = createAndAddScopeChildren(Scope, ScopeDIE))
1224 addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, *ObjectPointer);
1225 }
1226
1227 // If this is a variadic function, add an unspecified parameter.
1228 auto *SPTy = Sub->getType();
1229 if (!SPTy)
1230 return ScopeDIE;
1231
1232 DITypeArray FnArgs = SPTy->getTypeArray();
1233
1234 // If we have a single element of null, it is a function that returns void.
1235 // If we have more than one elements and the last one is null, it is a
1236 // variadic function.
1237 if (FnArgs.size() > 1 && !FnArgs[FnArgs.size() - 1] &&
1239 ScopeDIE.addChild(
1240 DIE::get(DIEValueAllocator, dwarf::DW_TAG_unspecified_parameters));
1241
1242 return ScopeDIE;
1243}
1244
1245bool DwarfCompileUnit::hasGlobalVariableInScope(const DILocalScope *ScopeNode) {
1246 return GlobalVarScopes.contains(ScopeNode);
1247}
1248
1250 DIE &ScopeDIE) {
1251 DIE *ObjectPointer = nullptr;
1252
1253 // Emit function arguments (order is significant).
1254 auto Vars = DU->getScopeVariables().lookup(Scope);
1255 for (auto &DV : Vars.Args)
1256 ScopeDIE.addChild(constructVariableDIE(*DV.second, *Scope, ObjectPointer));
1257
1258 // Emit local variables.
1259 auto Locals = sortLocalVars(Vars.Locals);
1260 for (DbgVariable *DV : Locals)
1261 ScopeDIE.addChild(constructVariableDIE(*DV, *Scope, ObjectPointer));
1262
1263 // Emit labels.
1264 for (DbgLabel *DL : DU->getScopeLabels().lookup(Scope))
1265 ScopeDIE.addChild(constructLabelDIE(*DL, *Scope));
1266
1267 // Track other local entities (skipped in gmlt-like data).
1268 // This creates mapping between CU and a set of local declarations that
1269 // should be emitted for subprograms in this CU.
1270 if (!includeMinimalInlineScopes() && !Scope->getInlinedAt()) {
1271 auto &LocalDecls = DD->getLocalDeclsForScope(Scope->getScopeNode());
1272 DeferredLocalDecls.insert_range(LocalDecls);
1273 }
1274
1275 // Emit inner lexical scopes.
1276 auto skipLexicalScope = [this](LexicalScope *S) -> bool {
1277 const DILocalScope *DS = S->getScopeNode();
1278 if (isa<DISubprogram>(DS))
1279 return false;
1280 // Don't skip abstract lexical blocks that are scope targets for global
1281 // variables (e.g., function-scope statics). Those globals are emitted
1282 // later in endModule() and need to find the block via
1283 // getOrCreateContextDIE().
1284 if (S->isAbstractScope() && hasGlobalVariableInScope(DS))
1285 return false;
1286 // Create a concrete lexical block for a scope with an abstract lexical
1287 // block to ensure visibility of scope-local types and static variables
1288 // within the scope range.
1289 if (getAbstractScopeDIEs().lookup(DS))
1290 return false;
1291 auto Vars = DU->getScopeVariables().lookup(S);
1292 if (!Vars.Args.empty() || !Vars.Locals.empty())
1293 return false;
1294 return includeMinimalInlineScopes() ||
1295 DD->getLocalDeclsForScope(DS).empty();
1296 };
1297 for (LexicalScope *LS : Scope->getChildren()) {
1298 // If the lexical block doesn't have non-scope children or global
1299 // variables scoped to it, skip its emission and put its children directly
1300 // to the parent scope.
1301 if (skipLexicalScope(LS))
1302 createAndAddScopeChildren(LS, ScopeDIE);
1303 else
1304 constructScopeDIE(LS, ScopeDIE);
1305 }
1306
1307 return ObjectPointer;
1308}
1309
1311 const DISubprogram *SP) {
1312 if (auto *AbsDef = getAbstractScopeDIEs().lookup(SP))
1313 return *AbsDef;
1314
1315 auto [ContextDIE, ContextCU] = getOrCreateAbstractSubprogramContextDIE(SP);
1316 return createAbstractSubprogramDIE(SP, ContextDIE, ContextCU);
1317}
1318
1319DIE &DwarfCompileUnit::createAbstractSubprogramDIE(
1320 const DISubprogram *SP, DIE *ContextDIE, DwarfCompileUnit *ContextCU) {
1321 // Passing null as the associated node because the abstract definition
1322 // shouldn't be found by lookup.
1323 DIE &AbsDef = ContextCU->createAndAddDIE(dwarf::DW_TAG_subprogram,
1324 *ContextDIE, nullptr);
1325
1326 // Store the DIE before creating children.
1327 ContextCU->getAbstractScopeDIEs()[SP] = &AbsDef;
1328
1329 ContextCU->applySubprogramAttributesToDefinition(SP, AbsDef);
1330 ContextCU->addSInt(AbsDef, dwarf::DW_AT_inline,
1331 DD->getDwarfVersion() <= 4 ? std::optional<dwarf::Form>()
1332 : dwarf::DW_FORM_implicit_const,
1334
1335 return AbsDef;
1336}
1337
1338std::pair<DIE *, DwarfCompileUnit *>
1339DwarfCompileUnit::getOrCreateAbstractSubprogramContextDIE(
1340 const DISubprogram *SP) {
1341 bool Minimal = includeMinimalInlineScopes();
1342 bool IgnoreScope = shouldPlaceInUnitDIE(SP, Minimal);
1343 DIE *ContextDIE = getOrCreateSubprogramContextDIE(SP, IgnoreScope);
1344
1345 if (auto *SPDecl = SP->getDeclaration())
1346 if (!Minimal)
1347 getOrCreateSubprogramDIE(SPDecl, nullptr);
1348
1349 // The scope may be shared with a subprogram that has already been
1350 // constructed in another CU, in which case we need to construct this
1351 // subprogram in the same CU.
1352 auto *ContextCU = IgnoreScope ? this : DD->lookupCU(ContextDIE->getUnitDie());
1353
1354 return std::make_pair(ContextDIE, ContextCU);
1355}
1356
1358 LexicalScope *Scope) {
1359 auto *SP = cast<DISubprogram>(Scope->getScopeNode());
1360
1361 // Populate subprogram DIE only once.
1362 if (!getFinalizedAbstractSubprograms().insert(SP).second)
1363 return;
1364
1365 auto [ContextDIE, ContextCU] = getOrCreateAbstractSubprogramContextDIE(SP);
1366 DIE *AbsDef = getAbstractScopeDIEs().lookup(SP);
1367 if (!AbsDef)
1368 AbsDef = &createAbstractSubprogramDIE(SP, ContextDIE, ContextCU);
1369
1370 if (DIE *ObjectPointer = ContextCU->createAndAddScopeChildren(Scope, *AbsDef))
1371 ContextCU->addDIEEntry(*AbsDef, dwarf::DW_AT_object_pointer,
1372 *ObjectPointer);
1373}
1374
1376 return DD->getDwarfVersion() <= 4 && !DD->tuneForLLDB();
1377}
1378
1381 return Tag;
1382 switch (Tag) {
1383 case dwarf::DW_TAG_call_site:
1384 return dwarf::DW_TAG_GNU_call_site;
1385 case dwarf::DW_TAG_call_site_parameter:
1386 return dwarf::DW_TAG_GNU_call_site_parameter;
1387 default:
1388 llvm_unreachable("DWARF5 tag with no GNU analog");
1389 }
1390}
1391
1395 return Attr;
1396 switch (Attr) {
1397 case dwarf::DW_AT_call_all_calls:
1398 return dwarf::DW_AT_GNU_all_call_sites;
1399 case dwarf::DW_AT_call_target:
1400 return dwarf::DW_AT_GNU_call_site_target;
1401 case dwarf::DW_AT_call_target_clobbered:
1402 return dwarf::DW_AT_GNU_call_site_target_clobbered;
1403 case dwarf::DW_AT_call_origin:
1404 return dwarf::DW_AT_abstract_origin;
1405 case dwarf::DW_AT_call_return_pc:
1406 return dwarf::DW_AT_low_pc;
1407 case dwarf::DW_AT_call_value:
1408 return dwarf::DW_AT_GNU_call_site_value;
1409 case dwarf::DW_AT_call_tail_call:
1410 return dwarf::DW_AT_GNU_tail_call;
1411 default:
1412 llvm_unreachable("DWARF5 attribute with no GNU analog");
1413 }
1414}
1415
1419 return Loc;
1420 switch (Loc) {
1421 case dwarf::DW_OP_entry_value:
1422 return dwarf::DW_OP_GNU_entry_value;
1423 default:
1424 llvm_unreachable("DWARF5 location atom with no GNU analog");
1425 }
1426}
1427
1429 DIE &ScopeDIE, const DISubprogram *CalleeSP, const Function *CalleeF,
1430 bool IsTail, const MCSymbol *PCAddr, const MCSymbol *CallAddr,
1431 MachineLocation CallTarget, int64_t Offset, DIType *AllocSiteTy) {
1432 // Insert a call site entry DIE within ScopeDIE.
1433 DIE &CallSiteDIE = createAndAddDIE(getDwarf5OrGNUTag(dwarf::DW_TAG_call_site),
1434 ScopeDIE, nullptr);
1435
1436 // A valid register in CallTarget indicates an indirect call.
1437 if (CallTarget.getReg()) {
1438 // Add a DW_AT_call_target location expression describing the location of
1439 // the address of the target function. If any register in the expression
1440 // (i.e., the single register we currently handle) is volatile we must use
1441 // DW_AT_call_target_clobbered instead.
1442 const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo();
1444 TRI.isCalleeSavedPhysReg(CallTarget.getReg(), *Asm->MF)
1445 ? dwarf::DW_AT_call_target
1446 : dwarf::DW_AT_call_target_clobbered);
1447
1448 // CallTarget is the location of the address of an indirect call. The
1449 // location may be indirect, modified by Offset.
1450 if (CallTarget.isIndirect())
1451 addMemoryLocation(CallSiteDIE, Attribute, CallTarget, Offset);
1452 else
1453 addAddress(CallSiteDIE, Attribute, CallTarget);
1454 } else if (CalleeSP) {
1455 DIE *CalleeDIE = getOrCreateSubprogramDIE(CalleeSP, CalleeF);
1456 assert(CalleeDIE && "Could not create DIE for call site entry origin");
1457 addLinkageNamesToDeclarations(*DD, *CalleeSP, *CalleeDIE);
1458
1459 addDIEEntry(CallSiteDIE, getDwarf5OrGNUAttr(dwarf::DW_AT_call_origin),
1460 *CalleeDIE);
1461 }
1462
1463 if (IsTail) {
1464 // Attach DW_AT_call_tail_call to tail calls for standards compliance.
1465 addFlag(CallSiteDIE, getDwarf5OrGNUAttr(dwarf::DW_AT_call_tail_call));
1466
1467 // Attach the address of the branch instruction to allow the debugger to
1468 // show where the tail call occurred. This attribute has no GNU analog.
1469 //
1470 // GDB works backwards from non-standard usage of DW_AT_low_pc (in DWARF4
1471 // mode -- equivalently, in DWARF5 mode, DW_AT_call_return_pc) at tail-call
1472 // site entries to figure out the PC of tail-calling branch instructions.
1473 // This means it doesn't need the compiler to emit DW_AT_call_pc, so we
1474 // don't emit it here.
1475 //
1476 // There's no need to tie non-GDB debuggers to this non-standardness, as it
1477 // adds unnecessary complexity to the debugger. For non-GDB debuggers, emit
1478 // the standard DW_AT_call_pc info.
1480 addLabelAddress(CallSiteDIE, dwarf::DW_AT_call_pc, CallAddr);
1481 }
1482
1483 // Attach the return PC to allow the debugger to disambiguate call paths
1484 // from one function to another.
1485 //
1486 // The return PC is only really needed when the call /isn't/ a tail call, but
1487 // GDB expects it in DWARF4 mode, even for tail calls (see the comment above
1488 // the DW_AT_call_pc emission logic for an explanation).
1489 if (!IsTail || useGNUAnalogForDwarf5Feature()) {
1490 assert(PCAddr && "Missing return PC information for a call");
1491 addLabelAddress(CallSiteDIE,
1492 getDwarf5OrGNUAttr(dwarf::DW_AT_call_return_pc), PCAddr);
1493 }
1494
1495 if (AllocSiteTy)
1496 addType(CallSiteDIE, AllocSiteTy, dwarf::DW_AT_LLVM_alloc_type);
1497
1498 return CallSiteDIE;
1499}
1500
1502 DIE &CallSiteDIE, SmallVector<DbgCallSiteParam, 4> &Params) {
1503 for (const auto &Param : Params) {
1504 unsigned Register = Param.getRegister();
1505 auto CallSiteDieParam =
1507 getDwarf5OrGNUTag(dwarf::DW_TAG_call_site_parameter));
1508 insertDIE(CallSiteDieParam);
1509 addAddress(*CallSiteDieParam, dwarf::DW_AT_location,
1511
1513 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
1514 DwarfExpr.setCallSiteParamValueFlag();
1515
1516 DwarfDebug::emitDebugLocValue(*Asm, nullptr, Param.getValue(), DwarfExpr);
1517
1518 addBlock(*CallSiteDieParam, getDwarf5OrGNUAttr(dwarf::DW_AT_call_value),
1519 DwarfExpr.finalize());
1520
1521 CallSiteDIE.addChild(CallSiteDieParam);
1522 }
1523}
1524
1526 const DIImportedEntity *Module) {
1527 DIE *IMDie = DIE::get(DIEValueAllocator, Module->getTag());
1528 insertDIE(Module, IMDie);
1529 DIE *EntityDie;
1530 auto *Entity = Module->getEntity();
1531 if (auto *NS = dyn_cast<DINamespace>(Entity))
1532 EntityDie = getOrCreateNameSpace(NS);
1533 else if (auto *M = dyn_cast<DIModule>(Entity))
1534 EntityDie = getOrCreateModule(M);
1535 else if (auto *SP = dyn_cast<DISubprogram>(Entity)) {
1536 // If there is an abstract subprogram, refer to it. Note that this assumes
1537 // that all the abstract subprograms have been already created (which is
1538 // correct until imported entities get emitted in DwarfDebug::endModule()).
1539 if (auto *AbsSPDie = getAbstractScopeDIEs().lookup(SP))
1540 EntityDie = AbsSPDie;
1541 else
1542 EntityDie = getOrCreateSubprogramDIE(SP, nullptr);
1543 } else if (auto *T = dyn_cast<DIType>(Entity))
1544 EntityDie = getOrCreateTypeDIE(T);
1545 else if (auto *GV = dyn_cast<DIGlobalVariable>(Entity))
1546 EntityDie = getOrCreateGlobalVariableDIE(GV, {});
1547 else if (auto *IE = dyn_cast<DIImportedEntity>(Entity))
1548 EntityDie = getOrCreateImportedEntityDIE(IE);
1549 else
1550 EntityDie = getDIE(Entity);
1551 assert(EntityDie);
1552 addSourceLine(*IMDie, Module->getLine(), /*Column*/ 0, Module->getFile());
1553 addDIEEntry(*IMDie, dwarf::DW_AT_import, *EntityDie);
1554 StringRef Name = Module->getName();
1555 if (!Name.empty()) {
1556 addString(*IMDie, dwarf::DW_AT_name, Name);
1557
1558 // FIXME: if consumers ever start caring about handling
1559 // unnamed import declarations such as `using ::nullptr_t`
1560 // or `using namespace std::ranges`, we could add the
1561 // import declaration into the accelerator table with the
1562 // name being the one of the entity being imported.
1563 DD->addAccelNamespace(*this, CUNode->getNameTableKind(), Name, *IMDie);
1564 }
1565
1566 // This is for imported module with renamed entities (such as variables and
1567 // subprograms).
1568 DINodeArray Elements = Module->getElements();
1569 for (const auto *Element : Elements) {
1570 if (!Element)
1571 continue;
1572 IMDie->addChild(
1574 }
1575
1576 return IMDie;
1577}
1578
1580 const DIImportedEntity *IE) {
1581
1582 // Check for pre-existence.
1583 if (DIE *Die = getDIE(IE))
1584 return Die;
1585
1586 DIE *ContextDIE = getOrCreateContextDIE(IE->getScope());
1587 assert(ContextDIE && "Empty scope for the imported entity!");
1588
1589 DIE *IMDie = constructImportedEntityDIE(IE);
1590 ContextDIE->addChild(IMDie);
1591 return IMDie;
1592}
1593
1595 DIE *D = getDIE(SP);
1596 if (DIE *AbsSPDIE = getAbstractScopeDIEs().lookup(SP)) {
1597 if (D)
1598 // If this subprogram has an abstract definition, reference that
1599 addDIEEntry(*D, dwarf::DW_AT_abstract_origin, *AbsSPDIE);
1600 } else {
1602 if (D)
1603 // And attach the attributes
1605 }
1606}
1607
1609 DbgEntity *AbsEntity = getExistingAbstractEntity(Entity->getEntity());
1610
1611 auto *Die = Entity->getDIE();
1612 /// Label may be used to generate DW_AT_low_pc, so put it outside
1613 /// if/else block.
1614 const DbgLabel *Label = nullptr;
1615 if (AbsEntity && AbsEntity->getDIE()) {
1616 addDIEEntry(*Die, dwarf::DW_AT_abstract_origin, *AbsEntity->getDIE());
1617 Label = dyn_cast<const DbgLabel>(Entity);
1618 } else {
1619 if (const DbgVariable *Var = dyn_cast<const DbgVariable>(Entity))
1621 else if ((Label = dyn_cast<const DbgLabel>(Entity)))
1622 applyLabelAttributes(*Label, *Die);
1623 else
1624 llvm_unreachable("DbgEntity must be DbgVariable or DbgLabel.");
1625 }
1626
1627 if (!Label)
1628 return;
1629
1630 const auto *Sym = Label->getSymbol();
1631 if (!Sym)
1632 return;
1633
1634 addLabelAddress(*Die, dwarf::DW_AT_low_pc, Sym);
1635
1636 // A TAG_label with a name and an AT_low_pc must be placed in debug_names.
1637 if (StringRef Name = Label->getName(); !Name.empty())
1638 getDwarfDebug().addAccelName(*this, CUNode->getNameTableKind(), Name, *Die);
1639}
1640
1642 auto AttachAO = [&](const DILocalScope *LS, DIE *ScopeDIE) {
1643 if (auto *AbsLSDie = getAbstractScopeDIEs().lookup(LS))
1644 addDIEEntry(*ScopeDIE, dwarf::DW_AT_abstract_origin, *AbsLSDie);
1645 };
1646
1647 for (auto [LScope, ScopeDIE] : LexicalBlockDIEs)
1648 AttachAO(LScope, ScopeDIE);
1649 for (auto &[LScope, ScopeDIEs] : InlinedLocalScopeDIEs)
1650 for (auto *ScopeDIE : ScopeDIEs)
1651 AttachAO(LScope, ScopeDIE);
1652}
1653
1655 auto &AbstractEntities = getAbstractEntities();
1656 auto I = AbstractEntities.find(Node);
1657 if (I != AbstractEntities.end())
1658 return I->second.get();
1659 return nullptr;
1660}
1661
1663 LexicalScope *Scope) {
1664 assert(Scope && Scope->isAbstractScope());
1665 auto &Entity = getAbstractEntities()[Node];
1667 Entity = std::make_unique<DbgVariable>(cast<const DILocalVariable>(Node),
1668 nullptr /* IA */);
1669 DU->addScopeVariable(Scope, cast<DbgVariable>(Entity.get()));
1670 } else if (isa<const DILabel>(Node)) {
1671 Entity = std::make_unique<DbgLabel>(
1672 cast<const DILabel>(Node), nullptr /* IA */);
1673 DU->addScopeLabel(Scope, cast<DbgLabel>(Entity.get()));
1674 }
1675}
1676
1677void DwarfCompileUnit::emitHeader(bool UseOffsets) {
1678 // Don't bother labeling the .dwo unit, as its offset isn't used.
1679 if (!Skeleton && !DD->useSectionsAsReferences()) {
1680 LabelBegin = Asm->createTempSymbol("cu_begin");
1681 Asm->OutStreamer->emitLabel(LabelBegin);
1682 }
1683
1684 dwarf::UnitType UT = Skeleton ? dwarf::DW_UT_split_compile
1685 : DD->useSplitDwarf() ? dwarf::DW_UT_skeleton
1686 : dwarf::DW_UT_compile;
1687 DwarfUnit::emitCommonHeader(UseOffsets, UT);
1688 if (DD->getDwarfVersion() >= 5 && UT != dwarf::DW_UT_compile)
1689 Asm->emitInt64(getDWOId());
1690}
1691
1693 if (!DD->shouldEmitDwarfPubSections())
1694 return false;
1695
1696 switch (CUNode->getNameTableKind()) {
1698 return false;
1699 // Opting in to GNU Pubnames/types overrides the default to ensure these are
1700 // generated for things like Gold's gdb_index generation.
1702 return true;
1704 return false;
1706 return DD->tuneForGDB() && !includeMinimalInlineScopes() &&
1707 !CUNode->isDebugDirectivesOnly() &&
1708 DD->getAccelTableKind() != AccelTableKind::Apple &&
1709 DD->getDwarfVersion() < 5;
1710 }
1711 llvm_unreachable("Unhandled DICompileUnit::DebugNameTableKind enum");
1712}
1713
1714/// addGlobalName - Add a new global name to the compile unit.
1716 const DIScope *Context) {
1717 if (!hasDwarfPubSections())
1718 return;
1719 std::string FullName = getParentContextString(Context) + Name.str();
1720 GlobalNames[FullName] = &Die;
1721}
1722
1724 const DIScope *Context) {
1725 if (!hasDwarfPubSections())
1726 return;
1727 std::string FullName = getParentContextString(Context) + Name.str();
1728 // Insert, allowing the entry to remain as-is if it's already present
1729 // This way the CU-level type DIE is preferred over the "can't describe this
1730 // type as a unit offset because it's not really in the CU at all, it's only
1731 // in a type unit"
1732 GlobalNames.insert(std::make_pair(std::move(FullName), &getUnitDie()));
1733}
1734
1735/// Add a new global type to the unit.
1737 const DIScope *Context) {
1738 if (!hasDwarfPubSections())
1739 return;
1740 std::string FullName = getParentContextString(Context) + Ty->getName().str();
1741 GlobalTypes[FullName] = &Die;
1742}
1743
1745 const DIScope *Context) {
1746 if (!hasDwarfPubSections())
1747 return;
1748 std::string FullName = getParentContextString(Context) + Ty->getName().str();
1749 // Insert, allowing the entry to remain as-is if it's already present
1750 // This way the CU-level type DIE is preferred over the "can't describe this
1751 // type as a unit offset because it's not really in the CU at all, it's only
1752 // in a type unit"
1753 GlobalTypes.insert(std::make_pair(std::move(FullName), &getUnitDie()));
1754}
1755
1757 MachineLocation Location) {
1758 auto *Single = std::get_if<Loc::Single>(&DV);
1759 if (Single && Single->getExpr())
1760 addComplexAddress(Single->getExpr(), Die, dwarf::DW_AT_location, Location);
1761 else
1762 addAddress(Die, dwarf::DW_AT_location, Location);
1763}
1764
1765void DwarfCompileUnit::addLocationWithExpr(DIE &Die, dwarf::Attribute Attribute,
1766 const MachineLocation &Location,
1767 ArrayRef<uint64_t> Expr) {
1769 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
1770 if (Location.isIndirect())
1771 DwarfExpr.setMemoryLocationKind();
1772
1773 DIExpressionCursor Cursor(Expr);
1775 if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
1776 return;
1777 DwarfExpr.addExpression(std::move(Cursor));
1778
1779 // Now attach the location information to the DIE.
1780 addBlock(Die, Attribute, DwarfExpr.finalize());
1781
1782 if (DwarfExpr.TagOffset)
1783 addUInt(Die, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1,
1784 *DwarfExpr.TagOffset);
1785}
1786
1787/// Add an address attribute to a die based on the location provided.
1789 const MachineLocation &Location) {
1790 addLocationWithExpr(Die, Attribute, Location, {});
1791}
1792
1793/// Add a memory location exprloc to \p DIE with attribute \p Attribute
1794/// at \p Location + \p Offset.
1796 const MachineLocation &Location,
1797 int64_t Offset) {
1798 assert(Location.isIndirect() && "Memory loc should be indirect");
1801 addLocationWithExpr(Die, Attribute, Location, Ops);
1802}
1803
1804/// Start with the address based on the location provided, and generate the
1805/// DWARF information necessary to find the actual variable given the extra
1806/// address information encoded in the DbgVariable, starting from the starting
1807/// location. Add the DWARF information to the die.
1810 const MachineLocation &Location) {
1812 DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
1813 DwarfExpr.addFragmentOffset(DIExpr);
1814 DwarfExpr.setLocation(Location, DIExpr);
1815
1816 DIExpressionCursor Cursor(DIExpr);
1817
1818 if (DIExpr->isEntryValue())
1819 DwarfExpr.beginEntryValueExpression(Cursor);
1820
1821 const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo();
1822 if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
1823 return;
1824 DwarfExpr.addExpression(std::move(Cursor));
1825
1826 // Now attach the location information to the DIE.
1827 addBlock(Die, Attribute, DwarfExpr.finalize());
1828
1829 if (DwarfExpr.TagOffset)
1830 addUInt(Die, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1,
1831 *DwarfExpr.TagOffset);
1832}
1833
1834/// Add a Dwarf loclistptr attribute data and value.
1836 unsigned Index) {
1837 dwarf::Form Form = (DD->getDwarfVersion() >= 5)
1838 ? dwarf::DW_FORM_loclistx
1839 : DD->getDwarfSectionOffsetForm();
1840 addAttribute(Die, Attribute, Form, DIELocList(Index));
1841}
1842
1844 DIE &VariableDie) {
1845 StringRef Name = Var.getName();
1846 if (!Name.empty())
1847 addString(VariableDie, dwarf::DW_AT_name, Name);
1848 const auto *DIVar = Var.getVariable();
1849 if (DIVar) {
1850 if (uint32_t AlignInBytes = DIVar->getAlignInBytes())
1851 addUInt(VariableDie, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
1852 AlignInBytes);
1853 addAnnotation(VariableDie, DIVar->getAnnotations());
1854 }
1855
1856 addSourceLine(VariableDie, DIVar);
1857 addType(VariableDie, Var.getType());
1858 if (Var.isArtificial())
1859 addFlag(VariableDie, dwarf::DW_AT_artificial);
1860}
1861
1863 DIE &LabelDie) {
1864 StringRef Name = Label.getName();
1865 if (!Name.empty())
1866 addString(LabelDie, dwarf::DW_AT_name, Name);
1867 const auto *DILabel = Label.getLabel();
1868 addSourceLine(LabelDie, DILabel);
1869 if (DILabel->isArtificial())
1870 addFlag(LabelDie, dwarf::DW_AT_artificial);
1872 addUInt(LabelDie, dwarf::DW_AT_LLVM_coro_suspend_idx, std::nullopt,
1874}
1875
1876/// Add a Dwarf expression attribute data and value.
1878 const MCExpr *Expr) {
1879 addAttribute(Die, (dwarf::Attribute)0, Form, DIEExpr(Expr));
1880}
1881
1883 const DISubprogram *SP, DIE &SPDie) {
1884 auto *SPDecl = SP->getDeclaration();
1885 auto *Context = SPDecl ? SPDecl->getScope() : SP->getScope();
1887 addGlobalName(SP->getName(), SPDie, Context);
1888}
1889
1890bool DwarfCompileUnit::isDwoUnit() const {
1891 return DD->useSplitDwarf() && Skeleton;
1892}
1893
1894void DwarfCompileUnit::finishNonUnitTypeDIE(DIE& D, const DICompositeType *CTy) {
1895 constructTypeDIE(D, CTy);
1896}
1897
1900 (DD->useSplitDwarf() && !Skeleton);
1901}
1902
1906
1908 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1909 MCSymbol *Label = DD->getAddressPool().getLabel();
1911 DD->getDwarfVersion() >= 5 ? dwarf::DW_AT_addr_base
1912 : dwarf::DW_AT_GNU_addr_base,
1913 Label, TLOF.getDwarfAddrSection()->getBeginSymbol());
1914}
1915
1917 addAttribute(Die, (dwarf::Attribute)0, dwarf::DW_FORM_udata,
1918 new (DIEValueAllocator) DIEBaseTypeRef(this, Idx));
1919}
1920
1922 // Insert the base_type DIEs directly after the CU so that their offsets will
1923 // fit in the fixed size ULEB128 used inside the location expressions.
1924 // Maintain order by iterating backwards and inserting to the front of CU
1925 // child list.
1926 for (auto &Btr : reverse(ExprRefedBaseTypes)) {
1927 DIE &Die = getUnitDie().addChildFront(
1928 DIE::get(DIEValueAllocator, dwarf::DW_TAG_base_type));
1929 SmallString<32> Str;
1930 addString(Die, dwarf::DW_AT_name,
1932 "_" + Twine(Btr.BitSize)).toStringRef(Str));
1933 addUInt(Die, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1, Btr.Encoding);
1934 // Round up to smallest number of bytes that contains this number of bits.
1935 // ExprRefedBaseTypes is populated with types referenced by
1936 // DW_OP_LLVM_convert operations in location expressions. These are often
1937 // byte-sized, but one common counter-example is 1-bit sized conversions
1938 // from `i1` types. TODO: Should these use DW_AT_bit_size? See
1939 // DwarfUnit::constructTypeDIE.
1940 addUInt(Die, dwarf::DW_AT_byte_size, std::nullopt,
1941 divideCeil(Btr.BitSize, 8));
1942 Btr.Die = &Die;
1943 }
1944}
1945
1947 // Assume if there is an abstract tree all the DIEs are already emitted.
1948 bool isAbstract = getAbstractScopeDIEs().count(LB->getSubprogram());
1949 if (isAbstract) {
1950 auto &DIEs = getAbstractScopeDIEs();
1951 if (auto It = DIEs.find(LB); It != DIEs.end())
1952 return It->second;
1953 }
1954 assert(!isAbstract && "Missed lexical block DIE in abstract tree!");
1955
1956 // Check if we have a concrete DIE.
1957 if (auto It = LexicalBlockDIEs.find(LB); It != LexicalBlockDIEs.end())
1958 return It->second;
1959
1960 // If nothing available found, we cannot just create a new lexical block,
1961 // because it isn't known where to put it into the DIE tree.
1962 // So, we may only try to find the most close avaiable parent DIE.
1964}
1965
1967 if (isa_and_nonnull<DILocalScope>(Context)) {
1968 if (auto *LFScope = dyn_cast<DILexicalBlockFile>(Context))
1969 Context = LFScope->getNonLexicalBlockFileScope();
1970 if (auto *LScope = dyn_cast<DILexicalBlock>(Context))
1971 return getLocalContextDIE(LScope);
1972
1973 // Otherwise the context must be a DISubprogram.
1974 auto *SPScope = cast<DISubprogram>(Context);
1975 const auto &DIEs = getAbstractScopeDIEs();
1976 if (auto It = DIEs.find(SPScope); It != DIEs.end())
1977 return It->second;
1978 }
1979 return DwarfUnit::getOrCreateContextDIE(Context);
1980}
1981
1983 const Function *F,
1984 bool Minimal) {
1985 if (!F && SP->isDefinition()) {
1986 F = DD->getLexicalScopes().getFunction(SP);
1987
1988 if (!F) {
1989 // SP may belong to another CU. Determine the CU similarly
1990 // to DwarfDebug::constructAbstractSubprogramScopeDIE.
1991 return &DD->getOrCreateAbstractSubprogramCU(SP, *this)
1992 .getOrCreateAbstractSubprogramDIE(SP);
1993 }
1994 }
1995
1996 return DwarfUnit::getOrCreateSubprogramDIE(SP, F, Minimal);
1997}
1998
2000 const DwarfDebug &DD, const DISubprogram &CalleeSP, DIE &CalleeDIE) {
2002 !CalleeSP.isDefinition() &&
2003 !CalleeDIE.findAttribute(dwarf::DW_AT_linkage_name)) {
2004 addLinkageName(CalleeDIE, CalleeSP.getLinkageName());
2005 }
2006}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
BitTracker BT
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
dxil translate DXIL Translate Metadata
static SmallVector< DbgVariable *, 8 > sortLocalVars(SmallVectorImpl< DbgVariable * > &Input)
Sort local variables so that variables appearing inside of helper expressions come first.
static const DIType * resolveTypeQualifiers(const DIType *Ty)
static SmallVector< const DIVariable *, 2 > dependencies(DbgVariable *Var)
Return all DIVariables that appear in count: expressions.
static cl::opt< bool > EmitFuncLineTableOffsetsOption("emit-func-debug-line-table-offsets", cl::Hidden, cl::desc("Include line table offset in function's debug info and emit end " "sequence after each function's line data."), cl::init(false))
static bool AddLinkageNamesToDeclCallOriginsForTuning(const DwarfDebug *DD)
static dwarf::Tag GetCompileUnitType(UnitKind Kind, DwarfDebug *DW)
static cl::opt< cl::boolOrDefault > AddLinkageNamesToDeclCallOrigins("add-linkage-names-to-declaration-call-origins", cl::Hidden, cl::desc("Add DW_AT_linkage_name to function declaration DIEs " "referenced by DW_AT_call_origin attributes. Enabled by default " "for -gsce debugger tuning."))
Query value using AddLinkageNamesToDeclCallOriginsForTuning.
This file contains constants used for implementing Dwarf debug support.
static bool lookup(const GsymReader &GR, GsymDataExtractor &Data, uint64_t &Offset, uint64_t BaseAddr, uint64_t Addr, SourceLocations &SrcLocs, llvm::Error &Err)
A Lookup helper functions.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define T
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallString class.
The Input class is used to parse a yaml document into in-memory structs and vectors.
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
This class is intended to be used as a driving class for all asm writers.
Definition AsmPrinter.h:91
MachineFunction * MF
The current machine function.
Definition AsmPrinter.h:109
const DataLayout & getDataLayout() const
Return information about data layout.
MCSymbol * GetExternalSymbolSymbol(const Twine &Sym) const
Return the MCSymbol for the specified ExternalSymbol.
Functions, function parameters, and return types can have attributes to indicate how they should be t...
Definition Attributes.h:106
Debug common block.
DIFile * getFile() const
unsigned getLineNo() const
StringRef getName() const
DIScope * getScope() const
DIGlobalVariable * getDecl() const
static LLVM_ABI std::optional< DebugEmissionKind > getEmissionKind(StringRef Str)
A BaseTypeRef DIE.
Definition DIE.h:356
A BaseTypeRef DIE.
Definition DIE.h:237
DIEBlock - Represents a block of values.
Definition DIE.h:1057
DwarfExpression implementation for singular DW_AT_location.
An expression DIE.
Definition DIE.h:207
An integer value DIE.
Definition DIE.h:169
A label DIE.
Definition DIE.h:222
Represents a pointer to a location list in the debug_loc section.
Definition DIE.h:337
DIELoc - Represents an expression location.
Definition DIE.h:1021
DIE & getUnitDie()
Definition DIE.h:1010
A list of DIE values.
Definition DIE.h:705
value_iterator addValue(BumpPtrAllocator &Alloc, const DIEValue &V)
Definition DIE.h:756
A structured debug information entry.
Definition DIE.h:835
LLVM_ABI DIEValue findAttribute(dwarf::Attribute Attribute) const
Find a value in the DIE with the attribute given.
Definition DIE.cpp:202
DIE & addChild(DIE *Child)
Add a child to the DIE.
Definition DIE.h:945
DIE & addChildFront(DIE *Child)
Definition DIE.h:952
static DIE * get(BumpPtrAllocator &Alloc, dwarf::Tag Tag)
Definition DIE.h:862
LLVM_ABI const DIE * getUnitDie() const
Climb up the parent chain to get the unit DIE that this DIE belongs to.
Definition DIE.cpp:197
Holds a DIExpression and keeps track of how many operands have been consumed so far.
DWARF expression.
element_iterator elements_end() const
LLVM_ABI bool isEntryValue() const
Check if the expression consists of exactly one entry value operand.
iterator_range< expr_op_iterator > expr_ops() const
unsigned getNumElements() const
static LLVM_ABI void appendOffset(SmallVectorImpl< uint64_t > &Ops, int64_t Offset)
Append Ops with operations to apply the Offset.
element_iterator elements_begin() const
ArrayRef< uint64_t > getElements() const
uint64_t getElement(unsigned I) const
LLVM_ABI std::optional< SignedOrUnsignedConstant > isConstant() const
Determine whether this represents a constant value, if so.
DIDerivedType * getStaticDataMemberDeclaration() const
MDTuple * getTemplateParams() const
StringRef getLinkageName() const
StringRef getDisplayName() const
DINodeArray getAnnotations() const
An imported module (C++ using directive or similar).
bool isArtificial() const
std::optional< unsigned > getCoroSuspendIdx() const
DILocalScope * getScope() const
Debug lexical block.
A scope for locals.
LLVM_ABI DISubprogram * getSubprogram() const
Get the subprogram for this scope.
LLVM_ABI DILocalScope * getNonLexicalBlockFileScope() const
Get the first non DILexicalBlockFile scope of this scope.
Tagged DWARF-like metadata node.
LLVM_ABI dwarf::Tag getTag() const
Base class for scope-like contexts.
Subprogram description. Uses SubclassData1.
Base class for types.
uint32_t getAlignInBytes() const
DIScope * getScope() const
DIType * getType() const
StringRef getName() const
LLVM_ABI unsigned getPointerSize(unsigned AS=0) const
The pointer representation size in bytes, rounded up to a whole number of bytes.
This class is defined as the common parent of DbgVariable and DbgLabel such that it could levarage po...
Definition DwarfDebug.h:66
const DINode * getEntity() const
Accessors.
Definition DwarfDebug.h:86
void setDIE(DIE &D)
Definition DwarfDebug.h:92
DIE * getDIE() const
Definition DwarfDebug.h:88
This class is used to track label information.
Definition DwarfDebug.h:290
ArrayRef< DbgValueLocEntry > getLocEntries() const
bool isVariadic() const
This class is used to track local variable information.
Definition DwarfDebug.h:215
bool isArtificial() const
Return true if DbgVariable is artificial.
Definition DwarfDebug.h:263
dwarf::Tag getTag() const
Definition DwarfDebug.h:254
bool isObjectPointer() const
Definition DwarfDebug.h:271
const DILocalVariable * getVariable() const
Definition DwarfDebug.h:247
StringRef getName() const
Definition DwarfDebug.h:251
const DIType * getType() const
Loc::Variant & asVariant()
To workaround P2162R0 https://github.com/cplusplus/papers/issues/873 the base class subobject needs t...
Definition DwarfDebug.h:221
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:809
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:843
bool useGNUAnalogForDwarf5Feature() const
Whether to use the GNU analog for a DWARF5 tag, attribute, or location atom.
void constructCallSiteParmEntryDIEs(DIE &CallSiteDIE, SmallVector< DbgCallSiteParam, 4 > &Params)
Construct call site parameter DIEs for the CallSiteDIE.
void addLinkageNamesToDeclarations(const DwarfDebug &DD, const DISubprogram &CalleeSP, DIE &CalleeDIE)
void attachLowHighPC(DIE &D, const MCSymbol *Begin, const MCSymbol *End)
void emitHeader(bool UseOffsets) override
Emit the header for this unit, not including the initial length field.
dwarf::Tag getDwarf5OrGNUTag(dwarf::Tag Tag) const
This takes a DWARF 5 tag and returns it or a GNU analog.
void constructAbstractSubprogramScopeDIE(LexicalScope *Scope)
bool includeMinimalInlineScopes() const
DIE * getOrCreateImportedEntityDIE(const DIImportedEntity *IE)
Get or create a DIE for an imported entity.
void addBaseTypeRef(DIEValueList &Die, int64_t Idx)
void addGlobalNameForTypeUnit(StringRef Name, const DIScope *Context)
Add a new global name present in a type unit to this compile unit.
void finishEntityDefinition(const DbgEntity *Entity)
void addMemoryLocation(DIE &Die, dwarf::Attribute Attribute, const MachineLocation &Location, int64_t Offset)
Add a memory location exprloc to DIE with attribute Attribute at Location + Offset.
void addRange(RangeSpan Range)
addRange - Add an address range to the list of ranges for this unit.
void addAddrTableBase()
Add the DW_AT_addr_base attribute to the unit DIE.
std::vector< BaseTypeRef > ExprRefedBaseTypes
DIE * constructInlinedScopeDIE(LexicalScope *Scope, DIE &ParentScopeDIE)
This scope represents an inlined body of a function.
void addScopeRangeList(DIE &ScopeDIE, SmallVector< RangeSpan, 2 > Range)
A helper function to construct a RangeSpanList for a given lexical scope.
uint64_t getDWOId() const
DIE * getOrCreateCommonBlock(const DICommonBlock *CB, ArrayRef< GlobalExpr > GlobalExprs)
void addVariableAddress(const DbgVariable &DV, DIE &Die, MachineLocation Location)
Add DW_AT_location attribute for a DbgVariable based on provided MachineLocation.
DIE & constructCallSiteEntryDIE(DIE &ScopeDIE, const DISubprogram *CalleeSP, const Function *CalleeF, bool IsTail, const MCSymbol *PCAddr, const MCSymbol *CallAddr, MachineLocation CallTarget, int64_t Offset, DIType *AllocSiteTy)
Construct a call site entry DIE describing a call within Scope to a callee described by CalleeSP and ...
DIE & getOrCreateAbstractSubprogramDIE(const DISubprogram *SP)
Create an abstract subprogram DIE, that should later be populated by constructAbstractSubprogramScope...
DIE & constructSubprogramScopeDIE(const DISubprogram *Sub, const Function &F, LexicalScope *Scope, MCSymbol *LineTableSym)
Construct a DIE for this subprogram scope.
void addGlobalName(StringRef Name, const DIE &Die, const DIScope *Context) override
Add a new global name to the compile unit.
DIE & updateSubprogramScopeDIE(const DISubprogram *SP, const Function &F, MCSymbol *LineTableSym)
Find DIE for the given subprogram and attach appropriate DW_AT_low_pc, DW_AT_high_pc and DW_AT_LLVM_s...
void createAbstractEntity(const DINode *Node, LexicalScope *Scope)
void applyStmtList(DIE &D)
Apply the DW_AT_stmt_list from this compile unit to the specified DIE.
DIE * getOrCreateSubprogramDIE(const DISubprogram *SP, const Function *F, bool Minimal=false) override
DIE * getOrCreateContextDIE(const DIScope *Ty) override
Construct a DIE for a given scope.
void applyCommonDbgVariableAttributes(const DbgVariable &Var, DIE &VariableDie)
Add attributes to Var which reflect the common attributes of VariableDie, namely those which are not ...
DIE * constructVariableDIE(DbgVariable &DV, bool Abstract=false)
Construct a DIE for the given DbgVariable.
dwarf::LocationAtom getDwarf5OrGNULocationAtom(dwarf::LocationAtom Loc) const
This takes a DWARF 5 location atom and either returns it or a GNU analog.
DIE * getLocalContextDIE(const DILexicalBlock *LB)
Get DW_TAG_lexical_block for the given DILexicalBlock if available, or the most close parent DIE,...
DIE * getOrCreateGlobalVariableDIE(const DIGlobalVariable *GV, ArrayRef< GlobalExpr > GlobalExprs)
Get or create global variable DIE.
void addLocationAttribute(DIE *ToDIE, const DIGlobalVariable *GV, ArrayRef< GlobalExpr > GlobalExprs)
void applySubprogramAttributesToDefinition(const DISubprogram *SP, DIE &SPDie)
DIE * createAndAddScopeChildren(LexicalScope *Scope, DIE &ScopeDIE)
void addExpr(DIELoc &Die, dwarf::Form Form, const MCExpr *Expr)
Add a Dwarf expression attribute data and value.
DIE * getOrCreateLexicalBlockDIE(LexicalScope *Scope, DIE &ParentDIE)
Get if available or create a new DW_TAG_lexical_block for the given LexicalScope and attach DW_AT_low...
dwarf::Attribute getDwarf5OrGNUAttr(dwarf::Attribute Attr) const
This takes a DWARF 5 attribute and returns it or a GNU analog.
void addAddress(DIE &Die, dwarf::Attribute Attribute, const MachineLocation &Location)
Add an address attribute to a die based on the location provided.
void applyLabelAttributes(const DbgLabel &Label, DIE &LabelDie)
void addLocalLabelAddress(DIE &Die, dwarf::Attribute Attribute, const MCSymbol *Label)
addLocalLabelAddress - Add a dwarf label attribute data and value using DW_FORM_addr only.
void addGlobalTypeImpl(const DIType *Ty, const DIE &Die, const DIScope *Context) override
Add a new global type to the compile unit.
unsigned getOrCreateSourceID(const DIFile *File) override
Look up the source ID for the given file.
void constructScopeDIE(LexicalScope *Scope, DIE &ParentScopeDIE)
DwarfCompileUnit(unsigned UID, const DICompileUnit *Node, AsmPrinter *A, DwarfDebug *DW, DwarfFile *DWU, UnitKind Kind=UnitKind::Full)
DIE * constructLabelDIE(DbgLabel &DL, const LexicalScope &Scope)
Construct a DIE for the given DbgLabel.
void addGlobalTypeUnitType(const DIType *Ty, const DIScope *Context)
Add a new global type present in a type unit to this compile unit.
DbgEntity * getExistingAbstractEntity(const DINode *Node)
void addLabelAddress(DIE &Die, dwarf::Attribute Attribute, const MCSymbol *Label)
addLabelAddress - Add a dwarf label attribute data and value using either DW_FORM_addr or DW_FORM_GNU...
void addLocationList(DIE &Die, dwarf::Attribute Attribute, unsigned Index)
Add a Dwarf loclistptr attribute data and value.
void addComplexAddress(const DIExpression *DIExpr, DIE &Die, dwarf::Attribute Attribute, const MachineLocation &Location)
Start with the address based on the location provided, and generate the DWARF information necessary t...
DIE * constructImportedEntityDIE(const DIImportedEntity *IE)
DwarfCompileUnit & getCU() override
void attachRangesOrLowHighPC(DIE &D, SmallVector< RangeSpan, 2 > Ranges)
void finishSubprogramDefinition(const DISubprogram *SP)
Collects and handles dwarf debug information.
Definition DwarfDebug.h:352
uint16_t getDwarfVersion() const
Returns the Dwarf Version.
DwarfCompileUnit * lookupCU(const DIE *Die)
Find the matching DwarfCompileUnit for the given CU DIE.
Definition DwarfDebug.h:952
static void emitDebugLocValue(const AsmPrinter &AP, const DIBasicType *BT, const DbgValueLoc &Value, DwarfExpression &DwarfExpr)
bool useSplitDwarf() const
Returns whether or not to change the current debug info for split DWARF.
Definition DwarfDebug.h:872
void addAccelName(const DwarfUnit &Unit, const DICompileUnit::DebugNameTableKind NameTableKind, StringRef Name, const DIE &Die)
void setLocation(const MachineLocation &Loc, const DIExpression *DIExpr)
Set the location (Loc) and DIExpression (DIExpr) to describe.
void addFragmentOffset(const DIExpression *Expr)
If applicable, emit an empty DW_OP_piece / DW_OP_bit_piece to advance to the fragment described by Ex...
bool addExpression(DIExpressionCursor &&Expr)
Emit all remaining operations in the DIExpressionCursor.
std::optional< uint8_t > TagOffset
void setCallSiteParamValueFlag()
Lock this down to become a call site parameter location.
bool addMachineRegExpression(const TargetRegisterInfo &TRI, DIExpressionCursor &Expr, llvm::Register MachineReg, unsigned FragmentOffsetInBits=0)
Emit a machine register location.
void addWasmLocation(unsigned Index, uint64_t Offset)
Emit location information expressed via WebAssembly location + offset The Index is an identifier for ...
void beginEntryValueExpression(DIExpressionCursor &ExprCursor)
Begin emission of an entry value dwarf operation.
virtual DIE * getOrCreateTypeDIE(const MDNode *TyNode)
Find existing DIE or create new DIE for the given type.
DwarfDebug & getDwarfDebug() const
Definition DwarfUnit.h:114
void addAnnotation(DIE &Buffer, DINodeArray Annotations)
Add DW_TAG_LLVM_annotation.
void addBlock(DIE &Die, dwarf::Attribute Attribute, DIELoc *Loc)
Add block data.
void addTemplateParams(DIE &Buffer, DINodeArray TParams)
Add template parameters in buffer.
virtual DIE * getOrCreateContextDIE(const DIScope *Context)
Get context owner's DIE.
void addAttribute(DIEValueList &Die, dwarf::Attribute Attribute, dwarf::Form Form, T &&Value)
Definition DwarfUnit.h:86
void addOpAddress(DIELoc &Die, const MCSymbol *Sym)
Add a dwarf op address data and value using the form given and an op of either DW_FORM_addr or DW_FOR...
void addUInt(DIEValueList &Die, dwarf::Attribute Attribute, std::optional< dwarf::Form > Form, uint64_t Integer)
Add an unsigned integer attribute data and value.
void addString(DIE &Die, dwarf::Attribute Attribute, StringRef Str)
Add a string attribute data and value.
void addConstantValue(DIE &Die, const ConstantInt *CI, const DIType *Ty)
Add constant value entry in variable DIE.
DIE * getOrCreateNameSpace(const DINamespace *NS)
void insertDIE(const DINode *Desc, DIE *D)
Insert DIE into the map.
bool shouldPlaceInUnitDIE(const DISubprogram *SP, bool Minimal)
Definition DwarfUnit.h:350
DwarfDebug * DD
Definition DwarfUnit.h:56
const DICompileUnit * CUNode
MDNode for the compile unit.
Definition DwarfUnit.h:41
virtual DIE * getOrCreateSubprogramDIE(const DISubprogram *SP, const Function *FnHint, bool Minimal=false)
DIE * getOrCreateSubprogramContextDIE(const DISubprogram *SP, bool IgnoreScope)
Definition DwarfUnit.h:355
DIE * getDIE(const DINode *D) const
Returns the DIE map slot for the specified debug variable.
MCSymbol * LabelBegin
The start of the unit within its section.
Definition DwarfUnit.h:50
void addSInt(DIEValueList &Die, dwarf::Attribute Attribute, std::optional< dwarf::Form > Form, int64_t Integer)
Add an signed integer attribute data and value.
DwarfUnit(dwarf::Tag, const DICompileUnit *Node, AsmPrinter *A, DwarfDebug *DW, DwarfFile *DWU, unsigned UniqueID=0)
Definition DwarfUnit.cpp:86
void addLabelDelta(DIEValueList &Die, dwarf::Attribute Attribute, const MCSymbol *Hi, const MCSymbol *Lo)
Add a label delta attribute data and value.
void addLinkageName(DIE &Die, StringRef LinkageName)
Add a linkage name, if it isn't empty.
std::string getParentContextString(const DIScope *Context) const
Get string containing language specific context for a global name.
void addSourceLine(DIE &Die, unsigned Line, unsigned Column, const DIFile *File)
Add location information to specified debug information entry.
void emitCommonHeader(bool UseOffsets, dwarf::UnitType UT)
Emit the common part of the header for this unit.
BumpPtrAllocator DIEValueAllocator
Definition DwarfUnit.h:44
DIE * getOrCreateModule(const DIModule *M)
const DICompileUnit * getCUNode() const
Definition DwarfUnit.h:113
DIE & createAndAddDIE(dwarf::Tag Tag, DIE &Parent, const DINode *N=nullptr)
Create a DIE with the given Tag, add the DIE to its parent, and call insertDIE if MD is not null.
DwarfFile * DU
Definition DwarfUnit.h:57
DIE * getOrCreateStaticMemberDIE(const DIDerivedType *DT)
Create new static data member DIE.
void addLabel(DIEValueList &Die, dwarf::Attribute Attribute, dwarf::Form Form, const MCSymbol *Label)
Add a Dwarf label attribute data and value.
void addConstantFPValue(DIE &Die, const ConstantFP *CFP)
Add constant value entry in variable DIE.
void addSectionLabel(DIE &Die, dwarf::Attribute Attribute, const MCSymbol *Label, const MCSymbol *Sec)
Add a Dwarf section label attribute data and value.
void addPoolOpAddress(DIEValueList &Die, const MCSymbol *Label)
void constructTypeDIE(DIE &Buffer, const DICompositeType *CTy)
MCSymbol * EndLabel
Emitted at the end of the CU and used to compute the CU Length field.
Definition DwarfUnit.h:53
void addFlag(DIE &Die, dwarf::Attribute Attribute)
Add a flag that is true to the DIE.
AsmPrinter * Asm
Target of Dwarf emission.
Definition DwarfUnit.h:47
unsigned getUniqueID() const
Gets Unique ID for this unit.
Definition DwarfUnit.h:103
void addType(DIE &Entity, const DIType *Ty, dwarf::Attribute Attribute=dwarf::DW_AT_type)
Add a new type attribute to the specified entity.
void applySubprogramAttributes(const DISubprogram *SP, DIE &SPDie, bool SkipSPAttributes=false)
void addDIEEntry(DIE &Die, dwarf::Attribute Attribute, DIE &Entry)
Add a DIE attribute data and value.
This class is used to track scope information.
Multi-value location description.
Definition DwarfDebug.h:143
unsigned getDebugLocListIndex() const
Definition DwarfDebug.h:154
std::optional< uint8_t > getDebugLocListTagOffset() const
Definition DwarfDebug.h:155
Single value location description.
Definition DwarfDebug.h:132
Base class for the full range of assembler expressions which are needed for parsing.
Definition MCExpr.h:34
MCSection * getDwarfRangesSection() const
MCSection * getDwarfAddrSection() const
MCSection * getDwarfLineSection() const
MCSymbol * getBeginSymbol()
Definition MCSection.h:653
void setType(wasm::WasmSymbolType type)
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition MCSymbol.h:42
bool isDefined() const
isDefined - Check if this symbol is defined (i.e., it has an address).
Definition MCSymbol.h:233
Tuple of metadata.
Definition Metadata.h:1496
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
unsigned getReg() const
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
StringRef getName() const
Get a short "name" for the module.
Definition Module.h:316
Wrapper class representing virtual and physical registers.
Definition Register.h:20
static constexpr bool isPhysicalRegister(unsigned Reg)
Return true if the specified register number is in the physical register namespace.
Definition Register.h:60
Implements a dense probed hash-table based set with some number of buckets stored inline.
Definition DenseSet.h:293
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
Information about stack frame layout on the target.
virtual DwarfFrameBase getDwarfFrameBase(const MachineFunction &MF) const
Return the frame base information to be encoded in the DWARF subprogram debug info.
virtual StackOffset getFrameIndexReference(const MachineFunction &MF, int FI, Register &FrameReg) const
getFrameIndexReference - This method should return the base register and offset used to reference a f...
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
StringRef toStringRef(SmallVectorImpl< char > &Out) const
This returns the twine as a single StringRef if it can be represented as such.
Definition Twine.h:461
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:209
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition DenseSet.h:187
A DeclContext is a named program scope that is used for ODR uniquing of types.
bool tuneForSCE() const
Definition DwarfDebug.h:967
LLVM_ABI StringRef AttributeEncodingString(unsigned Encoding)
Definition Dwarf.cpp:264
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ Entry
Definition COFF.h:862
initializer< Ty > init(const Ty &Val)
@ DW_INL_inlined
Definition Dwarf.h:875
Attribute
Attributes.
Definition Dwarf.h:125
UnitType
Constants for unit types in DWARF v5.
Definition Dwarf.h:994
@ DW_OP_LLVM_implicit_pointer
Only used in LLVM metadata.
Definition Dwarf.h:148
@ WASM_TYPE_I64
Definition Wasm.h:57
@ WASM_TYPE_I32
Definition Wasm.h:56
@ WASM_SYMBOL_TYPE_GLOBAL
Definition Wasm.h:233
This is an optimization pass for GlobalISel generic memory operations.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
Definition Casting.h:732
LLVM_ABI bool isRangeRelaxable(const MCSymbol *Begin, const MCSymbol *End)
Definition MCSymbol.cpp:94
bool isa_and_nonnull(const Y &Val)
Definition Casting.h:676
std::pair< const MachineInstr *, const MachineInstr * > InsnRange
This is used to track range of instructions with identical lexical scope.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
@ Apple
.apple_names, .apple_namespaces, .apple_types, .apple_objc.
Definition DwarfDebug.h:347
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
@ Global
Append to llvm.global_dtors.
constexpr T divideCeil(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
Definition MathExtras.h:389
@ Sub
Subtraction of integers.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition STLExtras.h:2028
DWARFExpression::Operation Op
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI DISubprogram * getDISubprogram(const MDNode *Scope)
Find subprogram that is enclosing this scope.
Single location defined by (potentially multiple) EntryValueInfo.
Definition DwarfDebug.h:173
std::set< EntryValueInfo > EntryValues
Definition DwarfDebug.h:174
Single location defined by (potentially multiple) MMI entries.
Definition DwarfDebug.h:160
const std::set< FrameIndexExpr > & getFrameIndexExprs() const
Get the FI entries, sorted by fragment offset.
const MCSymbol * End
Definition DwarfFile.h:41
const MCSymbol * Begin
Definition DwarfFile.h:40
Helper used to pair up a symbol and its DWARF compile unit.
Definition DwarfDebug.h:336
union llvm::TargetFrameLowering::DwarfFrameBase::@004076321055032247336074224075335064105264310375 Location
enum llvm::TargetFrameLowering::DwarfFrameBase::FrameBaseKind Kind