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