1 //===-- llvm/CodeGen/DwarfUnit.cpp - Dwarf Type and Compile Units ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains support for constructing a dwarf compile unit.
12 //===----------------------------------------------------------------------===//
14 #include "DwarfUnit.h"
15 #include "DwarfAccelTable.h"
16 #include "DwarfCompileUnit.h"
17 #include "DwarfDebug.h"
18 #include "DwarfExpression.h"
19 #include "llvm/ADT/APFloat.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/DIBuilder.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/GlobalVariable.h"
25 #include "llvm/IR/Instructions.h"
26 #include "llvm/IR/Mangler.h"
27 #include "llvm/MC/MCAsmInfo.h"
28 #include "llvm/MC/MCContext.h"
29 #include "llvm/MC/MCSection.h"
30 #include "llvm/MC/MCStreamer.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Target/TargetFrameLowering.h"
33 #include "llvm/Target/TargetLoweringObjectFile.h"
34 #include "llvm/Target/TargetMachine.h"
35 #include "llvm/Target/TargetRegisterInfo.h"
36 #include "llvm/Target/TargetSubtargetInfo.h"
40 #define DEBUG_TYPE "dwarfdebug"
43 GenerateDwarfTypeUnits("generate-type-units", cl::Hidden,
44 cl::desc("Generate DWARF4 type units."),
47 DIEDwarfExpression::DIEDwarfExpression(const AsmPrinter &AP, DwarfUnit &DU,
49 : DwarfExpression(*AP.MF->getSubtarget().getRegisterInfo(),
50 AP.getDwarfDebug()->getDwarfVersion()),
51 AP(AP), DU(DU), DIE(DIE) {}
53 void DIEDwarfExpression::EmitOp(uint8_t Op, const char* Comment) {
54 DU.addUInt(DIE, dwarf::DW_FORM_data1, Op);
56 void DIEDwarfExpression::EmitSigned(int64_t Value) {
57 DU.addSInt(DIE, dwarf::DW_FORM_sdata, Value);
59 void DIEDwarfExpression::EmitUnsigned(uint64_t Value) {
60 DU.addUInt(DIE, dwarf::DW_FORM_udata, Value);
62 bool DIEDwarfExpression::isFrameRegister(unsigned MachineReg) {
63 return MachineReg == TRI.getFrameRegister(*AP.MF);
66 DwarfUnit::DwarfUnit(unsigned UID, dwarf::Tag UnitTag,
67 const DICompileUnit *Node, AsmPrinter *A, DwarfDebug *DW,
69 : UniqueID(UID), CUNode(Node), UnitDie(UnitTag), DebugInfoOffset(0), Asm(A),
70 DD(DW), DU(DWU), IndexTyDie(nullptr), Section(nullptr) {
71 assert(UnitTag == dwarf::DW_TAG_compile_unit ||
72 UnitTag == dwarf::DW_TAG_type_unit);
75 DwarfTypeUnit::DwarfTypeUnit(unsigned UID, DwarfCompileUnit &CU, AsmPrinter *A,
76 DwarfDebug *DW, DwarfFile *DWU,
77 MCDwarfDwoLineTable *SplitLineTable)
78 : DwarfUnit(UID, dwarf::DW_TAG_type_unit, CU.getCUNode(), A, DW, DWU),
79 CU(CU), SplitLineTable(SplitLineTable) {
81 addSectionOffset(UnitDie, dwarf::DW_AT_stmt_list, 0);
84 DwarfUnit::~DwarfUnit() {
85 for (unsigned j = 0, M = DIEBlocks.size(); j < M; ++j)
86 DIEBlocks[j]->~DIEBlock();
87 for (unsigned j = 0, M = DIELocs.size(); j < M; ++j)
88 DIELocs[j]->~DIELoc();
91 int64_t DwarfUnit::getDefaultLowerBound() const {
92 switch (getLanguage()) {
96 case dwarf::DW_LANG_C89:
97 case dwarf::DW_LANG_C99:
98 case dwarf::DW_LANG_C:
99 case dwarf::DW_LANG_C_plus_plus:
100 case dwarf::DW_LANG_ObjC:
101 case dwarf::DW_LANG_ObjC_plus_plus:
104 case dwarf::DW_LANG_Fortran77:
105 case dwarf::DW_LANG_Fortran90:
106 case dwarf::DW_LANG_Fortran95:
109 // The languages below have valid values only if the DWARF version >= 4.
110 case dwarf::DW_LANG_Java:
111 case dwarf::DW_LANG_Python:
112 case dwarf::DW_LANG_UPC:
113 case dwarf::DW_LANG_D:
114 if (dwarf::DWARF_VERSION >= 4)
118 case dwarf::DW_LANG_Ada83:
119 case dwarf::DW_LANG_Ada95:
120 case dwarf::DW_LANG_Cobol74:
121 case dwarf::DW_LANG_Cobol85:
122 case dwarf::DW_LANG_Modula2:
123 case dwarf::DW_LANG_Pascal83:
124 case dwarf::DW_LANG_PLI:
125 if (dwarf::DWARF_VERSION >= 4)
129 // The languages below have valid values only if the DWARF version >= 5.
130 case dwarf::DW_LANG_OpenCL:
131 case dwarf::DW_LANG_Go:
132 case dwarf::DW_LANG_Haskell:
133 case dwarf::DW_LANG_C_plus_plus_03:
134 case dwarf::DW_LANG_C_plus_plus_11:
135 case dwarf::DW_LANG_OCaml:
136 case dwarf::DW_LANG_Rust:
137 case dwarf::DW_LANG_C11:
138 case dwarf::DW_LANG_Swift:
139 case dwarf::DW_LANG_Dylan:
140 case dwarf::DW_LANG_C_plus_plus_14:
141 if (dwarf::DWARF_VERSION >= 5)
145 case dwarf::DW_LANG_Modula3:
146 case dwarf::DW_LANG_Julia:
147 case dwarf::DW_LANG_Fortran03:
148 case dwarf::DW_LANG_Fortran08:
149 if (dwarf::DWARF_VERSION >= 5)
157 /// Check whether the DIE for this MDNode can be shared across CUs.
158 static bool isShareableAcrossCUs(const DINode *D) {
159 // When the MDNode can be part of the type system, the DIE can be shared
161 // Combining type units and cross-CU DIE sharing is lower value (since
162 // cross-CU DIE sharing is used in LTO and removes type redundancy at that
163 // level already) but may be implementable for some value in projects
164 // building multiple independent libraries with LTO and then linking those
166 return (isa<DIType>(D) ||
167 (isa<DISubprogram>(D) && !cast<DISubprogram>(D)->isDefinition())) &&
168 !GenerateDwarfTypeUnits;
171 DIE *DwarfUnit::getDIE(const DINode *D) const {
172 if (isShareableAcrossCUs(D))
173 return DU->getDIE(D);
174 return MDNodeToDieMap.lookup(D);
177 void DwarfUnit::insertDIE(const DINode *Desc, DIE *D) {
178 if (isShareableAcrossCUs(Desc)) {
179 DU->insertDIE(Desc, D);
182 MDNodeToDieMap.insert(std::make_pair(Desc, D));
185 void DwarfUnit::addFlag(DIE &Die, dwarf::Attribute Attribute) {
186 if (DD->getDwarfVersion() >= 4)
187 Die.addValue(Attribute, dwarf::DW_FORM_flag_present, DIEInteger(1));
189 Die.addValue(Attribute, dwarf::DW_FORM_flag, DIEInteger(1));
192 void DwarfUnit::addUInt(DIE &Die, dwarf::Attribute Attribute,
193 Optional<dwarf::Form> Form, uint64_t Integer) {
195 Form = DIEInteger::BestForm(false, Integer);
196 Die.addValue(Attribute, *Form, DIEInteger(Integer));
199 void DwarfUnit::addUInt(DIE &Block, dwarf::Form Form, uint64_t Integer) {
200 addUInt(Block, (dwarf::Attribute)0, Form, Integer);
203 void DwarfUnit::addSInt(DIE &Die, dwarf::Attribute Attribute,
204 Optional<dwarf::Form> Form, int64_t Integer) {
206 Form = DIEInteger::BestForm(true, Integer);
207 Die.addValue(Attribute, *Form, DIEInteger(Integer));
210 void DwarfUnit::addSInt(DIELoc &Die, Optional<dwarf::Form> Form,
212 addSInt(Die, (dwarf::Attribute)0, Form, Integer);
215 void DwarfUnit::addString(DIE &Die, dwarf::Attribute Attribute,
217 Die.addValue(Attribute,
218 isDwoUnit() ? dwarf::DW_FORM_GNU_str_index : dwarf::DW_FORM_strp,
219 DIEString(DU->getStringPool().getEntry(*Asm, String)));
222 void DwarfUnit::addLabel(DIE &Die, dwarf::Attribute Attribute, dwarf::Form Form,
223 const MCSymbol *Label) {
224 Die.addValue(Attribute, Form, DIELabel(Label));
227 void DwarfUnit::addLabel(DIELoc &Die, dwarf::Form Form, const MCSymbol *Label) {
228 addLabel(Die, (dwarf::Attribute)0, Form, Label);
231 void DwarfUnit::addSectionOffset(DIE &Die, dwarf::Attribute Attribute,
233 if (DD->getDwarfVersion() >= 4)
234 addUInt(Die, Attribute, dwarf::DW_FORM_sec_offset, Integer);
236 addUInt(Die, Attribute, dwarf::DW_FORM_data4, Integer);
239 unsigned DwarfTypeUnit::getOrCreateSourceID(StringRef FileName, StringRef DirName) {
240 return SplitLineTable ? SplitLineTable->getFile(DirName, FileName)
241 : getCU().getOrCreateSourceID(FileName, DirName);
244 void DwarfUnit::addOpAddress(DIELoc &Die, const MCSymbol *Sym) {
245 if (!DD->useSplitDwarf()) {
246 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
247 addLabel(Die, dwarf::DW_FORM_udata, Sym);
249 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index);
250 addUInt(Die, dwarf::DW_FORM_GNU_addr_index,
251 DD->getAddressPool().getIndex(Sym));
255 void DwarfUnit::addLabelDelta(DIE &Die, dwarf::Attribute Attribute,
256 const MCSymbol *Hi, const MCSymbol *Lo) {
257 Die.addValue(Attribute, dwarf::DW_FORM_data4,
258 new (DIEValueAllocator) DIEDelta(Hi, Lo));
261 void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute, DIE &Entry) {
262 addDIEEntry(Die, Attribute, DIEEntry(Entry));
265 void DwarfUnit::addDIETypeSignature(DIE &Die, const DwarfTypeUnit &Type) {
266 // Flag the type unit reference as a declaration so that if it contains
267 // members (implicit special members, static data member definitions, member
268 // declarations for definitions in this CU, etc) consumers don't get confused
269 // and think this is a full definition.
270 addFlag(Die, dwarf::DW_AT_declaration);
272 Die.addValue(dwarf::DW_AT_signature, dwarf::DW_FORM_ref_sig8,
273 DIETypeSignature(Type));
276 void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute,
278 const DIE *DieCU = Die.getUnitOrNull();
279 const DIE *EntryCU = Entry.getEntry().getUnitOrNull();
281 // We assume that Die belongs to this CU, if it is not linked to any CU yet.
282 DieCU = &getUnitDie();
284 EntryCU = &getUnitDie();
285 Die.addValue(Attribute,
286 EntryCU == DieCU ? dwarf::DW_FORM_ref4 : dwarf::DW_FORM_ref_addr,
290 DIE &DwarfUnit::createAndAddDIE(unsigned Tag, DIE &Parent, const DINode *N) {
291 assert(Tag != dwarf::DW_TAG_auto_variable &&
292 Tag != dwarf::DW_TAG_arg_variable);
293 DIE &Die = Parent.addChild(make_unique<DIE>((dwarf::Tag)Tag));
299 void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute, DIELoc *Loc) {
300 Loc->ComputeSize(Asm);
301 DIELocs.push_back(Loc); // Memoize so we can call the destructor later on.
302 Die.addValue(Attribute, Loc->BestForm(DD->getDwarfVersion()), Loc);
305 void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute,
307 Block->ComputeSize(Asm);
308 DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
309 Die.addValue(Attribute, Block->BestForm(), Block);
312 void DwarfUnit::addSourceLine(DIE &Die, unsigned Line, StringRef File,
313 StringRef Directory) {
317 unsigned FileID = getOrCreateSourceID(File, Directory);
318 assert(FileID && "Invalid file id");
319 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
320 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
323 void DwarfUnit::addSourceLine(DIE &Die, const DILocalVariable *V) {
326 addSourceLine(Die, V->getLine(), V->getScope()->getFilename(),
327 V->getScope()->getDirectory());
330 void DwarfUnit::addSourceLine(DIE &Die, const DIGlobalVariable *G) {
333 addSourceLine(Die, G->getLine(), G->getFilename(), G->getDirectory());
336 void DwarfUnit::addSourceLine(DIE &Die, const DISubprogram *SP) {
339 addSourceLine(Die, SP->getLine(), SP->getFilename(), SP->getDirectory());
342 void DwarfUnit::addSourceLine(DIE &Die, const DIType *Ty) {
345 addSourceLine(Die, Ty->getLine(), Ty->getFilename(), Ty->getDirectory());
348 void DwarfUnit::addSourceLine(DIE &Die, const DIObjCProperty *Ty) {
351 addSourceLine(Die, Ty->getLine(), Ty->getFilename(), Ty->getDirectory());
354 void DwarfUnit::addSourceLine(DIE &Die, const DINamespace *NS) {
355 addSourceLine(Die, NS->getLine(), NS->getFilename(), NS->getDirectory());
358 bool DwarfUnit::addRegisterOpPiece(DIELoc &TheDie, unsigned Reg,
359 unsigned SizeInBits, unsigned OffsetInBits) {
360 DIEDwarfExpression Expr(*Asm, *this, TheDie);
361 Expr.AddMachineRegPiece(Reg, SizeInBits, OffsetInBits);
365 bool DwarfUnit::addRegisterOffset(DIELoc &TheDie, unsigned Reg,
367 DIEDwarfExpression Expr(*Asm, *this, TheDie);
368 return Expr.AddMachineRegIndirect(Reg, Offset);
371 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
372 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
373 gives the variable VarName either the struct, or a pointer to the struct, as
374 its type. This is necessary for various behind-the-scenes things the
375 compiler needs to do with by-reference variables in Blocks.
377 However, as far as the original *programmer* is concerned, the variable
378 should still have type 'SomeType', as originally declared.
380 The function getBlockByrefType dives into the __Block_byref_x_VarName
381 struct to find the original type of the variable, which is then assigned to
382 the variable's Debug Information Entry as its real type. So far, so good.
383 However now the debugger will expect the variable VarName to have the type
384 SomeType. So we need the location attribute for the variable to be an
385 expression that explains to the debugger how to navigate through the
386 pointers and struct to find the actual variable of type SomeType.
388 The following function does just that. We start by getting
389 the "normal" location for the variable. This will be the location
390 of either the struct __Block_byref_x_VarName or the pointer to the
391 struct __Block_byref_x_VarName.
393 The struct will look something like:
395 struct __Block_byref_x_VarName {
397 struct __Block_byref_x_VarName *forwarding;
398 ... <various other fields>
400 ... <maybe more fields>
403 If we are given the struct directly (as our starting point) we
404 need to tell the debugger to:
406 1). Add the offset of the forwarding field.
408 2). Follow that pointer to get the real __Block_byref_x_VarName
409 struct to use (the real one may have been copied onto the heap).
411 3). Add the offset for the field VarName, to find the actual variable.
413 If we started with a pointer to the struct, then we need to
414 dereference that pointer first, before the other steps.
415 Translating this into DWARF ops, we will need to append the following
416 to the current location description for the variable:
418 DW_OP_deref -- optional, if we start with a pointer
419 DW_OP_plus_uconst <forward_fld_offset>
421 DW_OP_plus_uconst <varName_fld_offset>
423 That is what this function does. */
425 void DwarfUnit::addBlockByrefAddress(const DbgVariable &DV, DIE &Die,
426 dwarf::Attribute Attribute,
427 const MachineLocation &Location) {
428 const DIType *Ty = DV.getType();
429 const DIType *TmpTy = Ty;
430 uint16_t Tag = Ty->getTag();
431 bool isPointer = false;
433 StringRef varName = DV.getName();
435 if (Tag == dwarf::DW_TAG_pointer_type) {
436 auto *DTy = cast<DIDerivedType>(Ty);
437 TmpTy = resolve(DTy->getBaseType());
441 // Find the __forwarding field and the variable field in the __Block_byref
443 DINodeArray Fields = cast<DICompositeTypeBase>(TmpTy)->getElements();
444 const DIDerivedType *varField = nullptr;
445 const DIDerivedType *forwardingField = nullptr;
447 for (unsigned i = 0, N = Fields.size(); i < N; ++i) {
448 auto *DT = cast<DIDerivedType>(Fields[i]);
449 StringRef fieldName = DT->getName();
450 if (fieldName == "__forwarding")
451 forwardingField = DT;
452 else if (fieldName == varName)
456 // Get the offsets for the forwarding field and the variable field.
457 unsigned forwardingFieldOffset = forwardingField->getOffsetInBits() >> 3;
458 unsigned varFieldOffset = varField->getOffsetInBits() >> 2;
460 // Decode the original location, and use that as the start of the byref
461 // variable's location.
462 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
465 if (Location.isReg())
466 validReg = addRegisterOpPiece(*Loc, Location.getReg());
468 validReg = addRegisterOffset(*Loc, Location.getReg(), Location.getOffset());
473 // If we started with a pointer to the __Block_byref... struct, then
474 // the first thing we need to do is dereference the pointer (DW_OP_deref).
476 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
478 // Next add the offset for the '__forwarding' field:
479 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
480 // adding the offset if it's 0.
481 if (forwardingFieldOffset > 0) {
482 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
483 addUInt(*Loc, dwarf::DW_FORM_udata, forwardingFieldOffset);
486 // Now dereference the __forwarding field to get to the real __Block_byref
487 // struct: DW_OP_deref.
488 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
490 // Now that we've got the real __Block_byref... struct, add the offset
491 // for the variable's field to get to the location of the actual variable:
492 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
493 if (varFieldOffset > 0) {
494 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
495 addUInt(*Loc, dwarf::DW_FORM_udata, varFieldOffset);
498 // Now attach the location information to the DIE.
499 addBlock(Die, Attribute, Loc);
502 /// Return true if type encoding is unsigned.
503 static bool isUnsignedDIType(DwarfDebug *DD, const DIType *Ty) {
504 if (auto *DTy = dyn_cast<DIDerivedTypeBase>(Ty)) {
505 dwarf::Tag T = (dwarf::Tag)Ty->getTag();
506 // Encode pointer constants as unsigned bytes. This is used at least for
507 // null pointer constant emission.
508 // (Pieces of) aggregate types that get hacked apart by SROA may also be
509 // represented by a constant. Encode them as unsigned bytes.
510 // FIXME: reference and rvalue_reference /probably/ shouldn't be allowed
511 // here, but accept them for now due to a bug in SROA producing bogus
513 if (T == dwarf::DW_TAG_array_type ||
514 T == dwarf::DW_TAG_class_type ||
515 T == dwarf::DW_TAG_pointer_type ||
516 T == dwarf::DW_TAG_ptr_to_member_type ||
517 T == dwarf::DW_TAG_reference_type ||
518 T == dwarf::DW_TAG_rvalue_reference_type ||
519 T == dwarf::DW_TAG_structure_type ||
520 T == dwarf::DW_TAG_union_type)
522 assert(T == dwarf::DW_TAG_typedef || T == dwarf::DW_TAG_const_type ||
523 T == dwarf::DW_TAG_volatile_type ||
524 T == dwarf::DW_TAG_restrict_type ||
525 T == dwarf::DW_TAG_enumeration_type);
526 if (DITypeRef Deriv = DTy->getBaseType())
527 return isUnsignedDIType(DD, DD->resolve(Deriv));
528 // FIXME: Enums without a fixed underlying type have unknown signedness
529 // here, leading to incorrectly emitted constants.
530 assert(DTy->getTag() == dwarf::DW_TAG_enumeration_type);
534 auto *BTy = cast<DIBasicType>(Ty);
535 unsigned Encoding = BTy->getEncoding();
536 assert((Encoding == dwarf::DW_ATE_unsigned ||
537 Encoding == dwarf::DW_ATE_unsigned_char ||
538 Encoding == dwarf::DW_ATE_signed ||
539 Encoding == dwarf::DW_ATE_signed_char ||
540 Encoding == dwarf::DW_ATE_float || Encoding == dwarf::DW_ATE_UTF ||
541 Encoding == dwarf::DW_ATE_boolean ||
542 (Ty->getTag() == dwarf::DW_TAG_unspecified_type &&
543 Ty->getName() == "decltype(nullptr)")) &&
544 "Unsupported encoding");
545 return Encoding == dwarf::DW_ATE_unsigned ||
546 Encoding == dwarf::DW_ATE_unsigned_char ||
547 Encoding == dwarf::DW_ATE_UTF || Encoding == dwarf::DW_ATE_boolean ||
548 Ty->getTag() == dwarf::DW_TAG_unspecified_type;
551 /// If this type is derived from a base type then return base type size.
552 static uint64_t getBaseTypeSize(DwarfDebug *DD, const DIDerivedType *Ty) {
553 unsigned Tag = Ty->getTag();
555 if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef &&
556 Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type &&
557 Tag != dwarf::DW_TAG_restrict_type)
558 return Ty->getSizeInBits();
560 auto *BaseType = DD->resolve(Ty->getBaseType());
562 assert(BaseType && "Unexpected invalid base type");
564 // If this is a derived type, go ahead and get the base type, unless it's a
565 // reference then it's just the size of the field. Pointer types have no need
566 // of this since they're a different type of qualification on the type.
567 if (BaseType->getTag() == dwarf::DW_TAG_reference_type ||
568 BaseType->getTag() == dwarf::DW_TAG_rvalue_reference_type)
569 return Ty->getSizeInBits();
571 if (auto *DT = dyn_cast<DIDerivedType>(BaseType))
572 return getBaseTypeSize(DD, DT);
574 return BaseType->getSizeInBits();
577 void DwarfUnit::addConstantFPValue(DIE &Die, const MachineOperand &MO) {
578 assert(MO.isFPImm() && "Invalid machine operand!");
579 DIEBlock *Block = new (DIEValueAllocator) DIEBlock;
580 APFloat FPImm = MO.getFPImm()->getValueAPF();
582 // Get the raw data form of the floating point.
583 const APInt FltVal = FPImm.bitcastToAPInt();
584 const char *FltPtr = (const char *)FltVal.getRawData();
586 int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
587 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
588 int Incr = (LittleEndian ? 1 : -1);
589 int Start = (LittleEndian ? 0 : NumBytes - 1);
590 int Stop = (LittleEndian ? NumBytes : -1);
592 // Output the constant to DWARF one byte at a time.
593 for (; Start != Stop; Start += Incr)
594 addUInt(*Block, dwarf::DW_FORM_data1, (unsigned char)0xFF & FltPtr[Start]);
596 addBlock(Die, dwarf::DW_AT_const_value, Block);
599 void DwarfUnit::addConstantFPValue(DIE &Die, const ConstantFP *CFP) {
600 // Pass this down to addConstantValue as an unsigned bag of bits.
601 addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true);
604 void DwarfUnit::addConstantValue(DIE &Die, const ConstantInt *CI,
606 addConstantValue(Die, CI->getValue(), Ty);
609 void DwarfUnit::addConstantValue(DIE &Die, const MachineOperand &MO,
611 assert(MO.isImm() && "Invalid machine operand!");
613 addConstantValue(Die, isUnsignedDIType(DD, Ty), MO.getImm());
616 void DwarfUnit::addConstantValue(DIE &Die, bool Unsigned, uint64_t Val) {
617 // FIXME: This is a bit conservative/simple - it emits negative values always
618 // sign extended to 64 bits rather than minimizing the number of bytes.
619 addUInt(Die, dwarf::DW_AT_const_value,
620 Unsigned ? dwarf::DW_FORM_udata : dwarf::DW_FORM_sdata, Val);
623 void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, const DIType *Ty) {
624 addConstantValue(Die, Val, isUnsignedDIType(DD, Ty));
627 void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, bool Unsigned) {
628 unsigned CIBitWidth = Val.getBitWidth();
629 if (CIBitWidth <= 64) {
630 addConstantValue(Die, Unsigned,
631 Unsigned ? Val.getZExtValue() : Val.getSExtValue());
635 DIEBlock *Block = new (DIEValueAllocator) DIEBlock;
637 // Get the raw data form of the large APInt.
638 const uint64_t *Ptr64 = Val.getRawData();
640 int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
641 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
643 // Output the constant to DWARF one byte at a time.
644 for (int i = 0; i < NumBytes; i++) {
647 c = Ptr64[i / 8] >> (8 * (i & 7));
649 c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
650 addUInt(*Block, dwarf::DW_FORM_data1, c);
653 addBlock(Die, dwarf::DW_AT_const_value, Block);
656 void DwarfUnit::addLinkageName(DIE &Die, StringRef LinkageName) {
657 if (!LinkageName.empty())
659 DD->getDwarfVersion() >= 4 ? dwarf::DW_AT_linkage_name
660 : dwarf::DW_AT_MIPS_linkage_name,
661 GlobalValue::getRealLinkageName(LinkageName));
664 void DwarfUnit::addTemplateParams(DIE &Buffer, DINodeArray TParams) {
665 // Add template parameters.
666 for (const auto *Element : TParams) {
667 if (auto *TTP = dyn_cast<DITemplateTypeParameter>(Element))
668 constructTemplateTypeParameterDIE(Buffer, TTP);
669 else if (auto *TVP = dyn_cast<DITemplateValueParameter>(Element))
670 constructTemplateValueParameterDIE(Buffer, TVP);
674 DIE *DwarfUnit::getOrCreateContextDIE(const DIScope *Context) {
675 if (!Context || isa<DIFile>(Context))
676 return &getUnitDie();
677 if (auto *T = dyn_cast<DIType>(Context))
678 return getOrCreateTypeDIE(T);
679 if (auto *NS = dyn_cast<DINamespace>(Context))
680 return getOrCreateNameSpace(NS);
681 if (auto *SP = dyn_cast<DISubprogram>(Context))
682 return getOrCreateSubprogramDIE(SP);
683 return getDIE(Context);
686 DIE *DwarfUnit::createTypeDIE(const DICompositeType *Ty) {
687 auto *Context = resolve(Ty->getScope());
688 DIE *ContextDIE = getOrCreateContextDIE(Context);
690 if (DIE *TyDIE = getDIE(Ty))
694 DIE &TyDIE = createAndAddDIE(Ty->getTag(), *ContextDIE, Ty);
696 constructTypeDIE(TyDIE, cast<DICompositeType>(Ty));
698 updateAcceleratorTables(Context, Ty, TyDIE);
702 DIE *DwarfUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
706 auto *Ty = cast<DIType>(TyNode);
707 assert(Ty == resolve(Ty->getRef()) &&
708 "type was not uniqued, possible ODR violation.");
710 // DW_TAG_restrict_type is not supported in DWARF2
711 if (Ty->getTag() == dwarf::DW_TAG_restrict_type && DD->getDwarfVersion() <= 2)
712 return getOrCreateTypeDIE(resolve(cast<DIDerivedType>(Ty)->getBaseType()));
714 // Construct the context before querying for the existence of the DIE in case
715 // such construction creates the DIE.
716 auto *Context = resolve(Ty->getScope());
717 DIE *ContextDIE = getOrCreateContextDIE(Context);
720 if (DIE *TyDIE = getDIE(Ty))
724 DIE &TyDIE = createAndAddDIE(Ty->getTag(), *ContextDIE, Ty);
726 updateAcceleratorTables(Context, Ty, TyDIE);
728 if (auto *BT = dyn_cast<DIBasicType>(Ty))
729 constructTypeDIE(TyDIE, BT);
730 else if (auto *STy = dyn_cast<DISubroutineType>(Ty))
731 constructTypeDIE(TyDIE, STy);
732 else if (auto *CTy = dyn_cast<DICompositeType>(Ty)) {
733 if (GenerateDwarfTypeUnits && !Ty->isForwardDecl())
734 if (MDString *TypeId = CTy->getRawIdentifier()) {
735 DD->addDwarfTypeUnitType(getCU(), TypeId->getString(), TyDIE, CTy);
736 // Skip updating the accelerator tables since this is not the full type.
739 constructTypeDIE(TyDIE, CTy);
741 constructTypeDIE(TyDIE, cast<DIDerivedType>(Ty));
747 void DwarfUnit::updateAcceleratorTables(const DIScope *Context,
748 const DIType *Ty, const DIE &TyDIE) {
749 if (!Ty->getName().empty() && !Ty->isForwardDecl()) {
750 bool IsImplementation = 0;
751 if (auto *CT = dyn_cast<DICompositeTypeBase>(Ty)) {
752 // A runtime language of 0 actually means C/C++ and that any
753 // non-negative value is some version of Objective-C/C++.
754 IsImplementation = CT->getRuntimeLang() == 0 || CT->isObjcClassComplete();
756 unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0;
757 DD->addAccelType(Ty->getName(), TyDIE, Flags);
759 if (!Context || isa<DICompileUnit>(Context) || isa<DIFile>(Context) ||
760 isa<DINamespace>(Context))
761 addGlobalType(Ty, TyDIE, Context);
765 void DwarfUnit::addType(DIE &Entity, const DIType *Ty,
766 dwarf::Attribute Attribute) {
767 assert(Ty && "Trying to add a type that doesn't exist?");
768 addDIEEntry(Entity, Attribute, DIEEntry(*getOrCreateTypeDIE(Ty)));
771 std::string DwarfUnit::getParentContextString(const DIScope *Context) const {
775 // FIXME: Decide whether to implement this for non-C++ languages.
776 if (getLanguage() != dwarf::DW_LANG_C_plus_plus)
780 SmallVector<const DIScope *, 1> Parents;
781 while (!isa<DICompileUnit>(Context)) {
782 Parents.push_back(Context);
783 if (Context->getScope())
784 Context = resolve(Context->getScope());
786 // Structure, etc types will have a NULL context if they're at the top
791 // Reverse iterate over our list to go from the outermost construct to the
793 for (auto I = Parents.rbegin(), E = Parents.rend(); I != E; ++I) {
794 const DIScope *Ctx = *I;
795 StringRef Name = Ctx->getName();
796 if (Name.empty() && isa<DINamespace>(Ctx))
797 Name = "(anonymous namespace)";
806 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DIBasicType *BTy) {
807 // Get core information.
808 StringRef Name = BTy->getName();
809 // Add name if not anonymous or intermediate type.
811 addString(Buffer, dwarf::DW_AT_name, Name);
813 // An unspecified type only has a name attribute.
814 if (BTy->getTag() == dwarf::DW_TAG_unspecified_type)
817 addUInt(Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
820 uint64_t Size = BTy->getSizeInBits() >> 3;
821 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
824 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DIDerivedType *DTy) {
825 // Get core information.
826 StringRef Name = DTy->getName();
827 uint64_t Size = DTy->getSizeInBits() >> 3;
828 uint16_t Tag = Buffer.getTag();
830 // Map to main type, void will not have a type.
831 const DIType *FromTy = resolve(DTy->getBaseType());
833 addType(Buffer, FromTy);
835 // Add name if not anonymous or intermediate type.
837 addString(Buffer, dwarf::DW_AT_name, Name);
839 // Add size if non-zero (derived types might be zero-sized.)
840 if (Size && Tag != dwarf::DW_TAG_pointer_type
841 && Tag != dwarf::DW_TAG_ptr_to_member_type)
842 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
844 if (Tag == dwarf::DW_TAG_ptr_to_member_type)
846 Buffer, dwarf::DW_AT_containing_type,
847 *getOrCreateTypeDIE(resolve(cast<DIDerivedType>(DTy)->getClassType())));
848 // Add source line info if available and TyDesc is not a forward declaration.
849 if (!DTy->isForwardDecl())
850 addSourceLine(Buffer, DTy);
853 void DwarfUnit::constructSubprogramArguments(DIE &Buffer, DITypeRefArray Args) {
854 for (unsigned i = 1, N = Args.size(); i < N; ++i) {
855 const DIType *Ty = resolve(Args[i]);
857 assert(i == N-1 && "Unspecified parameter must be the last argument");
858 createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
860 DIE &Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
862 if (Ty->isArtificial())
863 addFlag(Arg, dwarf::DW_AT_artificial);
868 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DISubroutineType *CTy) {
869 // Add return type. A void return won't have a type.
870 auto Elements = cast<DISubroutineType>(CTy)->getTypeArray();
872 if (auto RTy = resolve(Elements[0]))
873 addType(Buffer, RTy);
875 bool isPrototyped = true;
876 if (Elements.size() == 2 && !Elements[1])
877 isPrototyped = false;
879 constructSubprogramArguments(Buffer, Elements);
881 // Add prototype flag if we're dealing with a C language and the function has
883 uint16_t Language = getLanguage();
885 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
886 Language == dwarf::DW_LANG_ObjC))
887 addFlag(Buffer, dwarf::DW_AT_prototyped);
889 if (CTy->isLValueReference())
890 addFlag(Buffer, dwarf::DW_AT_reference);
892 if (CTy->isRValueReference())
893 addFlag(Buffer, dwarf::DW_AT_rvalue_reference);
896 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
897 // Add name if not anonymous or intermediate type.
898 StringRef Name = CTy->getName();
900 uint64_t Size = CTy->getSizeInBits() >> 3;
901 uint16_t Tag = Buffer.getTag();
904 case dwarf::DW_TAG_array_type:
905 constructArrayTypeDIE(Buffer, CTy);
907 case dwarf::DW_TAG_enumeration_type:
908 constructEnumTypeDIE(Buffer, CTy);
910 case dwarf::DW_TAG_structure_type:
911 case dwarf::DW_TAG_union_type:
912 case dwarf::DW_TAG_class_type: {
913 // Add elements to structure type.
914 DINodeArray Elements = CTy->getElements();
915 for (const auto *Element : Elements) {
918 if (auto *SP = dyn_cast<DISubprogram>(Element))
919 getOrCreateSubprogramDIE(SP);
920 else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
921 if (DDTy->getTag() == dwarf::DW_TAG_friend) {
922 DIE &ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
923 addType(ElemDie, resolve(DDTy->getBaseType()), dwarf::DW_AT_friend);
924 } else if (DDTy->isStaticMember()) {
925 getOrCreateStaticMemberDIE(DDTy);
927 constructMemberDIE(Buffer, DDTy);
929 } else if (auto *Property = dyn_cast<DIObjCProperty>(Element)) {
930 DIE &ElemDie = createAndAddDIE(Property->getTag(), Buffer);
931 StringRef PropertyName = Property->getName();
932 addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
933 if (Property->getType())
934 addType(ElemDie, resolve(Property->getType()));
935 addSourceLine(ElemDie, Property);
936 StringRef GetterName = Property->getGetterName();
937 if (!GetterName.empty())
938 addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
939 StringRef SetterName = Property->getSetterName();
940 if (!SetterName.empty())
941 addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
942 if (unsigned PropertyAttributes = Property->getAttributes())
943 addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None,
948 if (CTy->isAppleBlockExtension())
949 addFlag(Buffer, dwarf::DW_AT_APPLE_block);
951 // This is outside the DWARF spec, but GDB expects a DW_AT_containing_type
952 // inside C++ composite types to point to the base class with the vtable.
953 if (auto *ContainingType =
954 dyn_cast_or_null<DICompositeType>(resolve(CTy->getVTableHolder())))
955 addDIEEntry(Buffer, dwarf::DW_AT_containing_type,
956 *getOrCreateTypeDIE(ContainingType));
958 if (CTy->isObjcClassComplete())
959 addFlag(Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
961 // Add template parameters to a class, structure or union types.
962 // FIXME: The support isn't in the metadata for this yet.
963 if (Tag == dwarf::DW_TAG_class_type ||
964 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
965 addTemplateParams(Buffer, CTy->getTemplateParams());
973 // Add name if not anonymous or intermediate type.
975 addString(Buffer, dwarf::DW_AT_name, Name);
977 if (Tag == dwarf::DW_TAG_enumeration_type ||
978 Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
979 Tag == dwarf::DW_TAG_union_type) {
980 // Add size if non-zero (derived types might be zero-sized.)
981 // TODO: Do we care about size for enum forward declarations?
983 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
984 else if (!CTy->isForwardDecl())
985 // Add zero size if it is not a forward declaration.
986 addUInt(Buffer, dwarf::DW_AT_byte_size, None, 0);
988 // If we're a forward decl, say so.
989 if (CTy->isForwardDecl())
990 addFlag(Buffer, dwarf::DW_AT_declaration);
992 // Add source line info if available.
993 if (!CTy->isForwardDecl())
994 addSourceLine(Buffer, CTy);
996 // No harm in adding the runtime language to the declaration.
997 unsigned RLang = CTy->getRuntimeLang();
999 addUInt(Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
1004 void DwarfUnit::constructTemplateTypeParameterDIE(
1005 DIE &Buffer, const DITemplateTypeParameter *TP) {
1007 createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
1008 // Add the type if it exists, it could be void and therefore no type.
1010 addType(ParamDIE, resolve(TP->getType()));
1011 if (!TP->getName().empty())
1012 addString(ParamDIE, dwarf::DW_AT_name, TP->getName());
1015 void DwarfUnit::constructTemplateValueParameterDIE(
1016 DIE &Buffer, const DITemplateValueParameter *VP) {
1017 DIE &ParamDIE = createAndAddDIE(VP->getTag(), Buffer);
1019 // Add the type if there is one, template template and template parameter
1020 // packs will not have a type.
1021 if (VP->getTag() == dwarf::DW_TAG_template_value_parameter)
1022 addType(ParamDIE, resolve(VP->getType()));
1023 if (!VP->getName().empty())
1024 addString(ParamDIE, dwarf::DW_AT_name, VP->getName());
1025 if (Metadata *Val = VP->getValue()) {
1026 if (ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(Val))
1027 addConstantValue(ParamDIE, CI, resolve(VP->getType()));
1028 else if (GlobalValue *GV = mdconst::dyn_extract<GlobalValue>(Val)) {
1029 // For declaration non-type template parameters (such as global values and
1031 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
1032 addOpAddress(*Loc, Asm->getSymbol(GV));
1033 // Emit DW_OP_stack_value to use the address as the immediate value of the
1034 // parameter, rather than a pointer to it.
1035 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
1036 addBlock(ParamDIE, dwarf::DW_AT_location, Loc);
1037 } else if (VP->getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1038 assert(isa<MDString>(Val));
1039 addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
1040 cast<MDString>(Val)->getString());
1041 } else if (VP->getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1042 addTemplateParams(ParamDIE, cast<MDTuple>(Val));
1047 DIE *DwarfUnit::getOrCreateNameSpace(const DINamespace *NS) {
1048 // Construct the context before querying for the existence of the DIE in case
1049 // such construction creates the DIE.
1050 DIE *ContextDIE = getOrCreateContextDIE(NS->getScope());
1052 if (DIE *NDie = getDIE(NS))
1054 DIE &NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS);
1056 StringRef Name = NS->getName();
1058 addString(NDie, dwarf::DW_AT_name, NS->getName());
1060 Name = "(anonymous namespace)";
1061 DD->addAccelNamespace(Name, NDie);
1062 addGlobalName(Name, NDie, NS->getScope());
1063 addSourceLine(NDie, NS);
1067 DIE *DwarfUnit::getOrCreateSubprogramDIE(const DISubprogram *SP, bool Minimal) {
1068 // Construct the context before querying for the existence of the DIE in case
1069 // such construction creates the DIE (as is the case for member function
1072 Minimal ? &getUnitDie() : getOrCreateContextDIE(resolve(SP->getScope()));
1074 if (DIE *SPDie = getDIE(SP))
1077 if (auto *SPDecl = SP->getDeclaration()) {
1079 // Add subprogram definitions to the CU die directly.
1080 ContextDIE = &getUnitDie();
1081 // Build the decl now to ensure it precedes the definition.
1082 getOrCreateSubprogramDIE(SPDecl);
1086 // DW_TAG_inlined_subroutine may refer to this DIE.
1087 DIE &SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
1089 // Stop here and fill this in later, depending on whether or not this
1090 // subprogram turns out to have inlined instances or not.
1091 if (SP->isDefinition())
1094 applySubprogramAttributes(SP, SPDie);
1098 bool DwarfUnit::applySubprogramDefinitionAttributes(const DISubprogram *SP,
1100 DIE *DeclDie = nullptr;
1101 StringRef DeclLinkageName;
1102 if (auto *SPDecl = SP->getDeclaration()) {
1103 DeclDie = getDIE(SPDecl);
1104 assert(DeclDie && "This DIE should've already been constructed when the "
1105 "definition DIE was created in "
1106 "getOrCreateSubprogramDIE");
1107 DeclLinkageName = SPDecl->getLinkageName();
1110 // Add function template parameters.
1111 addTemplateParams(SPDie, SP->getTemplateParams());
1113 // Add the linkage name if we have one and it isn't in the Decl.
1114 StringRef LinkageName = SP->getLinkageName();
1115 assert(((LinkageName.empty() || DeclLinkageName.empty()) ||
1116 LinkageName == DeclLinkageName) &&
1117 "decl has a linkage name and it is different");
1118 if (DeclLinkageName.empty())
1119 addLinkageName(SPDie, LinkageName);
1124 // Refer to the function declaration where all the other attributes will be
1126 addDIEEntry(SPDie, dwarf::DW_AT_specification, *DeclDie);
1130 void DwarfUnit::applySubprogramAttributes(const DISubprogram *SP, DIE &SPDie,
1133 if (applySubprogramDefinitionAttributes(SP, SPDie))
1136 // Constructors and operators for anonymous aggregates do not have names.
1137 if (!SP->getName().empty())
1138 addString(SPDie, dwarf::DW_AT_name, SP->getName());
1140 // Skip the rest of the attributes under -gmlt to save space.
1144 addSourceLine(SPDie, SP);
1146 // Add the prototype if we have a prototype and we have a C like
1148 uint16_t Language = getLanguage();
1149 if (SP->isPrototyped() &&
1150 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1151 Language == dwarf::DW_LANG_ObjC))
1152 addFlag(SPDie, dwarf::DW_AT_prototyped);
1154 const DISubroutineType *SPTy = SP->getType();
1155 assert(SPTy->getTag() == dwarf::DW_TAG_subroutine_type &&
1156 "the type of a subprogram should be a subroutine");
1158 auto Args = SPTy->getTypeArray();
1159 // Add a return type. If this is a type like a C/C++ void type we don't add a
1162 if (auto Ty = resolve(Args[0]))
1165 unsigned VK = SP->getVirtuality();
1167 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1168 DIELoc *Block = getDIELoc();
1169 addUInt(*Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1170 addUInt(*Block, dwarf::DW_FORM_udata, SP->getVirtualIndex());
1171 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
1172 ContainingTypeMap.insert(
1173 std::make_pair(&SPDie, resolve(SP->getContainingType())));
1176 if (!SP->isDefinition()) {
1177 addFlag(SPDie, dwarf::DW_AT_declaration);
1179 // Add arguments. Do not add arguments for subprogram definition. They will
1180 // be handled while processing variables.
1181 constructSubprogramArguments(SPDie, Args);
1184 if (SP->isArtificial())
1185 addFlag(SPDie, dwarf::DW_AT_artificial);
1187 if (!SP->isLocalToUnit())
1188 addFlag(SPDie, dwarf::DW_AT_external);
1190 if (SP->isOptimized())
1191 addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1193 if (unsigned isa = Asm->getISAEncoding())
1194 addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1196 if (SP->isLValueReference())
1197 addFlag(SPDie, dwarf::DW_AT_reference);
1199 if (SP->isRValueReference())
1200 addFlag(SPDie, dwarf::DW_AT_rvalue_reference);
1202 if (SP->isProtected())
1203 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1204 dwarf::DW_ACCESS_protected);
1205 else if (SP->isPrivate())
1206 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1207 dwarf::DW_ACCESS_private);
1208 else if (SP->isPublic())
1209 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1210 dwarf::DW_ACCESS_public);
1212 if (SP->isExplicit())
1213 addFlag(SPDie, dwarf::DW_AT_explicit);
1216 void DwarfUnit::constructSubrangeDIE(DIE &Buffer, const DISubrange *SR,
1218 DIE &DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
1219 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, *IndexTy);
1221 // The LowerBound value defines the lower bounds which is typically zero for
1222 // C/C++. The Count value is the number of elements. Values are 64 bit. If
1223 // Count == -1 then the array is unbounded and we do not emit
1224 // DW_AT_lower_bound and DW_AT_count attributes.
1225 int64_t LowerBound = SR->getLowerBound();
1226 int64_t DefaultLowerBound = getDefaultLowerBound();
1227 int64_t Count = SR->getCount();
1229 if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
1230 addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound);
1233 // FIXME: An unbounded array should reference the expression that defines
1235 addUInt(DW_Subrange, dwarf::DW_AT_count, None, Count);
1238 DIE *DwarfUnit::getIndexTyDie() {
1241 // Construct an integer type to use for indexes.
1242 IndexTyDie = &createAndAddDIE(dwarf::DW_TAG_base_type, UnitDie);
1243 addString(*IndexTyDie, dwarf::DW_AT_name, "sizetype");
1244 addUInt(*IndexTyDie, dwarf::DW_AT_byte_size, None, sizeof(int64_t));
1245 addUInt(*IndexTyDie, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1246 dwarf::DW_ATE_unsigned);
1250 void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
1251 if (CTy->isVector())
1252 addFlag(Buffer, dwarf::DW_AT_GNU_vector);
1254 // Emit the element type.
1255 addType(Buffer, resolve(CTy->getBaseType()));
1257 // Get an anonymous type for index type.
1258 // FIXME: This type should be passed down from the front end
1259 // as different languages may have different sizes for indexes.
1260 DIE *IdxTy = getIndexTyDie();
1262 // Add subranges to array type.
1263 DINodeArray Elements = CTy->getElements();
1264 for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
1265 // FIXME: Should this really be such a loose cast?
1266 if (auto *Element = dyn_cast_or_null<DINode>(Elements[i]))
1267 if (Element->getTag() == dwarf::DW_TAG_subrange_type)
1268 constructSubrangeDIE(Buffer, cast<DISubrange>(Element), IdxTy);
1272 void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
1273 DINodeArray Elements = CTy->getElements();
1275 // Add enumerators to enumeration type.
1276 for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
1277 auto *Enum = dyn_cast_or_null<DIEnumerator>(Elements[i]);
1279 DIE &Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
1280 StringRef Name = Enum->getName();
1281 addString(Enumerator, dwarf::DW_AT_name, Name);
1282 int64_t Value = Enum->getValue();
1283 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
1287 const DIType *DTy = resolve(CTy->getBaseType());
1289 addType(Buffer, DTy);
1290 addFlag(Buffer, dwarf::DW_AT_enum_class);
1294 void DwarfUnit::constructContainingTypeDIEs() {
1295 for (auto CI = ContainingTypeMap.begin(), CE = ContainingTypeMap.end();
1297 DIE &SPDie = *CI->first;
1298 const DINode *D = CI->second;
1301 DIE *NDie = getDIE(D);
1304 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, *NDie);
1308 void DwarfUnit::constructMemberDIE(DIE &Buffer, const DIDerivedType *DT) {
1309 DIE &MemberDie = createAndAddDIE(DT->getTag(), Buffer);
1310 StringRef Name = DT->getName();
1312 addString(MemberDie, dwarf::DW_AT_name, Name);
1314 addType(MemberDie, resolve(DT->getBaseType()));
1316 addSourceLine(MemberDie, DT);
1318 if (DT->getTag() == dwarf::DW_TAG_inheritance && DT->isVirtual()) {
1320 // For C++, virtual base classes are not at fixed offset. Use following
1321 // expression to extract appropriate offset from vtable.
1322 // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1324 DIELoc *VBaseLocationDie = new (DIEValueAllocator) DIELoc;
1325 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1326 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1327 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1328 addUInt(*VBaseLocationDie, dwarf::DW_FORM_udata, DT->getOffsetInBits());
1329 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1330 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1331 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1333 addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
1335 uint64_t Size = DT->getSizeInBits();
1336 uint64_t FieldSize = getBaseTypeSize(DD, DT);
1337 uint64_t OffsetInBytes;
1339 if (FieldSize && Size != FieldSize) {
1340 // Handle bitfield, assume bytes are 8 bits.
1341 addUInt(MemberDie, dwarf::DW_AT_byte_size, None, FieldSize/8);
1342 addUInt(MemberDie, dwarf::DW_AT_bit_size, None, Size);
1344 uint64_t Offset = DT->getOffsetInBits();
1345 uint64_t AlignMask = ~(DT->getAlignInBits() - 1);
1346 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1347 uint64_t FieldOffset = (HiMark - FieldSize);
1348 Offset -= FieldOffset;
1350 // Maybe we need to work from the other end.
1351 if (Asm->getDataLayout().isLittleEndian())
1352 Offset = FieldSize - (Offset + Size);
1353 addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset);
1355 // Here DW_AT_data_member_location points to the anonymous
1356 // field that includes this bit field.
1357 OffsetInBytes = FieldOffset >> 3;
1359 // This is not a bitfield.
1360 OffsetInBytes = DT->getOffsetInBits() >> 3;
1362 if (DD->getDwarfVersion() <= 2) {
1363 DIELoc *MemLocationDie = new (DIEValueAllocator) DIELoc;
1364 addUInt(*MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1365 addUInt(*MemLocationDie, dwarf::DW_FORM_udata, OffsetInBytes);
1366 addBlock(MemberDie, dwarf::DW_AT_data_member_location, MemLocationDie);
1368 addUInt(MemberDie, dwarf::DW_AT_data_member_location, None,
1372 if (DT->isProtected())
1373 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1374 dwarf::DW_ACCESS_protected);
1375 else if (DT->isPrivate())
1376 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1377 dwarf::DW_ACCESS_private);
1378 // Otherwise C++ member and base classes are considered public.
1379 else if (DT->isPublic())
1380 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1381 dwarf::DW_ACCESS_public);
1382 if (DT->isVirtual())
1383 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1384 dwarf::DW_VIRTUALITY_virtual);
1386 // Objective-C properties.
1387 if (DINode *PNode = DT->getObjCProperty())
1388 if (DIE *PDie = getDIE(PNode))
1389 MemberDie.addValue(dwarf::DW_AT_APPLE_property, dwarf::DW_FORM_ref4,
1392 if (DT->isArtificial())
1393 addFlag(MemberDie, dwarf::DW_AT_artificial);
1396 DIE *DwarfUnit::getOrCreateStaticMemberDIE(const DIDerivedType *DT) {
1400 // Construct the context before querying for the existence of the DIE in case
1401 // such construction creates the DIE.
1402 DIE *ContextDIE = getOrCreateContextDIE(resolve(DT->getScope()));
1403 assert(dwarf::isType(ContextDIE->getTag()) &&
1404 "Static member should belong to a type.");
1406 if (DIE *StaticMemberDIE = getDIE(DT))
1407 return StaticMemberDIE;
1409 DIE &StaticMemberDIE = createAndAddDIE(DT->getTag(), *ContextDIE, DT);
1411 const DIType *Ty = resolve(DT->getBaseType());
1413 addString(StaticMemberDIE, dwarf::DW_AT_name, DT->getName());
1414 addType(StaticMemberDIE, Ty);
1415 addSourceLine(StaticMemberDIE, DT);
1416 addFlag(StaticMemberDIE, dwarf::DW_AT_external);
1417 addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
1419 // FIXME: We could omit private if the parent is a class_type, and
1420 // public if the parent is something else.
1421 if (DT->isProtected())
1422 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1423 dwarf::DW_ACCESS_protected);
1424 else if (DT->isPrivate())
1425 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1426 dwarf::DW_ACCESS_private);
1427 else if (DT->isPublic())
1428 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1429 dwarf::DW_ACCESS_public);
1431 if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT->getConstant()))
1432 addConstantValue(StaticMemberDIE, CI, Ty);
1433 if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT->getConstant()))
1434 addConstantFPValue(StaticMemberDIE, CFP);
1436 return &StaticMemberDIE;
1439 void DwarfUnit::emitHeader(bool UseOffsets) {
1440 // Emit size of content not including length itself
1441 Asm->OutStreamer->AddComment("Length of Unit");
1442 Asm->EmitInt32(getHeaderSize() + UnitDie.getSize());
1444 Asm->OutStreamer->AddComment("DWARF version number");
1445 Asm->EmitInt16(DD->getDwarfVersion());
1446 Asm->OutStreamer->AddComment("Offset Into Abbrev. Section");
1448 // We share one abbreviations table across all units so it's always at the
1449 // start of the section. Use a relocatable offset where needed to ensure
1450 // linking doesn't invalidate that offset.
1451 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1452 Asm->emitDwarfSymbolReference(TLOF.getDwarfAbbrevSection()->getBeginSymbol(),
1455 Asm->OutStreamer->AddComment("Address Size (in bytes)");
1456 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
1459 void DwarfUnit::initSection(MCSection *Section) {
1460 assert(!this->Section);
1461 this->Section = Section;
1464 void DwarfTypeUnit::emitHeader(bool UseOffsets) {
1465 DwarfUnit::emitHeader(UseOffsets);
1466 Asm->OutStreamer->AddComment("Type Signature");
1467 Asm->OutStreamer->EmitIntValue(TypeSignature, sizeof(TypeSignature));
1468 Asm->OutStreamer->AddComment("Type DIE Offset");
1469 // In a skeleton type unit there is no type DIE so emit a zero offset.
1470 Asm->OutStreamer->EmitIntValue(Ty ? Ty->getOffset() : 0,
1471 sizeof(Ty->getOffset()));
1474 bool DwarfTypeUnit::isDwoUnit() const {
1475 // Since there are no skeleton type units, all type units are dwo type units
1476 // when split DWARF is being used.
1477 return DD->useSplitDwarf();