1//===-- llvm/CodeGen/DwarfUnit.cpp - Dwarf Type and 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 "DwarfUnit.h"
14#include "AddressPool.h"
15#include "DwarfCompileUnit.h"
16#include "DwarfExpression.h"
17#include "llvm/ADT/APFloat.h"
18#include "llvm/ADT/APInt.h"
19#include "llvm/CodeGen/TargetRegisterInfo.h"
20#include "llvm/IR/Constants.h"
21#include "llvm/IR/DataLayout.h"
22#include "llvm/IR/GlobalValue.h"
23#include "llvm/IR/Metadata.h"
24#include "llvm/MC/MCAsmInfo.h"
25#include "llvm/MC/MCContext.h"
26#include "llvm/MC/MCDwarf.h"
27#include "llvm/MC/MCSection.h"
28#include "llvm/MC/MCStreamer.h"
29#include "llvm/Support/Casting.h"
30#include "llvm/Target/TargetLoweringObjectFile.h"
31#include <cassert>
32#include <cstdint>
33#include <limits>
34#include <string>
35
36using namespace llvm;
37
38#define DEBUG_TYPE "dwarfdebug"
39
40DIEDwarfExpression::DIEDwarfExpression(const AsmPrinter &AP,
41 DwarfCompileUnit &CU, DIELoc &DIE)
42 : DwarfExpression(AP.getDwarfVersion(), CU), AP(AP), OutDIE(DIE) {}
43
44void DIEDwarfExpression::emitOp(uint8_t Op, const char* Comment) {
45 CU.addUInt(Block&: getActiveDIE(), Form: dwarf::DW_FORM_data1, Integer: Op);
46}
47
48void DIEDwarfExpression::emitSigned(int64_t Value) {
49 CU.addSInt(Die&: getActiveDIE(), Form: dwarf::DW_FORM_sdata, Integer: Value);
50}
51
52void DIEDwarfExpression::emitUnsigned(uint64_t Value) {
53 CU.addUInt(Block&: getActiveDIE(), Form: dwarf::DW_FORM_udata, Integer: Value);
54}
55
56void DIEDwarfExpression::emitData1(uint8_t Value) {
57 CU.addUInt(Block&: getActiveDIE(), Form: dwarf::DW_FORM_data1, Integer: Value);
58}
59
60void DIEDwarfExpression::emitBaseTypeRef(uint64_t Idx) {
61 CU.addBaseTypeRef(Die&: getActiveDIE(), Idx);
62}
63
64void DIEDwarfExpression::enableTemporaryBuffer() {
65 assert(!IsBuffering && "Already buffering?");
66 IsBuffering = true;
67}
68
69void DIEDwarfExpression::disableTemporaryBuffer() { IsBuffering = false; }
70
71unsigned DIEDwarfExpression::getTemporaryBufferSize() {
72 return TmpDIE.computeSize(FormParams: AP.getDwarfFormParams());
73}
74
75void DIEDwarfExpression::commitTemporaryBuffer() { OutDIE.takeValues(Other&: TmpDIE); }
76
77bool DIEDwarfExpression::isFrameRegister(const TargetRegisterInfo &TRI,
78 llvm::Register MachineReg) {
79 return MachineReg == TRI.getFrameRegister(MF: *AP.MF);
80}
81
82DwarfUnit::DwarfUnit(dwarf::Tag UnitTag, const DICompileUnit *Node,
83 AsmPrinter *A, DwarfDebug *DW, DwarfFile *DWU,
84 unsigned UniqueID)
85 : DIEUnit(UnitTag), UniqueID(UniqueID), CUNode(Node), Asm(A), DD(DW),
86 DU(DWU) {}
87
88DwarfTypeUnit::DwarfTypeUnit(DwarfCompileUnit &CU, AsmPrinter *A,
89 DwarfDebug *DW, DwarfFile *DWU, unsigned UniqueID,
90 MCDwarfDwoLineTable *SplitLineTable)
91 : DwarfUnit(dwarf::DW_TAG_type_unit, CU.getCUNode(), A, DW, DWU, UniqueID),
92 CU(CU), SplitLineTable(SplitLineTable) {}
93
94DwarfUnit::~DwarfUnit() {
95 for (DIEBlock *B : DIEBlocks)
96 B->~DIEBlock();
97 for (DIELoc *L : DIELocs)
98 L->~DIELoc();
99}
100
101int64_t DwarfUnit::getDefaultLowerBound() const {
102 switch (getSourceLanguage()) {
103 default:
104 break;
105
106 // The languages below have valid values in all DWARF versions.
107 case dwarf::DW_LANG_C:
108 case dwarf::DW_LANG_C89:
109 case dwarf::DW_LANG_C_plus_plus:
110 return 0;
111
112 case dwarf::DW_LANG_Fortran77:
113 case dwarf::DW_LANG_Fortran90:
114 return 1;
115
116 // The languages below have valid values only if the DWARF version >= 3.
117 case dwarf::DW_LANG_C99:
118 case dwarf::DW_LANG_ObjC:
119 case dwarf::DW_LANG_ObjC_plus_plus:
120 if (DD->getDwarfVersion() >= 3)
121 return 0;
122 break;
123
124 case dwarf::DW_LANG_Fortran95:
125 if (DD->getDwarfVersion() >= 3)
126 return 1;
127 break;
128
129 // Starting with DWARF v4, all defined languages have valid values.
130 case dwarf::DW_LANG_D:
131 case dwarf::DW_LANG_Java:
132 case dwarf::DW_LANG_Python:
133 case dwarf::DW_LANG_UPC:
134 if (DD->getDwarfVersion() >= 4)
135 return 0;
136 break;
137
138 case dwarf::DW_LANG_Ada83:
139 case dwarf::DW_LANG_Ada95:
140 case dwarf::DW_LANG_Cobol74:
141 case dwarf::DW_LANG_Cobol85:
142 case dwarf::DW_LANG_Modula2:
143 case dwarf::DW_LANG_Pascal83:
144 case dwarf::DW_LANG_PLI:
145 if (DD->getDwarfVersion() >= 4)
146 return 1;
147 break;
148
149 // The languages below are new in DWARF v5.
150 case dwarf::DW_LANG_BLISS:
151 case dwarf::DW_LANG_C11:
152 case dwarf::DW_LANG_C_plus_plus_03:
153 case dwarf::DW_LANG_C_plus_plus_11:
154 case dwarf::DW_LANG_C_plus_plus_14:
155 case dwarf::DW_LANG_Dylan:
156 case dwarf::DW_LANG_Go:
157 case dwarf::DW_LANG_Haskell:
158 case dwarf::DW_LANG_OCaml:
159 case dwarf::DW_LANG_OpenCL:
160 case dwarf::DW_LANG_RenderScript:
161 case dwarf::DW_LANG_Rust:
162 case dwarf::DW_LANG_Swift:
163 if (DD->getDwarfVersion() >= 5)
164 return 0;
165 break;
166
167 case dwarf::DW_LANG_Fortran03:
168 case dwarf::DW_LANG_Fortran08:
169 case dwarf::DW_LANG_Julia:
170 case dwarf::DW_LANG_Modula3:
171 if (DD->getDwarfVersion() >= 5)
172 return 1;
173 break;
174 }
175
176 return -1;
177}
178
179/// Check whether the DIE for this MDNode can be shared across CUs.
180bool DwarfUnit::isShareableAcrossCUs(const DINode *D) const {
181 // When the MDNode can be part of the type system, the DIE can be shared
182 // across CUs.
183 // Combining type units and cross-CU DIE sharing is lower value (since
184 // cross-CU DIE sharing is used in LTO and removes type redundancy at that
185 // level already) but may be implementable for some value in projects
186 // building multiple independent libraries with LTO and then linking those
187 // together.
188
189 // Prevent generation of cross-CU references for DWARF v2 due to conflicts
190 // resulting from the FAQ recommendation: "If you are producing DWARF V2,
191 // please use the DWARF V3 definition of DW_FORM_ref_addr."
192 // (https://dwarfstd.org/faq.html)
193 if (DD->getDwarfVersion() == 2)
194 return false;
195 if (isDwoUnit() && !DD->shareAcrossDWOCUs())
196 return false;
197 return (isa<DIType>(Val: D) ||
198 (isa<DISubprogram>(Val: D) && !cast<DISubprogram>(Val: D)->isDefinition())) &&
199 !DD->generateTypeUnits();
200}
201
202DIE *DwarfUnit::getDIE(const DINode *D) const {
203 if (isShareableAcrossCUs(D))
204 return DU->getDIE(TypeMD: D);
205 return MDNodeToDieMap.lookup(Val: D);
206}
207
208void DwarfUnit::insertDIE(const DINode *Desc, DIE *D) {
209 if (isShareableAcrossCUs(D: Desc)) {
210 DU->insertDIE(TypeMD: Desc, Die: D);
211 return;
212 }
213 MDNodeToDieMap.insert(KV: std::make_pair(x&: Desc, y&: D));
214}
215
216void DwarfUnit::insertDIE(DIE *D) {
217 MDNodeToDieMap.insert(KV: std::make_pair(x: nullptr, y&: D));
218}
219
220void DwarfUnit::addFlag(DIE &Die, dwarf::Attribute Attribute) {
221 if (DD->getDwarfVersion() >= 4)
222 addAttribute(Die, Attribute, Form: dwarf::DW_FORM_flag_present, Value: DIEInteger(1));
223 else
224 addAttribute(Die, Attribute, Form: dwarf::DW_FORM_flag, Value: DIEInteger(1));
225}
226
227void DwarfUnit::addUInt(DIEValueList &Die, dwarf::Attribute Attribute,
228 std::optional<dwarf::Form> Form, uint64_t Integer) {
229 if (!Form)
230 Form = DIEInteger::BestForm(IsSigned: false, Int: Integer);
231 assert(Form != dwarf::DW_FORM_implicit_const &&
232 "DW_FORM_implicit_const is used only for signed integers");
233 addAttribute(Die, Attribute, Form: *Form, Value: DIEInteger(Integer));
234}
235
236void DwarfUnit::addUInt(DIEValueList &Block, dwarf::Form Form,
237 uint64_t Integer) {
238 addUInt(Die&: Block, Attribute: (dwarf::Attribute)0, Form, Integer);
239}
240
241void DwarfUnit::addIntToBlock(DIEBlock &Block, const APInt &Val) {
242 // Get the raw data form of the large APInt.
243 const uint64_t *Ptr64 = Val.getRawData();
244
245 int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
246 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
247
248 // Output the constant to DWARF one byte at a time.
249 for (int i = 0; i < NumBytes; i++) {
250 uint8_t c;
251 if (LittleEndian)
252 c = Ptr64[i / 8] >> (8 * (i & 7));
253 else
254 c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
255 addUInt(Block, Form: dwarf::DW_FORM_data1, Integer: c);
256 }
257}
258
259void DwarfUnit::addIntAsBlock(DIE &Die, dwarf::Attribute Attribute,
260 const APInt &Val) {
261 DIEBlock *Block = new (DIEValueAllocator) DIEBlock;
262 addIntToBlock(Block&: *Block, Val);
263 Block->computeSize(FormParams: Asm->getDwarfFormParams());
264 addBlock(Die, Attribute, Form: Block->BestForm(), Block);
265}
266
267void DwarfUnit::addInt(DIE &Die, dwarf::Attribute Attribute,
268 const APInt &Val, bool Unsigned) {
269 unsigned CIBitWidth = Val.getBitWidth();
270 if (CIBitWidth <= 64) {
271 if (Unsigned)
272 addUInt(Die, Attribute, Form: std::nullopt, Integer: Val.getZExtValue());
273 else
274 addSInt(Die, Attribute, Form: std::nullopt, Integer: Val.getSExtValue());
275 return;
276 }
277
278 addIntAsBlock(Die, Attribute, Val);
279}
280
281void DwarfUnit::addSInt(DIEValueList &Die, dwarf::Attribute Attribute,
282 std::optional<dwarf::Form> Form, int64_t Integer) {
283 if (!Form)
284 Form = DIEInteger::BestForm(IsSigned: true, Int: Integer);
285 addAttribute(Die, Attribute, Form: *Form, Value: DIEInteger(Integer));
286}
287
288void DwarfUnit::addSInt(DIEValueList &Die, std::optional<dwarf::Form> Form,
289 int64_t Integer) {
290 addSInt(Die, Attribute: (dwarf::Attribute)0, Form, Integer);
291}
292
293void DwarfUnit::addString(DIE &Die, dwarf::Attribute Attribute,
294 StringRef String) {
295 if (CUNode->isDebugDirectivesOnly())
296 return;
297
298 if (DD->useInlineStrings()) {
299 addAttribute(Die, Attribute, Form: dwarf::DW_FORM_string,
300 Value: new (DIEValueAllocator)
301 DIEInlineString(String, DIEValueAllocator));
302 return;
303 }
304 dwarf::Form IxForm =
305 isDwoUnit() ? dwarf::DW_FORM_GNU_str_index : dwarf::DW_FORM_strp;
306
307 auto StringPoolEntry =
308 useSegmentedStringOffsetsTable() || IxForm == dwarf::DW_FORM_GNU_str_index
309 ? DU->getStringPool().getIndexedEntry(Asm&: *Asm, Str: String)
310 : DU->getStringPool().getEntry(Asm&: *Asm, Str: String);
311
312 // For DWARF v5 and beyond, use the smallest strx? form possible.
313 if (useSegmentedStringOffsetsTable()) {
314 IxForm = dwarf::DW_FORM_strx1;
315 unsigned Index = StringPoolEntry.getIndex();
316 if (Index > 0xffffff)
317 IxForm = dwarf::DW_FORM_strx4;
318 else if (Index > 0xffff)
319 IxForm = dwarf::DW_FORM_strx3;
320 else if (Index > 0xff)
321 IxForm = dwarf::DW_FORM_strx2;
322 }
323 addAttribute(Die, Attribute, Form: IxForm, Value: DIEString(StringPoolEntry));
324}
325
326void DwarfUnit::addLabel(DIEValueList &Die, dwarf::Attribute Attribute,
327 dwarf::Form Form, const MCSymbol *Label) {
328 addAttribute(Die, Attribute, Form, Value: DIELabel(Label));
329}
330
331void DwarfUnit::addLabel(DIELoc &Die, dwarf::Form Form, const MCSymbol *Label) {
332 addLabel(Die, Attribute: (dwarf::Attribute)0, Form, Label);
333}
334
335void DwarfUnit::addSectionOffset(DIE &Die, dwarf::Attribute Attribute,
336 uint64_t Integer) {
337 addUInt(Die, Attribute, Form: DD->getDwarfSectionOffsetForm(), Integer);
338}
339
340unsigned DwarfTypeUnit::getOrCreateSourceID(const DIFile *File) {
341 if (!SplitLineTable)
342 return getCU().getOrCreateSourceID(File);
343 if (!UsedLineTable) {
344 UsedLineTable = true;
345 // This is a split type unit that needs a line table.
346 addSectionOffset(Die&: getUnitDie(), Attribute: dwarf::DW_AT_stmt_list, Integer: 0);
347 }
348 return SplitLineTable->getFile(
349 Directory: File->getDirectory(), FileName: File->getFilename(), Checksum: DD->getMD5AsBytes(File),
350 DwarfVersion: Asm->OutContext.getDwarfVersion(), Source: File->getSource());
351}
352
353void DwarfUnit::addPoolOpAddress(DIEValueList &Die, const MCSymbol *Label) {
354 bool UseAddrOffsetFormOrExpressions =
355 DD->useAddrOffsetForm() || DD->useAddrOffsetExpressions();
356
357 const MCSymbol *Base = nullptr;
358 if (Label->isInSection() && UseAddrOffsetFormOrExpressions)
359 Base = DD->getSectionLabel(S: &Label->getSection());
360
361 uint32_t Index = DD->getAddressPool().getIndex(Sym: Base ? Base : Label);
362
363 if (DD->getDwarfVersion() >= 5) {
364 addUInt(Block&: Die, Form: dwarf::DW_FORM_data1, Integer: dwarf::DW_OP_addrx);
365 addUInt(Block&: Die, Form: dwarf::DW_FORM_addrx, Integer: Index);
366 } else {
367 addUInt(Block&: Die, Form: dwarf::DW_FORM_data1, Integer: dwarf::DW_OP_GNU_addr_index);
368 addUInt(Block&: Die, Form: dwarf::DW_FORM_GNU_addr_index, Integer: Index);
369 }
370
371 if (Base && Base != Label) {
372 addUInt(Block&: Die, Form: dwarf::DW_FORM_data1, Integer: dwarf::DW_OP_const4u);
373 addLabelDelta(Die, Attribute: (dwarf::Attribute)0, Hi: Label, Lo: Base);
374 addUInt(Block&: Die, Form: dwarf::DW_FORM_data1, Integer: dwarf::DW_OP_plus);
375 }
376}
377
378void DwarfUnit::addOpAddress(DIELoc &Die, const MCSymbol *Sym) {
379 if (DD->getDwarfVersion() >= 5) {
380 addPoolOpAddress(Die, Label: Sym);
381 return;
382 }
383
384 if (DD->useSplitDwarf()) {
385 addPoolOpAddress(Die, Label: Sym);
386 return;
387 }
388
389 addUInt(Block&: Die, Form: dwarf::DW_FORM_data1, Integer: dwarf::DW_OP_addr);
390 addLabel(Die, Form: dwarf::DW_FORM_addr, Label: Sym);
391}
392
393void DwarfUnit::addLabelDelta(DIEValueList &Die, dwarf::Attribute Attribute,
394 const MCSymbol *Hi, const MCSymbol *Lo) {
395 addAttribute(Die, Attribute, Form: dwarf::DW_FORM_data4,
396 Value: new (DIEValueAllocator) DIEDelta(Hi, Lo));
397}
398
399void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute, DIE &Entry) {
400 addDIEEntry(Die, Attribute, Entry: DIEEntry(Entry));
401}
402
403void DwarfUnit::addDIETypeSignature(DIE &Die, uint64_t Signature) {
404 // Flag the type unit reference as a declaration so that if it contains
405 // members (implicit special members, static data member definitions, member
406 // declarations for definitions in this CU, etc) consumers don't get confused
407 // and think this is a full definition.
408 addFlag(Die, Attribute: dwarf::DW_AT_declaration);
409
410 addAttribute(Die, Attribute: dwarf::DW_AT_signature, Form: dwarf::DW_FORM_ref_sig8,
411 Value: DIEInteger(Signature));
412}
413
414void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute,
415 DIEEntry Entry) {
416 const DIEUnit *CU = Die.getUnit();
417 const DIEUnit *EntryCU = Entry.getEntry().getUnit();
418 if (!CU)
419 // We assume that Die belongs to this CU, if it is not linked to any CU yet.
420 CU = getUnitDie().getUnit();
421 if (!EntryCU)
422 EntryCU = getUnitDie().getUnit();
423 assert(EntryCU == CU || !DD->useSplitDwarf() || DD->shareAcrossDWOCUs() ||
424 !static_cast<const DwarfUnit*>(CU)->isDwoUnit());
425 addAttribute(Die, Attribute,
426 Form: EntryCU == CU ? dwarf::DW_FORM_ref4 : dwarf::DW_FORM_ref_addr,
427 Value&: Entry);
428}
429
430DIE &DwarfUnit::createAndAddDIE(dwarf::Tag Tag, DIE &Parent, const DINode *N) {
431 DIE &Die = Parent.addChild(Child: DIE::get(Alloc&: DIEValueAllocator, Tag));
432 if (N)
433 insertDIE(Desc: N, D: &Die);
434 return Die;
435}
436
437void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute, DIELoc *Loc) {
438 Loc->computeSize(FormParams: Asm->getDwarfFormParams());
439 DIELocs.push_back(x: Loc); // Memoize so we can call the destructor later on.
440 addAttribute(Die, Attribute, Form: Loc->BestForm(DwarfVersion: DD->getDwarfVersion()), Value&: Loc);
441}
442
443void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute, dwarf::Form Form,
444 DIEBlock *Block) {
445 Block->computeSize(FormParams: Asm->getDwarfFormParams());
446 DIEBlocks.push_back(x: Block); // Memoize so we can call the destructor later on.
447 addAttribute(Die, Attribute, Form, Value&: Block);
448}
449
450void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute,
451 DIEBlock *Block) {
452 addBlock(Die, Attribute, Form: Block->BestForm(), Block);
453}
454
455void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute,
456 const DIExpression *Expr) {
457 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
458 DIEDwarfExpression DwarfExpr(*Asm, getCU(), *Loc);
459 DwarfExpr.setMemoryLocationKind();
460 DwarfExpr.addExpression(Expr);
461 addBlock(Die, Attribute, Loc: DwarfExpr.finalize());
462}
463
464void DwarfUnit::addSourceLine(DIE &Die, unsigned Line, unsigned Column,
465 const DIFile *File) {
466 if (Line == 0)
467 return;
468
469 unsigned FileID = getOrCreateSourceID(File);
470 addUInt(Die, Attribute: dwarf::DW_AT_decl_file, Form: std::nullopt, Integer: FileID);
471 addUInt(Die, Attribute: dwarf::DW_AT_decl_line, Form: std::nullopt, Integer: Line);
472
473 if (Column != 0)
474 addUInt(Die, Attribute: dwarf::DW_AT_decl_column, Form: std::nullopt, Integer: Column);
475}
476
477void DwarfUnit::addSourceLine(DIE &Die, const DILocalVariable *V) {
478 assert(V);
479
480 addSourceLine(Die, Line: V->getLine(), /*Column*/ 0, File: V->getFile());
481}
482
483void DwarfUnit::addSourceLine(DIE &Die, const DIGlobalVariable *G) {
484 assert(G);
485
486 addSourceLine(Die, Line: G->getLine(), /*Column*/ 0, File: G->getFile());
487}
488
489void DwarfUnit::addSourceLine(DIE &Die, const DISubprogram *SP) {
490 assert(SP);
491
492 addSourceLine(Die, Line: SP->getLine(), /*Column*/ 0, File: SP->getFile());
493}
494
495void DwarfUnit::addSourceLine(DIE &Die, const DILabel *L) {
496 assert(L);
497
498 addSourceLine(Die, Line: L->getLine(), Column: L->getColumn(), File: L->getFile());
499}
500
501void DwarfUnit::addSourceLine(DIE &Die, const DIType *Ty) {
502 assert(Ty);
503
504 addSourceLine(Die, Line: Ty->getLine(), /*Column*/ 0, File: Ty->getFile());
505}
506
507void DwarfUnit::addSourceLine(DIE &Die, const DIObjCProperty *Ty) {
508 assert(Ty);
509
510 addSourceLine(Die, Line: Ty->getLine(), /*Column*/ 0, File: Ty->getFile());
511}
512
513void DwarfUnit::addSourceLine(DIE &Die, const DIProperty *P) {
514 assert(P);
515
516 addSourceLine(Die, Line: P->getLine(), /*Column*/ 0, File: P->getFile());
517}
518
519void DwarfUnit::addConstantFPValue(DIE &Die, const ConstantFP *CFP) {
520 // Pass this down to addConstantValue as an unsigned bag of bits.
521 addConstantValue(Die, Val: CFP->getValueAPF().bitcastToAPInt(), Unsigned: true);
522}
523
524void DwarfUnit::addConstantValue(DIE &Die, const ConstantInt *CI,
525 const DIType *Ty) {
526 addConstantValue(Die, Val: CI->getValue(), Ty);
527}
528
529void DwarfUnit::addConstantValue(DIE &Die, uint64_t Val, const DIType *Ty) {
530 addConstantValue(Die, Unsigned: DD->isUnsignedDIType(Ty), Val);
531}
532
533void DwarfUnit::addConstantValue(DIE &Die, bool Unsigned, uint64_t Val) {
534 // FIXME: This is a bit conservative/simple - it emits negative values always
535 // sign extended to 64 bits rather than minimizing the number of bytes.
536 addUInt(Die, Attribute: dwarf::DW_AT_const_value,
537 Form: Unsigned ? dwarf::DW_FORM_udata : dwarf::DW_FORM_sdata, Integer: Val);
538}
539
540void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, const DIType *Ty) {
541 addConstantValue(Die, Val, Unsigned: DD->isUnsignedDIType(Ty));
542}
543
544void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, bool Unsigned) {
545 unsigned CIBitWidth = Val.getBitWidth();
546 if (CIBitWidth <= 64) {
547 addConstantValue(Die, Unsigned,
548 Val: Unsigned ? Val.getZExtValue() : Val.getSExtValue());
549 return;
550 }
551
552 addIntAsBlock(Die, Attribute: dwarf::DW_AT_const_value, Val);
553}
554
555void DwarfUnit::addLinkageName(DIE &Die, StringRef LinkageName) {
556 if (!LinkageName.empty())
557 addString(Die,
558 Attribute: DD->getDwarfVersion() >= 4 ? dwarf::DW_AT_linkage_name
559 : dwarf::DW_AT_MIPS_linkage_name,
560 String: GlobalValue::dropLLVMManglingEscape(Name: LinkageName));
561}
562
563void DwarfUnit::addTemplateParams(DIE &Buffer, DINodeArray TParams) {
564 // Add template parameters.
565 for (const auto *Element : TParams) {
566 if (auto *TTP = dyn_cast<DITemplateTypeParameter>(Val: Element))
567 constructTemplateTypeParameterDIE(Buffer, TP: TTP);
568 else if (auto *TVP = dyn_cast<DITemplateValueParameter>(Val: Element))
569 constructTemplateValueParameterDIE(Buffer, TVP);
570 }
571}
572
573/// Add thrown types.
574void DwarfUnit::addThrownTypes(DIE &Die, DINodeArray ThrownTypes) {
575 for (const auto *Ty : ThrownTypes) {
576 DIE &TT = createAndAddDIE(Tag: dwarf::DW_TAG_thrown_type, Parent&: Die);
577 addType(Entity&: TT, Ty: cast<DIType>(Val: Ty));
578 }
579}
580
581void DwarfUnit::addAccess(DIE &Die, DINode::DIFlags Flags) {
582 if ((Flags & DINode::FlagAccessibility) == DINode::FlagProtected)
583 addUInt(Die, Attribute: dwarf::DW_AT_accessibility, Form: dwarf::DW_FORM_data1,
584 Integer: dwarf::DW_ACCESS_protected);
585 else if ((Flags & DINode::FlagAccessibility) == DINode::FlagPrivate)
586 addUInt(Die, Attribute: dwarf::DW_AT_accessibility, Form: dwarf::DW_FORM_data1,
587 Integer: dwarf::DW_ACCESS_private);
588 else if ((Flags & DINode::FlagAccessibility) == DINode::FlagPublic)
589 addUInt(Die, Attribute: dwarf::DW_AT_accessibility, Form: dwarf::DW_FORM_data1,
590 Integer: dwarf::DW_ACCESS_public);
591}
592
593DIE *DwarfUnit::getOrCreateContextDIE(const DIScope *Context) {
594 if (!Context || isa<DIFile>(Val: Context) || isa<DICompileUnit>(Val: Context))
595 return &getUnitDie();
596 if (auto *T = dyn_cast<DIType>(Val: Context))
597 return getOrCreateTypeDIE(TyNode: T);
598 if (auto *NS = dyn_cast<DINamespace>(Val: Context))
599 return getOrCreateNameSpace(NS);
600 if (auto *SP = dyn_cast<DISubprogram>(Val: Context))
601 return getOrCreateSubprogramDIE(SP, FnHint: nullptr);
602 if (auto *M = dyn_cast<DIModule>(Val: Context))
603 return getOrCreateModule(M);
604 return getDIE(D: Context);
605}
606
607DIE *DwarfUnit::createTypeDIE(const DICompositeType *Ty) {
608 auto *Context = Ty->getScope();
609 DIE *ContextDIE = getOrCreateContextDIE(Context);
610
611 if (DIE *TyDIE = getDIE(D: Ty))
612 return TyDIE;
613
614 // Create new type.
615 DIE &TyDIE = createAndAddDIE(Tag: Ty->getTag(), Parent&: *ContextDIE, N: Ty);
616
617 constructTypeDIE(Buffer&: TyDIE, CTy: cast<DICompositeType>(Val: Ty));
618
619 updateAcceleratorTables(Context, Ty, TyDIE);
620 return &TyDIE;
621}
622
623DIE *DwarfUnit::createTypeDIE(const DIScope *Context, DIE &ContextDIE,
624 const DIType *Ty) {
625 // Create new type.
626 DIE &TyDIE = createAndAddDIE(Tag: Ty->getTag(), Parent&: ContextDIE, N: Ty);
627
628 auto construct = [&](const auto *Ty) {
629 updateAcceleratorTables(Context, Ty, TyDIE);
630 constructTypeDIE(TyDIE, Ty);
631 };
632
633 if (auto *CTy = dyn_cast<DICompositeType>(Val: Ty)) {
634 if (DD->generateTypeUnits() && !Ty->isForwardDecl() &&
635 (Ty->getRawName() || CTy->getRawIdentifier())) {
636 // Skip updating the accelerator tables since this is not the full type.
637 if (MDString *TypeId = CTy->getRawIdentifier()) {
638 addGlobalType(Ty, Die: TyDIE, Context);
639 DD->addDwarfTypeUnitType(CU&: getCU(), Identifier: TypeId->getString(), Die&: TyDIE, CTy);
640 } else {
641 updateAcceleratorTables(Context, Ty, TyDIE);
642 finishNonUnitTypeDIE(D&: TyDIE, CTy);
643 }
644 return &TyDIE;
645 }
646 construct(CTy);
647 } else if (auto *FPT = dyn_cast<DIFixedPointType>(Val: Ty))
648 construct(FPT);
649 else if (auto *BT = dyn_cast<DIBasicType>(Val: Ty))
650 construct(BT);
651 else if (auto *ST = dyn_cast<DIStringType>(Val: Ty))
652 construct(ST);
653 else if (auto *STy = dyn_cast<DISubroutineType>(Val: Ty))
654 construct(STy);
655 else if (auto *SRTy = dyn_cast<DISubrangeType>(Val: Ty))
656 constructSubrangeDIE(Buffer&: TyDIE, SR: SRTy);
657 else
658 construct(cast<DIDerivedType>(Val: Ty));
659
660 return &TyDIE;
661}
662
663DIE *DwarfUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
664 if (!TyNode)
665 return nullptr;
666
667 auto *Ty = cast<DIType>(Val: TyNode);
668
669 // DW_TAG_restrict_type is not supported in DWARF2
670 if (Ty->getTag() == dwarf::DW_TAG_restrict_type && DD->getDwarfVersion() <= 2)
671 return getOrCreateTypeDIE(TyNode: cast<DIDerivedType>(Val: Ty)->getBaseType());
672
673 // DW_TAG_atomic_type is not supported in DWARF < 5
674 if (Ty->getTag() == dwarf::DW_TAG_atomic_type && DD->getDwarfVersion() < 5)
675 return getOrCreateTypeDIE(TyNode: cast<DIDerivedType>(Val: Ty)->getBaseType());
676
677 // Construct the context before querying for the existence of the DIE in case
678 // such construction creates the DIE.
679 auto *Context = Ty->getScope();
680 DIE *ContextDIE = getOrCreateContextDIE(Context);
681 assert(ContextDIE);
682
683 if (DIE *TyDIE = getDIE(D: Ty))
684 return TyDIE;
685
686 return static_cast<DwarfUnit *>(ContextDIE->getUnit())
687 ->createTypeDIE(Context, ContextDIE&: *ContextDIE, Ty);
688}
689
690void DwarfUnit::updateAcceleratorTables(const DIScope *Context,
691 const DIType *Ty, const DIE &TyDIE) {
692 if (Ty->getName().empty())
693 return;
694 if (Ty->isForwardDecl())
695 return;
696
697 // add temporary record for this type to be added later
698
699 unsigned Flags = 0;
700 if (auto *CT = dyn_cast<DICompositeType>(Val: Ty)) {
701 // A runtime language of 0 actually means C/C++ and that any
702 // non-negative value is some version of Objective-C/C++.
703 if (CT->getRuntimeLang() == 0 || CT->isObjcClassComplete())
704 Flags = dwarf::DW_FLAG_type_implementation;
705 }
706
707 DD->addAccelType(Unit: *this, NameTableKind: CUNode->getNameTableKind(), Name: Ty->getName(), Die: TyDIE,
708 Flags);
709
710 if (auto *CT = dyn_cast<DICompositeType>(Val: Ty))
711 if (Ty->getName() != CT->getIdentifier() &&
712 CT->getRuntimeLang() == dwarf::DW_LANG_Swift)
713 DD->addAccelType(Unit: *this, NameTableKind: CUNode->getNameTableKind(), Name: CT->getIdentifier(),
714 Die: TyDIE, Flags);
715
716 addGlobalType(Ty, Die: TyDIE, Context);
717}
718
719void DwarfUnit::addGlobalType(const DIType *Ty, const DIE &TyDIE,
720 const DIScope *Context) {
721 if (!Context || isa<DICompileUnit>(Val: Context) || isa<DIFile>(Val: Context) ||
722 isa<DINamespace>(Val: Context) || isa<DICommonBlock>(Val: Context))
723 addGlobalTypeImpl(Ty, Die: TyDIE, Context);
724}
725
726void DwarfUnit::addType(DIE &Entity, const DIType *Ty,
727 dwarf::Attribute Attribute) {
728 assert(Ty && "Trying to add a type that doesn't exist?");
729 addDIEEntry(Die&: Entity, Attribute, Entry: DIEEntry(*getOrCreateTypeDIE(TyNode: Ty)));
730}
731
732// FIXME: change callsites to use the new DW_LNAME_ language codes.
733llvm::dwarf::SourceLanguage DwarfUnit::getSourceLanguage() const {
734 const auto &Lang = getLanguage();
735
736 if (!Lang.hasVersionedName())
737 return static_cast<llvm::dwarf::SourceLanguage>(Lang.getName());
738
739 return llvm::dwarf::toDW_LANG(
740 name: static_cast<llvm::dwarf::SourceLanguageName>(Lang.getName()),
741 version: Lang.getVersion())
742 .value_or(u: llvm::dwarf::DW_LANG_hi_user);
743}
744
745std::string DwarfUnit::getParentContextString(const DIScope *Context) const {
746 if (!Context)
747 return "";
748
749 // FIXME: Decide whether to implement this for non-C++ languages.
750 if (!dwarf::isCPlusPlus(S: getSourceLanguage()))
751 return "";
752
753 std::string CS;
754 SmallVector<const DIScope *, 1> Parents;
755 while (!isa<DICompileUnit>(Val: Context)) {
756 Parents.push_back(Elt: Context);
757 if (const DIScope *S = Context->getScope())
758 Context = S;
759 else
760 // Structure, etc types will have a NULL context if they're at the top
761 // level.
762 break;
763 }
764
765 // Reverse iterate over our list to go from the outermost construct to the
766 // innermost.
767 for (const DIScope *Ctx : llvm::reverse(C&: Parents)) {
768 StringRef Name = Ctx->getName();
769 if (Name.empty() && isa<DINamespace>(Val: Ctx))
770 Name = "(anonymous namespace)";
771 if (!Name.empty()) {
772 CS += Name;
773 CS += "::";
774 }
775 }
776 return CS;
777}
778
779void DwarfUnit::constructTypeDIE(DIE &Buffer, const DIBasicType *BTy) {
780 // Get core information.
781 StringRef Name = BTy->getName();
782 // Add name if not anonymous or intermediate type.
783 if (!Name.empty())
784 addString(Die&: Buffer, Attribute: dwarf::DW_AT_name, String: Name);
785
786 // An unspecified type only has a name attribute.
787 if (BTy->getTag() == dwarf::DW_TAG_unspecified_type)
788 return;
789
790 if (BTy->getTag() != dwarf::DW_TAG_string_type)
791 addUInt(Die&: Buffer, Attribute: dwarf::DW_AT_encoding, Form: dwarf::DW_FORM_data1,
792 Integer: BTy->getEncoding());
793
794 uint64_t SizeInBytes = divideCeil(Numerator: BTy->getSizeInBits(), Denominator: 8);
795 addUInt(Die&: Buffer, Attribute: dwarf::DW_AT_byte_size, Form: std::nullopt, Integer: SizeInBytes);
796 if (BTy->getTag() == dwarf::Tag::DW_TAG_base_type) {
797 // DW_TAG_base_type:
798 // If the value of an object of the given type does not fully occupy the
799 // storage described by a byte size attribute, the base type entry may also
800 // have a DW_AT_bit_size [...] attribute.
801 // TODO: Do big endian targets need DW_AT_data_bit_offset? See discussion in
802 // pull request #164372.
803 if (uint64_t DataSizeInBits = BTy->getDataSizeInBits();
804 DataSizeInBits && DataSizeInBits != SizeInBytes * 8)
805 addUInt(Die&: Buffer, Attribute: dwarf::DW_AT_bit_size, Form: std::nullopt, Integer: DataSizeInBits);
806 }
807
808 if (BTy->isBigEndian())
809 addUInt(Die&: Buffer, Attribute: dwarf::DW_AT_endianity, Form: std::nullopt, Integer: dwarf::DW_END_big);
810 else if (BTy->isLittleEndian())
811 addUInt(Die&: Buffer, Attribute: dwarf::DW_AT_endianity, Form: std::nullopt, Integer: dwarf::DW_END_little);
812
813 if (uint32_t NumExtraInhabitants = BTy->getNumExtraInhabitants())
814 addUInt(Die&: Buffer, Attribute: dwarf::DW_AT_LLVM_num_extra_inhabitants, Form: std::nullopt,
815 Integer: NumExtraInhabitants);
816}
817
818void DwarfUnit::constructTypeDIE(DIE &Buffer, const DIFixedPointType *BTy) {
819 // Base type handling.
820 constructTypeDIE(Buffer, BTy: static_cast<const DIBasicType *>(BTy));
821
822 if (BTy->isBinary())
823 addSInt(Die&: Buffer, Attribute: dwarf::DW_AT_binary_scale, Form: dwarf::DW_FORM_sdata,
824 Integer: BTy->getFactor());
825 else if (BTy->isDecimal())
826 addSInt(Die&: Buffer, Attribute: dwarf::DW_AT_decimal_scale, Form: dwarf::DW_FORM_sdata,
827 Integer: BTy->getFactor());
828 else {
829 assert(BTy->isRational());
830 DIE *ContextDIE = getOrCreateContextDIE(Context: BTy->getScope());
831 DIE &Constant = createAndAddDIE(Tag: dwarf::DW_TAG_constant, Parent&: *ContextDIE);
832
833 addInt(Die&: Constant, Attribute: dwarf::DW_AT_GNU_numerator, Val: BTy->getNumerator(),
834 Unsigned: !BTy->isSigned());
835 addInt(Die&: Constant, Attribute: dwarf::DW_AT_GNU_denominator, Val: BTy->getDenominator(),
836 Unsigned: !BTy->isSigned());
837
838 addDIEEntry(Die&: Buffer, Attribute: dwarf::DW_AT_small, Entry&: Constant);
839 }
840}
841
842void DwarfUnit::constructTypeDIE(DIE &Buffer, const DIStringType *STy) {
843 // Get core information.
844 StringRef Name = STy->getName();
845 // Add name if not anonymous or intermediate type.
846 if (!Name.empty())
847 addString(Die&: Buffer, Attribute: dwarf::DW_AT_name, String: Name);
848
849 if (DIVariable *Var = STy->getStringLength()) {
850 if (auto *VarDIE = getDIE(D: Var))
851 addDIEEntry(Die&: Buffer, Attribute: dwarf::DW_AT_string_length, Entry&: *VarDIE);
852 } else if (DIExpression *Expr = STy->getStringLengthExp()) {
853 addBlock(Die&: Buffer, Attribute: dwarf::DW_AT_string_length, Expr);
854 } else {
855 uint64_t Size = STy->getSizeInBits() >> 3;
856 addUInt(Die&: Buffer, Attribute: dwarf::DW_AT_byte_size, Form: std::nullopt, Integer: Size);
857 }
858
859 if (DIExpression *Expr = STy->getStringLocationExp()) {
860 addBlock(Die&: Buffer, Attribute: dwarf::DW_AT_data_location, Expr);
861 }
862
863 if (STy->getEncoding()) {
864 // For eventual Unicode support.
865 addUInt(Die&: Buffer, Attribute: dwarf::DW_AT_encoding, Form: dwarf::DW_FORM_data1,
866 Integer: STy->getEncoding());
867 }
868}
869
870void DwarfUnit::constructTypeDIE(DIE &Buffer, const DIDerivedType *DTy) {
871 // Get core information.
872 StringRef Name = DTy->getName();
873 uint64_t Size = DTy->getSizeInBits() >> 3;
874 uint16_t Tag = Buffer.getTag();
875
876 // Map to main type, void will not have a type.
877 const DIType *FromTy = DTy->getBaseType();
878 if (FromTy)
879 addType(Entity&: Buffer, Ty: FromTy);
880
881 // Add name if not anonymous or intermediate type.
882 if (!Name.empty())
883 addString(Die&: Buffer, Attribute: dwarf::DW_AT_name, String: Name);
884
885 addAnnotation(Buffer, Annotations: DTy->getAnnotations());
886
887 // If alignment is specified for a typedef , create and insert DW_AT_alignment
888 // attribute in DW_TAG_typedef DIE.
889 if (Tag == dwarf::DW_TAG_typedef && DD->getDwarfVersion() >= 5) {
890 uint32_t AlignInBytes = DTy->getAlignInBytes();
891 if (AlignInBytes > 0)
892 addUInt(Die&: Buffer, Attribute: dwarf::DW_AT_alignment, Form: dwarf::DW_FORM_udata,
893 Integer: AlignInBytes);
894 }
895
896 // Add size if non-zero (derived types might be zero-sized.)
897 if (Size && Tag != dwarf::DW_TAG_pointer_type
898 && Tag != dwarf::DW_TAG_ptr_to_member_type
899 && Tag != dwarf::DW_TAG_reference_type
900 && Tag != dwarf::DW_TAG_rvalue_reference_type)
901 addUInt(Die&: Buffer, Attribute: dwarf::DW_AT_byte_size, Form: std::nullopt, Integer: Size);
902
903 if (Tag == dwarf::DW_TAG_ptr_to_member_type)
904 addDIEEntry(Die&: Buffer, Attribute: dwarf::DW_AT_containing_type,
905 Entry&: *getOrCreateTypeDIE(TyNode: cast<DIDerivedType>(Val: DTy)->getClassType()));
906
907 addAccess(Die&: Buffer, Flags: DTy->getFlags());
908
909 // Add source line info if available and TyDesc is not a forward declaration.
910 if (!DTy->isForwardDecl())
911 addSourceLine(Die&: Buffer, Ty: DTy);
912
913 // If DWARF address space value is other than None, add it. The IR
914 // verifier checks that DWARF address space only exists for pointer
915 // or reference types.
916 if (DTy->getDWARFAddressSpace())
917 addUInt(Die&: Buffer, Attribute: dwarf::DW_AT_address_class, Form: dwarf::DW_FORM_data4,
918 Integer: *DTy->getDWARFAddressSpace());
919
920 // Add template alias template parameters.
921 if (Tag == dwarf::DW_TAG_template_alias)
922 addTemplateParams(Buffer, TParams: DTy->getTemplateParams());
923
924 if (auto PtrAuthData = DTy->getPtrAuthData()) {
925 addUInt(Die&: Buffer, Attribute: dwarf::DW_AT_LLVM_ptrauth_key, Form: dwarf::DW_FORM_data1,
926 Integer: PtrAuthData->key());
927 if (PtrAuthData->isAddressDiscriminated())
928 addFlag(Die&: Buffer, Attribute: dwarf::DW_AT_LLVM_ptrauth_address_discriminated);
929 addUInt(Die&: Buffer, Attribute: dwarf::DW_AT_LLVM_ptrauth_extra_discriminator,
930 Form: dwarf::DW_FORM_data2, Integer: PtrAuthData->extraDiscriminator());
931 if (PtrAuthData->isaPointer())
932 addFlag(Die&: Buffer, Attribute: dwarf::DW_AT_LLVM_ptrauth_isa_pointer);
933 if (PtrAuthData->authenticatesNullValues())
934 addFlag(Die&: Buffer, Attribute: dwarf::DW_AT_LLVM_ptrauth_authenticates_null_values);
935 }
936}
937
938std::optional<unsigned>
939DwarfUnit::constructSubprogramArguments(DIE &Buffer, DITypeArray Args) {
940 // Args[0] is the return type.
941 std::optional<unsigned> ObjectPointerIndex;
942 for (unsigned i = 1, N = Args.size(); i < N; ++i) {
943 const DIType *Ty = Args[i];
944 if (!Ty) {
945 assert(i == N-1 && "Unspecified parameter must be the last argument");
946 createAndAddDIE(Tag: dwarf::DW_TAG_unspecified_parameters, Parent&: Buffer);
947 } else {
948 DIE &Arg = createAndAddDIE(Tag: dwarf::DW_TAG_formal_parameter, Parent&: Buffer);
949 addType(Entity&: Arg, Ty);
950 if (Ty->isArtificial())
951 addFlag(Die&: Arg, Attribute: dwarf::DW_AT_artificial);
952
953 if (Ty->isObjectPointer()) {
954 assert(!ObjectPointerIndex &&
955 "Can't have more than one object pointer");
956 ObjectPointerIndex = i;
957 }
958 }
959 }
960
961 return ObjectPointerIndex;
962}
963
964void DwarfUnit::constructTypeDIE(DIE &Buffer, const DISubroutineType *CTy) {
965 // Add return type. A void return won't have a type.
966 auto Elements = cast<DISubroutineType>(Val: CTy)->getTypeArray();
967 if (Elements.size())
968 if (auto RTy = Elements[0])
969 addType(Entity&: Buffer, Ty: RTy);
970
971 bool isPrototyped = true;
972 if (Elements.size() == 2 && !Elements[1])
973 isPrototyped = false;
974
975 constructSubprogramArguments(Buffer, Args: Elements);
976
977 // Add prototype flag if we're dealing with a C language and the function has
978 // been prototyped.
979 if (isPrototyped && dwarf::isC(S: getSourceLanguage()))
980 addFlag(Die&: Buffer, Attribute: dwarf::DW_AT_prototyped);
981
982 // Add a DW_AT_calling_convention if this has an explicit convention.
983 if (CTy->getCC() && CTy->getCC() != dwarf::DW_CC_normal)
984 addUInt(Die&: Buffer, Attribute: dwarf::DW_AT_calling_convention, Form: dwarf::DW_FORM_data1,
985 Integer: CTy->getCC());
986
987 if (CTy->isLValueReference())
988 addFlag(Die&: Buffer, Attribute: dwarf::DW_AT_reference);
989
990 if (CTy->isRValueReference())
991 addFlag(Die&: Buffer, Attribute: dwarf::DW_AT_rvalue_reference);
992}
993
994void DwarfUnit::addAnnotation(DIE &Buffer, DINodeArray Annotations) {
995 if (!Annotations)
996 return;
997
998 for (const Metadata *Annotation : Annotations->operands()) {
999 const MDNode *MD = cast<MDNode>(Val: Annotation);
1000 const MDString *Name = cast<MDString>(Val: MD->getOperand(I: 0));
1001 const auto &Value = MD->getOperand(I: 1);
1002
1003 DIE &AnnotationDie = createAndAddDIE(Tag: dwarf::DW_TAG_LLVM_annotation, Parent&: Buffer);
1004 addString(Die&: AnnotationDie, Attribute: dwarf::DW_AT_name, String: Name->getString());
1005 if (const auto *Data = dyn_cast<MDString>(Val: Value))
1006 addString(Die&: AnnotationDie, Attribute: dwarf::DW_AT_const_value, String: Data->getString());
1007 else if (const auto *Data = dyn_cast<ConstantAsMetadata>(Val: Value))
1008 addConstantValue(Die&: AnnotationDie, Val: Data->getValue()->getUniqueInteger(),
1009 /*Unsigned=*/true);
1010 else
1011 assert(false && "Unsupported annotation value type");
1012 }
1013}
1014
1015void DwarfUnit::addDiscriminant(DIE &Variant, Constant *Discriminant,
1016 bool IsUnsigned) {
1017 if (const auto *CI = dyn_cast_or_null<ConstantInt>(Val: Discriminant)) {
1018 addInt(Die&: Variant, Attribute: dwarf::DW_AT_discr_value, Val: CI->getValue(), Unsigned: IsUnsigned);
1019 } else if (const auto *CA =
1020 dyn_cast_or_null<ConstantDataArray>(Val: Discriminant)) {
1021 // Must have an even number of operands.
1022 unsigned NElems = CA->getNumElements();
1023 if (NElems % 2 != 0) {
1024 return;
1025 }
1026
1027 DIEBlock *Block = new (DIEValueAllocator) DIEBlock;
1028
1029 auto AddInt = [&](const APInt &Val) {
1030 if (IsUnsigned)
1031 addUInt(Block&: *Block, Form: dwarf::DW_FORM_udata, Integer: Val.getZExtValue());
1032 else
1033 addSInt(Die&: *Block, Form: dwarf::DW_FORM_sdata, Integer: Val.getSExtValue());
1034 };
1035
1036 for (unsigned I = 0; I < NElems; I += 2) {
1037 APInt LV = CA->getElementAsAPInt(i: I);
1038 APInt HV = CA->getElementAsAPInt(i: I + 1);
1039 if (LV == HV) {
1040 addUInt(Block&: *Block, Form: dwarf::DW_FORM_data1, Integer: dwarf::DW_DSC_label);
1041 AddInt(LV);
1042 } else {
1043 addUInt(Block&: *Block, Form: dwarf::DW_FORM_data1, Integer: dwarf::DW_DSC_range);
1044 AddInt(LV);
1045 AddInt(HV);
1046 }
1047 }
1048 addBlock(Die&: Variant, Attribute: dwarf::DW_AT_discr_list, Block);
1049 }
1050}
1051
1052void DwarfUnit::constructTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
1053 // Add name if not anonymous or intermediate type.
1054 StringRef Name = CTy->getName();
1055
1056 uint16_t Tag = Buffer.getTag();
1057
1058 switch (Tag) {
1059 case dwarf::DW_TAG_array_type:
1060 constructArrayTypeDIE(Buffer, CTy);
1061 break;
1062 case dwarf::DW_TAG_enumeration_type:
1063 constructEnumTypeDIE(Buffer, CTy);
1064 break;
1065 case dwarf::DW_TAG_variant_part:
1066 case dwarf::DW_TAG_variant:
1067 case dwarf::DW_TAG_structure_type:
1068 case dwarf::DW_TAG_union_type:
1069 case dwarf::DW_TAG_class_type:
1070 case dwarf::DW_TAG_namelist: {
1071 // Emit the discriminator for a variant part.
1072 DIDerivedType *Discriminator = nullptr;
1073 if (Tag == dwarf::DW_TAG_variant_part) {
1074 Discriminator = CTy->getDiscriminator();
1075 if (Discriminator) {
1076 // DWARF says:
1077 // If the variant part has a discriminant, the discriminant is
1078 // represented by a separate debugging information entry which is
1079 // a child of the variant part entry.
1080 // However, for a language like Ada, this yields a weird
1081 // result: a discriminant field would have to be emitted
1082 // multiple times, once per variant part. Instead, this DWARF
1083 // restriction was lifted for DWARF 6 (see
1084 // https://dwarfstd.org/issues/180123.1.html) and so we allow
1085 // this here.
1086 DIE *DiscDIE = getDIE(D: Discriminator);
1087 if (DiscDIE == nullptr) {
1088 DiscDIE = &constructMemberDIE(Buffer, DT: Discriminator);
1089 }
1090 addDIEEntry(Die&: Buffer, Attribute: dwarf::DW_AT_discr, Entry&: *DiscDIE);
1091 }
1092 }
1093
1094 // Add template parameters to a class, structure or union types.
1095 if (Tag == dwarf::DW_TAG_class_type ||
1096 Tag == dwarf::DW_TAG_structure_type ||
1097 Tag == dwarf::DW_TAG_union_type) {
1098 if (!(DD->useSplitDwarf() && !getCU().getSkeleton()) ||
1099 CTy->isNameSimplified())
1100 addTemplateParams(Buffer, TParams: CTy->getTemplateParams());
1101 }
1102
1103 // Add elements to structure type.
1104 DINodeArray Elements = CTy->getElements();
1105 for (const auto *Element : Elements) {
1106 if (!Element)
1107 continue;
1108 if (auto *SP = dyn_cast<DISubprogram>(Val: Element))
1109 getOrCreateSubprogramDIE(SP, FnHint: nullptr);
1110 else if (auto *DDTy = dyn_cast<DIDerivedType>(Val: Element)) {
1111 if (DDTy->getTag() == dwarf::DW_TAG_friend) {
1112 DIE &ElemDie = createAndAddDIE(Tag: dwarf::DW_TAG_friend, Parent&: Buffer);
1113 addType(Entity&: ElemDie, Ty: DDTy->getBaseType(), Attribute: dwarf::DW_AT_friend);
1114 } else if (DDTy->isStaticMember()) {
1115 getOrCreateStaticMemberDIE(DT: DDTy);
1116 } else if (Tag == dwarf::DW_TAG_variant_part) {
1117 // When emitting a variant part, wrap each member in
1118 // DW_TAG_variant.
1119 DIE &Variant = createAndAddDIE(Tag: dwarf::DW_TAG_variant, Parent&: Buffer);
1120 if (Constant *CI = DDTy->getDiscriminantValue()) {
1121 addDiscriminant(Variant, Discriminant: CI,
1122 IsUnsigned: DD->isUnsignedDIType(Ty: Discriminator->getBaseType()));
1123 }
1124 // If the variant holds a composite type with tag
1125 // DW_TAG_variant, inline those members into the variant
1126 // DIE.
1127 if (auto *Composite =
1128 dyn_cast_or_null<DICompositeType>(Val: DDTy->getBaseType());
1129 Composite != nullptr &&
1130 Composite->getTag() == dwarf::DW_TAG_variant) {
1131 constructTypeDIE(Buffer&: Variant, CTy: Composite);
1132 } else {
1133 constructMemberDIE(Buffer&: Variant, DT: DDTy);
1134 }
1135 } else {
1136 constructMemberDIE(Buffer, DT: DDTy);
1137 }
1138 } else if (auto *Property = dyn_cast<DIObjCProperty>(Val: Element)) {
1139 DIE &ElemDie = createAndAddDIE(Tag: Property->getTag(), Parent&: Buffer, N: Property);
1140 StringRef PropertyName = Property->getName();
1141 addString(Die&: ElemDie, Attribute: dwarf::DW_AT_APPLE_property_name, String: PropertyName);
1142 if (Property->getType())
1143 addType(Entity&: ElemDie, Ty: Property->getType());
1144 addSourceLine(Die&: ElemDie, Ty: Property);
1145 StringRef GetterName = Property->getGetterName();
1146 if (!GetterName.empty())
1147 addString(Die&: ElemDie, Attribute: dwarf::DW_AT_APPLE_property_getter, String: GetterName);
1148 StringRef SetterName = Property->getSetterName();
1149 if (!SetterName.empty())
1150 addString(Die&: ElemDie, Attribute: dwarf::DW_AT_APPLE_property_setter, String: SetterName);
1151 if (unsigned PropertyAttributes = Property->getAttributes())
1152 addUInt(Die&: ElemDie, Attribute: dwarf::DW_AT_APPLE_property_attribute, Form: std::nullopt,
1153 Integer: PropertyAttributes);
1154 } else if (auto *Property = dyn_cast<DIProperty>(Val: Element)) {
1155 constructPropertyDIE(Buffer, P: Property);
1156 } else if (auto *Composite = dyn_cast<DICompositeType>(Val: Element)) {
1157 if (Composite->getTag() == dwarf::DW_TAG_variant_part) {
1158 DIE &VariantPart = createAndAddDIE(Tag: Composite->getTag(), Parent&: Buffer);
1159 constructTypeDIE(Buffer&: VariantPart, CTy: Composite);
1160 }
1161 } else if (Tag == dwarf::DW_TAG_namelist) {
1162 auto *VarDIE = getDIE(D: Element);
1163 if (VarDIE) {
1164 DIE &ItemDie = createAndAddDIE(Tag: dwarf::DW_TAG_namelist_item, Parent&: Buffer);
1165 addDIEEntry(Die&: ItemDie, Attribute: dwarf::DW_AT_namelist_item, Entry&: *VarDIE);
1166 }
1167 }
1168 }
1169
1170 if (CTy->isAppleBlockExtension())
1171 addFlag(Die&: Buffer, Attribute: dwarf::DW_AT_APPLE_block);
1172
1173 if (CTy->getExportSymbols())
1174 addFlag(Die&: Buffer, Attribute: dwarf::DW_AT_export_symbols);
1175
1176 // This is outside the DWARF spec, but GDB expects a DW_AT_containing_type
1177 // inside C++ composite types to point to the base class with the vtable.
1178 // Rust uses DW_AT_containing_type to link a vtable to the type
1179 // for which it was created.
1180 if (auto *ContainingType = CTy->getVTableHolder())
1181 addDIEEntry(Die&: Buffer, Attribute: dwarf::DW_AT_containing_type,
1182 Entry&: *getOrCreateTypeDIE(TyNode: ContainingType));
1183
1184 if (CTy->isObjcClassComplete())
1185 addFlag(Die&: Buffer, Attribute: dwarf::DW_AT_APPLE_objc_complete_type);
1186
1187 // Add the type's non-standard calling convention.
1188 // DW_CC_pass_by_value/DW_CC_pass_by_reference are introduced in DWARF 5.
1189 if (!Asm->TM.Options.DebugStrictDwarf || DD->getDwarfVersion() >= 5) {
1190 uint8_t CC = 0;
1191 if (CTy->isTypePassByValue())
1192 CC = dwarf::DW_CC_pass_by_value;
1193 else if (CTy->isTypePassByReference())
1194 CC = dwarf::DW_CC_pass_by_reference;
1195 if (CC)
1196 addUInt(Die&: Buffer, Attribute: dwarf::DW_AT_calling_convention, Form: dwarf::DW_FORM_data1,
1197 Integer: CC);
1198 }
1199
1200 if (auto *SpecifiedFrom = CTy->getSpecification())
1201 addDIEEntry(Die&: Buffer, Attribute: dwarf::DW_AT_specification,
1202 Entry&: *getOrCreateContextDIE(Context: SpecifiedFrom));
1203
1204 break;
1205 }
1206 default:
1207 break;
1208 }
1209
1210 // Add name if not anonymous or intermediate type.
1211 if (!Name.empty())
1212 addString(Die&: Buffer, Attribute: dwarf::DW_AT_name, String: Name);
1213
1214 // For Swift, mangled names are put into DW_AT_linkage_name.
1215 if (CTy->getRuntimeLang() == dwarf::DW_LANG_Swift && CTy->getRawIdentifier())
1216 addString(Die&: Buffer, Attribute: dwarf::DW_AT_linkage_name, String: CTy->getIdentifier());
1217
1218 addAnnotation(Buffer, Annotations: CTy->getAnnotations());
1219
1220 if (Tag == dwarf::DW_TAG_enumeration_type ||
1221 Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
1222 Tag == dwarf::DW_TAG_union_type) {
1223 if (auto *Var = dyn_cast_or_null<DIVariable>(Val: CTy->getRawSizeInBits())) {
1224 if (auto *VarDIE = getDIE(D: Var))
1225 addDIEEntry(Die&: Buffer, Attribute: dwarf::DW_AT_bit_size, Entry&: *VarDIE);
1226 } else if (auto *Exp =
1227 dyn_cast_or_null<DIExpression>(Val: CTy->getRawSizeInBits())) {
1228 addBlock(Die&: Buffer, Attribute: dwarf::DW_AT_bit_size, Expr: Exp);
1229 } else {
1230 uint64_t Size = CTy->getSizeInBits() >> 3;
1231 // Add size if non-zero (derived types might be zero-sized.)
1232 // Ignore the size if it's a non-enum forward decl.
1233 // TODO: Do we care about size for enum forward declarations?
1234 if (Size &&
1235 (!CTy->isForwardDecl() || Tag == dwarf::DW_TAG_enumeration_type))
1236 addUInt(Die&: Buffer, Attribute: dwarf::DW_AT_byte_size, Form: std::nullopt, Integer: Size);
1237 else if (!CTy->isForwardDecl())
1238 // Add zero size if it is not a forward declaration.
1239 addUInt(Die&: Buffer, Attribute: dwarf::DW_AT_byte_size, Form: std::nullopt, Integer: 0);
1240 }
1241
1242 // If we're a forward decl, say so.
1243 if (CTy->isForwardDecl())
1244 addFlag(Die&: Buffer, Attribute: dwarf::DW_AT_declaration);
1245
1246 // Add accessibility info if available.
1247 addAccess(Die&: Buffer, Flags: CTy->getFlags());
1248
1249 // Add source line info if available.
1250 if (!CTy->isForwardDecl())
1251 addSourceLine(Die&: Buffer, Ty: CTy);
1252
1253 // No harm in adding the runtime language to the declaration.
1254 unsigned RLang = CTy->getRuntimeLang();
1255 if (RLang)
1256 addUInt(Die&: Buffer, Attribute: dwarf::DW_AT_APPLE_runtime_class, Form: dwarf::DW_FORM_data1,
1257 Integer: RLang);
1258
1259 // Add align info if available.
1260 if (uint32_t AlignInBytes = CTy->getAlignInBytes())
1261 addUInt(Die&: Buffer, Attribute: dwarf::DW_AT_alignment, Form: dwarf::DW_FORM_udata,
1262 Integer: AlignInBytes);
1263
1264 if (uint32_t NumExtraInhabitants = CTy->getNumExtraInhabitants())
1265 addUInt(Die&: Buffer, Attribute: dwarf::DW_AT_LLVM_num_extra_inhabitants, Form: std::nullopt,
1266 Integer: NumExtraInhabitants);
1267 }
1268}
1269
1270void DwarfUnit::constructTemplateTypeParameterDIE(
1271 DIE &Buffer, const DITemplateTypeParameter *TP) {
1272 DIE &ParamDIE =
1273 createAndAddDIE(Tag: dwarf::DW_TAG_template_type_parameter, Parent&: Buffer);
1274 // Add the type if it exists, it could be void and therefore no type.
1275 if (TP->getType())
1276 addType(Entity&: ParamDIE, Ty: TP->getType());
1277 if (!TP->getName().empty())
1278 addString(Die&: ParamDIE, Attribute: dwarf::DW_AT_name, String: TP->getName());
1279 if (TP->isDefault() && isCompatibleWithVersion(Version: 5))
1280 addFlag(Die&: ParamDIE, Attribute: dwarf::DW_AT_default_value);
1281}
1282
1283void DwarfUnit::constructTemplateValueParameterDIE(
1284 DIE &Buffer, const DITemplateValueParameter *VP) {
1285 DIE &ParamDIE = createAndAddDIE(Tag: VP->getTag(), Parent&: Buffer);
1286
1287 // Add the type if there is one, template template and template parameter
1288 // packs will not have a type.
1289 if (VP->getTag() == dwarf::DW_TAG_template_value_parameter)
1290 addType(Entity&: ParamDIE, Ty: VP->getType());
1291 if (!VP->getName().empty())
1292 addString(Die&: ParamDIE, Attribute: dwarf::DW_AT_name, String: VP->getName());
1293 if (VP->isDefault() && isCompatibleWithVersion(Version: 5))
1294 addFlag(Die&: ParamDIE, Attribute: dwarf::DW_AT_default_value);
1295 if (Metadata *Val = VP->getValue()) {
1296 if (ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(MD&: Val))
1297 addConstantValue(Die&: ParamDIE, CI, Ty: VP->getType());
1298 else if (ConstantFP *CF = mdconst::dyn_extract<ConstantFP>(MD&: Val))
1299 addConstantFPValue(Die&: ParamDIE, CFP: CF);
1300 else if (GlobalValue *GV = mdconst::dyn_extract<GlobalValue>(MD&: Val)) {
1301 // We cannot describe the location of dllimport'd entities: the
1302 // computation of their address requires loads from the IAT.
1303 if (!GV->hasDLLImportStorageClass()) {
1304 // For declaration non-type template parameters (such as global values
1305 // and functions)
1306 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
1307 addOpAddress(Die&: *Loc, Sym: Asm->getSymbol(GV));
1308 // Emit DW_OP_stack_value to use the address as the immediate value of
1309 // the parameter, rather than a pointer to it.
1310 addUInt(Block&: *Loc, Form: dwarf::DW_FORM_data1, Integer: dwarf::DW_OP_stack_value);
1311 addBlock(Die&: ParamDIE, Attribute: dwarf::DW_AT_location, Loc);
1312 }
1313 } else if (VP->getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1314 assert(isa<MDString>(Val));
1315 addString(Die&: ParamDIE, Attribute: dwarf::DW_AT_GNU_template_name,
1316 String: cast<MDString>(Val)->getString());
1317 } else if (VP->getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1318 addTemplateParams(Buffer&: ParamDIE, TParams: cast<MDTuple>(Val));
1319 }
1320 }
1321}
1322
1323DIE *DwarfUnit::getOrCreateNameSpace(const DINamespace *NS) {
1324 // Construct the context before querying for the existence of the DIE in case
1325 // such construction creates the DIE.
1326 DIE *ContextDIE = getOrCreateContextDIE(Context: NS->getScope());
1327
1328 if (DIE *NDie = getDIE(D: NS))
1329 return NDie;
1330 DIE &NDie = createAndAddDIE(Tag: dwarf::DW_TAG_namespace, Parent&: *ContextDIE, N: NS);
1331
1332 StringRef Name = NS->getName();
1333 if (!Name.empty())
1334 addString(Die&: NDie, Attribute: dwarf::DW_AT_name, String: NS->getName());
1335 else
1336 Name = "(anonymous namespace)";
1337 DD->addAccelNamespace(Unit: *this, NameTableKind: CUNode->getNameTableKind(), Name, Die: NDie);
1338 addGlobalName(Name, Die: NDie, Context: NS->getScope());
1339 if (NS->getExportSymbols())
1340 addFlag(Die&: NDie, Attribute: dwarf::DW_AT_export_symbols);
1341 return &NDie;
1342}
1343
1344DIE *DwarfUnit::getOrCreateModule(const DIModule *M) {
1345 // Construct the context before querying for the existence of the DIE in case
1346 // such construction creates the DIE.
1347 DIE *ContextDIE = getOrCreateContextDIE(Context: M->getScope());
1348
1349 if (DIE *MDie = getDIE(D: M))
1350 return MDie;
1351 DIE &MDie = createAndAddDIE(Tag: dwarf::DW_TAG_module, Parent&: *ContextDIE, N: M);
1352
1353 if (!M->getName().empty()) {
1354 addString(Die&: MDie, Attribute: dwarf::DW_AT_name, String: M->getName());
1355 addGlobalName(Name: M->getName(), Die: MDie, Context: M->getScope());
1356 }
1357 if (!M->getConfigurationMacros().empty())
1358 addString(Die&: MDie, Attribute: dwarf::DW_AT_LLVM_config_macros,
1359 String: M->getConfigurationMacros());
1360 if (!M->getIncludePath().empty())
1361 addString(Die&: MDie, Attribute: dwarf::DW_AT_LLVM_include_path, String: M->getIncludePath());
1362 if (!M->getAPINotesFile().empty())
1363 addString(Die&: MDie, Attribute: dwarf::DW_AT_LLVM_apinotes, String: M->getAPINotesFile());
1364 if (M->getFile())
1365 addUInt(Die&: MDie, Attribute: dwarf::DW_AT_decl_file, Form: std::nullopt,
1366 Integer: getOrCreateSourceID(File: M->getFile()));
1367 if (M->getLineNo())
1368 addUInt(Die&: MDie, Attribute: dwarf::DW_AT_decl_line, Form: std::nullopt, Integer: M->getLineNo());
1369 if (M->getIsDecl())
1370 addFlag(Die&: MDie, Attribute: dwarf::DW_AT_declaration);
1371
1372 return &MDie;
1373}
1374
1375DIE *DwarfUnit::getOrCreateSubprogramDIE(const DISubprogram *SP,
1376 const Function *FnHint, bool Minimal) {
1377 // Construct the context before querying for the existence of the DIE in case
1378 // such construction creates the DIE (as is the case for member function
1379 // declarations).
1380 DIE *ContextDIE =
1381 getOrCreateSubprogramContextDIE(SP, IgnoreScope: shouldPlaceInUnitDIE(SP, Minimal));
1382
1383 if (DIE *SPDie = getDIE(D: SP))
1384 return SPDie;
1385
1386 if (auto *SPDecl = SP->getDeclaration()) {
1387 if (!Minimal) {
1388 // Build the decl now to ensure it precedes the definition.
1389 getOrCreateSubprogramDIE(SP: SPDecl, FnHint: nullptr);
1390 // Check whether the DIE for SP has already been created after the call
1391 // above.
1392 // FIXME: Should the creation of definition subprogram DIE during
1393 // the creation of declaration subprogram DIE be allowed?
1394 // See https://github.com/llvm/llvm-project/pull/154636.
1395 if (DIE *SPDie = getDIE(D: SP))
1396 return SPDie;
1397 }
1398 }
1399
1400 // DW_TAG_inlined_subroutine may refer to this DIE.
1401 DIE &SPDie = createAndAddDIE(Tag: dwarf::DW_TAG_subprogram, Parent&: *ContextDIE, N: SP);
1402
1403 // Stop here and fill this in later, depending on whether or not this
1404 // subprogram turns out to have inlined instances or not.
1405 if (SP->isDefinition())
1406 return &SPDie;
1407
1408 static_cast<DwarfUnit *>(SPDie.getUnit())
1409 ->applySubprogramAttributes(SP, SPDie);
1410 return &SPDie;
1411}
1412
1413bool DwarfUnit::applySubprogramDefinitionAttributes(const DISubprogram *SP,
1414 DIE &SPDie, bool Minimal) {
1415 DIE *DeclDie = nullptr;
1416 StringRef DeclLinkageName;
1417 if (auto *SPDecl = SP->getDeclaration()) {
1418 if (!Minimal) {
1419 DITypeArray DeclArgs, DefinitionArgs;
1420 DeclArgs = SPDecl->getType()->getTypeArray();
1421 DefinitionArgs = SP->getType()->getTypeArray();
1422
1423 if (DeclArgs.size() && DefinitionArgs.size())
1424 if (DefinitionArgs[0] != nullptr && DeclArgs[0] != DefinitionArgs[0])
1425 addType(Entity&: SPDie, Ty: DefinitionArgs[0]);
1426
1427 DeclDie = getDIE(D: SPDecl);
1428 assert(DeclDie && "This DIE should've already been constructed when the "
1429 "definition DIE was created in "
1430 "getOrCreateSubprogramDIE");
1431 // Look at the Decl's linkage name only if we emitted it.
1432 if (DD->useAllLinkageNames())
1433 DeclLinkageName = SPDecl->getLinkageName();
1434 unsigned DeclID = getOrCreateSourceID(File: SPDecl->getFile());
1435 unsigned DefID = getOrCreateSourceID(File: SP->getFile());
1436 if (DeclID != DefID)
1437 addUInt(Die&: SPDie, Attribute: dwarf::DW_AT_decl_file, Form: std::nullopt, Integer: DefID);
1438
1439 if (SP->getLine() != SPDecl->getLine())
1440 addUInt(Die&: SPDie, Attribute: dwarf::DW_AT_decl_line, Form: std::nullopt, Integer: SP->getLine());
1441 }
1442 }
1443
1444 // Add function template parameters.
1445 if (!Minimal || SP->isNameSimplified())
1446 addTemplateParams(Buffer&: SPDie, TParams: SP->getTemplateParams());
1447
1448 // Add the linkage name if we have one and it isn't in the Decl.
1449 StringRef LinkageName = SP->getLinkageName();
1450 // Always emit linkage name for abstract subprograms.
1451 if (DeclLinkageName != LinkageName &&
1452 (DD->useAllLinkageNames() || DU->getAbstractScopeDIEs().lookup(Val: SP)))
1453 addLinkageName(Die&: SPDie, LinkageName);
1454
1455 if (!DeclDie)
1456 return false;
1457
1458 // Refer to the function declaration where all the other attributes will be
1459 // found.
1460 addDIEEntry(Die&: SPDie, Attribute: dwarf::DW_AT_specification, Entry&: *DeclDie);
1461 return true;
1462}
1463
1464void DwarfUnit::applySubprogramAttributes(const DISubprogram *SP, DIE &SPDie,
1465 bool SkipSPAttributes) {
1466 // If -fdebug-info-for-profiling is enabled, need to emit the subprogram
1467 // and its source location.
1468 bool SkipSPSourceLocation = SkipSPAttributes &&
1469 !CUNode->getDebugInfoForProfiling();
1470 if (!SkipSPSourceLocation)
1471 if (applySubprogramDefinitionAttributes(SP, SPDie, Minimal: SkipSPAttributes))
1472 return;
1473
1474 // Constructors and operators for anonymous aggregates do not have names.
1475 if (!SP->getName().empty())
1476 addString(Die&: SPDie, Attribute: dwarf::DW_AT_name, String: SP->getName());
1477
1478 addAnnotation(Buffer&: SPDie, Annotations: SP->getAnnotations());
1479
1480 if (!SkipSPSourceLocation)
1481 addSourceLine(Die&: SPDie, SP);
1482
1483 // Skip the rest of the attributes under -gmlt to save space.
1484 if (SkipSPAttributes)
1485 return;
1486
1487 // Add the prototype if we have a prototype and we have a C like
1488 // language.
1489 if (SP->isPrototyped() && dwarf::isC(S: getSourceLanguage()))
1490 addFlag(Die&: SPDie, Attribute: dwarf::DW_AT_prototyped);
1491
1492 if (SP->isObjCDirect())
1493 addFlag(Die&: SPDie, Attribute: dwarf::DW_AT_APPLE_objc_direct);
1494
1495 unsigned CC = 0;
1496 DITypeArray Args;
1497 if (const DISubroutineType *SPTy = SP->getType()) {
1498 Args = SPTy->getTypeArray();
1499 CC = SPTy->getCC();
1500 }
1501
1502 // Add a DW_AT_calling_convention if this has an explicit convention.
1503 if (CC && CC != dwarf::DW_CC_normal)
1504 addUInt(Die&: SPDie, Attribute: dwarf::DW_AT_calling_convention, Form: dwarf::DW_FORM_data1, Integer: CC);
1505
1506 // Add a return type. If this is a type like a C/C++ void type we don't add a
1507 // return type.
1508 if (Args.size())
1509 if (auto Ty = Args[0])
1510 addType(Entity&: SPDie, Ty);
1511
1512 unsigned VK = SP->getVirtuality();
1513 if (VK) {
1514 addUInt(Die&: SPDie, Attribute: dwarf::DW_AT_virtuality, Form: dwarf::DW_FORM_data1, Integer: VK);
1515 if (SP->getVirtualIndex() != -1u) {
1516 DIELoc *Block = getDIELoc();
1517 addUInt(Block&: *Block, Form: dwarf::DW_FORM_data1, Integer: dwarf::DW_OP_constu);
1518 addUInt(Block&: *Block, Form: dwarf::DW_FORM_udata, Integer: SP->getVirtualIndex());
1519 addBlock(Die&: SPDie, Attribute: dwarf::DW_AT_vtable_elem_location, Loc: Block);
1520 }
1521 ContainingTypeMap.insert(KV: std::make_pair(x: &SPDie, y: SP->getContainingType()));
1522 }
1523
1524 if (!SP->isDefinition()) {
1525 addFlag(Die&: SPDie, Attribute: dwarf::DW_AT_declaration);
1526
1527 // Add arguments. Do not add arguments for subprogram definition. They will
1528 // be handled while processing variables.
1529 //
1530 // Encode the object pointer as an index instead of a DIE reference in order
1531 // to minimize the affect on the .debug_info size.
1532 if (std::optional<unsigned> ObjectPointerIndex =
1533 constructSubprogramArguments(Buffer&: SPDie, Args)) {
1534 if (getDwarfDebug().tuneForLLDB() &&
1535 getDwarfDebug().getDwarfVersion() >= 5) {
1536 // 0th index in Args is the return type, hence adjust by 1. In DWARF
1537 // we want the first parameter to be at index 0.
1538 assert(*ObjectPointerIndex > 0);
1539 addSInt(Die&: SPDie, Attribute: dwarf::DW_AT_object_pointer,
1540 Form: dwarf::DW_FORM_implicit_const, Integer: *ObjectPointerIndex - 1);
1541 }
1542 }
1543 }
1544
1545 addThrownTypes(Die&: SPDie, ThrownTypes: SP->getThrownTypes());
1546
1547 if (SP->isArtificial())
1548 addFlag(Die&: SPDie, Attribute: dwarf::DW_AT_artificial);
1549
1550 if (!SP->isLocalToUnit())
1551 addFlag(Die&: SPDie, Attribute: dwarf::DW_AT_external);
1552
1553 if (SP->isOptimized())
1554 addFlag(Die&: SPDie, Attribute: dwarf::DW_AT_APPLE_optimized);
1555
1556 if (DD->useAppleExtensionAttributes())
1557 if (unsigned isa = Asm->getISAEncoding())
1558 addUInt(Die&: SPDie, Attribute: dwarf::DW_AT_APPLE_isa, Form: dwarf::DW_FORM_flag, Integer: isa);
1559
1560 if (SP->isLValueReference())
1561 addFlag(Die&: SPDie, Attribute: dwarf::DW_AT_reference);
1562
1563 if (SP->isRValueReference())
1564 addFlag(Die&: SPDie, Attribute: dwarf::DW_AT_rvalue_reference);
1565
1566 if (SP->isNoReturn())
1567 addFlag(Die&: SPDie, Attribute: dwarf::DW_AT_noreturn);
1568
1569 addAccess(Die&: SPDie, Flags: SP->getFlags());
1570
1571 if (SP->isExplicit())
1572 addFlag(Die&: SPDie, Attribute: dwarf::DW_AT_explicit);
1573
1574 if (SP->isMainSubprogram())
1575 addFlag(Die&: SPDie, Attribute: dwarf::DW_AT_main_subprogram);
1576 if (SP->isPure())
1577 addFlag(Die&: SPDie, Attribute: dwarf::DW_AT_pure);
1578 if (SP->isElemental())
1579 addFlag(Die&: SPDie, Attribute: dwarf::DW_AT_elemental);
1580 if (SP->isRecursive())
1581 addFlag(Die&: SPDie, Attribute: dwarf::DW_AT_recursive);
1582
1583 if (!SP->getTargetFuncName().empty())
1584 addString(Die&: SPDie, Attribute: dwarf::DW_AT_trampoline, String: SP->getTargetFuncName());
1585
1586 if (DD->getDwarfVersion() >= 5 && SP->isDeleted())
1587 addFlag(Die&: SPDie, Attribute: dwarf::DW_AT_deleted);
1588}
1589
1590void DwarfUnit::constructSubrangeDIE(DIE &DW_Subrange, const DISubrangeType *SR,
1591 bool ForArray) {
1592 StringRef Name = SR->getName();
1593 if (!Name.empty())
1594 addString(Die&: DW_Subrange, Attribute: dwarf::DW_AT_name, String: Name);
1595
1596 if (SR->getBaseType())
1597 addType(Entity&: DW_Subrange, Ty: SR->getBaseType());
1598
1599 addSourceLine(Die&: DW_Subrange, Ty: SR);
1600
1601 if (uint64_t Size = SR->getSizeInBits())
1602 addUInt(Die&: DW_Subrange, Attribute: dwarf::DW_AT_byte_size, Form: std::nullopt, Integer: Size >> 3);
1603 if (uint32_t AlignInBytes = SR->getAlignInBytes())
1604 addUInt(Die&: DW_Subrange, Attribute: dwarf::DW_AT_alignment, Form: dwarf::DW_FORM_udata,
1605 Integer: AlignInBytes);
1606
1607 if (SR->isBigEndian())
1608 addUInt(Die&: DW_Subrange, Attribute: dwarf::DW_AT_endianity, Form: std::nullopt,
1609 Integer: dwarf::DW_END_big);
1610 else if (SR->isLittleEndian())
1611 addUInt(Die&: DW_Subrange, Attribute: dwarf::DW_AT_endianity, Form: std::nullopt,
1612 Integer: dwarf::DW_END_little);
1613
1614 // The LowerBound value defines the lower bounds which is typically
1615 // zero for C/C++. Values are 64 bit.
1616 int64_t DefaultLowerBound = getDefaultLowerBound();
1617
1618 auto AddBoundTypeEntry = [&](dwarf::Attribute Attr,
1619 DISubrangeType::BoundType Bound) -> void {
1620 if (auto *BV = dyn_cast_if_present<DIVariable *>(Val&: Bound)) {
1621 if (auto *VarDIE = getDIE(D: BV))
1622 addDIEEntry(Die&: DW_Subrange, Attribute: Attr, Entry&: *VarDIE);
1623 } else if (auto *DT = dyn_cast_if_present<DIDerivedType *>(Val&: Bound)) {
1624 if (auto *DTDIE = getDIE(D: DT))
1625 addDIEEntry(Die&: DW_Subrange, Attribute: Attr, Entry&: *DTDIE);
1626 } else if (auto *BE = dyn_cast_if_present<DIExpression *>(Val&: Bound)) {
1627 addBlock(Die&: DW_Subrange, Attribute: Attr, Expr: BE);
1628 } else if (auto *BI = dyn_cast_if_present<ConstantInt *>(Val&: Bound)) {
1629 if (Attr == dwarf::DW_AT_GNU_bias) {
1630 if (BI->getSExtValue() != 0)
1631 addUInt(Die&: DW_Subrange, Attribute: Attr, Form: dwarf::DW_FORM_sdata, Integer: BI->getSExtValue());
1632 } else if (Attr != dwarf::DW_AT_lower_bound || DefaultLowerBound == -1 ||
1633 BI->getSExtValue() != DefaultLowerBound || !ForArray)
1634 addSInt(Die&: DW_Subrange, Attribute: Attr, Form: dwarf::DW_FORM_sdata, Integer: BI->getSExtValue());
1635 }
1636 };
1637
1638 AddBoundTypeEntry(dwarf::DW_AT_lower_bound, SR->getLowerBound());
1639
1640 AddBoundTypeEntry(dwarf::DW_AT_upper_bound, SR->getUpperBound());
1641
1642 AddBoundTypeEntry(dwarf::DW_AT_bit_stride, SR->getStride());
1643
1644 AddBoundTypeEntry(dwarf::DW_AT_GNU_bias, SR->getBias());
1645}
1646
1647void DwarfUnit::constructSubrangeDIE(DIE &Buffer, const DISubrange *SR) {
1648 DIE &DW_Subrange = createAndAddDIE(Tag: dwarf::DW_TAG_subrange_type, Parent&: Buffer);
1649
1650 DIE *IdxTy = getIndexTyDie();
1651 addDIEEntry(Die&: DW_Subrange, Attribute: dwarf::DW_AT_type, Entry&: *IdxTy);
1652
1653 // The LowerBound value defines the lower bounds which is typically zero for
1654 // C/C++. The Count value is the number of elements. Values are 64 bit. If
1655 // Count == -1 then the array is unbounded and we do not emit
1656 // DW_AT_lower_bound and DW_AT_count attributes.
1657 int64_t DefaultLowerBound = getDefaultLowerBound();
1658
1659 auto AddBoundTypeEntry = [&](dwarf::Attribute Attr,
1660 DISubrange::BoundType Bound) -> void {
1661 if (auto *BV = dyn_cast_if_present<DIVariable *>(Val&: Bound)) {
1662 if (auto *VarDIE = getDIE(D: BV))
1663 addDIEEntry(Die&: DW_Subrange, Attribute: Attr, Entry&: *VarDIE);
1664 } else if (auto *BE = dyn_cast_if_present<DIExpression *>(Val&: Bound)) {
1665 addBlock(Die&: DW_Subrange, Attribute: Attr, Expr: BE);
1666 } else if (auto *BI = dyn_cast_if_present<ConstantInt *>(Val&: Bound)) {
1667 if (Attr == dwarf::DW_AT_count) {
1668 if (BI->getSExtValue() != -1)
1669 addUInt(Die&: DW_Subrange, Attribute: Attr, Form: std::nullopt, Integer: BI->getSExtValue());
1670 } else if (Attr != dwarf::DW_AT_lower_bound || DefaultLowerBound == -1 ||
1671 BI->getSExtValue() != DefaultLowerBound)
1672 addSInt(Die&: DW_Subrange, Attribute: Attr, Form: dwarf::DW_FORM_sdata, Integer: BI->getSExtValue());
1673 }
1674 };
1675
1676 AddBoundTypeEntry(dwarf::DW_AT_lower_bound, SR->getLowerBound());
1677
1678 AddBoundTypeEntry(dwarf::DW_AT_count, SR->getCount());
1679
1680 AddBoundTypeEntry(dwarf::DW_AT_upper_bound, SR->getUpperBound());
1681
1682 AddBoundTypeEntry(dwarf::DW_AT_byte_stride, SR->getStride());
1683}
1684
1685void DwarfUnit::constructGenericSubrangeDIE(DIE &Buffer,
1686 const DIGenericSubrange *GSR) {
1687 DIE &DwGenericSubrange =
1688 createAndAddDIE(Tag: dwarf::DW_TAG_generic_subrange, Parent&: Buffer);
1689 // Get an anonymous type for index type.
1690 // FIXME: This type should be passed down from the front end
1691 // as different languages may have different sizes for indexes.
1692 DIE *IdxTy = getIndexTyDie();
1693 addDIEEntry(Die&: DwGenericSubrange, Attribute: dwarf::DW_AT_type, Entry&: *IdxTy);
1694
1695 int64_t DefaultLowerBound = getDefaultLowerBound();
1696
1697 auto AddBoundTypeEntry = [&](dwarf::Attribute Attr,
1698 DIGenericSubrange::BoundType Bound) -> void {
1699 if (auto *BV = dyn_cast_if_present<DIVariable *>(Val&: Bound)) {
1700 if (auto *VarDIE = getDIE(D: BV))
1701 addDIEEntry(Die&: DwGenericSubrange, Attribute: Attr, Entry&: *VarDIE);
1702 } else if (auto *BE = dyn_cast_if_present<DIExpression *>(Val&: Bound)) {
1703 if (BE->isConstant() &&
1704 DIExpression::SignedOrUnsignedConstant::SignedConstant ==
1705 *BE->isConstant()) {
1706 if (Attr != dwarf::DW_AT_lower_bound || DefaultLowerBound == -1 ||
1707 static_cast<int64_t>(BE->getElement(I: 1)) != DefaultLowerBound)
1708 addSInt(Die&: DwGenericSubrange, Attribute: Attr, Form: dwarf::DW_FORM_sdata,
1709 Integer: BE->getElement(I: 1));
1710 } else {
1711 addBlock(Die&: DwGenericSubrange, Attribute: Attr, Expr: BE);
1712 }
1713 }
1714 };
1715
1716 AddBoundTypeEntry(dwarf::DW_AT_lower_bound, GSR->getLowerBound());
1717 AddBoundTypeEntry(dwarf::DW_AT_count, GSR->getCount());
1718 AddBoundTypeEntry(dwarf::DW_AT_upper_bound, GSR->getUpperBound());
1719 AddBoundTypeEntry(dwarf::DW_AT_byte_stride, GSR->getStride());
1720}
1721
1722DIE *DwarfUnit::getIndexTyDie() {
1723 if (IndexTyDie)
1724 return IndexTyDie;
1725 // Construct an integer type to use for indexes.
1726 IndexTyDie = &createAndAddDIE(Tag: dwarf::DW_TAG_base_type, Parent&: getUnitDie());
1727 StringRef Name = "__ARRAY_SIZE_TYPE__";
1728 addString(Die&: *IndexTyDie, Attribute: dwarf::DW_AT_name, String: Name);
1729 addUInt(Die&: *IndexTyDie, Attribute: dwarf::DW_AT_byte_size, Form: std::nullopt, Integer: sizeof(int64_t));
1730 addUInt(Die&: *IndexTyDie, Attribute: dwarf::DW_AT_encoding, Form: dwarf::DW_FORM_data1,
1731 Integer: dwarf::getArrayIndexTypeEncoding(S: getSourceLanguage()));
1732 DD->addAccelType(Unit: *this, NameTableKind: CUNode->getNameTableKind(), Name, Die: *IndexTyDie,
1733 /*Flags*/ 0);
1734 return IndexTyDie;
1735}
1736
1737/// Returns true if the vector's size differs from the sum of sizes of elements
1738/// the user specified. This can occur if the vector has been rounded up to
1739/// fit memory alignment constraints.
1740static bool hasVectorBeenPadded(const DICompositeType *CTy) {
1741 assert(CTy && CTy->isVector() && "Composite type is not a vector");
1742 const uint64_t ActualSize = CTy->getSizeInBits();
1743
1744 // Obtain the size of each element in the vector.
1745 DIType *BaseTy = CTy->getBaseType();
1746 assert(BaseTy && "Unknown vector element type.");
1747 const uint64_t ElementSize = BaseTy->getSizeInBits();
1748
1749 // Locate the number of elements in the vector.
1750 const DINodeArray Elements = CTy->getElements();
1751 assert(Elements.size() == 1 &&
1752 Elements[0]->getTag() == dwarf::DW_TAG_subrange_type &&
1753 "Invalid vector element array, expected one element of type subrange");
1754 const auto Subrange = cast<DISubrange>(Val: Elements[0]);
1755 const auto NumVecElements =
1756 Subrange->getCount()
1757 ? cast<ConstantInt *>(Val: Subrange->getCount())->getSExtValue()
1758 : 0;
1759
1760 // Ensure we found the element count and that the actual size is wide
1761 // enough to contain the requested size.
1762 assert(ActualSize >= (NumVecElements * ElementSize) && "Invalid vector size");
1763 return ActualSize != (NumVecElements * ElementSize);
1764}
1765
1766void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
1767 if (CTy->isVector()) {
1768 addFlag(Die&: Buffer, Attribute: dwarf::DW_AT_GNU_vector);
1769 if (hasVectorBeenPadded(CTy))
1770 addUInt(Die&: Buffer, Attribute: dwarf::DW_AT_byte_size, Form: std::nullopt,
1771 Integer: CTy->getSizeInBits() / CHAR_BIT);
1772 }
1773
1774 if (DIVariable *Var = CTy->getDataLocation()) {
1775 if (auto *VarDIE = getDIE(D: Var))
1776 addDIEEntry(Die&: Buffer, Attribute: dwarf::DW_AT_data_location, Entry&: *VarDIE);
1777 } else if (DIExpression *Expr = CTy->getDataLocationExp()) {
1778 addBlock(Die&: Buffer, Attribute: dwarf::DW_AT_data_location, Expr);
1779 }
1780
1781 if (DIVariable *Var = CTy->getAssociated()) {
1782 if (auto *VarDIE = getDIE(D: Var))
1783 addDIEEntry(Die&: Buffer, Attribute: dwarf::DW_AT_associated, Entry&: *VarDIE);
1784 } else if (DIExpression *Expr = CTy->getAssociatedExp()) {
1785 addBlock(Die&: Buffer, Attribute: dwarf::DW_AT_associated, Expr);
1786 }
1787
1788 if (DIVariable *Var = CTy->getAllocated()) {
1789 if (auto *VarDIE = getDIE(D: Var))
1790 addDIEEntry(Die&: Buffer, Attribute: dwarf::DW_AT_allocated, Entry&: *VarDIE);
1791 } else if (DIExpression *Expr = CTy->getAllocatedExp()) {
1792 addBlock(Die&: Buffer, Attribute: dwarf::DW_AT_allocated, Expr);
1793 }
1794
1795 if (auto *RankConst = CTy->getRankConst()) {
1796 addSInt(Die&: Buffer, Attribute: dwarf::DW_AT_rank, Form: dwarf::DW_FORM_sdata,
1797 Integer: RankConst->getSExtValue());
1798 } else if (auto *RankExpr = CTy->getRankExp()) {
1799 addBlock(Die&: Buffer, Attribute: dwarf::DW_AT_rank, Expr: RankExpr);
1800 }
1801
1802 if (auto *BitStride = CTy->getBitStrideConst()) {
1803 addUInt(Die&: Buffer, Attribute: dwarf::DW_AT_bit_stride, Form: {}, Integer: BitStride->getZExtValue());
1804 }
1805
1806 // Emit the element type.
1807 addType(Entity&: Buffer, Ty: CTy->getBaseType());
1808
1809 // Add subranges to array type.
1810 DINodeArray Elements = CTy->getElements();
1811 for (DINode *E : Elements) {
1812 if (auto *Element = dyn_cast_or_null<DISubrangeType>(Val: E)) {
1813 DIE &TyDIE = createAndAddDIE(Tag: Element->getTag(), Parent&: Buffer, N: CTy);
1814 constructSubrangeDIE(DW_Subrange&: TyDIE, SR: Element, ForArray: true);
1815 } else if (auto *Element = dyn_cast_or_null<DISubrange>(Val: E))
1816 constructSubrangeDIE(Buffer, SR: Element);
1817 else if (auto *Element = dyn_cast_or_null<DIGenericSubrange>(Val: E))
1818 constructGenericSubrangeDIE(Buffer, GSR: Element);
1819 }
1820}
1821
1822void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
1823 const DIType *DTy = CTy->getBaseType();
1824 bool IsUnsigned = DTy && DD->isUnsignedDIType(Ty: DTy);
1825 if (DTy) {
1826 if (!Asm->TM.Options.DebugStrictDwarf || DD->getDwarfVersion() >= 3)
1827 addType(Entity&: Buffer, Ty: DTy);
1828 if (DD->getDwarfVersion() >= 4 && (CTy->getFlags() & DINode::FlagEnumClass))
1829 addFlag(Die&: Buffer, Attribute: dwarf::DW_AT_enum_class);
1830 }
1831
1832 if (auto Kind = CTy->getEnumKind())
1833 addUInt(Die&: Buffer, Attribute: dwarf::DW_AT_APPLE_enum_kind, Form: dwarf::DW_FORM_data1, Integer: *Kind);
1834
1835 auto *Context = CTy->getScope();
1836 bool IndexEnumerators = !Context || isa<DICompileUnit>(Val: Context) || isa<DIFile>(Val: Context) ||
1837 isa<DINamespace>(Val: Context) || isa<DICommonBlock>(Val: Context);
1838 DINodeArray Elements = CTy->getElements();
1839
1840 // Add enumerators to enumeration type.
1841 for (const DINode *E : Elements) {
1842 auto *Enum = dyn_cast_or_null<DIEnumerator>(Val: E);
1843 if (Enum) {
1844 DIE &Enumerator = createAndAddDIE(Tag: dwarf::DW_TAG_enumerator, Parent&: Buffer);
1845 StringRef Name = Enum->getName();
1846 addString(Die&: Enumerator, Attribute: dwarf::DW_AT_name, String: Name);
1847 addConstantValue(Die&: Enumerator, Val: Enum->getValue(), Unsigned: IsUnsigned);
1848 if (IndexEnumerators)
1849 addGlobalName(Name, Die: Enumerator, Context);
1850 }
1851 }
1852}
1853
1854void DwarfUnit::constructContainingTypeDIEs() {
1855 for (auto &P : ContainingTypeMap) {
1856 DIE &SPDie = *P.first;
1857 const DINode *D = P.second;
1858 if (!D)
1859 continue;
1860 DIE *NDie = getDIE(D);
1861 if (!NDie)
1862 continue;
1863 addDIEEntry(Die&: SPDie, Attribute: dwarf::DW_AT_containing_type, Entry&: *NDie);
1864 }
1865}
1866
1867DIE &DwarfUnit::constructMemberDIE(DIE &Buffer, const DIDerivedType *DT) {
1868 DIE &MemberDie = createAndAddDIE(Tag: DT->getTag(), Parent&: Buffer, N: DT);
1869 StringRef Name = DT->getName();
1870 if (!Name.empty())
1871 addString(Die&: MemberDie, Attribute: dwarf::DW_AT_name, String: Name);
1872
1873 addAnnotation(Buffer&: MemberDie, Annotations: DT->getAnnotations());
1874
1875 if (DIType *Resolved = DT->getBaseType())
1876 addType(Entity&: MemberDie, Ty: Resolved);
1877
1878 addSourceLine(Die&: MemberDie, Ty: DT);
1879
1880 if (DT->getTag() == dwarf::DW_TAG_inheritance && DT->isVirtual()) {
1881
1882 // For C++, virtual base classes are not at fixed offset. Use following
1883 // expression to extract appropriate offset from vtable.
1884 // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1885
1886 DIELoc *VBaseLocationDie = new (DIEValueAllocator) DIELoc;
1887 addUInt(Block&: *VBaseLocationDie, Form: dwarf::DW_FORM_data1, Integer: dwarf::DW_OP_dup);
1888 addUInt(Block&: *VBaseLocationDie, Form: dwarf::DW_FORM_data1, Integer: dwarf::DW_OP_deref);
1889 addUInt(Block&: *VBaseLocationDie, Form: dwarf::DW_FORM_data1, Integer: dwarf::DW_OP_constu);
1890 addUInt(Block&: *VBaseLocationDie, Form: dwarf::DW_FORM_udata, Integer: DT->getOffsetInBits());
1891 addUInt(Block&: *VBaseLocationDie, Form: dwarf::DW_FORM_data1, Integer: dwarf::DW_OP_minus);
1892 addUInt(Block&: *VBaseLocationDie, Form: dwarf::DW_FORM_data1, Integer: dwarf::DW_OP_deref);
1893 addUInt(Block&: *VBaseLocationDie, Form: dwarf::DW_FORM_data1, Integer: dwarf::DW_OP_plus);
1894
1895 addBlock(Die&: MemberDie, Attribute: dwarf::DW_AT_data_member_location, Loc: VBaseLocationDie);
1896 } else {
1897 uint64_t Size = 0;
1898 uint64_t FieldSize = 0;
1899
1900 bool IsBitfield = DT->isBitField();
1901
1902 // Handle the size.
1903 if (DT->getRawSizeInBits() == nullptr) {
1904 // No size, just ignore.
1905 } else if (auto *Var = dyn_cast<DIVariable>(Val: DT->getRawSizeInBits())) {
1906 if (auto *VarDIE = getDIE(D: Var))
1907 addDIEEntry(Die&: MemberDie, Attribute: dwarf::DW_AT_bit_size, Entry&: *VarDIE);
1908 } else if (auto *Exp = dyn_cast<DIExpression>(Val: DT->getRawSizeInBits())) {
1909 addBlock(Die&: MemberDie, Attribute: dwarf::DW_AT_bit_size, Expr: Exp);
1910 } else {
1911 Size = DT->getSizeInBits();
1912 FieldSize = DD->getBaseTypeSize(Ty: DT);
1913 if (IsBitfield) {
1914 // Handle bitfield, assume bytes are 8 bits.
1915 if (DD->useDWARF2Bitfields())
1916 addUInt(Die&: MemberDie, Attribute: dwarf::DW_AT_byte_size, Form: std::nullopt,
1917 Integer: FieldSize / 8);
1918 addUInt(Die&: MemberDie, Attribute: dwarf::DW_AT_bit_size, Form: std::nullopt, Integer: Size);
1919 }
1920 }
1921
1922 // Handle the location. DW_AT_data_bit_offset won't allow an
1923 // expression until DWARF 6, but it can be used as an extension.
1924 // See https://dwarfstd.org/issues/250501.1.html
1925 if (auto *Var = dyn_cast_or_null<DIVariable>(Val: DT->getRawOffsetInBits())) {
1926 if (!Asm->TM.Options.DebugStrictDwarf || DD->getDwarfVersion() >= 6) {
1927 if (auto *VarDIE = getDIE(D: Var))
1928 addDIEEntry(Die&: MemberDie, Attribute: dwarf::DW_AT_data_bit_offset, Entry&: *VarDIE);
1929 }
1930 } else if (auto *Expr =
1931 dyn_cast_or_null<DIExpression>(Val: DT->getRawOffsetInBits())) {
1932 if (!Asm->TM.Options.DebugStrictDwarf || DD->getDwarfVersion() >= 6) {
1933 addBlock(Die&: MemberDie, Attribute: dwarf::DW_AT_data_bit_offset, Expr);
1934 }
1935 } else {
1936 uint32_t AlignInBytes = DT->getAlignInBytes();
1937 uint64_t OffsetInBytes;
1938
1939 if (IsBitfield) {
1940 assert(DT->getOffsetInBits() <=
1941 (uint64_t)std::numeric_limits<int64_t>::max());
1942 int64_t Offset = DT->getOffsetInBits();
1943 // We can't use DT->getAlignInBits() here: AlignInBits for member type
1944 // is non-zero if and only if alignment was forced (e.g. _Alignas()),
1945 // which can't be done with bitfields. Thus we use FieldSize here.
1946 uint32_t AlignInBits = FieldSize;
1947 uint32_t AlignMask = ~(AlignInBits - 1);
1948 // The bits from the start of the storage unit to the start of the
1949 // field.
1950 uint64_t StartBitOffset = Offset - (Offset & AlignMask);
1951 // The byte offset of the field's aligned storage unit inside the
1952 // struct.
1953 OffsetInBytes = (Offset - StartBitOffset) / 8;
1954
1955 if (DD->useDWARF2Bitfields()) {
1956 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1957 uint64_t FieldOffset = (HiMark - FieldSize);
1958 Offset -= FieldOffset;
1959
1960 // Maybe we need to work from the other end.
1961 if (Asm->getDataLayout().isLittleEndian())
1962 Offset = FieldSize - (Offset + Size);
1963
1964 if (Offset < 0)
1965 addSInt(Die&: MemberDie, Attribute: dwarf::DW_AT_bit_offset, Form: dwarf::DW_FORM_sdata,
1966 Integer: Offset);
1967 else
1968 addUInt(Die&: MemberDie, Attribute: dwarf::DW_AT_bit_offset, Form: std::nullopt,
1969 Integer: (uint64_t)Offset);
1970 OffsetInBytes = FieldOffset >> 3;
1971 } else {
1972 addUInt(Die&: MemberDie, Attribute: dwarf::DW_AT_data_bit_offset, Form: std::nullopt,
1973 Integer: Offset);
1974 }
1975 } else {
1976 // This is not a bitfield.
1977 OffsetInBytes = DT->getOffsetInBits() / 8;
1978 if (AlignInBytes)
1979 addUInt(Die&: MemberDie, Attribute: dwarf::DW_AT_alignment, Form: dwarf::DW_FORM_udata,
1980 Integer: AlignInBytes);
1981 }
1982
1983 if (DD->getDwarfVersion() <= 2) {
1984 DIELoc *MemLocationDie = new (DIEValueAllocator) DIELoc;
1985 addUInt(Block&: *MemLocationDie, Form: dwarf::DW_FORM_data1,
1986 Integer: dwarf::DW_OP_plus_uconst);
1987 addUInt(Block&: *MemLocationDie, Form: dwarf::DW_FORM_udata, Integer: OffsetInBytes);
1988 addBlock(Die&: MemberDie, Attribute: dwarf::DW_AT_data_member_location, Loc: MemLocationDie);
1989 } else if (!IsBitfield || DD->useDWARF2Bitfields()) {
1990 // In DWARF v3, DW_FORM_data4/8 in DW_AT_data_member_location are
1991 // interpreted as location-list pointers. Interpreting constants as
1992 // pointers is not expected, so we use DW_FORM_udata to encode the
1993 // constants here.
1994 if (DD->getDwarfVersion() == 3)
1995 addUInt(Die&: MemberDie, Attribute: dwarf::DW_AT_data_member_location,
1996 Form: dwarf::DW_FORM_udata, Integer: OffsetInBytes);
1997 else
1998 addUInt(Die&: MemberDie, Attribute: dwarf::DW_AT_data_member_location, Form: std::nullopt,
1999 Integer: OffsetInBytes);
2000 }
2001 }
2002 }
2003
2004 addAccess(Die&: MemberDie, Flags: DT->getFlags());
2005
2006 if (DT->isVirtual())
2007 addUInt(Die&: MemberDie, Attribute: dwarf::DW_AT_virtuality, Form: dwarf::DW_FORM_data1,
2008 Integer: dwarf::DW_VIRTUALITY_virtual);
2009
2010 // Objective-C properties.
2011 if (DINode *PNode = DT->getObjCProperty())
2012 if (DIE *PDie = getDIE(D: PNode))
2013 addAttribute(Die&: MemberDie, Attribute: dwarf::DW_AT_APPLE_property,
2014 Form: dwarf::DW_FORM_ref4, Value: DIEEntry(*PDie));
2015
2016 if (DT->isArtificial())
2017 addFlag(Die&: MemberDie, Attribute: dwarf::DW_AT_artificial);
2018
2019 return MemberDie;
2020}
2021
2022void DwarfUnit::constructPropertyDIE(DIE &Buffer, const DIProperty *P) {
2023 DIE &PropertyDie = createAndAddDIE(Tag: dwarf::DW_TAG_property, Parent&: Buffer, N: P);
2024 addString(Die&: PropertyDie, Attribute: dwarf::DW_AT_name, String: P->getName());
2025 if (DIType *Ty = P->getType())
2026 addType(Entity&: PropertyDie, Ty);
2027 addSourceLine(Die&: PropertyDie, P);
2028
2029 if (DINode *BackingStorage = P->getBackingStorage()) {
2030 DIE &GetterDie =
2031 createAndAddDIE(Tag: dwarf::DW_TAG_property_getter, Parent&: PropertyDie);
2032 PropertyForwardMap.insert(KV: std::make_pair(x: &GetterDie, y&: BackingStorage));
2033 }
2034}
2035
2036void DwarfUnit::constructPropertyForwardDIEs() {
2037 for (auto &P : PropertyForwardMap) {
2038 DIE &GetterDie = *P.first;
2039 const DINode *Target = P.second;
2040 if (!Target)
2041 continue;
2042 DIE *TargetDie = getDIE(D: Target);
2043 if (!TargetDie)
2044 continue;
2045 addDIEEntry(Die&: GetterDie, Attribute: dwarf::DW_AT_property_forward, Entry&: *TargetDie);
2046 }
2047}
2048
2049DIE *DwarfUnit::getOrCreateStaticMemberDIE(const DIDerivedType *DT) {
2050 if (!DT)
2051 return nullptr;
2052
2053 // Construct the context before querying for the existence of the DIE in case
2054 // such construction creates the DIE.
2055 DIE *ContextDIE = getOrCreateContextDIE(Context: DT->getScope());
2056 assert(dwarf::isType(ContextDIE->getTag()) &&
2057 "Static member should belong to a type.");
2058
2059 if (DIE *StaticMemberDIE = getDIE(D: DT))
2060 return StaticMemberDIE;
2061
2062 DwarfUnit *ContextUnit = static_cast<DwarfUnit *>(ContextDIE->getUnit());
2063 DIE &StaticMemberDIE = createAndAddDIE(Tag: DT->getTag(), Parent&: *ContextDIE, N: DT);
2064
2065 const DIType *Ty = DT->getBaseType();
2066
2067 addString(Die&: StaticMemberDIE, Attribute: dwarf::DW_AT_name, String: DT->getName());
2068 addType(Entity&: StaticMemberDIE, Ty);
2069 ContextUnit->addSourceLine(Die&: StaticMemberDIE, Ty: DT);
2070 addFlag(Die&: StaticMemberDIE, Attribute: dwarf::DW_AT_external);
2071 addFlag(Die&: StaticMemberDIE, Attribute: dwarf::DW_AT_declaration);
2072
2073 // Consider the case when the static member was created by the compiler.
2074 if (DT->isArtificial())
2075 addFlag(Die&: StaticMemberDIE, Attribute: dwarf::DW_AT_artificial);
2076
2077 // FIXME: We could omit private if the parent is a class_type, and
2078 // public if the parent is something else.
2079 addAccess(Die&: StaticMemberDIE, Flags: DT->getFlags());
2080
2081 if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(Val: DT->getConstant()))
2082 addConstantValue(Die&: StaticMemberDIE, CI, Ty);
2083 else if (const ConstantFP *CFP =
2084 dyn_cast_or_null<ConstantFP>(Val: DT->getConstant()))
2085 addConstantFPValue(Die&: StaticMemberDIE, CFP);
2086 else if (auto *CDS =
2087 dyn_cast_or_null<ConstantDataSequential>(Val: DT->getConstant())) {
2088 assert(CDS->getElementType()->isIntegerTy() &&
2089 "Non-integer arrays not supported.");
2090 DIEBlock *Block = new (DIEValueAllocator) DIEBlock;
2091 for (unsigned I = 0; I != CDS->getNumElements(); ++I)
2092 addIntToBlock(Block&: *Block, Val: CDS->getElementAsAPInt(i: I));
2093 Block->computeSize(FormParams: Asm->getDwarfFormParams());
2094 addBlock(Die&: StaticMemberDIE, Attribute: dwarf::DW_AT_const_value, Form: Block->BestForm(),
2095 Block);
2096 }
2097
2098 if (uint32_t AlignInBytes = DT->getAlignInBytes())
2099 addUInt(Die&: StaticMemberDIE, Attribute: dwarf::DW_AT_alignment, Form: dwarf::DW_FORM_udata,
2100 Integer: AlignInBytes);
2101
2102 return &StaticMemberDIE;
2103}
2104
2105void DwarfUnit::emitCommonHeader(bool UseOffsets, dwarf::UnitType UT) {
2106 // Emit size of content not including length itself
2107 if (!DD->useSectionsAsReferences())
2108 EndLabel = Asm->emitDwarfUnitLength(
2109 Prefix: isDwoUnit() ? "debug_info_dwo" : "debug_info", Comment: "Length of Unit");
2110 else
2111 Asm->emitDwarfUnitLength(Length: getHeaderSize() + getUnitDie().getSize(),
2112 Comment: "Length of Unit");
2113
2114 Asm->OutStreamer->AddComment(T: "DWARF version number");
2115 unsigned Version = DD->getDwarfVersion();
2116 Asm->emitInt16(Value: Version);
2117
2118 // DWARF v5 reorders the address size and adds a unit type.
2119 if (Version >= 5) {
2120 Asm->OutStreamer->AddComment(T: "DWARF Unit Type");
2121 Asm->emitInt8(Value: UT);
2122 Asm->OutStreamer->AddComment(T: "Address Size (in bytes)");
2123 Asm->emitInt8(Value: Asm->MAI.getCodePointerSize());
2124 }
2125
2126 // We share one abbreviations table across all units so it's always at the
2127 // start of the section. Use a relocatable offset where needed to ensure
2128 // linking doesn't invalidate that offset.
2129 Asm->OutStreamer->AddComment(T: "Offset Into Abbrev. Section");
2130 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
2131 if (UseOffsets)
2132 Asm->emitDwarfLengthOrOffset(Value: 0);
2133 else
2134 Asm->emitDwarfSymbolReference(
2135 Label: TLOF.getDwarfAbbrevSection()->getBeginSymbol(), ForceOffset: false);
2136
2137 if (Version <= 4) {
2138 Asm->OutStreamer->AddComment(T: "Address Size (in bytes)");
2139 Asm->emitInt8(Value: Asm->MAI.getCodePointerSize());
2140 }
2141}
2142
2143void DwarfTypeUnit::emitHeader(bool UseOffsets) {
2144 if (!DD->useSplitDwarf()) {
2145 LabelBegin = Asm->createTempSymbol(Name: "tu_begin");
2146 Asm->OutStreamer->emitLabel(Symbol: LabelBegin);
2147 }
2148 DwarfUnit::emitCommonHeader(UseOffsets,
2149 UT: DD->useSplitDwarf() ? dwarf::DW_UT_split_type
2150 : dwarf::DW_UT_type);
2151 Asm->OutStreamer->AddComment(T: "Type Signature");
2152 Asm->OutStreamer->emitIntValue(Value: TypeSignature, Size: sizeof(TypeSignature));
2153 Asm->OutStreamer->AddComment(T: "Type DIE Offset");
2154 // In a skeleton type unit there is no type DIE so emit a zero offset.
2155 Asm->emitDwarfLengthOrOffset(Value: Ty ? Ty->getOffset() : 0);
2156}
2157
2158void DwarfUnit::addSectionDelta(DIE &Die, dwarf::Attribute Attribute,
2159 const MCSymbol *Hi, const MCSymbol *Lo) {
2160 addAttribute(Die, Attribute, Form: DD->getDwarfSectionOffsetForm(),
2161 Value: new (DIEValueAllocator) DIEDelta(Hi, Lo));
2162}
2163
2164void DwarfUnit::addSectionLabel(DIE &Die, dwarf::Attribute Attribute,
2165 const MCSymbol *Label, const MCSymbol *Sec) {
2166 // If we are in an object file and not a DWO, emit a label. Otherwise we are
2167 // in a DWO and we cannot emit relocations, so emit a section delta.
2168 if (Asm->doesDwarfUseRelocationsAcrossSections() && !isDwoUnit())
2169 addLabel(Die, Attribute, Form: DD->getDwarfSectionOffsetForm(), Label);
2170 else
2171 addSectionDelta(Die, Attribute, Hi: Label, Lo: Sec);
2172}
2173
2174bool DwarfTypeUnit::isDwoUnit() const {
2175 // Since there are no skeleton type units, all type units are dwo type units
2176 // when split DWARF is being used.
2177 return DD->useSplitDwarf();
2178}
2179
2180void DwarfTypeUnit::addGlobalName(StringRef Name, const DIE &Die,
2181 const DIScope *Context) {
2182 getCU().addGlobalNameForTypeUnit(Name, Context);
2183}
2184
2185void DwarfTypeUnit::addGlobalTypeImpl(const DIType *Ty, const DIE &Die,
2186 const DIScope *Context) {
2187 getCU().addGlobalTypeUnitType(Ty, Context);
2188}
2189
2190const MCSymbol *DwarfUnit::getCrossSectionRelativeBaseAddress() const {
2191 if (!Asm->doesDwarfUseRelocationsAcrossSections())
2192 return nullptr;
2193 if (isDwoUnit())
2194 return nullptr;
2195 return getSection()->getBeginSymbol();
2196}
2197
2198void DwarfUnit::addStringOffsetsStart() {
2199 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
2200 addSectionLabel(Die&: getUnitDie(), Attribute: dwarf::DW_AT_str_offsets_base,
2201 Label: DU->getStringOffsetsStartSym(),
2202 Sec: TLOF.getDwarfStrOffSection()->getBeginSymbol());
2203}
2204
2205void DwarfUnit::addRnglistsBase() {
2206 assert(DD->getDwarfVersion() >= 5 &&
2207 "DW_AT_rnglists_base requires DWARF version 5 or later");
2208 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
2209 addSectionLabel(Die&: getUnitDie(), Attribute: dwarf::DW_AT_rnglists_base,
2210 Label: DU->getRnglistsTableBaseSym(),
2211 Sec: TLOF.getDwarfRnglistsSection()->getBeginSymbol());
2212}
2213
2214void DwarfTypeUnit::finishNonUnitTypeDIE(DIE& D, const DICompositeType *CTy) {
2215 DD->getAddressPool().resetUsedFlag(HasBeenUsed: true);
2216}
2217
2218bool DwarfUnit::isCompatibleWithVersion(uint16_t Version) const {
2219 return !Asm->TM.Options.DebugStrictDwarf || DD->getDwarfVersion() >= Version;
2220}
2221