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),
70 UnitDie(*DIE::get(DIEValueAllocator, UnitTag)), DebugInfoOffset(0),
71 Asm(A), DD(DW), DU(DWU), IndexTyDie(nullptr), Section(nullptr) {
72 assert(UnitTag == dwarf::DW_TAG_compile_unit ||
73 UnitTag == dwarf::DW_TAG_type_unit);
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 int64_t DwarfUnit::getDefaultLowerBound() const {
93 switch (getLanguage()) {
97 case dwarf::DW_LANG_C89:
98 case dwarf::DW_LANG_C99:
99 case dwarf::DW_LANG_C:
100 case dwarf::DW_LANG_C_plus_plus:
101 case dwarf::DW_LANG_ObjC:
102 case dwarf::DW_LANG_ObjC_plus_plus:
105 case dwarf::DW_LANG_Fortran77:
106 case dwarf::DW_LANG_Fortran90:
107 case dwarf::DW_LANG_Fortran95:
110 // The languages below have valid values only if the DWARF version >= 4.
111 case dwarf::DW_LANG_Java:
112 case dwarf::DW_LANG_Python:
113 case dwarf::DW_LANG_UPC:
114 case dwarf::DW_LANG_D:
115 if (dwarf::DWARF_VERSION >= 4)
119 case dwarf::DW_LANG_Ada83:
120 case dwarf::DW_LANG_Ada95:
121 case dwarf::DW_LANG_Cobol74:
122 case dwarf::DW_LANG_Cobol85:
123 case dwarf::DW_LANG_Modula2:
124 case dwarf::DW_LANG_Pascal83:
125 case dwarf::DW_LANG_PLI:
126 if (dwarf::DWARF_VERSION >= 4)
130 // The languages below have valid values only if the DWARF version >= 5.
131 case dwarf::DW_LANG_OpenCL:
132 case dwarf::DW_LANG_Go:
133 case dwarf::DW_LANG_Haskell:
134 case dwarf::DW_LANG_C_plus_plus_03:
135 case dwarf::DW_LANG_C_plus_plus_11:
136 case dwarf::DW_LANG_OCaml:
137 case dwarf::DW_LANG_Rust:
138 case dwarf::DW_LANG_C11:
139 case dwarf::DW_LANG_Swift:
140 case dwarf::DW_LANG_Dylan:
141 case dwarf::DW_LANG_C_plus_plus_14:
142 if (dwarf::DWARF_VERSION >= 5)
146 case dwarf::DW_LANG_Modula3:
147 case dwarf::DW_LANG_Julia:
148 case dwarf::DW_LANG_Fortran03:
149 case dwarf::DW_LANG_Fortran08:
150 if (dwarf::DWARF_VERSION >= 5)
158 /// Check whether the DIE for this MDNode can be shared across CUs.
159 static bool isShareableAcrossCUs(const DINode *D) {
160 // When the MDNode can be part of the type system, the DIE can be shared
162 // Combining type units and cross-CU DIE sharing is lower value (since
163 // cross-CU DIE sharing is used in LTO and removes type redundancy at that
164 // level already) but may be implementable for some value in projects
165 // building multiple independent libraries with LTO and then linking those
167 return (isa<DIType>(D) ||
168 (isa<DISubprogram>(D) && !cast<DISubprogram>(D)->isDefinition())) &&
169 !GenerateDwarfTypeUnits;
172 DIE *DwarfUnit::getDIE(const DINode *D) const {
173 if (isShareableAcrossCUs(D))
174 return DU->getDIE(D);
175 return MDNodeToDieMap.lookup(D);
178 void DwarfUnit::insertDIE(const DINode *Desc, DIE *D) {
179 if (isShareableAcrossCUs(Desc)) {
180 DU->insertDIE(Desc, D);
183 MDNodeToDieMap.insert(std::make_pair(Desc, D));
186 void DwarfUnit::addFlag(DIE &Die, dwarf::Attribute Attribute) {
187 if (DD->getDwarfVersion() >= 4)
188 Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_flag_present,
191 Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_flag,
195 void DwarfUnit::addUInt(DIE &Die, dwarf::Attribute Attribute,
196 Optional<dwarf::Form> Form, uint64_t Integer) {
198 Form = DIEInteger::BestForm(false, Integer);
199 Die.addValue(DIEValueAllocator, Attribute, *Form, DIEInteger(Integer));
202 void DwarfUnit::addUInt(DIE &Block, dwarf::Form Form, uint64_t Integer) {
203 addUInt(Block, (dwarf::Attribute)0, Form, Integer);
206 void DwarfUnit::addSInt(DIE &Die, dwarf::Attribute Attribute,
207 Optional<dwarf::Form> Form, int64_t Integer) {
209 Form = DIEInteger::BestForm(true, Integer);
210 Die.addValue(DIEValueAllocator, Attribute, *Form, DIEInteger(Integer));
213 void DwarfUnit::addSInt(DIELoc &Die, Optional<dwarf::Form> Form,
215 addSInt(Die, (dwarf::Attribute)0, Form, Integer);
218 void DwarfUnit::addString(DIE &Die, dwarf::Attribute Attribute,
220 Die.addValue(DIEValueAllocator, Attribute,
221 isDwoUnit() ? dwarf::DW_FORM_GNU_str_index : dwarf::DW_FORM_strp,
222 DIEString(DU->getStringPool().getEntry(*Asm, String)));
225 DIE::value_iterator DwarfUnit::addLabel(DIE &Die, dwarf::Attribute Attribute,
227 const MCSymbol *Label) {
228 return Die.addValue(DIEValueAllocator, Attribute, Form, DIELabel(Label));
231 void DwarfUnit::addLabel(DIELoc &Die, dwarf::Form Form, const MCSymbol *Label) {
232 addLabel(Die, (dwarf::Attribute)0, Form, Label);
235 void DwarfUnit::addSectionOffset(DIE &Die, dwarf::Attribute Attribute,
237 if (DD->getDwarfVersion() >= 4)
238 addUInt(Die, Attribute, dwarf::DW_FORM_sec_offset, Integer);
240 addUInt(Die, Attribute, dwarf::DW_FORM_data4, Integer);
243 unsigned DwarfTypeUnit::getOrCreateSourceID(StringRef FileName, StringRef DirName) {
244 return SplitLineTable ? SplitLineTable->getFile(DirName, FileName)
245 : getCU().getOrCreateSourceID(FileName, DirName);
248 void DwarfUnit::addOpAddress(DIELoc &Die, const MCSymbol *Sym) {
249 if (!DD->useSplitDwarf()) {
250 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
251 addLabel(Die, dwarf::DW_FORM_udata, Sym);
253 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index);
254 addUInt(Die, dwarf::DW_FORM_GNU_addr_index,
255 DD->getAddressPool().getIndex(Sym));
259 void DwarfUnit::addLabelDelta(DIE &Die, dwarf::Attribute Attribute,
260 const MCSymbol *Hi, const MCSymbol *Lo) {
261 Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_data4,
262 new (DIEValueAllocator) DIEDelta(Hi, Lo));
265 void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute, DIE &Entry) {
266 addDIEEntry(Die, Attribute, DIEEntry(Entry));
269 void DwarfUnit::addDIETypeSignature(DIE &Die, const DwarfTypeUnit &Type) {
270 // Flag the type unit reference as a declaration so that if it contains
271 // members (implicit special members, static data member definitions, member
272 // declarations for definitions in this CU, etc) consumers don't get confused
273 // and think this is a full definition.
274 addFlag(Die, dwarf::DW_AT_declaration);
276 Die.addValue(DIEValueAllocator, dwarf::DW_AT_signature,
277 dwarf::DW_FORM_ref_sig8, DIETypeSignature(Type));
280 void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute,
282 const DIE *DieCU = Die.getUnitOrNull();
283 const DIE *EntryCU = Entry.getEntry().getUnitOrNull();
285 // We assume that Die belongs to this CU, if it is not linked to any CU yet.
286 DieCU = &getUnitDie();
288 EntryCU = &getUnitDie();
289 Die.addValue(DIEValueAllocator, Attribute,
290 EntryCU == DieCU ? dwarf::DW_FORM_ref4 : dwarf::DW_FORM_ref_addr,
294 DIE &DwarfUnit::createAndAddDIE(unsigned Tag, DIE &Parent, const DINode *N) {
295 assert(Tag != dwarf::DW_TAG_auto_variable &&
296 Tag != dwarf::DW_TAG_arg_variable);
297 DIE &Die = Parent.addChild(DIE::get(DIEValueAllocator, (dwarf::Tag)Tag));
303 void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute, DIELoc *Loc) {
304 Loc->ComputeSize(Asm);
305 DIELocs.push_back(Loc); // Memoize so we can call the destructor later on.
306 Die.addValue(DIEValueAllocator, Attribute,
307 Loc->BestForm(DD->getDwarfVersion()), Loc);
310 void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute,
312 Block->ComputeSize(Asm);
313 DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
314 Die.addValue(DIEValueAllocator, Attribute, Block->BestForm(), Block);
317 void DwarfUnit::addSourceLine(DIE &Die, unsigned Line, StringRef File,
318 StringRef Directory) {
322 unsigned FileID = getOrCreateSourceID(File, Directory);
323 assert(FileID && "Invalid file id");
324 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
325 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
328 void DwarfUnit::addSourceLine(DIE &Die, const DILocalVariable *V) {
331 addSourceLine(Die, V->getLine(), V->getScope()->getFilename(),
332 V->getScope()->getDirectory());
335 void DwarfUnit::addSourceLine(DIE &Die, const DIGlobalVariable *G) {
338 addSourceLine(Die, G->getLine(), G->getFilename(), G->getDirectory());
341 void DwarfUnit::addSourceLine(DIE &Die, const DISubprogram *SP) {
344 addSourceLine(Die, SP->getLine(), SP->getFilename(), SP->getDirectory());
347 void DwarfUnit::addSourceLine(DIE &Die, const DIType *Ty) {
350 addSourceLine(Die, Ty->getLine(), Ty->getFilename(), Ty->getDirectory());
353 void DwarfUnit::addSourceLine(DIE &Die, const DIObjCProperty *Ty) {
356 addSourceLine(Die, Ty->getLine(), Ty->getFilename(), Ty->getDirectory());
359 void DwarfUnit::addSourceLine(DIE &Die, const DINamespace *NS) {
360 addSourceLine(Die, NS->getLine(), NS->getFilename(), NS->getDirectory());
363 bool DwarfUnit::addRegisterOpPiece(DIELoc &TheDie, unsigned Reg,
364 unsigned SizeInBits, unsigned OffsetInBits) {
365 DIEDwarfExpression Expr(*Asm, *this, TheDie);
366 Expr.AddMachineRegPiece(Reg, SizeInBits, OffsetInBits);
370 bool DwarfUnit::addRegisterOffset(DIELoc &TheDie, unsigned Reg,
372 DIEDwarfExpression Expr(*Asm, *this, TheDie);
373 return Expr.AddMachineRegIndirect(Reg, Offset);
376 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
377 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
378 gives the variable VarName either the struct, or a pointer to the struct, as
379 its type. This is necessary for various behind-the-scenes things the
380 compiler needs to do with by-reference variables in Blocks.
382 However, as far as the original *programmer* is concerned, the variable
383 should still have type 'SomeType', as originally declared.
385 The function getBlockByrefType dives into the __Block_byref_x_VarName
386 struct to find the original type of the variable, which is then assigned to
387 the variable's Debug Information Entry as its real type. So far, so good.
388 However now the debugger will expect the variable VarName to have the type
389 SomeType. So we need the location attribute for the variable to be an
390 expression that explains to the debugger how to navigate through the
391 pointers and struct to find the actual variable of type SomeType.
393 The following function does just that. We start by getting
394 the "normal" location for the variable. This will be the location
395 of either the struct __Block_byref_x_VarName or the pointer to the
396 struct __Block_byref_x_VarName.
398 The struct will look something like:
400 struct __Block_byref_x_VarName {
402 struct __Block_byref_x_VarName *forwarding;
403 ... <various other fields>
405 ... <maybe more fields>
408 If we are given the struct directly (as our starting point) we
409 need to tell the debugger to:
411 1). Add the offset of the forwarding field.
413 2). Follow that pointer to get the real __Block_byref_x_VarName
414 struct to use (the real one may have been copied onto the heap).
416 3). Add the offset for the field VarName, to find the actual variable.
418 If we started with a pointer to the struct, then we need to
419 dereference that pointer first, before the other steps.
420 Translating this into DWARF ops, we will need to append the following
421 to the current location description for the variable:
423 DW_OP_deref -- optional, if we start with a pointer
424 DW_OP_plus_uconst <forward_fld_offset>
426 DW_OP_plus_uconst <varName_fld_offset>
428 That is what this function does. */
430 void DwarfUnit::addBlockByrefAddress(const DbgVariable &DV, DIE &Die,
431 dwarf::Attribute Attribute,
432 const MachineLocation &Location) {
433 const DIType *Ty = DV.getType();
434 const DIType *TmpTy = Ty;
435 uint16_t Tag = Ty->getTag();
436 bool isPointer = false;
438 StringRef varName = DV.getName();
440 if (Tag == dwarf::DW_TAG_pointer_type) {
441 auto *DTy = cast<DIDerivedType>(Ty);
442 TmpTy = resolve(DTy->getBaseType());
446 // Find the __forwarding field and the variable field in the __Block_byref
448 DINodeArray Fields = cast<DICompositeTypeBase>(TmpTy)->getElements();
449 const DIDerivedType *varField = nullptr;
450 const DIDerivedType *forwardingField = nullptr;
452 for (unsigned i = 0, N = Fields.size(); i < N; ++i) {
453 auto *DT = cast<DIDerivedType>(Fields[i]);
454 StringRef fieldName = DT->getName();
455 if (fieldName == "__forwarding")
456 forwardingField = DT;
457 else if (fieldName == varName)
461 // Get the offsets for the forwarding field and the variable field.
462 unsigned forwardingFieldOffset = forwardingField->getOffsetInBits() >> 3;
463 unsigned varFieldOffset = varField->getOffsetInBits() >> 2;
465 // Decode the original location, and use that as the start of the byref
466 // variable's location.
467 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
470 if (Location.isReg())
471 validReg = addRegisterOpPiece(*Loc, Location.getReg());
473 validReg = addRegisterOffset(*Loc, Location.getReg(), Location.getOffset());
478 // If we started with a pointer to the __Block_byref... struct, then
479 // the first thing we need to do is dereference the pointer (DW_OP_deref).
481 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
483 // Next add the offset for the '__forwarding' field:
484 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
485 // adding the offset if it's 0.
486 if (forwardingFieldOffset > 0) {
487 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
488 addUInt(*Loc, dwarf::DW_FORM_udata, forwardingFieldOffset);
491 // Now dereference the __forwarding field to get to the real __Block_byref
492 // struct: DW_OP_deref.
493 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
495 // Now that we've got the real __Block_byref... struct, add the offset
496 // for the variable's field to get to the location of the actual variable:
497 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
498 if (varFieldOffset > 0) {
499 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
500 addUInt(*Loc, dwarf::DW_FORM_udata, varFieldOffset);
503 // Now attach the location information to the DIE.
504 addBlock(Die, Attribute, Loc);
507 /// Return true if type encoding is unsigned.
508 static bool isUnsignedDIType(DwarfDebug *DD, const DIType *Ty) {
509 if (auto *DTy = dyn_cast<DIDerivedTypeBase>(Ty)) {
510 dwarf::Tag T = (dwarf::Tag)Ty->getTag();
511 // Encode pointer constants as unsigned bytes. This is used at least for
512 // null pointer constant emission.
513 // (Pieces of) aggregate types that get hacked apart by SROA may also be
514 // represented by a constant. Encode them as unsigned bytes.
515 // FIXME: reference and rvalue_reference /probably/ shouldn't be allowed
516 // here, but accept them for now due to a bug in SROA producing bogus
518 if (T == dwarf::DW_TAG_array_type ||
519 T == dwarf::DW_TAG_class_type ||
520 T == dwarf::DW_TAG_pointer_type ||
521 T == dwarf::DW_TAG_ptr_to_member_type ||
522 T == dwarf::DW_TAG_reference_type ||
523 T == dwarf::DW_TAG_rvalue_reference_type ||
524 T == dwarf::DW_TAG_structure_type ||
525 T == dwarf::DW_TAG_union_type)
527 assert(T == dwarf::DW_TAG_typedef || T == dwarf::DW_TAG_const_type ||
528 T == dwarf::DW_TAG_volatile_type ||
529 T == dwarf::DW_TAG_restrict_type ||
530 T == dwarf::DW_TAG_enumeration_type);
531 if (DITypeRef Deriv = DTy->getBaseType())
532 return isUnsignedDIType(DD, DD->resolve(Deriv));
533 // FIXME: Enums without a fixed underlying type have unknown signedness
534 // here, leading to incorrectly emitted constants.
535 assert(DTy->getTag() == dwarf::DW_TAG_enumeration_type);
539 auto *BTy = cast<DIBasicType>(Ty);
540 unsigned Encoding = BTy->getEncoding();
541 assert((Encoding == dwarf::DW_ATE_unsigned ||
542 Encoding == dwarf::DW_ATE_unsigned_char ||
543 Encoding == dwarf::DW_ATE_signed ||
544 Encoding == dwarf::DW_ATE_signed_char ||
545 Encoding == dwarf::DW_ATE_float || Encoding == dwarf::DW_ATE_UTF ||
546 Encoding == dwarf::DW_ATE_boolean ||
547 (Ty->getTag() == dwarf::DW_TAG_unspecified_type &&
548 Ty->getName() == "decltype(nullptr)")) &&
549 "Unsupported encoding");
550 return Encoding == dwarf::DW_ATE_unsigned ||
551 Encoding == dwarf::DW_ATE_unsigned_char ||
552 Encoding == dwarf::DW_ATE_UTF || Encoding == dwarf::DW_ATE_boolean ||
553 Ty->getTag() == dwarf::DW_TAG_unspecified_type;
556 /// If this type is derived from a base type then return base type size.
557 static uint64_t getBaseTypeSize(DwarfDebug *DD, const DIDerivedType *Ty) {
558 unsigned Tag = Ty->getTag();
560 if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef &&
561 Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type &&
562 Tag != dwarf::DW_TAG_restrict_type)
563 return Ty->getSizeInBits();
565 auto *BaseType = DD->resolve(Ty->getBaseType());
567 assert(BaseType && "Unexpected invalid base type");
569 // If this is a derived type, go ahead and get the base type, unless it's a
570 // reference then it's just the size of the field. Pointer types have no need
571 // of this since they're a different type of qualification on the type.
572 if (BaseType->getTag() == dwarf::DW_TAG_reference_type ||
573 BaseType->getTag() == dwarf::DW_TAG_rvalue_reference_type)
574 return Ty->getSizeInBits();
576 if (auto *DT = dyn_cast<DIDerivedType>(BaseType))
577 return getBaseTypeSize(DD, DT);
579 return BaseType->getSizeInBits();
582 void DwarfUnit::addConstantFPValue(DIE &Die, const MachineOperand &MO) {
583 assert(MO.isFPImm() && "Invalid machine operand!");
584 DIEBlock *Block = new (DIEValueAllocator) DIEBlock;
585 APFloat FPImm = MO.getFPImm()->getValueAPF();
587 // Get the raw data form of the floating point.
588 const APInt FltVal = FPImm.bitcastToAPInt();
589 const char *FltPtr = (const char *)FltVal.getRawData();
591 int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
592 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
593 int Incr = (LittleEndian ? 1 : -1);
594 int Start = (LittleEndian ? 0 : NumBytes - 1);
595 int Stop = (LittleEndian ? NumBytes : -1);
597 // Output the constant to DWARF one byte at a time.
598 for (; Start != Stop; Start += Incr)
599 addUInt(*Block, dwarf::DW_FORM_data1, (unsigned char)0xFF & FltPtr[Start]);
601 addBlock(Die, dwarf::DW_AT_const_value, Block);
604 void DwarfUnit::addConstantFPValue(DIE &Die, const ConstantFP *CFP) {
605 // Pass this down to addConstantValue as an unsigned bag of bits.
606 addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true);
609 void DwarfUnit::addConstantValue(DIE &Die, const ConstantInt *CI,
611 addConstantValue(Die, CI->getValue(), Ty);
614 void DwarfUnit::addConstantValue(DIE &Die, const MachineOperand &MO,
616 assert(MO.isImm() && "Invalid machine operand!");
618 addConstantValue(Die, isUnsignedDIType(DD, Ty), MO.getImm());
621 void DwarfUnit::addConstantValue(DIE &Die, bool Unsigned, uint64_t Val) {
622 // FIXME: This is a bit conservative/simple - it emits negative values always
623 // sign extended to 64 bits rather than minimizing the number of bytes.
624 addUInt(Die, dwarf::DW_AT_const_value,
625 Unsigned ? dwarf::DW_FORM_udata : dwarf::DW_FORM_sdata, Val);
628 void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, const DIType *Ty) {
629 addConstantValue(Die, Val, isUnsignedDIType(DD, Ty));
632 void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, bool Unsigned) {
633 unsigned CIBitWidth = Val.getBitWidth();
634 if (CIBitWidth <= 64) {
635 addConstantValue(Die, Unsigned,
636 Unsigned ? Val.getZExtValue() : Val.getSExtValue());
640 DIEBlock *Block = new (DIEValueAllocator) DIEBlock;
642 // Get the raw data form of the large APInt.
643 const uint64_t *Ptr64 = Val.getRawData();
645 int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
646 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
648 // Output the constant to DWARF one byte at a time.
649 for (int i = 0; i < NumBytes; i++) {
652 c = Ptr64[i / 8] >> (8 * (i & 7));
654 c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
655 addUInt(*Block, dwarf::DW_FORM_data1, c);
658 addBlock(Die, dwarf::DW_AT_const_value, Block);
661 void DwarfUnit::addLinkageName(DIE &Die, StringRef LinkageName) {
662 if (!LinkageName.empty())
664 DD->getDwarfVersion() >= 4 ? dwarf::DW_AT_linkage_name
665 : dwarf::DW_AT_MIPS_linkage_name,
666 GlobalValue::getRealLinkageName(LinkageName));
669 void DwarfUnit::addTemplateParams(DIE &Buffer, DINodeArray TParams) {
670 // Add template parameters.
671 for (const auto *Element : TParams) {
672 if (auto *TTP = dyn_cast<DITemplateTypeParameter>(Element))
673 constructTemplateTypeParameterDIE(Buffer, TTP);
674 else if (auto *TVP = dyn_cast<DITemplateValueParameter>(Element))
675 constructTemplateValueParameterDIE(Buffer, TVP);
679 DIE *DwarfUnit::getOrCreateContextDIE(const DIScope *Context) {
680 if (!Context || isa<DIFile>(Context))
681 return &getUnitDie();
682 if (auto *T = dyn_cast<DIType>(Context))
683 return getOrCreateTypeDIE(T);
684 if (auto *NS = dyn_cast<DINamespace>(Context))
685 return getOrCreateNameSpace(NS);
686 if (auto *SP = dyn_cast<DISubprogram>(Context))
687 return getOrCreateSubprogramDIE(SP);
688 return getDIE(Context);
691 DIE *DwarfUnit::createTypeDIE(const DICompositeType *Ty) {
692 auto *Context = resolve(Ty->getScope());
693 DIE *ContextDIE = getOrCreateContextDIE(Context);
695 if (DIE *TyDIE = getDIE(Ty))
699 DIE &TyDIE = createAndAddDIE(Ty->getTag(), *ContextDIE, Ty);
701 constructTypeDIE(TyDIE, cast<DICompositeType>(Ty));
703 updateAcceleratorTables(Context, Ty, TyDIE);
707 DIE *DwarfUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
711 auto *Ty = cast<DIType>(TyNode);
712 assert(Ty == resolve(Ty->getRef()) &&
713 "type was not uniqued, possible ODR violation.");
715 // DW_TAG_restrict_type is not supported in DWARF2
716 if (Ty->getTag() == dwarf::DW_TAG_restrict_type && DD->getDwarfVersion() <= 2)
717 return getOrCreateTypeDIE(resolve(cast<DIDerivedType>(Ty)->getBaseType()));
719 // Construct the context before querying for the existence of the DIE in case
720 // such construction creates the DIE.
721 auto *Context = resolve(Ty->getScope());
722 DIE *ContextDIE = getOrCreateContextDIE(Context);
725 if (DIE *TyDIE = getDIE(Ty))
729 DIE &TyDIE = createAndAddDIE(Ty->getTag(), *ContextDIE, Ty);
731 updateAcceleratorTables(Context, Ty, TyDIE);
733 if (auto *BT = dyn_cast<DIBasicType>(Ty))
734 constructTypeDIE(TyDIE, BT);
735 else if (auto *STy = dyn_cast<DISubroutineType>(Ty))
736 constructTypeDIE(TyDIE, STy);
737 else if (auto *CTy = dyn_cast<DICompositeType>(Ty)) {
738 if (GenerateDwarfTypeUnits && !Ty->isForwardDecl())
739 if (MDString *TypeId = CTy->getRawIdentifier()) {
740 DD->addDwarfTypeUnitType(getCU(), TypeId->getString(), TyDIE, CTy);
741 // Skip updating the accelerator tables since this is not the full type.
744 constructTypeDIE(TyDIE, CTy);
746 constructTypeDIE(TyDIE, cast<DIDerivedType>(Ty));
752 void DwarfUnit::updateAcceleratorTables(const DIScope *Context,
753 const DIType *Ty, const DIE &TyDIE) {
754 if (!Ty->getName().empty() && !Ty->isForwardDecl()) {
755 bool IsImplementation = 0;
756 if (auto *CT = dyn_cast<DICompositeTypeBase>(Ty)) {
757 // A runtime language of 0 actually means C/C++ and that any
758 // non-negative value is some version of Objective-C/C++.
759 IsImplementation = CT->getRuntimeLang() == 0 || CT->isObjcClassComplete();
761 unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0;
762 DD->addAccelType(Ty->getName(), TyDIE, Flags);
764 if (!Context || isa<DICompileUnit>(Context) || isa<DIFile>(Context) ||
765 isa<DINamespace>(Context))
766 addGlobalType(Ty, TyDIE, Context);
770 void DwarfUnit::addType(DIE &Entity, const DIType *Ty,
771 dwarf::Attribute Attribute) {
772 assert(Ty && "Trying to add a type that doesn't exist?");
773 addDIEEntry(Entity, Attribute, DIEEntry(*getOrCreateTypeDIE(Ty)));
776 std::string DwarfUnit::getParentContextString(const DIScope *Context) const {
780 // FIXME: Decide whether to implement this for non-C++ languages.
781 if (getLanguage() != dwarf::DW_LANG_C_plus_plus)
785 SmallVector<const DIScope *, 1> Parents;
786 while (!isa<DICompileUnit>(Context)) {
787 Parents.push_back(Context);
788 if (Context->getScope())
789 Context = resolve(Context->getScope());
791 // Structure, etc types will have a NULL context if they're at the top
796 // Reverse iterate over our list to go from the outermost construct to the
798 for (auto I = Parents.rbegin(), E = Parents.rend(); I != E; ++I) {
799 const DIScope *Ctx = *I;
800 StringRef Name = Ctx->getName();
801 if (Name.empty() && isa<DINamespace>(Ctx))
802 Name = "(anonymous namespace)";
811 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DIBasicType *BTy) {
812 // Get core information.
813 StringRef Name = BTy->getName();
814 // Add name if not anonymous or intermediate type.
816 addString(Buffer, dwarf::DW_AT_name, Name);
818 // An unspecified type only has a name attribute.
819 if (BTy->getTag() == dwarf::DW_TAG_unspecified_type)
822 addUInt(Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
825 uint64_t Size = BTy->getSizeInBits() >> 3;
826 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
829 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DIDerivedType *DTy) {
830 // Get core information.
831 StringRef Name = DTy->getName();
832 uint64_t Size = DTy->getSizeInBits() >> 3;
833 uint16_t Tag = Buffer.getTag();
835 // Map to main type, void will not have a type.
836 const DIType *FromTy = resolve(DTy->getBaseType());
838 addType(Buffer, FromTy);
840 // Add name if not anonymous or intermediate type.
842 addString(Buffer, dwarf::DW_AT_name, Name);
844 // Add size if non-zero (derived types might be zero-sized.)
845 if (Size && Tag != dwarf::DW_TAG_pointer_type
846 && Tag != dwarf::DW_TAG_ptr_to_member_type)
847 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
849 if (Tag == dwarf::DW_TAG_ptr_to_member_type)
851 Buffer, dwarf::DW_AT_containing_type,
852 *getOrCreateTypeDIE(resolve(cast<DIDerivedType>(DTy)->getClassType())));
853 // Add source line info if available and TyDesc is not a forward declaration.
854 if (!DTy->isForwardDecl())
855 addSourceLine(Buffer, DTy);
858 void DwarfUnit::constructSubprogramArguments(DIE &Buffer, DITypeRefArray Args) {
859 for (unsigned i = 1, N = Args.size(); i < N; ++i) {
860 const DIType *Ty = resolve(Args[i]);
862 assert(i == N-1 && "Unspecified parameter must be the last argument");
863 createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
865 DIE &Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
867 if (Ty->isArtificial())
868 addFlag(Arg, dwarf::DW_AT_artificial);
873 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DISubroutineType *CTy) {
874 // Add return type. A void return won't have a type.
875 auto Elements = cast<DISubroutineType>(CTy)->getTypeArray();
877 if (auto RTy = resolve(Elements[0]))
878 addType(Buffer, RTy);
880 bool isPrototyped = true;
881 if (Elements.size() == 2 && !Elements[1])
882 isPrototyped = false;
884 constructSubprogramArguments(Buffer, Elements);
886 // Add prototype flag if we're dealing with a C language and the function has
888 uint16_t Language = getLanguage();
890 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
891 Language == dwarf::DW_LANG_ObjC))
892 addFlag(Buffer, dwarf::DW_AT_prototyped);
894 if (CTy->isLValueReference())
895 addFlag(Buffer, dwarf::DW_AT_reference);
897 if (CTy->isRValueReference())
898 addFlag(Buffer, dwarf::DW_AT_rvalue_reference);
901 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
902 // Add name if not anonymous or intermediate type.
903 StringRef Name = CTy->getName();
905 uint64_t Size = CTy->getSizeInBits() >> 3;
906 uint16_t Tag = Buffer.getTag();
909 case dwarf::DW_TAG_array_type:
910 constructArrayTypeDIE(Buffer, CTy);
912 case dwarf::DW_TAG_enumeration_type:
913 constructEnumTypeDIE(Buffer, CTy);
915 case dwarf::DW_TAG_structure_type:
916 case dwarf::DW_TAG_union_type:
917 case dwarf::DW_TAG_class_type: {
918 // Add elements to structure type.
919 DINodeArray Elements = CTy->getElements();
920 for (const auto *Element : Elements) {
923 if (auto *SP = dyn_cast<DISubprogram>(Element))
924 getOrCreateSubprogramDIE(SP);
925 else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
926 if (DDTy->getTag() == dwarf::DW_TAG_friend) {
927 DIE &ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
928 addType(ElemDie, resolve(DDTy->getBaseType()), dwarf::DW_AT_friend);
929 } else if (DDTy->isStaticMember()) {
930 getOrCreateStaticMemberDIE(DDTy);
932 constructMemberDIE(Buffer, DDTy);
934 } else if (auto *Property = dyn_cast<DIObjCProperty>(Element)) {
935 DIE &ElemDie = createAndAddDIE(Property->getTag(), Buffer);
936 StringRef PropertyName = Property->getName();
937 addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
938 if (Property->getType())
939 addType(ElemDie, resolve(Property->getType()));
940 addSourceLine(ElemDie, Property);
941 StringRef GetterName = Property->getGetterName();
942 if (!GetterName.empty())
943 addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
944 StringRef SetterName = Property->getSetterName();
945 if (!SetterName.empty())
946 addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
947 if (unsigned PropertyAttributes = Property->getAttributes())
948 addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None,
953 if (CTy->isAppleBlockExtension())
954 addFlag(Buffer, dwarf::DW_AT_APPLE_block);
956 // This is outside the DWARF spec, but GDB expects a DW_AT_containing_type
957 // inside C++ composite types to point to the base class with the vtable.
958 if (auto *ContainingType =
959 dyn_cast_or_null<DICompositeType>(resolve(CTy->getVTableHolder())))
960 addDIEEntry(Buffer, dwarf::DW_AT_containing_type,
961 *getOrCreateTypeDIE(ContainingType));
963 if (CTy->isObjcClassComplete())
964 addFlag(Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
966 // Add template parameters to a class, structure or union types.
967 // FIXME: The support isn't in the metadata for this yet.
968 if (Tag == dwarf::DW_TAG_class_type ||
969 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
970 addTemplateParams(Buffer, CTy->getTemplateParams());
978 // Add name if not anonymous or intermediate type.
980 addString(Buffer, dwarf::DW_AT_name, Name);
982 if (Tag == dwarf::DW_TAG_enumeration_type ||
983 Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
984 Tag == dwarf::DW_TAG_union_type) {
985 // Add size if non-zero (derived types might be zero-sized.)
986 // TODO: Do we care about size for enum forward declarations?
988 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
989 else if (!CTy->isForwardDecl())
990 // Add zero size if it is not a forward declaration.
991 addUInt(Buffer, dwarf::DW_AT_byte_size, None, 0);
993 // If we're a forward decl, say so.
994 if (CTy->isForwardDecl())
995 addFlag(Buffer, dwarf::DW_AT_declaration);
997 // Add source line info if available.
998 if (!CTy->isForwardDecl())
999 addSourceLine(Buffer, CTy);
1001 // No harm in adding the runtime language to the declaration.
1002 unsigned RLang = CTy->getRuntimeLang();
1004 addUInt(Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
1009 void DwarfUnit::constructTemplateTypeParameterDIE(
1010 DIE &Buffer, const DITemplateTypeParameter *TP) {
1012 createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
1013 // Add the type if it exists, it could be void and therefore no type.
1015 addType(ParamDIE, resolve(TP->getType()));
1016 if (!TP->getName().empty())
1017 addString(ParamDIE, dwarf::DW_AT_name, TP->getName());
1020 void DwarfUnit::constructTemplateValueParameterDIE(
1021 DIE &Buffer, const DITemplateValueParameter *VP) {
1022 DIE &ParamDIE = createAndAddDIE(VP->getTag(), Buffer);
1024 // Add the type if there is one, template template and template parameter
1025 // packs will not have a type.
1026 if (VP->getTag() == dwarf::DW_TAG_template_value_parameter)
1027 addType(ParamDIE, resolve(VP->getType()));
1028 if (!VP->getName().empty())
1029 addString(ParamDIE, dwarf::DW_AT_name, VP->getName());
1030 if (Metadata *Val = VP->getValue()) {
1031 if (ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(Val))
1032 addConstantValue(ParamDIE, CI, resolve(VP->getType()));
1033 else if (GlobalValue *GV = mdconst::dyn_extract<GlobalValue>(Val)) {
1034 // For declaration non-type template parameters (such as global values and
1036 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
1037 addOpAddress(*Loc, Asm->getSymbol(GV));
1038 // Emit DW_OP_stack_value to use the address as the immediate value of the
1039 // parameter, rather than a pointer to it.
1040 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
1041 addBlock(ParamDIE, dwarf::DW_AT_location, Loc);
1042 } else if (VP->getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1043 assert(isa<MDString>(Val));
1044 addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
1045 cast<MDString>(Val)->getString());
1046 } else if (VP->getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1047 addTemplateParams(ParamDIE, cast<MDTuple>(Val));
1052 DIE *DwarfUnit::getOrCreateNameSpace(const DINamespace *NS) {
1053 // Construct the context before querying for the existence of the DIE in case
1054 // such construction creates the DIE.
1055 DIE *ContextDIE = getOrCreateContextDIE(NS->getScope());
1057 if (DIE *NDie = getDIE(NS))
1059 DIE &NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS);
1061 StringRef Name = NS->getName();
1063 addString(NDie, dwarf::DW_AT_name, NS->getName());
1065 Name = "(anonymous namespace)";
1066 DD->addAccelNamespace(Name, NDie);
1067 addGlobalName(Name, NDie, NS->getScope());
1068 addSourceLine(NDie, NS);
1072 DIE *DwarfUnit::getOrCreateModule(const DIModule *M) {
1073 // Construct the context before querying for the existence of the DIE in case
1074 // such construction creates the DIE.
1075 DIE *ContextDIE = getOrCreateContextDIE(M->getScope());
1077 if (DIE *MDie = getDIE(M))
1079 DIE &MDie = createAndAddDIE(dwarf::DW_TAG_module, *ContextDIE, M);
1081 if (!M->getName().empty()) {
1082 addString(MDie, dwarf::DW_AT_name, M->getName());
1083 addGlobalName(M->getName(), MDie, M->getScope());
1085 if (!M->getConfigurationMacros().empty())
1086 addString(MDie, dwarf::DW_AT_LLVM_config_macros,
1087 M->getConfigurationMacros());
1088 if (!M->getIncludePath().empty())
1089 addString(MDie, dwarf::DW_AT_LLVM_include_path, M->getIncludePath());
1090 if (!M->getISysRoot().empty())
1091 addString(MDie, dwarf::DW_AT_LLVM_isysroot, M->getISysRoot());
1096 DIE *DwarfUnit::getOrCreateSubprogramDIE(const DISubprogram *SP, bool Minimal) {
1097 // Construct the context before querying for the existence of the DIE in case
1098 // such construction creates the DIE (as is the case for member function
1101 Minimal ? &getUnitDie() : getOrCreateContextDIE(resolve(SP->getScope()));
1103 if (DIE *SPDie = getDIE(SP))
1106 if (auto *SPDecl = SP->getDeclaration()) {
1108 // Add subprogram definitions to the CU die directly.
1109 ContextDIE = &getUnitDie();
1110 // Build the decl now to ensure it precedes the definition.
1111 getOrCreateSubprogramDIE(SPDecl);
1115 // DW_TAG_inlined_subroutine may refer to this DIE.
1116 DIE &SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
1118 // Stop here and fill this in later, depending on whether or not this
1119 // subprogram turns out to have inlined instances or not.
1120 if (SP->isDefinition())
1123 applySubprogramAttributes(SP, SPDie);
1127 bool DwarfUnit::applySubprogramDefinitionAttributes(const DISubprogram *SP,
1129 DIE *DeclDie = nullptr;
1130 StringRef DeclLinkageName;
1131 if (auto *SPDecl = SP->getDeclaration()) {
1132 DeclDie = getDIE(SPDecl);
1133 assert(DeclDie && "This DIE should've already been constructed when the "
1134 "definition DIE was created in "
1135 "getOrCreateSubprogramDIE");
1136 DeclLinkageName = SPDecl->getLinkageName();
1139 // Add function template parameters.
1140 addTemplateParams(SPDie, SP->getTemplateParams());
1142 // Add the linkage name if we have one and it isn't in the Decl.
1143 StringRef LinkageName = SP->getLinkageName();
1144 assert(((LinkageName.empty() || DeclLinkageName.empty()) ||
1145 LinkageName == DeclLinkageName) &&
1146 "decl has a linkage name and it is different");
1147 if (DeclLinkageName.empty())
1148 addLinkageName(SPDie, LinkageName);
1153 // Refer to the function declaration where all the other attributes will be
1155 addDIEEntry(SPDie, dwarf::DW_AT_specification, *DeclDie);
1159 void DwarfUnit::applySubprogramAttributes(const DISubprogram *SP, DIE &SPDie,
1162 if (applySubprogramDefinitionAttributes(SP, SPDie))
1165 // Constructors and operators for anonymous aggregates do not have names.
1166 if (!SP->getName().empty())
1167 addString(SPDie, dwarf::DW_AT_name, SP->getName());
1169 // Skip the rest of the attributes under -gmlt to save space.
1173 addSourceLine(SPDie, SP);
1175 // Add the prototype if we have a prototype and we have a C like
1177 uint16_t Language = getLanguage();
1178 if (SP->isPrototyped() &&
1179 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1180 Language == dwarf::DW_LANG_ObjC))
1181 addFlag(SPDie, dwarf::DW_AT_prototyped);
1183 const DISubroutineType *SPTy = SP->getType();
1184 assert(SPTy->getTag() == dwarf::DW_TAG_subroutine_type &&
1185 "the type of a subprogram should be a subroutine");
1187 auto Args = SPTy->getTypeArray();
1188 // Add a return type. If this is a type like a C/C++ void type we don't add a
1191 if (auto Ty = resolve(Args[0]))
1194 unsigned VK = SP->getVirtuality();
1196 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1197 DIELoc *Block = getDIELoc();
1198 addUInt(*Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1199 addUInt(*Block, dwarf::DW_FORM_udata, SP->getVirtualIndex());
1200 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
1201 ContainingTypeMap.insert(
1202 std::make_pair(&SPDie, resolve(SP->getContainingType())));
1205 if (!SP->isDefinition()) {
1206 addFlag(SPDie, dwarf::DW_AT_declaration);
1208 // Add arguments. Do not add arguments for subprogram definition. They will
1209 // be handled while processing variables.
1210 constructSubprogramArguments(SPDie, Args);
1213 if (SP->isArtificial())
1214 addFlag(SPDie, dwarf::DW_AT_artificial);
1216 if (!SP->isLocalToUnit())
1217 addFlag(SPDie, dwarf::DW_AT_external);
1219 if (SP->isOptimized())
1220 addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1222 if (unsigned isa = Asm->getISAEncoding())
1223 addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1225 if (SP->isLValueReference())
1226 addFlag(SPDie, dwarf::DW_AT_reference);
1228 if (SP->isRValueReference())
1229 addFlag(SPDie, dwarf::DW_AT_rvalue_reference);
1231 if (SP->isProtected())
1232 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1233 dwarf::DW_ACCESS_protected);
1234 else if (SP->isPrivate())
1235 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1236 dwarf::DW_ACCESS_private);
1237 else if (SP->isPublic())
1238 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1239 dwarf::DW_ACCESS_public);
1241 if (SP->isExplicit())
1242 addFlag(SPDie, dwarf::DW_AT_explicit);
1245 void DwarfUnit::constructSubrangeDIE(DIE &Buffer, const DISubrange *SR,
1247 DIE &DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
1248 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, *IndexTy);
1250 // The LowerBound value defines the lower bounds which is typically zero for
1251 // C/C++. The Count value is the number of elements. Values are 64 bit. If
1252 // Count == -1 then the array is unbounded and we do not emit
1253 // DW_AT_lower_bound and DW_AT_count attributes.
1254 int64_t LowerBound = SR->getLowerBound();
1255 int64_t DefaultLowerBound = getDefaultLowerBound();
1256 int64_t Count = SR->getCount();
1258 if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
1259 addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound);
1262 // FIXME: An unbounded array should reference the expression that defines
1264 addUInt(DW_Subrange, dwarf::DW_AT_count, None, Count);
1267 DIE *DwarfUnit::getIndexTyDie() {
1270 // Construct an integer type to use for indexes.
1271 IndexTyDie = &createAndAddDIE(dwarf::DW_TAG_base_type, UnitDie);
1272 addString(*IndexTyDie, dwarf::DW_AT_name, "sizetype");
1273 addUInt(*IndexTyDie, dwarf::DW_AT_byte_size, None, sizeof(int64_t));
1274 addUInt(*IndexTyDie, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1275 dwarf::DW_ATE_unsigned);
1279 void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
1280 if (CTy->isVector())
1281 addFlag(Buffer, dwarf::DW_AT_GNU_vector);
1283 // Emit the element type.
1284 addType(Buffer, resolve(CTy->getBaseType()));
1286 // Get an anonymous type for index type.
1287 // FIXME: This type should be passed down from the front end
1288 // as different languages may have different sizes for indexes.
1289 DIE *IdxTy = getIndexTyDie();
1291 // Add subranges to array type.
1292 DINodeArray Elements = CTy->getElements();
1293 for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
1294 // FIXME: Should this really be such a loose cast?
1295 if (auto *Element = dyn_cast_or_null<DINode>(Elements[i]))
1296 if (Element->getTag() == dwarf::DW_TAG_subrange_type)
1297 constructSubrangeDIE(Buffer, cast<DISubrange>(Element), IdxTy);
1301 void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
1302 DINodeArray Elements = CTy->getElements();
1304 // Add enumerators to enumeration type.
1305 for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
1306 auto *Enum = dyn_cast_or_null<DIEnumerator>(Elements[i]);
1308 DIE &Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
1309 StringRef Name = Enum->getName();
1310 addString(Enumerator, dwarf::DW_AT_name, Name);
1311 int64_t Value = Enum->getValue();
1312 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
1316 const DIType *DTy = resolve(CTy->getBaseType());
1318 addType(Buffer, DTy);
1319 addFlag(Buffer, dwarf::DW_AT_enum_class);
1323 void DwarfUnit::constructContainingTypeDIEs() {
1324 for (auto CI = ContainingTypeMap.begin(), CE = ContainingTypeMap.end();
1326 DIE &SPDie = *CI->first;
1327 const DINode *D = CI->second;
1330 DIE *NDie = getDIE(D);
1333 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, *NDie);
1337 void DwarfUnit::constructMemberDIE(DIE &Buffer, const DIDerivedType *DT) {
1338 DIE &MemberDie = createAndAddDIE(DT->getTag(), Buffer);
1339 StringRef Name = DT->getName();
1341 addString(MemberDie, dwarf::DW_AT_name, Name);
1343 addType(MemberDie, resolve(DT->getBaseType()));
1345 addSourceLine(MemberDie, DT);
1347 if (DT->getTag() == dwarf::DW_TAG_inheritance && DT->isVirtual()) {
1349 // For C++, virtual base classes are not at fixed offset. Use following
1350 // expression to extract appropriate offset from vtable.
1351 // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1353 DIELoc *VBaseLocationDie = new (DIEValueAllocator) DIELoc;
1354 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1355 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1356 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1357 addUInt(*VBaseLocationDie, dwarf::DW_FORM_udata, DT->getOffsetInBits());
1358 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1359 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1360 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1362 addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
1364 uint64_t Size = DT->getSizeInBits();
1365 uint64_t FieldSize = getBaseTypeSize(DD, DT);
1366 uint64_t OffsetInBytes;
1368 if (FieldSize && Size != FieldSize) {
1369 // Handle bitfield, assume bytes are 8 bits.
1370 addUInt(MemberDie, dwarf::DW_AT_byte_size, None, FieldSize/8);
1371 addUInt(MemberDie, dwarf::DW_AT_bit_size, None, Size);
1373 // The DWARF 2 DW_AT_bit_offset is counting the bits between the most
1374 // significant bit of the aligned storage unit containing the bit field to
1375 // the most significan bit of the bit field.
1377 // FIXME: DWARF 4 states that DW_AT_data_bit_offset (which
1378 // counts from the beginning, regardless of endianness) should
1382 // Struct Align Align Align
1384 // +-----------+-----*-----+-----*-----+--
1385 // | ... |b1|b2|b3|b4|
1386 // +-----------+-----*-----+-----*-----+--
1387 // | | |<-- Size ->| |
1388 // |<---- Offset --->| |<--->|
1389 // | | | \_ DW_AT_bit_offset (little endian)
1391 // |<--------->| \_ StartBitOffset = DW_AT_bit_offset (big endian)
1392 // \ = DW_AT_data_bit_offset (biendian)
1394 uint64_t Offset = DT->getOffsetInBits();
1395 uint64_t Align = DT->getAlignInBits() ? DT->getAlignInBits() : FieldSize;
1396 uint64_t AlignMask = ~(Align - 1);
1397 // The bits from the start of the storage unit to the start of the field.
1398 uint64_t StartBitOffset = Offset - (Offset & AlignMask);
1399 // The endian-dependent DWARF 2 offset.
1400 uint64_t DwarfBitOffset = Asm->getDataLayout().isLittleEndian()
1401 ? OffsetToAlignment(Offset + Size, Align)
1404 // The byte offset of the field's aligned storage unit inside the struct.
1405 OffsetInBytes = (Offset - StartBitOffset) / 8;
1406 addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, DwarfBitOffset);
1408 // This is not a bitfield.
1409 OffsetInBytes = DT->getOffsetInBits() / 8;
1411 if (DD->getDwarfVersion() <= 2) {
1412 DIELoc *MemLocationDie = new (DIEValueAllocator) DIELoc;
1413 addUInt(*MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1414 addUInt(*MemLocationDie, dwarf::DW_FORM_udata, OffsetInBytes);
1415 addBlock(MemberDie, dwarf::DW_AT_data_member_location, MemLocationDie);
1417 addUInt(MemberDie, dwarf::DW_AT_data_member_location, None,
1421 if (DT->isProtected())
1422 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1423 dwarf::DW_ACCESS_protected);
1424 else if (DT->isPrivate())
1425 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1426 dwarf::DW_ACCESS_private);
1427 // Otherwise C++ member and base classes are considered public.
1428 else if (DT->isPublic())
1429 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1430 dwarf::DW_ACCESS_public);
1431 if (DT->isVirtual())
1432 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1433 dwarf::DW_VIRTUALITY_virtual);
1435 // Objective-C properties.
1436 if (DINode *PNode = DT->getObjCProperty())
1437 if (DIE *PDie = getDIE(PNode))
1438 MemberDie.addValue(DIEValueAllocator, dwarf::DW_AT_APPLE_property,
1439 dwarf::DW_FORM_ref4, DIEEntry(*PDie));
1441 if (DT->isArtificial())
1442 addFlag(MemberDie, dwarf::DW_AT_artificial);
1445 DIE *DwarfUnit::getOrCreateStaticMemberDIE(const DIDerivedType *DT) {
1449 // Construct the context before querying for the existence of the DIE in case
1450 // such construction creates the DIE.
1451 DIE *ContextDIE = getOrCreateContextDIE(resolve(DT->getScope()));
1452 assert(dwarf::isType(ContextDIE->getTag()) &&
1453 "Static member should belong to a type.");
1455 if (DIE *StaticMemberDIE = getDIE(DT))
1456 return StaticMemberDIE;
1458 DIE &StaticMemberDIE = createAndAddDIE(DT->getTag(), *ContextDIE, DT);
1460 const DIType *Ty = resolve(DT->getBaseType());
1462 addString(StaticMemberDIE, dwarf::DW_AT_name, DT->getName());
1463 addType(StaticMemberDIE, Ty);
1464 addSourceLine(StaticMemberDIE, DT);
1465 addFlag(StaticMemberDIE, dwarf::DW_AT_external);
1466 addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
1468 // FIXME: We could omit private if the parent is a class_type, and
1469 // public if the parent is something else.
1470 if (DT->isProtected())
1471 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1472 dwarf::DW_ACCESS_protected);
1473 else if (DT->isPrivate())
1474 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1475 dwarf::DW_ACCESS_private);
1476 else if (DT->isPublic())
1477 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1478 dwarf::DW_ACCESS_public);
1480 if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT->getConstant()))
1481 addConstantValue(StaticMemberDIE, CI, Ty);
1482 if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT->getConstant()))
1483 addConstantFPValue(StaticMemberDIE, CFP);
1485 return &StaticMemberDIE;
1488 void DwarfUnit::emitHeader(bool UseOffsets) {
1489 // Emit size of content not including length itself
1490 Asm->OutStreamer->AddComment("Length of Unit");
1491 Asm->EmitInt32(getHeaderSize() + UnitDie.getSize());
1493 Asm->OutStreamer->AddComment("DWARF version number");
1494 Asm->EmitInt16(DD->getDwarfVersion());
1495 Asm->OutStreamer->AddComment("Offset Into Abbrev. Section");
1497 // We share one abbreviations table across all units so it's always at the
1498 // start of the section. Use a relocatable offset where needed to ensure
1499 // linking doesn't invalidate that offset.
1500 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1501 Asm->emitDwarfSymbolReference(TLOF.getDwarfAbbrevSection()->getBeginSymbol(),
1504 Asm->OutStreamer->AddComment("Address Size (in bytes)");
1505 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
1508 void DwarfUnit::initSection(MCSection *Section) {
1509 assert(!this->Section);
1510 this->Section = Section;
1513 void DwarfTypeUnit::emitHeader(bool UseOffsets) {
1514 DwarfUnit::emitHeader(UseOffsets);
1515 Asm->OutStreamer->AddComment("Type Signature");
1516 Asm->OutStreamer->EmitIntValue(TypeSignature, sizeof(TypeSignature));
1517 Asm->OutStreamer->AddComment("Type DIE Offset");
1518 // In a skeleton type unit there is no type DIE so emit a zero offset.
1519 Asm->OutStreamer->EmitIntValue(Ty ? Ty->getOffset() : 0,
1520 sizeof(Ty->getOffset()));
1523 bool DwarfTypeUnit::isDwoUnit() const {
1524 // Since there are no skeleton type units, all type units are dwo type units
1525 // when split DWARF is being used.
1526 return DD->useSplitDwarf();