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"
16 #include "DwarfAccelTable.h"
17 #include "DwarfCompileUnit.h"
18 #include "DwarfDebug.h"
19 #include "llvm/ADT/APFloat.h"
20 #include "llvm/IR/Constants.h"
21 #include "llvm/IR/DIBuilder.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/GlobalVariable.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/IR/Mangler.h"
26 #include "llvm/MC/MCAsmInfo.h"
27 #include "llvm/MC/MCContext.h"
28 #include "llvm/MC/MCSection.h"
29 #include "llvm/MC/MCStreamer.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Target/TargetFrameLowering.h"
32 #include "llvm/Target/TargetLoweringObjectFile.h"
33 #include "llvm/Target/TargetMachine.h"
34 #include "llvm/Target/TargetRegisterInfo.h"
35 #include "llvm/Target/TargetSubtargetInfo.h"
39 #define DEBUG_TYPE "dwarfdebug"
42 GenerateDwarfTypeUnits("generate-type-units", cl::Hidden,
43 cl::desc("Generate DWARF4 type units."),
46 /// Unit - Unit constructor.
47 DwarfUnit::DwarfUnit(unsigned UID, dwarf::Tag UnitTag, DICompileUnit Node,
48 AsmPrinter *A, DwarfDebug *DW, DwarfFile *DWU)
49 : UniqueID(UID), CUNode(Node), UnitDie(UnitTag), DebugInfoOffset(0), Asm(A),
50 DD(DW), DU(DWU), IndexTyDie(nullptr), Section(nullptr) {
51 assert(UnitTag == dwarf::DW_TAG_compile_unit ||
52 UnitTag == dwarf::DW_TAG_type_unit);
53 DIEIntegerOne = new (DIEValueAllocator) DIEInteger(1);
56 DwarfTypeUnit::DwarfTypeUnit(unsigned UID, DwarfCompileUnit &CU, AsmPrinter *A,
57 DwarfDebug *DW, DwarfFile *DWU,
58 MCDwarfDwoLineTable *SplitLineTable)
59 : DwarfUnit(UID, dwarf::DW_TAG_type_unit, CU.getCUNode(), A, DW, DWU),
60 CU(CU), SplitLineTable(SplitLineTable) {
62 addSectionOffset(UnitDie, dwarf::DW_AT_stmt_list, 0);
65 /// ~Unit - Destructor for compile unit.
66 DwarfUnit::~DwarfUnit() {
67 for (unsigned j = 0, M = DIEBlocks.size(); j < M; ++j)
68 DIEBlocks[j]->~DIEBlock();
69 for (unsigned j = 0, M = DIELocs.size(); j < M; ++j)
70 DIELocs[j]->~DIELoc();
73 /// createDIEEntry - Creates a new DIEEntry to be a proxy for a debug
74 /// information entry.
75 DIEEntry *DwarfUnit::createDIEEntry(DIE &Entry) {
76 DIEEntry *Value = new (DIEValueAllocator) DIEEntry(Entry);
80 /// getDefaultLowerBound - Return the default lower bound for an array. If the
81 /// DWARF version doesn't handle the language, return -1.
82 int64_t DwarfUnit::getDefaultLowerBound() const {
83 switch (getLanguage()) {
87 case dwarf::DW_LANG_C89:
88 case dwarf::DW_LANG_C99:
89 case dwarf::DW_LANG_C:
90 case dwarf::DW_LANG_C_plus_plus:
91 case dwarf::DW_LANG_ObjC:
92 case dwarf::DW_LANG_ObjC_plus_plus:
95 case dwarf::DW_LANG_Fortran77:
96 case dwarf::DW_LANG_Fortran90:
97 case dwarf::DW_LANG_Fortran95:
100 // The languages below have valid values only if the DWARF version >= 4.
101 case dwarf::DW_LANG_Java:
102 case dwarf::DW_LANG_Python:
103 case dwarf::DW_LANG_UPC:
104 case dwarf::DW_LANG_D:
105 if (dwarf::DWARF_VERSION >= 4)
109 case dwarf::DW_LANG_Ada83:
110 case dwarf::DW_LANG_Ada95:
111 case dwarf::DW_LANG_Cobol74:
112 case dwarf::DW_LANG_Cobol85:
113 case dwarf::DW_LANG_Modula2:
114 case dwarf::DW_LANG_Pascal83:
115 case dwarf::DW_LANG_PLI:
116 if (dwarf::DWARF_VERSION >= 4)
124 /// Check whether the DIE for this MDNode can be shared across CUs.
125 static bool isShareableAcrossCUs(DIDescriptor D) {
126 // When the MDNode can be part of the type system, the DIE can be shared
128 // Combining type units and cross-CU DIE sharing is lower value (since
129 // cross-CU DIE sharing is used in LTO and removes type redundancy at that
130 // level already) but may be implementable for some value in projects
131 // building multiple independent libraries with LTO and then linking those
133 return (D.isType() ||
134 (D.isSubprogram() && !DISubprogram(D).isDefinition())) &&
135 !GenerateDwarfTypeUnits;
138 /// getDIE - Returns the debug information entry map slot for the
139 /// specified debug variable. We delegate the request to DwarfDebug
140 /// when the DIE for this MDNode can be shared across CUs. The mappings
141 /// will be kept in DwarfDebug for shareable DIEs.
142 DIE *DwarfUnit::getDIE(DIDescriptor D) const {
143 if (isShareableAcrossCUs(D))
144 return DD->getDIE(D);
145 return MDNodeToDieMap.lookup(D);
148 /// insertDIE - Insert DIE into the map. We delegate the request to DwarfDebug
149 /// when the DIE for this MDNode can be shared across CUs. The mappings
150 /// will be kept in DwarfDebug for shareable DIEs.
151 void DwarfUnit::insertDIE(DIDescriptor Desc, DIE *D) {
152 if (isShareableAcrossCUs(Desc)) {
153 DD->insertDIE(Desc, D);
156 MDNodeToDieMap.insert(std::make_pair(Desc, D));
159 /// addFlag - Add a flag that is true.
160 void DwarfUnit::addFlag(DIE &Die, dwarf::Attribute Attribute) {
161 if (DD->getDwarfVersion() >= 4)
162 Die.addValue(Attribute, dwarf::DW_FORM_flag_present, DIEIntegerOne);
164 Die.addValue(Attribute, dwarf::DW_FORM_flag, DIEIntegerOne);
167 /// addUInt - Add an unsigned integer attribute data and value.
169 void DwarfUnit::addUInt(DIE &Die, dwarf::Attribute Attribute,
170 Optional<dwarf::Form> Form, uint64_t Integer) {
172 Form = DIEInteger::BestForm(false, Integer);
173 DIEValue *Value = Integer == 1 ? DIEIntegerOne : new (DIEValueAllocator)
175 Die.addValue(Attribute, *Form, Value);
178 void DwarfUnit::addUInt(DIE &Block, dwarf::Form Form, uint64_t Integer) {
179 addUInt(Block, (dwarf::Attribute)0, Form, Integer);
182 /// addSInt - Add an signed integer attribute data and value.
184 void DwarfUnit::addSInt(DIE &Die, dwarf::Attribute Attribute,
185 Optional<dwarf::Form> Form, int64_t Integer) {
187 Form = DIEInteger::BestForm(true, Integer);
188 DIEValue *Value = new (DIEValueAllocator) DIEInteger(Integer);
189 Die.addValue(Attribute, *Form, Value);
192 void DwarfUnit::addSInt(DIELoc &Die, Optional<dwarf::Form> Form,
194 addSInt(Die, (dwarf::Attribute)0, Form, Integer);
197 /// addString - Add a string attribute data and value. We always emit a
198 /// reference to the string pool instead of immediate strings so that DIEs have
199 /// more predictable sizes. In the case of split dwarf we emit an index
200 /// into another table which gets us the static offset into the string
202 void DwarfUnit::addString(DIE &Die, dwarf::Attribute Attribute,
205 if (!DD->useSplitDwarf())
206 return addLocalString(Die, Attribute, String);
208 unsigned idx = DU->getStringPool().getIndex(*Asm, String);
209 DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
210 DIEValue *Str = new (DIEValueAllocator) DIEString(Value, String);
211 Die.addValue(Attribute, dwarf::DW_FORM_GNU_str_index, Str);
214 /// addLocalString - Add a string attribute data and value. This is guaranteed
215 /// to be in the local string pool instead of indirected.
216 void DwarfUnit::addLocalString(DIE &Die, dwarf::Attribute Attribute,
218 MCSymbol *Symb = DU->getStringPool().getSymbol(*Asm, String);
220 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
221 Value = new (DIEValueAllocator) DIELabel(Symb);
223 Value = new (DIEValueAllocator) DIEDelta(Symb, DD->getDebugStrSym());
224 DIEValue *Str = new (DIEValueAllocator) DIEString(Value, String);
225 Die.addValue(Attribute, dwarf::DW_FORM_strp, Str);
228 /// addExpr - Add a Dwarf expression attribute data and value.
230 void DwarfUnit::addExpr(DIELoc &Die, dwarf::Form Form, const MCExpr *Expr) {
231 DIEValue *Value = new (DIEValueAllocator) DIEExpr(Expr);
232 Die.addValue((dwarf::Attribute)0, Form, Value);
235 /// addLocationList - Add a Dwarf loclistptr attribute data and value.
237 void DwarfUnit::addLocationList(DIE &Die, dwarf::Attribute Attribute,
239 DIEValue *Value = new (DIEValueAllocator) DIELocList(Index);
240 dwarf::Form Form = DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
241 : dwarf::DW_FORM_data4;
242 Die.addValue(Attribute, Form, Value);
245 /// addLabel - Add a Dwarf label attribute data and value.
247 void DwarfUnit::addLabel(DIE &Die, dwarf::Attribute Attribute, dwarf::Form Form,
248 const MCSymbol *Label) {
249 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
250 Die.addValue(Attribute, Form, Value);
253 void DwarfUnit::addLabel(DIELoc &Die, dwarf::Form Form, const MCSymbol *Label) {
254 addLabel(Die, (dwarf::Attribute)0, Form, Label);
257 /// addSectionOffset - Add an offset into a section attribute data and value.
259 void DwarfUnit::addSectionOffset(DIE &Die, dwarf::Attribute Attribute,
261 if (DD->getDwarfVersion() >= 4)
262 addUInt(Die, Attribute, dwarf::DW_FORM_sec_offset, Integer);
264 addUInt(Die, Attribute, dwarf::DW_FORM_data4, Integer);
267 unsigned DwarfTypeUnit::getOrCreateSourceID(StringRef FileName, StringRef DirName) {
268 return SplitLineTable ? SplitLineTable->getFile(DirName, FileName)
269 : getCU().getOrCreateSourceID(FileName, DirName);
272 /// addOpAddress - Add a dwarf op address data and value using the
273 /// form given and an op of either DW_FORM_addr or DW_FORM_GNU_addr_index.
275 void DwarfUnit::addOpAddress(DIELoc &Die, const MCSymbol *Sym) {
276 if (!DD->useSplitDwarf()) {
277 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
278 addLabel(Die, dwarf::DW_FORM_udata, Sym);
280 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index);
281 addUInt(Die, dwarf::DW_FORM_GNU_addr_index,
282 DD->getAddressPool().getIndex(Sym));
286 void DwarfUnit::addLabelDelta(DIE &Die, dwarf::Attribute Attribute,
287 const MCSymbol *Hi, const MCSymbol *Lo) {
288 DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
289 Die.addValue(Attribute, dwarf::DW_FORM_data4, Value);
292 /// addDIEEntry - Add a DIE attribute data and value.
294 void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute, DIE &Entry) {
295 addDIEEntry(Die, Attribute, createDIEEntry(Entry));
298 void DwarfUnit::addDIETypeSignature(DIE &Die, const DwarfTypeUnit &Type) {
299 // Flag the type unit reference as a declaration so that if it contains
300 // members (implicit special members, static data member definitions, member
301 // declarations for definitions in this CU, etc) consumers don't get confused
302 // and think this is a full definition.
303 addFlag(Die, dwarf::DW_AT_declaration);
305 Die.addValue(dwarf::DW_AT_signature, dwarf::DW_FORM_ref_sig8,
306 new (DIEValueAllocator) DIETypeSignature(Type));
309 void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute,
311 const DIE *DieCU = Die.getUnitOrNull();
312 const DIE *EntryCU = Entry->getEntry().getUnitOrNull();
314 // We assume that Die belongs to this CU, if it is not linked to any CU yet.
315 DieCU = &getUnitDie();
317 EntryCU = &getUnitDie();
318 Die.addValue(Attribute,
319 EntryCU == DieCU ? dwarf::DW_FORM_ref4 : dwarf::DW_FORM_ref_addr,
323 /// Create a DIE with the given Tag, add the DIE to its parent, and
324 /// call insertDIE if MD is not null.
325 DIE &DwarfUnit::createAndAddDIE(unsigned Tag, DIE &Parent, DIDescriptor N) {
326 assert(Tag != dwarf::DW_TAG_auto_variable &&
327 Tag != dwarf::DW_TAG_arg_variable);
328 Parent.addChild(make_unique<DIE>((dwarf::Tag)Tag));
329 DIE &Die = *Parent.getChildren().back();
335 /// addBlock - Add block data.
337 void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute, DIELoc *Loc) {
338 Loc->ComputeSize(Asm);
339 DIELocs.push_back(Loc); // Memoize so we can call the destructor later on.
340 Die.addValue(Attribute, Loc->BestForm(DD->getDwarfVersion()), Loc);
343 void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute,
345 Block->ComputeSize(Asm);
346 DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
347 Die.addValue(Attribute, Block->BestForm(), Block);
350 /// addSourceLine - Add location information to specified debug information
352 void DwarfUnit::addSourceLine(DIE &Die, unsigned Line, StringRef File,
353 StringRef Directory) {
357 unsigned FileID = getOrCreateSourceID(File, Directory);
358 assert(FileID && "Invalid file id");
359 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
360 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
363 /// addSourceLine - Add location information to specified debug information
365 void DwarfUnit::addSourceLine(DIE &Die, DIVariable V) {
366 assert(V.isVariable());
368 addSourceLine(Die, V.getLineNumber(), V.getContext().getFilename(),
369 V.getContext().getDirectory());
372 /// addSourceLine - Add location information to specified debug information
374 void DwarfUnit::addSourceLine(DIE &Die, DIGlobalVariable G) {
375 assert(G.isGlobalVariable());
377 addSourceLine(Die, G.getLineNumber(), G.getFilename(), G.getDirectory());
380 /// addSourceLine - Add location information to specified debug information
382 void DwarfUnit::addSourceLine(DIE &Die, DISubprogram SP) {
383 assert(SP.isSubprogram());
385 addSourceLine(Die, SP.getLineNumber(), SP.getFilename(), SP.getDirectory());
388 /// addSourceLine - Add location information to specified debug information
390 void DwarfUnit::addSourceLine(DIE &Die, DIType Ty) {
393 addSourceLine(Die, Ty.getLineNumber(), Ty.getFilename(), Ty.getDirectory());
396 /// addSourceLine - Add location information to specified debug information
398 void DwarfUnit::addSourceLine(DIE &Die, DIObjCProperty Ty) {
399 assert(Ty.isObjCProperty());
401 DIFile File = Ty.getFile();
402 addSourceLine(Die, Ty.getLineNumber(), File.getFilename(),
403 File.getDirectory());
406 /// addSourceLine - Add location information to specified debug information
408 void DwarfUnit::addSourceLine(DIE &Die, DINameSpace NS) {
411 addSourceLine(Die, NS.getLineNumber(), NS.getFilename(), NS.getDirectory());
414 /// addRegisterOp - Add register operand.
415 // FIXME: Ideally, this would share the implementation with
416 // AsmPrinter::EmitDwarfRegOpPiece.
417 void DwarfUnit::addRegisterOpPiece(DIELoc &TheDie, unsigned Reg,
418 unsigned SizeInBits, unsigned OffsetInBits) {
419 const TargetRegisterInfo *RI = Asm->TM.getSubtargetImpl()->getRegisterInfo();
420 int DWReg = RI->getDwarfRegNum(Reg, false);
421 bool isSubRegister = DWReg < 0;
425 // Go up the super-register chain until we hit a valid dwarf register number.
426 for (MCSuperRegIterator SR(Reg, RI); SR.isValid() && DWReg < 0; ++SR) {
427 DWReg = RI->getDwarfRegNum(*SR, false);
429 Idx = RI->getSubRegIndex(*SR, Reg);
433 DEBUG(dbgs() << "Invalid Dwarf register number.\n");
434 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_nop);
440 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + DWReg);
442 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
443 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
447 bool isPiece = SizeInBits > 0;
448 if (isSubRegister || isPiece) {
449 const unsigned SizeOfByte = 8;
450 unsigned RegSizeInBits = RI->getSubRegIdxSize(Idx);
451 unsigned RegOffsetInBits = RI->getSubRegIdxOffset(Idx);
452 unsigned PieceSizeInBits = std::max(SizeInBits, RegSizeInBits);
453 unsigned PieceOffsetInBits = OffsetInBits ? OffsetInBits : RegOffsetInBits;
454 assert(RegSizeInBits >= SizeInBits && "register smaller than value");
456 if (RegOffsetInBits != PieceOffsetInBits) {
457 // Manually shift the value into place, since the DW_OP_piece
458 // describes the part of the variable, not the position of the
460 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
461 addUInt(TheDie, dwarf::DW_FORM_data1, RegOffsetInBits);
462 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_shr);
465 if (PieceOffsetInBits > 0 || PieceSizeInBits % SizeOfByte) {
466 assert(PieceSizeInBits > 0 && "piece has zero size");
467 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_bit_piece);
468 addUInt(TheDie, dwarf::DW_FORM_data1, PieceSizeInBits);
469 addUInt(TheDie, dwarf::DW_FORM_data1, PieceOffsetInBits);
471 assert(PieceSizeInBits > 0 && "piece has zero size");
472 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_piece);
473 addUInt(TheDie, dwarf::DW_FORM_data1, PieceSizeInBits/SizeOfByte);
478 /// addRegisterOffset - Add register offset.
479 void DwarfUnit::addRegisterOffset(DIELoc &TheDie, unsigned Reg,
481 const TargetRegisterInfo *RI = Asm->TM.getSubtargetImpl()->getRegisterInfo();
482 unsigned DWReg = RI->getDwarfRegNum(Reg, false);
483 const TargetRegisterInfo *TRI = Asm->TM.getSubtargetImpl()->getRegisterInfo();
484 if (Reg == TRI->getFrameRegister(*Asm->MF))
485 // If variable offset is based in frame register then use fbreg.
486 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_fbreg);
488 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + DWReg);
490 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
491 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
493 addSInt(TheDie, dwarf::DW_FORM_sdata, Offset);
496 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
497 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
498 gives the variable VarName either the struct, or a pointer to the struct, as
499 its type. This is necessary for various behind-the-scenes things the
500 compiler needs to do with by-reference variables in Blocks.
502 However, as far as the original *programmer* is concerned, the variable
503 should still have type 'SomeType', as originally declared.
505 The function getBlockByrefType dives into the __Block_byref_x_VarName
506 struct to find the original type of the variable, which is then assigned to
507 the variable's Debug Information Entry as its real type. So far, so good.
508 However now the debugger will expect the variable VarName to have the type
509 SomeType. So we need the location attribute for the variable to be an
510 expression that explains to the debugger how to navigate through the
511 pointers and struct to find the actual variable of type SomeType.
513 The following function does just that. We start by getting
514 the "normal" location for the variable. This will be the location
515 of either the struct __Block_byref_x_VarName or the pointer to the
516 struct __Block_byref_x_VarName.
518 The struct will look something like:
520 struct __Block_byref_x_VarName {
522 struct __Block_byref_x_VarName *forwarding;
523 ... <various other fields>
525 ... <maybe more fields>
528 If we are given the struct directly (as our starting point) we
529 need to tell the debugger to:
531 1). Add the offset of the forwarding field.
533 2). Follow that pointer to get the real __Block_byref_x_VarName
534 struct to use (the real one may have been copied onto the heap).
536 3). Add the offset for the field VarName, to find the actual variable.
538 If we started with a pointer to the struct, then we need to
539 dereference that pointer first, before the other steps.
540 Translating this into DWARF ops, we will need to append the following
541 to the current location description for the variable:
543 DW_OP_deref -- optional, if we start with a pointer
544 DW_OP_plus_uconst <forward_fld_offset>
546 DW_OP_plus_uconst <varName_fld_offset>
548 That is what this function does. */
550 /// addBlockByrefAddress - Start with the address based on the location
551 /// provided, and generate the DWARF information necessary to find the
552 /// actual Block variable (navigating the Block struct) based on the
553 /// starting location. Add the DWARF information to the die. For
554 /// more information, read large comment just above here.
556 void DwarfUnit::addBlockByrefAddress(const DbgVariable &DV, DIE &Die,
557 dwarf::Attribute Attribute,
558 const MachineLocation &Location) {
559 DIType Ty = DV.getType();
561 uint16_t Tag = Ty.getTag();
562 bool isPointer = false;
564 StringRef varName = DV.getName();
566 if (Tag == dwarf::DW_TAG_pointer_type) {
567 DIDerivedType DTy(Ty);
568 TmpTy = resolve(DTy.getTypeDerivedFrom());
572 DICompositeType blockStruct(TmpTy);
574 // Find the __forwarding field and the variable field in the __Block_byref
576 DIArray Fields = blockStruct.getElements();
577 DIDerivedType varField;
578 DIDerivedType forwardingField;
580 for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
581 DIDerivedType DT(Fields.getElement(i));
582 StringRef fieldName = DT.getName();
583 if (fieldName == "__forwarding")
584 forwardingField = DT;
585 else if (fieldName == varName)
589 // Get the offsets for the forwarding field and the variable field.
590 unsigned forwardingFieldOffset = forwardingField.getOffsetInBits() >> 3;
591 unsigned varFieldOffset = varField.getOffsetInBits() >> 2;
593 // Decode the original location, and use that as the start of the byref
594 // variable's location.
595 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
597 if (Location.isReg())
598 addRegisterOpPiece(*Loc, Location.getReg());
600 addRegisterOffset(*Loc, Location.getReg(), Location.getOffset());
602 // If we started with a pointer to the __Block_byref... struct, then
603 // the first thing we need to do is dereference the pointer (DW_OP_deref).
605 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
607 // Next add the offset for the '__forwarding' field:
608 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
609 // adding the offset if it's 0.
610 if (forwardingFieldOffset > 0) {
611 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
612 addUInt(*Loc, dwarf::DW_FORM_udata, forwardingFieldOffset);
615 // Now dereference the __forwarding field to get to the real __Block_byref
616 // struct: DW_OP_deref.
617 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
619 // Now that we've got the real __Block_byref... struct, add the offset
620 // for the variable's field to get to the location of the actual variable:
621 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
622 if (varFieldOffset > 0) {
623 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
624 addUInt(*Loc, dwarf::DW_FORM_udata, varFieldOffset);
627 // Now attach the location information to the DIE.
628 addBlock(Die, Attribute, Loc);
631 /// Return true if type encoding is unsigned.
632 static bool isUnsignedDIType(DwarfDebug *DD, DIType Ty) {
633 DIDerivedType DTy(Ty);
634 if (DTy.isDerivedType()) {
635 dwarf::Tag T = (dwarf::Tag)Ty.getTag();
636 // Encode pointer constants as unsigned bytes. This is used at least for
637 // null pointer constant emission.
638 // FIXME: reference and rvalue_reference /probably/ shouldn't be allowed
639 // here, but accept them for now due to a bug in SROA producing bogus
641 if (T == dwarf::DW_TAG_pointer_type ||
642 T == dwarf::DW_TAG_ptr_to_member_type ||
643 T == dwarf::DW_TAG_reference_type ||
644 T == dwarf::DW_TAG_rvalue_reference_type)
646 assert(T == dwarf::DW_TAG_typedef || T == dwarf::DW_TAG_const_type ||
647 T == dwarf::DW_TAG_volatile_type ||
648 T == dwarf::DW_TAG_restrict_type ||
649 T == dwarf::DW_TAG_enumeration_type);
650 if (DITypeRef Deriv = DTy.getTypeDerivedFrom())
651 return isUnsignedDIType(DD, DD->resolve(Deriv));
652 // FIXME: Enums without a fixed underlying type have unknown signedness
653 // here, leading to incorrectly emitted constants.
654 assert(DTy.getTag() == dwarf::DW_TAG_enumeration_type);
659 assert(BTy.isBasicType());
660 unsigned Encoding = BTy.getEncoding();
661 assert((Encoding == dwarf::DW_ATE_unsigned ||
662 Encoding == dwarf::DW_ATE_unsigned_char ||
663 Encoding == dwarf::DW_ATE_signed ||
664 Encoding == dwarf::DW_ATE_signed_char ||
665 Encoding == dwarf::DW_ATE_UTF || Encoding == dwarf::DW_ATE_boolean) &&
666 "Unsupported encoding");
667 return (Encoding == dwarf::DW_ATE_unsigned ||
668 Encoding == dwarf::DW_ATE_unsigned_char ||
669 Encoding == dwarf::DW_ATE_UTF || Encoding == dwarf::DW_ATE_boolean);
672 /// If this type is derived from a base type then return base type size.
673 static uint64_t getBaseTypeSize(DwarfDebug *DD, DIDerivedType Ty) {
674 unsigned Tag = Ty.getTag();
676 if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef &&
677 Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type &&
678 Tag != dwarf::DW_TAG_restrict_type)
679 return Ty.getSizeInBits();
681 DIType BaseType = DD->resolve(Ty.getTypeDerivedFrom());
683 // If this type is not derived from any type or the type is a declaration then
684 // take conservative approach.
685 if (!BaseType.isValid() || BaseType.isForwardDecl())
686 return Ty.getSizeInBits();
688 // If this is a derived type, go ahead and get the base type, unless it's a
689 // reference then it's just the size of the field. Pointer types have no need
690 // of this since they're a different type of qualification on the type.
691 if (BaseType.getTag() == dwarf::DW_TAG_reference_type ||
692 BaseType.getTag() == dwarf::DW_TAG_rvalue_reference_type)
693 return Ty.getSizeInBits();
695 if (BaseType.isDerivedType())
696 return getBaseTypeSize(DD, DIDerivedType(BaseType));
698 return BaseType.getSizeInBits();
701 /// addConstantFPValue - Add constant value entry in variable DIE.
702 void DwarfUnit::addConstantFPValue(DIE &Die, const MachineOperand &MO) {
703 assert(MO.isFPImm() && "Invalid machine operand!");
704 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
705 APFloat FPImm = MO.getFPImm()->getValueAPF();
707 // Get the raw data form of the floating point.
708 const APInt FltVal = FPImm.bitcastToAPInt();
709 const char *FltPtr = (const char *)FltVal.getRawData();
711 int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
712 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
713 int Incr = (LittleEndian ? 1 : -1);
714 int Start = (LittleEndian ? 0 : NumBytes - 1);
715 int Stop = (LittleEndian ? NumBytes : -1);
717 // Output the constant to DWARF one byte at a time.
718 for (; Start != Stop; Start += Incr)
719 addUInt(*Block, dwarf::DW_FORM_data1, (unsigned char)0xFF & FltPtr[Start]);
721 addBlock(Die, dwarf::DW_AT_const_value, Block);
724 /// addConstantFPValue - Add constant value entry in variable DIE.
725 void DwarfUnit::addConstantFPValue(DIE &Die, const ConstantFP *CFP) {
726 // Pass this down to addConstantValue as an unsigned bag of bits.
727 addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true);
730 /// addConstantValue - Add constant value entry in variable DIE.
731 void DwarfUnit::addConstantValue(DIE &Die, const ConstantInt *CI, DIType Ty) {
732 addConstantValue(Die, CI->getValue(), Ty);
735 /// addConstantValue - Add constant value entry in variable DIE.
736 void DwarfUnit::addConstantValue(DIE &Die, const MachineOperand &MO,
738 assert(MO.isImm() && "Invalid machine operand!");
740 addConstantValue(Die, isUnsignedDIType(DD, Ty), MO.getImm());
743 void DwarfUnit::addConstantValue(DIE &Die, bool Unsigned, uint64_t Val) {
744 // FIXME: This is a bit conservative/simple - it emits negative values always
745 // sign extended to 64 bits rather than minimizing the number of bytes.
746 addUInt(Die, dwarf::DW_AT_const_value,
747 Unsigned ? dwarf::DW_FORM_udata : dwarf::DW_FORM_sdata, Val);
750 void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, DIType Ty) {
751 addConstantValue(Die, Val, isUnsignedDIType(DD, Ty));
754 // addConstantValue - Add constant value entry in variable DIE.
755 void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, bool Unsigned) {
756 unsigned CIBitWidth = Val.getBitWidth();
757 if (CIBitWidth <= 64) {
758 addConstantValue(Die, Unsigned,
759 Unsigned ? Val.getZExtValue() : Val.getSExtValue());
763 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
765 // Get the raw data form of the large APInt.
766 const uint64_t *Ptr64 = Val.getRawData();
768 int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
769 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
771 // Output the constant to DWARF one byte at a time.
772 for (int i = 0; i < NumBytes; i++) {
775 c = Ptr64[i / 8] >> (8 * (i & 7));
777 c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
778 addUInt(*Block, dwarf::DW_FORM_data1, c);
781 addBlock(Die, dwarf::DW_AT_const_value, Block);
784 /// addTemplateParams - Add template parameters into buffer.
785 void DwarfUnit::addTemplateParams(DIE &Buffer, DIArray TParams) {
786 // Add template parameters.
787 for (unsigned i = 0, e = TParams.getNumElements(); i != e; ++i) {
788 DIDescriptor Element = TParams.getElement(i);
789 if (Element.isTemplateTypeParameter())
790 constructTemplateTypeParameterDIE(Buffer,
791 DITemplateTypeParameter(Element));
792 else if (Element.isTemplateValueParameter())
793 constructTemplateValueParameterDIE(Buffer,
794 DITemplateValueParameter(Element));
798 /// getOrCreateContextDIE - Get context owner's DIE.
799 DIE *DwarfUnit::getOrCreateContextDIE(DIScope Context) {
800 if (!Context || Context.isFile())
801 return &getUnitDie();
802 if (Context.isType())
803 return getOrCreateTypeDIE(DIType(Context));
804 if (Context.isNameSpace())
805 return getOrCreateNameSpace(DINameSpace(Context));
806 if (Context.isSubprogram())
807 return getOrCreateSubprogramDIE(DISubprogram(Context));
808 return getDIE(Context);
811 DIE *DwarfUnit::createTypeDIE(DICompositeType Ty) {
812 DIScope Context = resolve(Ty.getContext());
813 DIE *ContextDIE = getOrCreateContextDIE(Context);
815 if (DIE *TyDIE = getDIE(Ty))
819 DIE &TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
821 constructTypeDIE(TyDIE, Ty);
823 updateAcceleratorTables(Context, Ty, TyDIE);
827 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
829 DIE *DwarfUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
835 assert(Ty == resolve(Ty.getRef()) &&
836 "type was not uniqued, possible ODR violation.");
838 // DW_TAG_restrict_type is not supported in DWARF2
839 if (Ty.getTag() == dwarf::DW_TAG_restrict_type && DD->getDwarfVersion() <= 2)
840 return getOrCreateTypeDIE(resolve(DIDerivedType(Ty).getTypeDerivedFrom()));
842 // Construct the context before querying for the existence of the DIE in case
843 // such construction creates the DIE.
844 DIScope Context = resolve(Ty.getContext());
845 DIE *ContextDIE = getOrCreateContextDIE(Context);
848 if (DIE *TyDIE = getDIE(Ty))
852 DIE &TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
854 updateAcceleratorTables(Context, Ty, TyDIE);
856 if (Ty.isBasicType())
857 constructTypeDIE(TyDIE, DIBasicType(Ty));
858 else if (Ty.isCompositeType()) {
859 DICompositeType CTy(Ty);
860 if (GenerateDwarfTypeUnits && !Ty.isForwardDecl())
861 if (MDString *TypeId = CTy.getIdentifier()) {
862 DD->addDwarfTypeUnitType(getCU(), TypeId->getString(), TyDIE, CTy);
863 // Skip updating the accelerator tables since this is not the full type.
866 constructTypeDIE(TyDIE, CTy);
868 assert(Ty.isDerivedType() && "Unknown kind of DIType");
869 constructTypeDIE(TyDIE, DIDerivedType(Ty));
875 void DwarfUnit::updateAcceleratorTables(DIScope Context, DIType Ty,
877 if (!Ty.getName().empty() && !Ty.isForwardDecl()) {
878 bool IsImplementation = 0;
879 if (Ty.isCompositeType()) {
880 DICompositeType CT(Ty);
881 // A runtime language of 0 actually means C/C++ and that any
882 // non-negative value is some version of Objective-C/C++.
883 IsImplementation = (CT.getRunTimeLang() == 0) || CT.isObjcClassComplete();
885 unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0;
886 DD->addAccelType(Ty.getName(), TyDIE, Flags);
888 if (!Context || Context.isCompileUnit() || Context.isFile() ||
889 Context.isNameSpace())
890 addGlobalType(Ty, TyDIE, Context);
894 /// addType - Add a new type attribute to the specified entity.
895 void DwarfUnit::addType(DIE &Entity, DIType Ty, dwarf::Attribute Attribute) {
896 assert(Ty && "Trying to add a type that doesn't exist?");
898 // Check for pre-existence.
899 DIEEntry *Entry = getDIEEntry(Ty);
900 // If it exists then use the existing value.
902 addDIEEntry(Entity, Attribute, Entry);
907 DIE *Buffer = getOrCreateTypeDIE(Ty);
910 Entry = createDIEEntry(*Buffer);
911 insertDIEEntry(Ty, Entry);
912 addDIEEntry(Entity, Attribute, Entry);
915 /// getParentContextString - Walks the metadata parent chain in a language
916 /// specific manner (using the compile unit language) and returns
917 /// it as a string. This is done at the metadata level because DIEs may
918 /// not currently have been added to the parent context and walking the
919 /// DIEs looking for names is more expensive than walking the metadata.
920 std::string DwarfUnit::getParentContextString(DIScope Context) const {
924 // FIXME: Decide whether to implement this for non-C++ languages.
925 if (getLanguage() != dwarf::DW_LANG_C_plus_plus)
929 SmallVector<DIScope, 1> Parents;
930 while (!Context.isCompileUnit()) {
931 Parents.push_back(Context);
932 if (Context.getContext())
933 Context = resolve(Context.getContext());
935 // Structure, etc types will have a NULL context if they're at the top
940 // Reverse iterate over our list to go from the outermost construct to the
942 for (SmallVectorImpl<DIScope>::reverse_iterator I = Parents.rbegin(),
946 StringRef Name = Ctx.getName();
947 if (Name.empty() && Ctx.isNameSpace())
948 Name = "(anonymous namespace)";
957 /// constructTypeDIE - Construct basic type die from DIBasicType.
958 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
959 // Get core information.
960 StringRef Name = BTy.getName();
961 // Add name if not anonymous or intermediate type.
963 addString(Buffer, dwarf::DW_AT_name, Name);
965 // An unspecified type only has a name attribute.
966 if (BTy.getTag() == dwarf::DW_TAG_unspecified_type)
969 addUInt(Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
972 uint64_t Size = BTy.getSizeInBits() >> 3;
973 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
976 /// constructTypeDIE - Construct derived type die from DIDerivedType.
977 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
978 // Get core information.
979 StringRef Name = DTy.getName();
980 uint64_t Size = DTy.getSizeInBits() >> 3;
981 uint16_t Tag = Buffer.getTag();
983 // Map to main type, void will not have a type.
984 DIType FromTy = resolve(DTy.getTypeDerivedFrom());
986 addType(Buffer, FromTy);
988 // Add name if not anonymous or intermediate type.
990 addString(Buffer, dwarf::DW_AT_name, Name);
992 // Add size if non-zero (derived types might be zero-sized.)
993 if (Size && Tag != dwarf::DW_TAG_pointer_type)
994 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
996 if (Tag == dwarf::DW_TAG_ptr_to_member_type)
997 addDIEEntry(Buffer, dwarf::DW_AT_containing_type,
998 *getOrCreateTypeDIE(resolve(DTy.getClassType())));
999 // Add source line info if available and TyDesc is not a forward declaration.
1000 if (!DTy.isForwardDecl())
1001 addSourceLine(Buffer, DTy);
1004 /// constructSubprogramArguments - Construct function argument DIEs.
1005 void DwarfUnit::constructSubprogramArguments(DIE &Buffer, DITypeArray Args) {
1006 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1007 DIType Ty = resolve(Args.getElement(i));
1009 assert(i == N-1 && "Unspecified parameter must be the last argument");
1010 createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
1012 DIE &Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
1014 if (Ty.isArtificial())
1015 addFlag(Arg, dwarf::DW_AT_artificial);
1020 /// constructTypeDIE - Construct type DIE from DICompositeType.
1021 void DwarfUnit::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
1022 // Add name if not anonymous or intermediate type.
1023 StringRef Name = CTy.getName();
1025 uint64_t Size = CTy.getSizeInBits() >> 3;
1026 uint16_t Tag = Buffer.getTag();
1029 case dwarf::DW_TAG_array_type:
1030 constructArrayTypeDIE(Buffer, CTy);
1032 case dwarf::DW_TAG_enumeration_type:
1033 constructEnumTypeDIE(Buffer, CTy);
1035 case dwarf::DW_TAG_subroutine_type: {
1036 // Add return type. A void return won't have a type.
1037 DITypeArray Elements = DISubroutineType(CTy).getTypeArray();
1038 DIType RTy(resolve(Elements.getElement(0)));
1040 addType(Buffer, RTy);
1042 bool isPrototyped = true;
1043 if (Elements.getNumElements() == 2 &&
1044 !Elements.getElement(1))
1045 isPrototyped = false;
1047 constructSubprogramArguments(Buffer, Elements);
1049 // Add prototype flag if we're dealing with a C language and the
1050 // function has been prototyped.
1051 uint16_t Language = getLanguage();
1053 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1054 Language == dwarf::DW_LANG_ObjC))
1055 addFlag(Buffer, dwarf::DW_AT_prototyped);
1057 if (CTy.isLValueReference())
1058 addFlag(Buffer, dwarf::DW_AT_reference);
1060 if (CTy.isRValueReference())
1061 addFlag(Buffer, dwarf::DW_AT_rvalue_reference);
1063 case dwarf::DW_TAG_structure_type:
1064 case dwarf::DW_TAG_union_type:
1065 case dwarf::DW_TAG_class_type: {
1066 // Add elements to structure type.
1067 DIArray Elements = CTy.getElements();
1068 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1069 DIDescriptor Element = Elements.getElement(i);
1070 if (Element.isSubprogram())
1071 getOrCreateSubprogramDIE(DISubprogram(Element));
1072 else if (Element.isDerivedType()) {
1073 DIDerivedType DDTy(Element);
1074 if (DDTy.getTag() == dwarf::DW_TAG_friend) {
1075 DIE &ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
1076 addType(ElemDie, resolve(DDTy.getTypeDerivedFrom()),
1077 dwarf::DW_AT_friend);
1078 } else if (DDTy.isStaticMember()) {
1079 getOrCreateStaticMemberDIE(DDTy);
1081 constructMemberDIE(Buffer, DDTy);
1083 } else if (Element.isObjCProperty()) {
1084 DIObjCProperty Property(Element);
1085 DIE &ElemDie = createAndAddDIE(Property.getTag(), Buffer);
1086 StringRef PropertyName = Property.getObjCPropertyName();
1087 addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
1088 if (Property.getType())
1089 addType(ElemDie, Property.getType());
1090 addSourceLine(ElemDie, Property);
1091 StringRef GetterName = Property.getObjCPropertyGetterName();
1092 if (!GetterName.empty())
1093 addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
1094 StringRef SetterName = Property.getObjCPropertySetterName();
1095 if (!SetterName.empty())
1096 addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
1097 unsigned PropertyAttributes = 0;
1098 if (Property.isReadOnlyObjCProperty())
1099 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readonly;
1100 if (Property.isReadWriteObjCProperty())
1101 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readwrite;
1102 if (Property.isAssignObjCProperty())
1103 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_assign;
1104 if (Property.isRetainObjCProperty())
1105 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_retain;
1106 if (Property.isCopyObjCProperty())
1107 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_copy;
1108 if (Property.isNonAtomicObjCProperty())
1109 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_nonatomic;
1110 if (PropertyAttributes)
1111 addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None,
1112 PropertyAttributes);
1114 DIEEntry *Entry = getDIEEntry(Element);
1116 Entry = createDIEEntry(ElemDie);
1117 insertDIEEntry(Element, Entry);
1123 if (CTy.isAppleBlockExtension())
1124 addFlag(Buffer, dwarf::DW_AT_APPLE_block);
1126 DICompositeType ContainingType(resolve(CTy.getContainingType()));
1128 addDIEEntry(Buffer, dwarf::DW_AT_containing_type,
1129 *getOrCreateTypeDIE(ContainingType));
1131 if (CTy.isObjcClassComplete())
1132 addFlag(Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
1134 // Add template parameters to a class, structure or union types.
1135 // FIXME: The support isn't in the metadata for this yet.
1136 if (Tag == dwarf::DW_TAG_class_type ||
1137 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
1138 addTemplateParams(Buffer, CTy.getTemplateParams());
1146 // Add name if not anonymous or intermediate type.
1148 addString(Buffer, dwarf::DW_AT_name, Name);
1150 if (Tag == dwarf::DW_TAG_enumeration_type ||
1151 Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
1152 Tag == dwarf::DW_TAG_union_type) {
1153 // Add size if non-zero (derived types might be zero-sized.)
1154 // TODO: Do we care about size for enum forward declarations?
1156 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
1157 else if (!CTy.isForwardDecl())
1158 // Add zero size if it is not a forward declaration.
1159 addUInt(Buffer, dwarf::DW_AT_byte_size, None, 0);
1161 // If we're a forward decl, say so.
1162 if (CTy.isForwardDecl())
1163 addFlag(Buffer, dwarf::DW_AT_declaration);
1165 // Add source line info if available.
1166 if (!CTy.isForwardDecl())
1167 addSourceLine(Buffer, CTy);
1169 // No harm in adding the runtime language to the declaration.
1170 unsigned RLang = CTy.getRunTimeLang();
1172 addUInt(Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
1177 /// constructTemplateTypeParameterDIE - Construct new DIE for the given
1178 /// DITemplateTypeParameter.
1179 void DwarfUnit::constructTemplateTypeParameterDIE(DIE &Buffer,
1180 DITemplateTypeParameter TP) {
1182 createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
1183 // Add the type if it exists, it could be void and therefore no type.
1185 addType(ParamDIE, resolve(TP.getType()));
1186 if (!TP.getName().empty())
1187 addString(ParamDIE, dwarf::DW_AT_name, TP.getName());
1190 /// constructTemplateValueParameterDIE - Construct new DIE for the given
1191 /// DITemplateValueParameter.
1193 DwarfUnit::constructTemplateValueParameterDIE(DIE &Buffer,
1194 DITemplateValueParameter VP) {
1195 DIE &ParamDIE = createAndAddDIE(VP.getTag(), Buffer);
1197 // Add the type if there is one, template template and template parameter
1198 // packs will not have a type.
1199 if (VP.getTag() == dwarf::DW_TAG_template_value_parameter)
1200 addType(ParamDIE, resolve(VP.getType()));
1201 if (!VP.getName().empty())
1202 addString(ParamDIE, dwarf::DW_AT_name, VP.getName());
1203 if (Value *Val = VP.getValue()) {
1204 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val))
1205 addConstantValue(ParamDIE, CI, resolve(VP.getType()));
1206 else if (GlobalValue *GV = dyn_cast<GlobalValue>(Val)) {
1207 // For declaration non-type template parameters (such as global values and
1209 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
1210 addOpAddress(*Loc, Asm->getSymbol(GV));
1211 // Emit DW_OP_stack_value to use the address as the immediate value of the
1212 // parameter, rather than a pointer to it.
1213 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
1214 addBlock(ParamDIE, dwarf::DW_AT_location, Loc);
1215 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1216 assert(isa<MDString>(Val));
1217 addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
1218 cast<MDString>(Val)->getString());
1219 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1220 assert(isa<MDNode>(Val));
1221 DIArray A(cast<MDNode>(Val));
1222 addTemplateParams(ParamDIE, A);
1227 /// getOrCreateNameSpace - Create a DIE for DINameSpace.
1228 DIE *DwarfUnit::getOrCreateNameSpace(DINameSpace NS) {
1229 // Construct the context before querying for the existence of the DIE in case
1230 // such construction creates the DIE.
1231 DIE *ContextDIE = getOrCreateContextDIE(NS.getContext());
1233 if (DIE *NDie = getDIE(NS))
1235 DIE &NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS);
1237 StringRef Name = NS.getName();
1239 addString(NDie, dwarf::DW_AT_name, NS.getName());
1241 Name = "(anonymous namespace)";
1242 DD->addAccelNamespace(Name, NDie);
1243 addGlobalName(Name, NDie, NS.getContext());
1244 addSourceLine(NDie, NS);
1248 /// getOrCreateSubprogramDIE - Create new DIE using SP.
1249 DIE *DwarfUnit::getOrCreateSubprogramDIE(DISubprogram SP) {
1250 // Construct the context before querying for the existence of the DIE in case
1251 // such construction creates the DIE (as is the case for member function
1253 DIE *ContextDIE = getOrCreateContextDIE(resolve(SP.getContext()));
1255 if (DIE *SPDie = getDIE(SP))
1258 if (DISubprogram SPDecl = SP.getFunctionDeclaration()) {
1259 // Add subprogram definitions to the CU die directly.
1260 ContextDIE = &getUnitDie();
1261 // Build the decl now to ensure it precedes the definition.
1262 getOrCreateSubprogramDIE(SPDecl);
1265 // DW_TAG_inlined_subroutine may refer to this DIE.
1266 DIE &SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
1268 // Stop here and fill this in later, depending on whether or not this
1269 // subprogram turns out to have inlined instances or not.
1270 if (SP.isDefinition())
1273 applySubprogramAttributes(SP, SPDie);
1277 void DwarfUnit::applySubprogramAttributesToDefinition(DISubprogram SP, DIE &SPDie) {
1278 DISubprogram SPDecl = SP.getFunctionDeclaration();
1279 DIScope Context = resolve(SPDecl ? SPDecl.getContext() : SP.getContext());
1280 applySubprogramAttributes(SP, SPDie);
1281 addGlobalName(SP.getName(), SPDie, Context);
1284 void DwarfUnit::applySubprogramAttributes(DISubprogram SP, DIE &SPDie) {
1285 DIE *DeclDie = nullptr;
1286 StringRef DeclLinkageName;
1287 if (DISubprogram SPDecl = SP.getFunctionDeclaration()) {
1288 DeclDie = getDIE(SPDecl);
1289 assert(DeclDie && "This DIE should've already been constructed when the "
1290 "definition DIE was created in "
1291 "getOrCreateSubprogramDIE");
1292 DeclLinkageName = SPDecl.getLinkageName();
1295 // Add function template parameters.
1296 addTemplateParams(SPDie, SP.getTemplateParams());
1298 // Add the linkage name if we have one and it isn't in the Decl.
1299 StringRef LinkageName = SP.getLinkageName();
1300 assert(((LinkageName.empty() || DeclLinkageName.empty()) ||
1301 LinkageName == DeclLinkageName) &&
1302 "decl has a linkage name and it is different");
1303 if (!LinkageName.empty() && DeclLinkageName.empty())
1304 addString(SPDie, dwarf::DW_AT_MIPS_linkage_name,
1305 GlobalValue::getRealLinkageName(LinkageName));
1308 // Refer to the function declaration where all the other attributes will be
1310 addDIEEntry(SPDie, dwarf::DW_AT_specification, *DeclDie);
1314 // Constructors and operators for anonymous aggregates do not have names.
1315 if (!SP.getName().empty())
1316 addString(SPDie, dwarf::DW_AT_name, SP.getName());
1318 // Skip the rest of the attributes under -gmlt to save space.
1319 if(getCUNode().getEmissionKind() == DIBuilder::LineTablesOnly)
1322 addSourceLine(SPDie, SP);
1324 // Add the prototype if we have a prototype and we have a C like
1326 uint16_t Language = getLanguage();
1327 if (SP.isPrototyped() &&
1328 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1329 Language == dwarf::DW_LANG_ObjC))
1330 addFlag(SPDie, dwarf::DW_AT_prototyped);
1332 DISubroutineType SPTy = SP.getType();
1333 assert(SPTy.getTag() == dwarf::DW_TAG_subroutine_type &&
1334 "the type of a subprogram should be a subroutine");
1336 DITypeArray Args = SPTy.getTypeArray();
1337 // Add a return type. If this is a type like a C/C++ void type we don't add a
1339 if (resolve(Args.getElement(0)))
1340 addType(SPDie, DIType(resolve(Args.getElement(0))));
1342 unsigned VK = SP.getVirtuality();
1344 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1345 DIELoc *Block = getDIELoc();
1346 addUInt(*Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1347 addUInt(*Block, dwarf::DW_FORM_udata, SP.getVirtualIndex());
1348 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
1349 ContainingTypeMap.insert(
1350 std::make_pair(&SPDie, resolve(SP.getContainingType())));
1353 if (!SP.isDefinition()) {
1354 addFlag(SPDie, dwarf::DW_AT_declaration);
1356 // Add arguments. Do not add arguments for subprogram definition. They will
1357 // be handled while processing variables.
1358 constructSubprogramArguments(SPDie, Args);
1361 if (SP.isArtificial())
1362 addFlag(SPDie, dwarf::DW_AT_artificial);
1364 if (!SP.isLocalToUnit())
1365 addFlag(SPDie, dwarf::DW_AT_external);
1367 if (SP.isOptimized())
1368 addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1370 if (unsigned isa = Asm->getISAEncoding()) {
1371 addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1374 if (SP.isLValueReference())
1375 addFlag(SPDie, dwarf::DW_AT_reference);
1377 if (SP.isRValueReference())
1378 addFlag(SPDie, dwarf::DW_AT_rvalue_reference);
1380 if (SP.isProtected())
1381 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1382 dwarf::DW_ACCESS_protected);
1383 else if (SP.isPrivate())
1384 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1385 dwarf::DW_ACCESS_private);
1386 else if (SP.isPublic())
1387 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1388 dwarf::DW_ACCESS_public);
1390 if (SP.isExplicit())
1391 addFlag(SPDie, dwarf::DW_AT_explicit);
1394 void DwarfUnit::applyVariableAttributes(const DbgVariable &Var,
1396 StringRef Name = Var.getName();
1398 addString(VariableDie, dwarf::DW_AT_name, Name);
1399 addSourceLine(VariableDie, Var.getVariable());
1400 addType(VariableDie, Var.getType());
1401 if (Var.isArtificial())
1402 addFlag(VariableDie, dwarf::DW_AT_artificial);
1405 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
1406 void DwarfUnit::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy) {
1407 DIE &DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
1408 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, *IndexTy);
1410 // The LowerBound value defines the lower bounds which is typically zero for
1411 // C/C++. The Count value is the number of elements. Values are 64 bit. If
1412 // Count == -1 then the array is unbounded and we do not emit
1413 // DW_AT_lower_bound and DW_AT_count attributes.
1414 int64_t LowerBound = SR.getLo();
1415 int64_t DefaultLowerBound = getDefaultLowerBound();
1416 int64_t Count = SR.getCount();
1418 if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
1419 addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound);
1422 // FIXME: An unbounded array should reference the expression that defines
1424 addUInt(DW_Subrange, dwarf::DW_AT_count, None, Count);
1427 DIE *DwarfUnit::getIndexTyDie() {
1430 // Construct an integer type to use for indexes.
1431 IndexTyDie = &createAndAddDIE(dwarf::DW_TAG_base_type, UnitDie);
1432 addString(*IndexTyDie, dwarf::DW_AT_name, "sizetype");
1433 addUInt(*IndexTyDie, dwarf::DW_AT_byte_size, None, sizeof(int64_t));
1434 addUInt(*IndexTyDie, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1435 dwarf::DW_ATE_unsigned);
1439 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
1440 void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, DICompositeType CTy) {
1442 addFlag(Buffer, dwarf::DW_AT_GNU_vector);
1444 // Emit the element type.
1445 addType(Buffer, resolve(CTy.getTypeDerivedFrom()));
1447 // Get an anonymous type for index type.
1448 // FIXME: This type should be passed down from the front end
1449 // as different languages may have different sizes for indexes.
1450 DIE *IdxTy = getIndexTyDie();
1452 // Add subranges to array type.
1453 DIArray Elements = CTy.getElements();
1454 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1455 DIDescriptor Element = Elements.getElement(i);
1456 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1457 constructSubrangeDIE(Buffer, DISubrange(Element), IdxTy);
1461 /// constructEnumTypeDIE - Construct an enum type DIE from DICompositeType.
1462 void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, DICompositeType CTy) {
1463 DIArray Elements = CTy.getElements();
1465 // Add enumerators to enumeration type.
1466 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1467 DIEnumerator Enum(Elements.getElement(i));
1468 if (Enum.isEnumerator()) {
1469 DIE &Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
1470 StringRef Name = Enum.getName();
1471 addString(Enumerator, dwarf::DW_AT_name, Name);
1472 int64_t Value = Enum.getEnumValue();
1473 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
1477 DIType DTy = resolve(CTy.getTypeDerivedFrom());
1479 addType(Buffer, DTy);
1480 addFlag(Buffer, dwarf::DW_AT_enum_class);
1484 /// constructContainingTypeDIEs - Construct DIEs for types that contain
1486 void DwarfUnit::constructContainingTypeDIEs() {
1487 for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(),
1488 CE = ContainingTypeMap.end();
1490 DIE &SPDie = *CI->first;
1491 DIDescriptor D(CI->second);
1494 DIE *NDie = getDIE(D);
1497 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, *NDie);
1501 /// constructMemberDIE - Construct member DIE from DIDerivedType.
1502 void DwarfUnit::constructMemberDIE(DIE &Buffer, DIDerivedType DT) {
1503 DIE &MemberDie = createAndAddDIE(DT.getTag(), Buffer);
1504 StringRef Name = DT.getName();
1506 addString(MemberDie, dwarf::DW_AT_name, Name);
1508 addType(MemberDie, resolve(DT.getTypeDerivedFrom()));
1510 addSourceLine(MemberDie, DT);
1512 if (DT.getTag() == dwarf::DW_TAG_inheritance && DT.isVirtual()) {
1514 // For C++, virtual base classes are not at fixed offset. Use following
1515 // expression to extract appropriate offset from vtable.
1516 // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1518 DIELoc *VBaseLocationDie = new (DIEValueAllocator) DIELoc();
1519 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1520 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1521 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1522 addUInt(*VBaseLocationDie, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1523 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1524 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1525 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1527 addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
1529 uint64_t Size = DT.getSizeInBits();
1530 uint64_t FieldSize = getBaseTypeSize(DD, DT);
1531 uint64_t OffsetInBytes;
1533 if (Size != FieldSize) {
1534 // Handle bitfield, assume bytes are 8 bits.
1535 addUInt(MemberDie, dwarf::DW_AT_byte_size, None, FieldSize/8);
1536 addUInt(MemberDie, dwarf::DW_AT_bit_size, None, Size);
1538 uint64_t Offset = DT.getOffsetInBits();
1539 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1540 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1541 uint64_t FieldOffset = (HiMark - FieldSize);
1542 Offset -= FieldOffset;
1544 // Maybe we need to work from the other end.
1545 if (Asm->getDataLayout().isLittleEndian())
1546 Offset = FieldSize - (Offset + Size);
1547 addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset);
1549 // Here DW_AT_data_member_location points to the anonymous
1550 // field that includes this bit field.
1551 OffsetInBytes = FieldOffset >> 3;
1553 // This is not a bitfield.
1554 OffsetInBytes = DT.getOffsetInBits() >> 3;
1556 if (DD->getDwarfVersion() <= 2) {
1557 DIELoc *MemLocationDie = new (DIEValueAllocator) DIELoc();
1558 addUInt(*MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1559 addUInt(*MemLocationDie, dwarf::DW_FORM_udata, OffsetInBytes);
1560 addBlock(MemberDie, dwarf::DW_AT_data_member_location, MemLocationDie);
1562 addUInt(MemberDie, dwarf::DW_AT_data_member_location, None,
1566 if (DT.isProtected())
1567 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1568 dwarf::DW_ACCESS_protected);
1569 else if (DT.isPrivate())
1570 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1571 dwarf::DW_ACCESS_private);
1572 // Otherwise C++ member and base classes are considered public.
1573 else if (DT.isPublic())
1574 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1575 dwarf::DW_ACCESS_public);
1577 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1578 dwarf::DW_VIRTUALITY_virtual);
1580 // Objective-C properties.
1581 if (MDNode *PNode = DT.getObjCProperty())
1582 if (DIEEntry *PropertyDie = getDIEEntry(PNode))
1583 MemberDie.addValue(dwarf::DW_AT_APPLE_property, dwarf::DW_FORM_ref4,
1586 if (DT.isArtificial())
1587 addFlag(MemberDie, dwarf::DW_AT_artificial);
1590 /// getOrCreateStaticMemberDIE - Create new DIE for C++ static member.
1591 DIE *DwarfUnit::getOrCreateStaticMemberDIE(DIDerivedType DT) {
1595 // Construct the context before querying for the existence of the DIE in case
1596 // such construction creates the DIE.
1597 DIE *ContextDIE = getOrCreateContextDIE(resolve(DT.getContext()));
1598 assert(dwarf::isType(ContextDIE->getTag()) &&
1599 "Static member should belong to a type.");
1601 if (DIE *StaticMemberDIE = getDIE(DT))
1602 return StaticMemberDIE;
1604 DIE &StaticMemberDIE = createAndAddDIE(DT.getTag(), *ContextDIE, DT);
1606 DIType Ty = resolve(DT.getTypeDerivedFrom());
1608 addString(StaticMemberDIE, dwarf::DW_AT_name, DT.getName());
1609 addType(StaticMemberDIE, Ty);
1610 addSourceLine(StaticMemberDIE, DT);
1611 addFlag(StaticMemberDIE, dwarf::DW_AT_external);
1612 addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
1614 // FIXME: We could omit private if the parent is a class_type, and
1615 // public if the parent is something else.
1616 if (DT.isProtected())
1617 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1618 dwarf::DW_ACCESS_protected);
1619 else if (DT.isPrivate())
1620 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1621 dwarf::DW_ACCESS_private);
1622 else if (DT.isPublic())
1623 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1624 dwarf::DW_ACCESS_public);
1626 if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT.getConstant()))
1627 addConstantValue(StaticMemberDIE, CI, Ty);
1628 if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT.getConstant()))
1629 addConstantFPValue(StaticMemberDIE, CFP);
1631 return &StaticMemberDIE;
1634 void DwarfUnit::emitHeader(const MCSymbol *ASectionSym) const {
1635 // Emit size of content not including length itself
1636 Asm->OutStreamer.AddComment("Length of Unit");
1637 Asm->EmitInt32(getHeaderSize() + UnitDie.getSize());
1639 Asm->OutStreamer.AddComment("DWARF version number");
1640 Asm->EmitInt16(DD->getDwarfVersion());
1641 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
1642 // We share one abbreviations table across all units so it's always at the
1643 // start of the section. Use a relocatable offset where needed to ensure
1644 // linking doesn't invalidate that offset.
1646 Asm->EmitSectionOffset(ASectionSym, ASectionSym);
1648 // Use a constant value when no symbol is provided.
1650 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1651 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
1654 void DwarfUnit::initSection(const MCSection *Section) {
1655 assert(!this->Section);
1656 this->Section = Section;
1659 void DwarfTypeUnit::emitHeader(const MCSymbol *ASectionSym) const {
1660 DwarfUnit::emitHeader(ASectionSym);
1661 Asm->OutStreamer.AddComment("Type Signature");
1662 Asm->OutStreamer.EmitIntValue(TypeSignature, sizeof(TypeSignature));
1663 Asm->OutStreamer.AddComment("Type DIE Offset");
1664 // In a skeleton type unit there is no type DIE so emit a zero offset.
1665 Asm->OutStreamer.EmitIntValue(Ty ? Ty->getOffset() : 0,
1666 sizeof(Ty->getOffset()));