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