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