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