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);
73 DIEIntegerOne = new (DIEValueAllocator) DIEInteger(1);
76 DwarfTypeUnit::DwarfTypeUnit(unsigned UID, DwarfCompileUnit &CU, AsmPrinter *A,
77 DwarfDebug *DW, DwarfFile *DWU,
78 MCDwarfDwoLineTable *SplitLineTable)
79 : DwarfUnit(UID, dwarf::DW_TAG_type_unit, CU.getCUNode(), A, DW, DWU),
80 CU(CU), SplitLineTable(SplitLineTable) {
82 addSectionOffset(UnitDie, dwarf::DW_AT_stmt_list, 0);
85 DwarfUnit::~DwarfUnit() {
86 for (unsigned j = 0, M = DIEBlocks.size(); j < M; ++j)
87 DIEBlocks[j]->~DIEBlock();
88 for (unsigned j = 0, M = DIELocs.size(); j < M; ++j)
89 DIELocs[j]->~DIELoc();
92 DIEEntry *DwarfUnit::createDIEEntry(DIE &Entry) {
93 DIEEntry *Value = new (DIEValueAllocator) DIEEntry(Entry);
97 int64_t DwarfUnit::getDefaultLowerBound() const {
98 switch (getLanguage()) {
102 case dwarf::DW_LANG_C89:
103 case dwarf::DW_LANG_C99:
104 case dwarf::DW_LANG_C:
105 case dwarf::DW_LANG_C_plus_plus:
106 case dwarf::DW_LANG_ObjC:
107 case dwarf::DW_LANG_ObjC_plus_plus:
110 case dwarf::DW_LANG_Fortran77:
111 case dwarf::DW_LANG_Fortran90:
112 case dwarf::DW_LANG_Fortran95:
115 // The languages below have valid values only if the DWARF version >= 4.
116 case dwarf::DW_LANG_Java:
117 case dwarf::DW_LANG_Python:
118 case dwarf::DW_LANG_UPC:
119 case dwarf::DW_LANG_D:
120 if (dwarf::DWARF_VERSION >= 4)
124 case dwarf::DW_LANG_Ada83:
125 case dwarf::DW_LANG_Ada95:
126 case dwarf::DW_LANG_Cobol74:
127 case dwarf::DW_LANG_Cobol85:
128 case dwarf::DW_LANG_Modula2:
129 case dwarf::DW_LANG_Pascal83:
130 case dwarf::DW_LANG_PLI:
131 if (dwarf::DWARF_VERSION >= 4)
135 // The languages below have valid values only if the DWARF version >= 5.
136 case dwarf::DW_LANG_OpenCL:
137 case dwarf::DW_LANG_Go:
138 case dwarf::DW_LANG_Haskell:
139 case dwarf::DW_LANG_C_plus_plus_03:
140 case dwarf::DW_LANG_C_plus_plus_11:
141 case dwarf::DW_LANG_OCaml:
142 case dwarf::DW_LANG_Rust:
143 case dwarf::DW_LANG_C11:
144 case dwarf::DW_LANG_Swift:
145 case dwarf::DW_LANG_Dylan:
146 case dwarf::DW_LANG_C_plus_plus_14:
147 if (dwarf::DWARF_VERSION >= 5)
151 case dwarf::DW_LANG_Modula3:
152 case dwarf::DW_LANG_Julia:
153 case dwarf::DW_LANG_Fortran03:
154 case dwarf::DW_LANG_Fortran08:
155 if (dwarf::DWARF_VERSION >= 5)
163 /// Check whether the DIE for this MDNode can be shared across CUs.
164 static bool isShareableAcrossCUs(const DINode *D) {
165 // When the MDNode can be part of the type system, the DIE can be shared
167 // Combining type units and cross-CU DIE sharing is lower value (since
168 // cross-CU DIE sharing is used in LTO and removes type redundancy at that
169 // level already) but may be implementable for some value in projects
170 // building multiple independent libraries with LTO and then linking those
172 return (isa<DIType>(D) ||
173 (isa<DISubprogram>(D) && !cast<DISubprogram>(D)->isDefinition())) &&
174 !GenerateDwarfTypeUnits;
177 DIE *DwarfUnit::getDIE(const DINode *D) const {
178 if (isShareableAcrossCUs(D))
179 return DU->getDIE(D);
180 return MDNodeToDieMap.lookup(D);
183 void DwarfUnit::insertDIE(const DINode *Desc, DIE *D) {
184 if (isShareableAcrossCUs(Desc)) {
185 DU->insertDIE(Desc, D);
188 MDNodeToDieMap.insert(std::make_pair(Desc, D));
191 void DwarfUnit::addFlag(DIE &Die, dwarf::Attribute Attribute) {
192 if (DD->getDwarfVersion() >= 4)
193 Die.addValue(Attribute, dwarf::DW_FORM_flag_present, DIEIntegerOne);
195 Die.addValue(Attribute, dwarf::DW_FORM_flag, DIEIntegerOne);
198 void DwarfUnit::addUInt(DIE &Die, dwarf::Attribute Attribute,
199 Optional<dwarf::Form> Form, uint64_t Integer) {
201 Form = DIEInteger::BestForm(false, Integer);
202 DIEValue *Value = Integer == 1 ? DIEIntegerOne : new (DIEValueAllocator)
204 Die.addValue(Attribute, *Form, Value);
207 void DwarfUnit::addUInt(DIE &Block, dwarf::Form Form, uint64_t Integer) {
208 addUInt(Block, (dwarf::Attribute)0, Form, Integer);
211 void DwarfUnit::addSInt(DIE &Die, dwarf::Attribute Attribute,
212 Optional<dwarf::Form> Form, int64_t Integer) {
214 Form = DIEInteger::BestForm(true, Integer);
215 DIEValue *Value = new (DIEValueAllocator) DIEInteger(Integer);
216 Die.addValue(Attribute, *Form, Value);
219 void DwarfUnit::addSInt(DIELoc &Die, Optional<dwarf::Form> Form,
221 addSInt(Die, (dwarf::Attribute)0, Form, Integer);
224 void DwarfUnit::addString(DIE &Die, dwarf::Attribute Attribute,
226 Die.addValue(Attribute,
227 isDwoUnit() ? dwarf::DW_FORM_GNU_str_index : dwarf::DW_FORM_strp,
228 new (DIEValueAllocator)
229 DIEString(DU->getStringPool().getEntry(*Asm, String)));
232 void DwarfUnit::addLabel(DIE &Die, dwarf::Attribute Attribute, dwarf::Form Form,
233 const MCSymbol *Label) {
234 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
235 Die.addValue(Attribute, Form, Value);
238 void DwarfUnit::addLabel(DIELoc &Die, dwarf::Form Form, const MCSymbol *Label) {
239 addLabel(Die, (dwarf::Attribute)0, Form, Label);
242 void DwarfUnit::addSectionOffset(DIE &Die, dwarf::Attribute Attribute,
244 if (DD->getDwarfVersion() >= 4)
245 addUInt(Die, Attribute, dwarf::DW_FORM_sec_offset, Integer);
247 addUInt(Die, Attribute, dwarf::DW_FORM_data4, Integer);
250 unsigned DwarfTypeUnit::getOrCreateSourceID(StringRef FileName, StringRef DirName) {
251 return SplitLineTable ? SplitLineTable->getFile(DirName, FileName)
252 : getCU().getOrCreateSourceID(FileName, DirName);
255 void DwarfUnit::addOpAddress(DIELoc &Die, const MCSymbol *Sym) {
256 if (!DD->useSplitDwarf()) {
257 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
258 addLabel(Die, dwarf::DW_FORM_udata, Sym);
260 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index);
261 addUInt(Die, dwarf::DW_FORM_GNU_addr_index,
262 DD->getAddressPool().getIndex(Sym));
266 void DwarfUnit::addLabelDelta(DIE &Die, dwarf::Attribute Attribute,
267 const MCSymbol *Hi, const MCSymbol *Lo) {
268 DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
269 Die.addValue(Attribute, dwarf::DW_FORM_data4, Value);
272 void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute, DIE &Entry) {
273 addDIEEntry(Die, Attribute, createDIEEntry(Entry));
276 void DwarfUnit::addDIETypeSignature(DIE &Die, const DwarfTypeUnit &Type) {
277 // Flag the type unit reference as a declaration so that if it contains
278 // members (implicit special members, static data member definitions, member
279 // declarations for definitions in this CU, etc) consumers don't get confused
280 // and think this is a full definition.
281 addFlag(Die, dwarf::DW_AT_declaration);
283 Die.addValue(dwarf::DW_AT_signature, dwarf::DW_FORM_ref_sig8,
284 new (DIEValueAllocator) DIETypeSignature(Type));
287 void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute,
289 const DIE *DieCU = Die.getUnitOrNull();
290 const DIE *EntryCU = Entry->getEntry().getUnitOrNull();
292 // We assume that Die belongs to this CU, if it is not linked to any CU yet.
293 DieCU = &getUnitDie();
295 EntryCU = &getUnitDie();
296 Die.addValue(Attribute,
297 EntryCU == DieCU ? dwarf::DW_FORM_ref4 : dwarf::DW_FORM_ref_addr,
301 DIE &DwarfUnit::createAndAddDIE(unsigned Tag, DIE &Parent, const DINode *N) {
302 assert(Tag != dwarf::DW_TAG_auto_variable &&
303 Tag != dwarf::DW_TAG_arg_variable);
304 Parent.addChild(make_unique<DIE>((dwarf::Tag)Tag));
305 DIE &Die = *Parent.getChildren().back();
311 void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute, DIELoc *Loc) {
312 Loc->ComputeSize(Asm);
313 DIELocs.push_back(Loc); // Memoize so we can call the destructor later on.
314 Die.addValue(Attribute, Loc->BestForm(DD->getDwarfVersion()), Loc);
317 void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute,
319 Block->ComputeSize(Asm);
320 DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
321 Die.addValue(Attribute, Block->BestForm(), Block);
324 void DwarfUnit::addSourceLine(DIE &Die, unsigned Line, StringRef File,
325 StringRef Directory) {
329 unsigned FileID = getOrCreateSourceID(File, Directory);
330 assert(FileID && "Invalid file id");
331 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
332 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
335 void DwarfUnit::addSourceLine(DIE &Die, const DILocalVariable *V) {
338 addSourceLine(Die, V->getLine(), V->getScope()->getFilename(),
339 V->getScope()->getDirectory());
342 void DwarfUnit::addSourceLine(DIE &Die, const DIGlobalVariable *G) {
345 addSourceLine(Die, G->getLine(), G->getFilename(), G->getDirectory());
348 void DwarfUnit::addSourceLine(DIE &Die, const DISubprogram *SP) {
351 addSourceLine(Die, SP->getLine(), SP->getFilename(), SP->getDirectory());
354 void DwarfUnit::addSourceLine(DIE &Die, const DIType *Ty) {
357 addSourceLine(Die, Ty->getLine(), Ty->getFilename(), Ty->getDirectory());
360 void DwarfUnit::addSourceLine(DIE &Die, const DIObjCProperty *Ty) {
363 addSourceLine(Die, Ty->getLine(), Ty->getFilename(), Ty->getDirectory());
366 void DwarfUnit::addSourceLine(DIE &Die, const DINamespace *NS) {
367 addSourceLine(Die, NS->getLine(), NS->getFilename(), NS->getDirectory());
370 bool DwarfUnit::addRegisterOpPiece(DIELoc &TheDie, unsigned Reg,
371 unsigned SizeInBits, unsigned OffsetInBits) {
372 DIEDwarfExpression Expr(*Asm, *this, TheDie);
373 Expr.AddMachineRegPiece(Reg, SizeInBits, OffsetInBits);
377 bool DwarfUnit::addRegisterOffset(DIELoc &TheDie, unsigned Reg,
379 DIEDwarfExpression Expr(*Asm, *this, TheDie);
380 return Expr.AddMachineRegIndirect(Reg, Offset);
383 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
384 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
385 gives the variable VarName either the struct, or a pointer to the struct, as
386 its type. This is necessary for various behind-the-scenes things the
387 compiler needs to do with by-reference variables in Blocks.
389 However, as far as the original *programmer* is concerned, the variable
390 should still have type 'SomeType', as originally declared.
392 The function getBlockByrefType dives into the __Block_byref_x_VarName
393 struct to find the original type of the variable, which is then assigned to
394 the variable's Debug Information Entry as its real type. So far, so good.
395 However now the debugger will expect the variable VarName to have the type
396 SomeType. So we need the location attribute for the variable to be an
397 expression that explains to the debugger how to navigate through the
398 pointers and struct to find the actual variable of type SomeType.
400 The following function does just that. We start by getting
401 the "normal" location for the variable. This will be the location
402 of either the struct __Block_byref_x_VarName or the pointer to the
403 struct __Block_byref_x_VarName.
405 The struct will look something like:
407 struct __Block_byref_x_VarName {
409 struct __Block_byref_x_VarName *forwarding;
410 ... <various other fields>
412 ... <maybe more fields>
415 If we are given the struct directly (as our starting point) we
416 need to tell the debugger to:
418 1). Add the offset of the forwarding field.
420 2). Follow that pointer to get the real __Block_byref_x_VarName
421 struct to use (the real one may have been copied onto the heap).
423 3). Add the offset for the field VarName, to find the actual variable.
425 If we started with a pointer to the struct, then we need to
426 dereference that pointer first, before the other steps.
427 Translating this into DWARF ops, we will need to append the following
428 to the current location description for the variable:
430 DW_OP_deref -- optional, if we start with a pointer
431 DW_OP_plus_uconst <forward_fld_offset>
433 DW_OP_plus_uconst <varName_fld_offset>
435 That is what this function does. */
437 void DwarfUnit::addBlockByrefAddress(const DbgVariable &DV, DIE &Die,
438 dwarf::Attribute Attribute,
439 const MachineLocation &Location) {
440 const DIType *Ty = DV.getType();
441 const DIType *TmpTy = Ty;
442 uint16_t Tag = Ty->getTag();
443 bool isPointer = false;
445 StringRef varName = DV.getName();
447 if (Tag == dwarf::DW_TAG_pointer_type) {
448 auto *DTy = cast<DIDerivedType>(Ty);
449 TmpTy = resolve(DTy->getBaseType());
453 // Find the __forwarding field and the variable field in the __Block_byref
455 DINodeArray Fields = cast<DICompositeTypeBase>(TmpTy)->getElements();
456 const DIDerivedType *varField = nullptr;
457 const DIDerivedType *forwardingField = nullptr;
459 for (unsigned i = 0, N = Fields.size(); i < N; ++i) {
460 auto *DT = cast<DIDerivedType>(Fields[i]);
461 StringRef fieldName = DT->getName();
462 if (fieldName == "__forwarding")
463 forwardingField = DT;
464 else if (fieldName == varName)
468 // Get the offsets for the forwarding field and the variable field.
469 unsigned forwardingFieldOffset = forwardingField->getOffsetInBits() >> 3;
470 unsigned varFieldOffset = varField->getOffsetInBits() >> 2;
472 // Decode the original location, and use that as the start of the byref
473 // variable's location.
474 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
477 if (Location.isReg())
478 validReg = addRegisterOpPiece(*Loc, Location.getReg());
480 validReg = addRegisterOffset(*Loc, Location.getReg(), Location.getOffset());
485 // If we started with a pointer to the __Block_byref... struct, then
486 // the first thing we need to do is dereference the pointer (DW_OP_deref).
488 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
490 // Next add the offset for the '__forwarding' field:
491 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
492 // adding the offset if it's 0.
493 if (forwardingFieldOffset > 0) {
494 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
495 addUInt(*Loc, dwarf::DW_FORM_udata, forwardingFieldOffset);
498 // Now dereference the __forwarding field to get to the real __Block_byref
499 // struct: DW_OP_deref.
500 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
502 // Now that we've got the real __Block_byref... struct, add the offset
503 // for the variable's field to get to the location of the actual variable:
504 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
505 if (varFieldOffset > 0) {
506 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
507 addUInt(*Loc, dwarf::DW_FORM_udata, varFieldOffset);
510 // Now attach the location information to the DIE.
511 addBlock(Die, Attribute, Loc);
514 /// Return true if type encoding is unsigned.
515 static bool isUnsignedDIType(DwarfDebug *DD, const DIType *Ty) {
516 if (auto *DTy = dyn_cast<DIDerivedTypeBase>(Ty)) {
517 dwarf::Tag T = (dwarf::Tag)Ty->getTag();
518 // Encode pointer constants as unsigned bytes. This is used at least for
519 // null pointer constant emission.
520 // (Pieces of) aggregate types that get hacked apart by SROA may also be
521 // represented by a constant. Encode them as unsigned bytes.
522 // FIXME: reference and rvalue_reference /probably/ shouldn't be allowed
523 // here, but accept them for now due to a bug in SROA producing bogus
525 if (T == dwarf::DW_TAG_array_type ||
526 T == dwarf::DW_TAG_class_type ||
527 T == dwarf::DW_TAG_pointer_type ||
528 T == dwarf::DW_TAG_ptr_to_member_type ||
529 T == dwarf::DW_TAG_reference_type ||
530 T == dwarf::DW_TAG_rvalue_reference_type ||
531 T == dwarf::DW_TAG_structure_type ||
532 T == dwarf::DW_TAG_union_type)
534 assert(T == dwarf::DW_TAG_typedef || T == dwarf::DW_TAG_const_type ||
535 T == dwarf::DW_TAG_volatile_type ||
536 T == dwarf::DW_TAG_restrict_type ||
537 T == dwarf::DW_TAG_enumeration_type);
538 if (DITypeRef Deriv = DTy->getBaseType())
539 return isUnsignedDIType(DD, DD->resolve(Deriv));
540 // FIXME: Enums without a fixed underlying type have unknown signedness
541 // here, leading to incorrectly emitted constants.
542 assert(DTy->getTag() == dwarf::DW_TAG_enumeration_type);
546 auto *BTy = cast<DIBasicType>(Ty);
547 unsigned Encoding = BTy->getEncoding();
548 assert((Encoding == dwarf::DW_ATE_unsigned ||
549 Encoding == dwarf::DW_ATE_unsigned_char ||
550 Encoding == dwarf::DW_ATE_signed ||
551 Encoding == dwarf::DW_ATE_signed_char ||
552 Encoding == dwarf::DW_ATE_float || Encoding == dwarf::DW_ATE_UTF ||
553 Encoding == dwarf::DW_ATE_boolean ||
554 (Ty->getTag() == dwarf::DW_TAG_unspecified_type &&
555 Ty->getName() == "decltype(nullptr)")) &&
556 "Unsupported encoding");
557 return Encoding == dwarf::DW_ATE_unsigned ||
558 Encoding == dwarf::DW_ATE_unsigned_char ||
559 Encoding == dwarf::DW_ATE_UTF || Encoding == dwarf::DW_ATE_boolean ||
560 Ty->getTag() == dwarf::DW_TAG_unspecified_type;
563 /// If this type is derived from a base type then return base type size.
564 static uint64_t getBaseTypeSize(DwarfDebug *DD, const DIDerivedType *Ty) {
565 unsigned Tag = Ty->getTag();
567 if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef &&
568 Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type &&
569 Tag != dwarf::DW_TAG_restrict_type)
570 return Ty->getSizeInBits();
572 auto *BaseType = DD->resolve(Ty->getBaseType());
574 assert(BaseType && "Unexpected invalid base type");
576 // If this is a derived type, go ahead and get the base type, unless it's a
577 // reference then it's just the size of the field. Pointer types have no need
578 // of this since they're a different type of qualification on the type.
579 if (BaseType->getTag() == dwarf::DW_TAG_reference_type ||
580 BaseType->getTag() == dwarf::DW_TAG_rvalue_reference_type)
581 return Ty->getSizeInBits();
583 if (auto *DT = dyn_cast<DIDerivedType>(BaseType))
584 return getBaseTypeSize(DD, DT);
586 return BaseType->getSizeInBits();
589 void DwarfUnit::addConstantFPValue(DIE &Die, const MachineOperand &MO) {
590 assert(MO.isFPImm() && "Invalid machine operand!");
591 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
592 APFloat FPImm = MO.getFPImm()->getValueAPF();
594 // Get the raw data form of the floating point.
595 const APInt FltVal = FPImm.bitcastToAPInt();
596 const char *FltPtr = (const char *)FltVal.getRawData();
598 int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
599 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
600 int Incr = (LittleEndian ? 1 : -1);
601 int Start = (LittleEndian ? 0 : NumBytes - 1);
602 int Stop = (LittleEndian ? NumBytes : -1);
604 // Output the constant to DWARF one byte at a time.
605 for (; Start != Stop; Start += Incr)
606 addUInt(*Block, dwarf::DW_FORM_data1, (unsigned char)0xFF & FltPtr[Start]);
608 addBlock(Die, dwarf::DW_AT_const_value, Block);
611 void DwarfUnit::addConstantFPValue(DIE &Die, const ConstantFP *CFP) {
612 // Pass this down to addConstantValue as an unsigned bag of bits.
613 addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true);
616 void DwarfUnit::addConstantValue(DIE &Die, const ConstantInt *CI,
618 addConstantValue(Die, CI->getValue(), Ty);
621 void DwarfUnit::addConstantValue(DIE &Die, const MachineOperand &MO,
623 assert(MO.isImm() && "Invalid machine operand!");
625 addConstantValue(Die, isUnsignedDIType(DD, Ty), MO.getImm());
628 void DwarfUnit::addConstantValue(DIE &Die, bool Unsigned, uint64_t Val) {
629 // FIXME: This is a bit conservative/simple - it emits negative values always
630 // sign extended to 64 bits rather than minimizing the number of bytes.
631 addUInt(Die, dwarf::DW_AT_const_value,
632 Unsigned ? dwarf::DW_FORM_udata : dwarf::DW_FORM_sdata, Val);
635 void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, const DIType *Ty) {
636 addConstantValue(Die, Val, isUnsignedDIType(DD, Ty));
639 void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, bool Unsigned) {
640 unsigned CIBitWidth = Val.getBitWidth();
641 if (CIBitWidth <= 64) {
642 addConstantValue(Die, Unsigned,
643 Unsigned ? Val.getZExtValue() : Val.getSExtValue());
647 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
649 // Get the raw data form of the large APInt.
650 const uint64_t *Ptr64 = Val.getRawData();
652 int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
653 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
655 // Output the constant to DWARF one byte at a time.
656 for (int i = 0; i < NumBytes; i++) {
659 c = Ptr64[i / 8] >> (8 * (i & 7));
661 c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
662 addUInt(*Block, dwarf::DW_FORM_data1, c);
665 addBlock(Die, dwarf::DW_AT_const_value, Block);
668 void DwarfUnit::addLinkageName(DIE &Die, StringRef LinkageName) {
669 if (!LinkageName.empty())
671 DD->getDwarfVersion() >= 4 ? dwarf::DW_AT_linkage_name
672 : dwarf::DW_AT_MIPS_linkage_name,
673 GlobalValue::getRealLinkageName(LinkageName));
676 void DwarfUnit::addTemplateParams(DIE &Buffer, DINodeArray TParams) {
677 // Add template parameters.
678 for (const auto *Element : TParams) {
679 if (auto *TTP = dyn_cast<DITemplateTypeParameter>(Element))
680 constructTemplateTypeParameterDIE(Buffer, TTP);
681 else if (auto *TVP = dyn_cast<DITemplateValueParameter>(Element))
682 constructTemplateValueParameterDIE(Buffer, TVP);
686 DIE *DwarfUnit::getOrCreateContextDIE(const DIScope *Context) {
687 if (!Context || isa<DIFile>(Context))
688 return &getUnitDie();
689 if (auto *T = dyn_cast<DIType>(Context))
690 return getOrCreateTypeDIE(T);
691 if (auto *NS = dyn_cast<DINamespace>(Context))
692 return getOrCreateNameSpace(NS);
693 if (auto *SP = dyn_cast<DISubprogram>(Context))
694 return getOrCreateSubprogramDIE(SP);
695 return getDIE(Context);
698 DIE *DwarfUnit::createTypeDIE(const DICompositeType *Ty) {
699 auto *Context = resolve(Ty->getScope());
700 DIE *ContextDIE = getOrCreateContextDIE(Context);
702 if (DIE *TyDIE = getDIE(Ty))
706 DIE &TyDIE = createAndAddDIE(Ty->getTag(), *ContextDIE, Ty);
708 constructTypeDIE(TyDIE, cast<DICompositeType>(Ty));
710 updateAcceleratorTables(Context, Ty, TyDIE);
714 DIE *DwarfUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
718 auto *Ty = cast<DIType>(TyNode);
719 assert(Ty == resolve(Ty->getRef()) &&
720 "type was not uniqued, possible ODR violation.");
722 // DW_TAG_restrict_type is not supported in DWARF2
723 if (Ty->getTag() == dwarf::DW_TAG_restrict_type && DD->getDwarfVersion() <= 2)
724 return getOrCreateTypeDIE(resolve(cast<DIDerivedType>(Ty)->getBaseType()));
726 // Construct the context before querying for the existence of the DIE in case
727 // such construction creates the DIE.
728 auto *Context = resolve(Ty->getScope());
729 DIE *ContextDIE = getOrCreateContextDIE(Context);
732 if (DIE *TyDIE = getDIE(Ty))
736 DIE &TyDIE = createAndAddDIE(Ty->getTag(), *ContextDIE, Ty);
738 updateAcceleratorTables(Context, Ty, TyDIE);
740 if (auto *BT = dyn_cast<DIBasicType>(Ty))
741 constructTypeDIE(TyDIE, BT);
742 else if (auto *STy = dyn_cast<DISubroutineType>(Ty))
743 constructTypeDIE(TyDIE, STy);
744 else if (auto *CTy = dyn_cast<DICompositeType>(Ty)) {
745 if (GenerateDwarfTypeUnits && !Ty->isForwardDecl())
746 if (MDString *TypeId = CTy->getRawIdentifier()) {
747 DD->addDwarfTypeUnitType(getCU(), TypeId->getString(), TyDIE, CTy);
748 // Skip updating the accelerator tables since this is not the full type.
751 constructTypeDIE(TyDIE, CTy);
753 constructTypeDIE(TyDIE, cast<DIDerivedType>(Ty));
759 void DwarfUnit::updateAcceleratorTables(const DIScope *Context,
760 const DIType *Ty, const DIE &TyDIE) {
761 if (!Ty->getName().empty() && !Ty->isForwardDecl()) {
762 bool IsImplementation = 0;
763 if (auto *CT = dyn_cast<DICompositeTypeBase>(Ty)) {
764 // A runtime language of 0 actually means C/C++ and that any
765 // non-negative value is some version of Objective-C/C++.
766 IsImplementation = CT->getRuntimeLang() == 0 || CT->isObjcClassComplete();
768 unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0;
769 DD->addAccelType(Ty->getName(), TyDIE, Flags);
771 if (!Context || isa<DICompileUnit>(Context) || isa<DIFile>(Context) ||
772 isa<DINamespace>(Context))
773 addGlobalType(Ty, TyDIE, Context);
777 void DwarfUnit::addType(DIE &Entity, const DIType *Ty,
778 dwarf::Attribute Attribute) {
779 assert(Ty && "Trying to add a type that doesn't exist?");
781 // Check for pre-existence.
782 DIEEntry *Entry = getDIEEntry(Ty);
783 // If it exists then use the existing value.
785 addDIEEntry(Entity, Attribute, Entry);
790 DIE *Buffer = getOrCreateTypeDIE(Ty);
793 Entry = createDIEEntry(*Buffer);
794 insertDIEEntry(Ty, Entry);
795 addDIEEntry(Entity, Attribute, Entry);
798 std::string DwarfUnit::getParentContextString(const DIScope *Context) const {
802 // FIXME: Decide whether to implement this for non-C++ languages.
803 if (getLanguage() != dwarf::DW_LANG_C_plus_plus)
807 SmallVector<const DIScope *, 1> Parents;
808 while (!isa<DICompileUnit>(Context)) {
809 Parents.push_back(Context);
810 if (Context->getScope())
811 Context = resolve(Context->getScope());
813 // Structure, etc types will have a NULL context if they're at the top
818 // Reverse iterate over our list to go from the outermost construct to the
820 for (auto I = Parents.rbegin(), E = Parents.rend(); I != E; ++I) {
821 const DIScope *Ctx = *I;
822 StringRef Name = Ctx->getName();
823 if (Name.empty() && isa<DINamespace>(Ctx))
824 Name = "(anonymous namespace)";
833 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DIBasicType *BTy) {
834 // Get core information.
835 StringRef Name = BTy->getName();
836 // Add name if not anonymous or intermediate type.
838 addString(Buffer, dwarf::DW_AT_name, Name);
840 // An unspecified type only has a name attribute.
841 if (BTy->getTag() == dwarf::DW_TAG_unspecified_type)
844 addUInt(Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
847 uint64_t Size = BTy->getSizeInBits() >> 3;
848 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
851 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DIDerivedType *DTy) {
852 // Get core information.
853 StringRef Name = DTy->getName();
854 uint64_t Size = DTy->getSizeInBits() >> 3;
855 uint16_t Tag = Buffer.getTag();
857 // Map to main type, void will not have a type.
858 const DIType *FromTy = resolve(DTy->getBaseType());
860 addType(Buffer, FromTy);
862 // Add name if not anonymous or intermediate type.
864 addString(Buffer, dwarf::DW_AT_name, Name);
866 // Add size if non-zero (derived types might be zero-sized.)
867 if (Size && Tag != dwarf::DW_TAG_pointer_type
868 && Tag != dwarf::DW_TAG_ptr_to_member_type)
869 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
871 if (Tag == dwarf::DW_TAG_ptr_to_member_type)
873 Buffer, dwarf::DW_AT_containing_type,
874 *getOrCreateTypeDIE(resolve(cast<DIDerivedType>(DTy)->getClassType())));
875 // Add source line info if available and TyDesc is not a forward declaration.
876 if (!DTy->isForwardDecl())
877 addSourceLine(Buffer, DTy);
880 void DwarfUnit::constructSubprogramArguments(DIE &Buffer, DITypeRefArray Args) {
881 for (unsigned i = 1, N = Args.size(); i < N; ++i) {
882 const DIType *Ty = resolve(Args[i]);
884 assert(i == N-1 && "Unspecified parameter must be the last argument");
885 createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
887 DIE &Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
889 if (Ty->isArtificial())
890 addFlag(Arg, dwarf::DW_AT_artificial);
895 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DISubroutineType *CTy) {
896 // Add return type. A void return won't have a type.
897 auto Elements = cast<DISubroutineType>(CTy)->getTypeArray();
899 if (auto RTy = resolve(Elements[0]))
900 addType(Buffer, RTy);
902 bool isPrototyped = true;
903 if (Elements.size() == 2 && !Elements[1])
904 isPrototyped = false;
906 constructSubprogramArguments(Buffer, Elements);
908 // Add prototype flag if we're dealing with a C language and the function has
910 uint16_t Language = getLanguage();
912 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
913 Language == dwarf::DW_LANG_ObjC))
914 addFlag(Buffer, dwarf::DW_AT_prototyped);
916 if (CTy->isLValueReference())
917 addFlag(Buffer, dwarf::DW_AT_reference);
919 if (CTy->isRValueReference())
920 addFlag(Buffer, dwarf::DW_AT_rvalue_reference);
923 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
924 // Add name if not anonymous or intermediate type.
925 StringRef Name = CTy->getName();
927 uint64_t Size = CTy->getSizeInBits() >> 3;
928 uint16_t Tag = Buffer.getTag();
931 case dwarf::DW_TAG_array_type:
932 constructArrayTypeDIE(Buffer, CTy);
934 case dwarf::DW_TAG_enumeration_type:
935 constructEnumTypeDIE(Buffer, CTy);
937 case dwarf::DW_TAG_structure_type:
938 case dwarf::DW_TAG_union_type:
939 case dwarf::DW_TAG_class_type: {
940 // Add elements to structure type.
941 DINodeArray Elements = CTy->getElements();
942 for (const auto *Element : Elements) {
945 if (auto *SP = dyn_cast<DISubprogram>(Element))
946 getOrCreateSubprogramDIE(SP);
947 else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
948 if (DDTy->getTag() == dwarf::DW_TAG_friend) {
949 DIE &ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
950 addType(ElemDie, resolve(DDTy->getBaseType()), dwarf::DW_AT_friend);
951 } else if (DDTy->isStaticMember()) {
952 getOrCreateStaticMemberDIE(DDTy);
954 constructMemberDIE(Buffer, DDTy);
956 } else if (auto *Property = dyn_cast<DIObjCProperty>(Element)) {
957 DIE &ElemDie = createAndAddDIE(Property->getTag(), Buffer);
958 StringRef PropertyName = Property->getName();
959 addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
960 if (Property->getType())
961 addType(ElemDie, Property->getType());
962 addSourceLine(ElemDie, Property);
963 StringRef GetterName = Property->getGetterName();
964 if (!GetterName.empty())
965 addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
966 StringRef SetterName = Property->getSetterName();
967 if (!SetterName.empty())
968 addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
969 if (unsigned PropertyAttributes = Property->getAttributes())
970 addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None,
973 DIEEntry *Entry = getDIEEntry(Element);
975 Entry = createDIEEntry(ElemDie);
976 insertDIEEntry(Element, Entry);
981 if (CTy->isAppleBlockExtension())
982 addFlag(Buffer, dwarf::DW_AT_APPLE_block);
984 // This is outside the DWARF spec, but GDB expects a DW_AT_containing_type
985 // inside C++ composite types to point to the base class with the vtable.
986 if (auto *ContainingType =
987 dyn_cast_or_null<DICompositeType>(resolve(CTy->getVTableHolder())))
988 addDIEEntry(Buffer, dwarf::DW_AT_containing_type,
989 *getOrCreateTypeDIE(ContainingType));
991 if (CTy->isObjcClassComplete())
992 addFlag(Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
994 // Add template parameters to a class, structure or union types.
995 // FIXME: The support isn't in the metadata for this yet.
996 if (Tag == dwarf::DW_TAG_class_type ||
997 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
998 addTemplateParams(Buffer, CTy->getTemplateParams());
1006 // Add name if not anonymous or intermediate type.
1008 addString(Buffer, dwarf::DW_AT_name, Name);
1010 if (Tag == dwarf::DW_TAG_enumeration_type ||
1011 Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
1012 Tag == dwarf::DW_TAG_union_type) {
1013 // Add size if non-zero (derived types might be zero-sized.)
1014 // TODO: Do we care about size for enum forward declarations?
1016 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
1017 else if (!CTy->isForwardDecl())
1018 // Add zero size if it is not a forward declaration.
1019 addUInt(Buffer, dwarf::DW_AT_byte_size, None, 0);
1021 // If we're a forward decl, say so.
1022 if (CTy->isForwardDecl())
1023 addFlag(Buffer, dwarf::DW_AT_declaration);
1025 // Add source line info if available.
1026 if (!CTy->isForwardDecl())
1027 addSourceLine(Buffer, CTy);
1029 // No harm in adding the runtime language to the declaration.
1030 unsigned RLang = CTy->getRuntimeLang();
1032 addUInt(Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
1037 void DwarfUnit::constructTemplateTypeParameterDIE(
1038 DIE &Buffer, const DITemplateTypeParameter *TP) {
1040 createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
1041 // Add the type if it exists, it could be void and therefore no type.
1043 addType(ParamDIE, resolve(TP->getType()));
1044 if (!TP->getName().empty())
1045 addString(ParamDIE, dwarf::DW_AT_name, TP->getName());
1048 void DwarfUnit::constructTemplateValueParameterDIE(
1049 DIE &Buffer, const DITemplateValueParameter *VP) {
1050 DIE &ParamDIE = createAndAddDIE(VP->getTag(), Buffer);
1052 // Add the type if there is one, template template and template parameter
1053 // packs will not have a type.
1054 if (VP->getTag() == dwarf::DW_TAG_template_value_parameter)
1055 addType(ParamDIE, resolve(VP->getType()));
1056 if (!VP->getName().empty())
1057 addString(ParamDIE, dwarf::DW_AT_name, VP->getName());
1058 if (Metadata *Val = VP->getValue()) {
1059 if (ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(Val))
1060 addConstantValue(ParamDIE, CI, resolve(VP->getType()));
1061 else if (GlobalValue *GV = mdconst::dyn_extract<GlobalValue>(Val)) {
1062 // For declaration non-type template parameters (such as global values and
1064 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
1065 addOpAddress(*Loc, Asm->getSymbol(GV));
1066 // Emit DW_OP_stack_value to use the address as the immediate value of the
1067 // parameter, rather than a pointer to it.
1068 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
1069 addBlock(ParamDIE, dwarf::DW_AT_location, Loc);
1070 } else if (VP->getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1071 assert(isa<MDString>(Val));
1072 addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
1073 cast<MDString>(Val)->getString());
1074 } else if (VP->getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1075 addTemplateParams(ParamDIE, cast<MDTuple>(Val));
1080 DIE *DwarfUnit::getOrCreateNameSpace(const DINamespace *NS) {
1081 // Construct the context before querying for the existence of the DIE in case
1082 // such construction creates the DIE.
1083 DIE *ContextDIE = getOrCreateContextDIE(NS->getScope());
1085 if (DIE *NDie = getDIE(NS))
1087 DIE &NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS);
1089 StringRef Name = NS->getName();
1091 addString(NDie, dwarf::DW_AT_name, NS->getName());
1093 Name = "(anonymous namespace)";
1094 DD->addAccelNamespace(Name, NDie);
1095 addGlobalName(Name, NDie, NS->getScope());
1096 addSourceLine(NDie, NS);
1100 DIE *DwarfUnit::getOrCreateSubprogramDIE(const DISubprogram *SP, bool Minimal) {
1101 // Construct the context before querying for the existence of the DIE in case
1102 // such construction creates the DIE (as is the case for member function
1105 Minimal ? &getUnitDie() : getOrCreateContextDIE(resolve(SP->getScope()));
1107 if (DIE *SPDie = getDIE(SP))
1110 if (auto *SPDecl = SP->getDeclaration()) {
1112 // Add subprogram definitions to the CU die directly.
1113 ContextDIE = &getUnitDie();
1114 // Build the decl now to ensure it precedes the definition.
1115 getOrCreateSubprogramDIE(SPDecl);
1119 // DW_TAG_inlined_subroutine may refer to this DIE.
1120 DIE &SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
1122 // Stop here and fill this in later, depending on whether or not this
1123 // subprogram turns out to have inlined instances or not.
1124 if (SP->isDefinition())
1127 applySubprogramAttributes(SP, SPDie);
1131 bool DwarfUnit::applySubprogramDefinitionAttributes(const DISubprogram *SP,
1133 DIE *DeclDie = nullptr;
1134 StringRef DeclLinkageName;
1135 if (auto *SPDecl = SP->getDeclaration()) {
1136 DeclDie = getDIE(SPDecl);
1137 assert(DeclDie && "This DIE should've already been constructed when the "
1138 "definition DIE was created in "
1139 "getOrCreateSubprogramDIE");
1140 DeclLinkageName = SPDecl->getLinkageName();
1143 // Add function template parameters.
1144 addTemplateParams(SPDie, SP->getTemplateParams());
1146 // Add the linkage name if we have one and it isn't in the Decl.
1147 StringRef LinkageName = SP->getLinkageName();
1148 assert(((LinkageName.empty() || DeclLinkageName.empty()) ||
1149 LinkageName == DeclLinkageName) &&
1150 "decl has a linkage name and it is different");
1151 if (DeclLinkageName.empty())
1152 addLinkageName(SPDie, LinkageName);
1157 // Refer to the function declaration where all the other attributes will be
1159 addDIEEntry(SPDie, dwarf::DW_AT_specification, *DeclDie);
1163 void DwarfUnit::applySubprogramAttributes(const DISubprogram *SP, DIE &SPDie,
1166 if (applySubprogramDefinitionAttributes(SP, SPDie))
1169 // Constructors and operators for anonymous aggregates do not have names.
1170 if (!SP->getName().empty())
1171 addString(SPDie, dwarf::DW_AT_name, SP->getName());
1173 // Skip the rest of the attributes under -gmlt to save space.
1177 addSourceLine(SPDie, SP);
1179 // Add the prototype if we have a prototype and we have a C like
1181 uint16_t Language = getLanguage();
1182 if (SP->isPrototyped() &&
1183 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1184 Language == dwarf::DW_LANG_ObjC))
1185 addFlag(SPDie, dwarf::DW_AT_prototyped);
1187 const DISubroutineType *SPTy = SP->getType();
1188 assert(SPTy->getTag() == dwarf::DW_TAG_subroutine_type &&
1189 "the type of a subprogram should be a subroutine");
1191 auto Args = SPTy->getTypeArray();
1192 // Add a return type. If this is a type like a C/C++ void type we don't add a
1195 if (auto Ty = resolve(Args[0]))
1198 unsigned VK = SP->getVirtuality();
1200 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1201 DIELoc *Block = getDIELoc();
1202 addUInt(*Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1203 addUInt(*Block, dwarf::DW_FORM_udata, SP->getVirtualIndex());
1204 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
1205 ContainingTypeMap.insert(
1206 std::make_pair(&SPDie, resolve(SP->getContainingType())));
1209 if (!SP->isDefinition()) {
1210 addFlag(SPDie, dwarf::DW_AT_declaration);
1212 // Add arguments. Do not add arguments for subprogram definition. They will
1213 // be handled while processing variables.
1214 constructSubprogramArguments(SPDie, Args);
1217 if (SP->isArtificial())
1218 addFlag(SPDie, dwarf::DW_AT_artificial);
1220 if (!SP->isLocalToUnit())
1221 addFlag(SPDie, dwarf::DW_AT_external);
1223 if (SP->isOptimized())
1224 addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1226 if (unsigned isa = Asm->getISAEncoding())
1227 addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1229 if (SP->isLValueReference())
1230 addFlag(SPDie, dwarf::DW_AT_reference);
1232 if (SP->isRValueReference())
1233 addFlag(SPDie, dwarf::DW_AT_rvalue_reference);
1235 if (SP->isProtected())
1236 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1237 dwarf::DW_ACCESS_protected);
1238 else if (SP->isPrivate())
1239 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1240 dwarf::DW_ACCESS_private);
1241 else if (SP->isPublic())
1242 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1243 dwarf::DW_ACCESS_public);
1245 if (SP->isExplicit())
1246 addFlag(SPDie, dwarf::DW_AT_explicit);
1249 void DwarfUnit::constructSubrangeDIE(DIE &Buffer, const DISubrange *SR,
1251 DIE &DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
1252 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, *IndexTy);
1254 // The LowerBound value defines the lower bounds which is typically zero for
1255 // C/C++. The Count value is the number of elements. Values are 64 bit. If
1256 // Count == -1 then the array is unbounded and we do not emit
1257 // DW_AT_lower_bound and DW_AT_count attributes.
1258 int64_t LowerBound = SR->getLowerBound();
1259 int64_t DefaultLowerBound = getDefaultLowerBound();
1260 int64_t Count = SR->getCount();
1262 if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
1263 addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound);
1266 // FIXME: An unbounded array should reference the expression that defines
1268 addUInt(DW_Subrange, dwarf::DW_AT_count, None, Count);
1271 DIE *DwarfUnit::getIndexTyDie() {
1274 // Construct an integer type to use for indexes.
1275 IndexTyDie = &createAndAddDIE(dwarf::DW_TAG_base_type, UnitDie);
1276 addString(*IndexTyDie, dwarf::DW_AT_name, "sizetype");
1277 addUInt(*IndexTyDie, dwarf::DW_AT_byte_size, None, sizeof(int64_t));
1278 addUInt(*IndexTyDie, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1279 dwarf::DW_ATE_unsigned);
1283 void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
1284 if (CTy->isVector())
1285 addFlag(Buffer, dwarf::DW_AT_GNU_vector);
1287 // Emit the element type.
1288 addType(Buffer, resolve(CTy->getBaseType()));
1290 // Get an anonymous type for index type.
1291 // FIXME: This type should be passed down from the front end
1292 // as different languages may have different sizes for indexes.
1293 DIE *IdxTy = getIndexTyDie();
1295 // Add subranges to array type.
1296 DINodeArray Elements = CTy->getElements();
1297 for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
1298 // FIXME: Should this really be such a loose cast?
1299 if (auto *Element = dyn_cast_or_null<DINode>(Elements[i]))
1300 if (Element->getTag() == dwarf::DW_TAG_subrange_type)
1301 constructSubrangeDIE(Buffer, cast<DISubrange>(Element), IdxTy);
1305 void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
1306 DINodeArray Elements = CTy->getElements();
1308 // Add enumerators to enumeration type.
1309 for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
1310 auto *Enum = dyn_cast_or_null<DIEnumerator>(Elements[i]);
1312 DIE &Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
1313 StringRef Name = Enum->getName();
1314 addString(Enumerator, dwarf::DW_AT_name, Name);
1315 int64_t Value = Enum->getValue();
1316 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
1320 const DIType *DTy = resolve(CTy->getBaseType());
1322 addType(Buffer, DTy);
1323 addFlag(Buffer, dwarf::DW_AT_enum_class);
1327 void DwarfUnit::constructContainingTypeDIEs() {
1328 for (auto CI = ContainingTypeMap.begin(), CE = ContainingTypeMap.end();
1330 DIE &SPDie = *CI->first;
1331 const DINode *D = CI->second;
1334 DIE *NDie = getDIE(D);
1337 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, *NDie);
1341 void DwarfUnit::constructMemberDIE(DIE &Buffer, const DIDerivedType *DT) {
1342 DIE &MemberDie = createAndAddDIE(DT->getTag(), Buffer);
1343 StringRef Name = DT->getName();
1345 addString(MemberDie, dwarf::DW_AT_name, Name);
1347 addType(MemberDie, resolve(DT->getBaseType()));
1349 addSourceLine(MemberDie, DT);
1351 if (DT->getTag() == dwarf::DW_TAG_inheritance && DT->isVirtual()) {
1353 // For C++, virtual base classes are not at fixed offset. Use following
1354 // expression to extract appropriate offset from vtable.
1355 // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1357 DIELoc *VBaseLocationDie = new (DIEValueAllocator) DIELoc();
1358 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1359 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1360 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1361 addUInt(*VBaseLocationDie, dwarf::DW_FORM_udata, DT->getOffsetInBits());
1362 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1363 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1364 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1366 addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
1368 uint64_t Size = DT->getSizeInBits();
1369 uint64_t FieldSize = getBaseTypeSize(DD, DT);
1370 uint64_t OffsetInBytes;
1372 if (FieldSize && Size != FieldSize) {
1373 // Handle bitfield, assume bytes are 8 bits.
1374 addUInt(MemberDie, dwarf::DW_AT_byte_size, None, FieldSize/8);
1375 addUInt(MemberDie, dwarf::DW_AT_bit_size, None, Size);
1377 uint64_t Offset = DT->getOffsetInBits();
1378 uint64_t AlignMask = ~(DT->getAlignInBits() - 1);
1379 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1380 uint64_t FieldOffset = (HiMark - FieldSize);
1381 Offset -= FieldOffset;
1383 // Maybe we need to work from the other end.
1384 if (Asm->getDataLayout().isLittleEndian())
1385 Offset = FieldSize - (Offset + Size);
1386 addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset);
1388 // Here DW_AT_data_member_location points to the anonymous
1389 // field that includes this bit field.
1390 OffsetInBytes = FieldOffset >> 3;
1392 // This is not a bitfield.
1393 OffsetInBytes = DT->getOffsetInBits() >> 3;
1395 if (DD->getDwarfVersion() <= 2) {
1396 DIELoc *MemLocationDie = new (DIEValueAllocator) DIELoc();
1397 addUInt(*MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1398 addUInt(*MemLocationDie, dwarf::DW_FORM_udata, OffsetInBytes);
1399 addBlock(MemberDie, dwarf::DW_AT_data_member_location, MemLocationDie);
1401 addUInt(MemberDie, dwarf::DW_AT_data_member_location, None,
1405 if (DT->isProtected())
1406 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1407 dwarf::DW_ACCESS_protected);
1408 else if (DT->isPrivate())
1409 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1410 dwarf::DW_ACCESS_private);
1411 // Otherwise C++ member and base classes are considered public.
1412 else if (DT->isPublic())
1413 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1414 dwarf::DW_ACCESS_public);
1415 if (DT->isVirtual())
1416 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1417 dwarf::DW_VIRTUALITY_virtual);
1419 // Objective-C properties.
1420 if (MDNode *PNode = DT->getObjCProperty())
1421 if (DIEEntry *PropertyDie = getDIEEntry(PNode))
1422 MemberDie.addValue(dwarf::DW_AT_APPLE_property, dwarf::DW_FORM_ref4,
1425 if (DT->isArtificial())
1426 addFlag(MemberDie, dwarf::DW_AT_artificial);
1429 DIE *DwarfUnit::getOrCreateStaticMemberDIE(const DIDerivedType *DT) {
1433 // Construct the context before querying for the existence of the DIE in case
1434 // such construction creates the DIE.
1435 DIE *ContextDIE = getOrCreateContextDIE(resolve(DT->getScope()));
1436 assert(dwarf::isType(ContextDIE->getTag()) &&
1437 "Static member should belong to a type.");
1439 if (DIE *StaticMemberDIE = getDIE(DT))
1440 return StaticMemberDIE;
1442 DIE &StaticMemberDIE = createAndAddDIE(DT->getTag(), *ContextDIE, DT);
1444 const DIType *Ty = resolve(DT->getBaseType());
1446 addString(StaticMemberDIE, dwarf::DW_AT_name, DT->getName());
1447 addType(StaticMemberDIE, Ty);
1448 addSourceLine(StaticMemberDIE, DT);
1449 addFlag(StaticMemberDIE, dwarf::DW_AT_external);
1450 addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
1452 // FIXME: We could omit private if the parent is a class_type, and
1453 // public if the parent is something else.
1454 if (DT->isProtected())
1455 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1456 dwarf::DW_ACCESS_protected);
1457 else if (DT->isPrivate())
1458 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1459 dwarf::DW_ACCESS_private);
1460 else if (DT->isPublic())
1461 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1462 dwarf::DW_ACCESS_public);
1464 if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT->getConstant()))
1465 addConstantValue(StaticMemberDIE, CI, Ty);
1466 if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT->getConstant()))
1467 addConstantFPValue(StaticMemberDIE, CFP);
1469 return &StaticMemberDIE;
1472 void DwarfUnit::emitHeader(bool UseOffsets) {
1473 // Emit size of content not including length itself
1474 Asm->OutStreamer->AddComment("Length of Unit");
1475 Asm->EmitInt32(getHeaderSize() + UnitDie.getSize());
1477 Asm->OutStreamer->AddComment("DWARF version number");
1478 Asm->EmitInt16(DD->getDwarfVersion());
1479 Asm->OutStreamer->AddComment("Offset Into Abbrev. Section");
1481 // We share one abbreviations table across all units so it's always at the
1482 // start of the section. Use a relocatable offset where needed to ensure
1483 // linking doesn't invalidate that offset.
1484 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1486 Asm->emitSectionOffset(TLOF.getDwarfAbbrevSection()->getBeginSymbol());
1490 Asm->OutStreamer->AddComment("Address Size (in bytes)");
1491 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
1494 void DwarfUnit::initSection(MCSection *Section) {
1495 assert(!this->Section);
1496 this->Section = Section;
1499 void DwarfTypeUnit::emitHeader(bool UseOffsets) {
1500 DwarfUnit::emitHeader(UseOffsets);
1501 Asm->OutStreamer->AddComment("Type Signature");
1502 Asm->OutStreamer->EmitIntValue(TypeSignature, sizeof(TypeSignature));
1503 Asm->OutStreamer->AddComment("Type DIE Offset");
1504 // In a skeleton type unit there is no type DIE so emit a zero offset.
1505 Asm->OutStreamer->EmitIntValue(Ty ? Ty->getOffset() : 0,
1506 sizeof(Ty->getOffset()));
1509 bool DwarfTypeUnit::isDwoUnit() const {
1510 // Since there are no skeleton type units, all type units are dwo type units
1511 // when split DWARF is being used.
1512 return DD->useSplitDwarf();