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