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