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 #define DEBUG_TYPE "dwarfdebug"
16 #include "DwarfUnit.h"
17 #include "DwarfAccelTable.h"
18 #include "DwarfDebug.h"
19 #include "llvm/ADT/APFloat.h"
20 #include "llvm/DIBuilder.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/GlobalVariable.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/MC/MCSection.h"
26 #include "llvm/MC/MCStreamer.h"
27 #include "llvm/Target/Mangler.h"
28 #include "llvm/Target/TargetFrameLowering.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/Target/TargetLoweringObjectFile.h"
31 #include "llvm/Target/TargetRegisterInfo.h"
32 #include "llvm/Support/CommandLine.h"
37 GenerateDwarfTypeUnits("generate-type-units", cl::Hidden,
38 cl::desc("Generate DWARF4 type units."),
41 /// Unit - Unit constructor.
42 DwarfUnit::DwarfUnit(unsigned UID, DIE *D, DICompileUnit Node, AsmPrinter *A,
43 DwarfDebug *DW, DwarfFile *DWU)
44 : UniqueID(UID), Node(Node), UnitDie(D), DebugInfoOffset(0), Asm(A), DD(DW),
45 DU(DWU), IndexTyDie(0), Section(0) {
46 DIEIntegerOne = new (DIEValueAllocator) DIEInteger(1);
49 DwarfCompileUnit::DwarfCompileUnit(unsigned UID, DIE *D, DICompileUnit Node,
50 AsmPrinter *A, DwarfDebug *DW,
52 : DwarfUnit(UID, D, Node, A, DW, DWU) {
56 DwarfTypeUnit::DwarfTypeUnit(unsigned UID, DIE *D, uint16_t Language,
57 AsmPrinter *A, DwarfDebug *DW, DwarfFile *DWU)
58 : DwarfUnit(UID, D, DICompileUnit(), A, DW, DWU), Language(Language) {}
60 /// ~Unit - Destructor for compile unit.
61 DwarfUnit::~DwarfUnit() {
62 for (unsigned j = 0, M = DIEBlocks.size(); j < M; ++j)
63 DIEBlocks[j]->~DIEBlock();
66 /// createDIEEntry - Creates a new DIEEntry to be a proxy for a debug
67 /// information entry.
68 DIEEntry *DwarfUnit::createDIEEntry(DIE *Entry) {
69 DIEEntry *Value = new (DIEValueAllocator) DIEEntry(Entry);
73 /// getDefaultLowerBound - Return the default lower bound for an array. If the
74 /// DWARF version doesn't handle the language, return -1.
75 int64_t DwarfUnit::getDefaultLowerBound() const {
76 switch (getLanguage()) {
80 case dwarf::DW_LANG_C89:
81 case dwarf::DW_LANG_C99:
82 case dwarf::DW_LANG_C:
83 case dwarf::DW_LANG_C_plus_plus:
84 case dwarf::DW_LANG_ObjC:
85 case dwarf::DW_LANG_ObjC_plus_plus:
88 case dwarf::DW_LANG_Fortran77:
89 case dwarf::DW_LANG_Fortran90:
90 case dwarf::DW_LANG_Fortran95:
93 // The languages below have valid values only if the DWARF version >= 4.
94 case dwarf::DW_LANG_Java:
95 case dwarf::DW_LANG_Python:
96 case dwarf::DW_LANG_UPC:
97 case dwarf::DW_LANG_D:
98 if (dwarf::DWARF_VERSION >= 4)
102 case dwarf::DW_LANG_Ada83:
103 case dwarf::DW_LANG_Ada95:
104 case dwarf::DW_LANG_Cobol74:
105 case dwarf::DW_LANG_Cobol85:
106 case dwarf::DW_LANG_Modula2:
107 case dwarf::DW_LANG_Pascal83:
108 case dwarf::DW_LANG_PLI:
109 if (dwarf::DWARF_VERSION >= 4)
117 /// Check whether the DIE for this MDNode can be shared across CUs.
118 static bool isShareableAcrossCUs(DIDescriptor D) {
119 // When the MDNode can be part of the type system, the DIE can be shared
121 // Combining type units and cross-CU DIE sharing is lower value (since
122 // cross-CU DIE sharing is used in LTO and removes type redundancy at that
123 // level already) but may be implementable for some value in projects
124 // building multiple independent libraries with LTO and then linking those
126 return (D.isType() ||
127 (D.isSubprogram() && !DISubprogram(D).isDefinition())) &&
128 !GenerateDwarfTypeUnits;
131 /// getDIE - Returns the debug information entry map slot for the
132 /// specified debug variable. We delegate the request to DwarfDebug
133 /// when the DIE for this MDNode can be shared across CUs. The mappings
134 /// will be kept in DwarfDebug for shareable DIEs.
135 DIE *DwarfUnit::getDIE(DIDescriptor D) const {
136 if (isShareableAcrossCUs(D))
137 return DD->getDIE(D);
138 return MDNodeToDieMap.lookup(D);
141 /// insertDIE - Insert DIE into the map. We delegate the request to DwarfDebug
142 /// when the DIE for this MDNode can be shared across CUs. The mappings
143 /// will be kept in DwarfDebug for shareable DIEs.
144 void DwarfUnit::insertDIE(DIDescriptor Desc, DIE *D) {
145 if (isShareableAcrossCUs(Desc)) {
146 DD->insertDIE(Desc, D);
149 MDNodeToDieMap.insert(std::make_pair(Desc, D));
152 /// addFlag - Add a flag that is true.
153 void DwarfUnit::addFlag(DIE *Die, dwarf::Attribute Attribute) {
154 if (DD->getDwarfVersion() >= 4)
155 Die->addValue(Attribute, dwarf::DW_FORM_flag_present, DIEIntegerOne);
157 Die->addValue(Attribute, dwarf::DW_FORM_flag, DIEIntegerOne);
160 /// addUInt - Add an unsigned integer attribute data and value.
162 void DwarfUnit::addUInt(DIE *Die, dwarf::Attribute Attribute,
163 Optional<dwarf::Form> Form, uint64_t Integer) {
165 Form = DIEInteger::BestForm(false, Integer);
166 DIEValue *Value = Integer == 1 ? DIEIntegerOne : new (DIEValueAllocator)
168 Die->addValue(Attribute, *Form, Value);
171 void DwarfUnit::addUInt(DIEBlock *Block, dwarf::Form Form, uint64_t Integer) {
172 addUInt(Block, (dwarf::Attribute)0, Form, Integer);
175 /// addSInt - Add an signed integer attribute data and value.
177 void DwarfUnit::addSInt(DIE *Die, dwarf::Attribute Attribute,
178 Optional<dwarf::Form> Form, int64_t Integer) {
180 Form = DIEInteger::BestForm(true, Integer);
181 DIEValue *Value = new (DIEValueAllocator) DIEInteger(Integer);
182 Die->addValue(Attribute, *Form, Value);
185 void DwarfUnit::addSInt(DIEBlock *Die, Optional<dwarf::Form> Form,
187 addSInt(Die, (dwarf::Attribute)0, Form, Integer);
190 /// addString - Add a string attribute data and value. We always emit a
191 /// reference to the string pool instead of immediate strings so that DIEs have
192 /// more predictable sizes. In the case of split dwarf we emit an index
193 /// into another table which gets us the static offset into the string
195 void DwarfUnit::addString(DIE *Die, dwarf::Attribute Attribute,
199 if (!DD->useSplitDwarf()) {
200 MCSymbol *Symb = DU->getStringPoolEntry(String);
201 if (Asm->needsRelocationsForDwarfStringPool())
202 Value = new (DIEValueAllocator) DIELabel(Symb);
204 MCSymbol *StringPool = DU->getStringPoolSym();
205 Value = new (DIEValueAllocator) DIEDelta(Symb, StringPool);
207 Form = dwarf::DW_FORM_strp;
209 unsigned idx = DU->getStringPoolIndex(String);
210 Value = new (DIEValueAllocator) DIEInteger(idx);
211 Form = dwarf::DW_FORM_GNU_str_index;
213 DIEValue *Str = new (DIEValueAllocator) DIEString(Value, String);
214 Die->addValue(Attribute, Form, Str);
217 /// addLocalString - Add a string attribute data and value. This is guaranteed
218 /// to be in the local string pool instead of indirected.
219 void DwarfUnit::addLocalString(DIE *Die, dwarf::Attribute Attribute,
221 MCSymbol *Symb = DU->getStringPoolEntry(String);
223 if (Asm->needsRelocationsForDwarfStringPool())
224 Value = new (DIEValueAllocator) DIELabel(Symb);
226 MCSymbol *StringPool = DU->getStringPoolSym();
227 Value = new (DIEValueAllocator) DIEDelta(Symb, StringPool);
229 Die->addValue(Attribute, dwarf::DW_FORM_strp, Value);
232 /// addExpr - Add a Dwarf expression attribute data and value.
234 void DwarfUnit::addExpr(DIEBlock *Die, dwarf::Form Form, const MCExpr *Expr) {
235 DIEValue *Value = new (DIEValueAllocator) DIEExpr(Expr);
236 Die->addValue((dwarf::Attribute)0, Form, Value);
239 /// addLabel - Add a Dwarf label attribute data and value.
241 void DwarfUnit::addLabel(DIE *Die, dwarf::Attribute Attribute, dwarf::Form Form,
242 const MCSymbol *Label) {
243 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
244 Die->addValue(Attribute, Form, Value);
247 void DwarfUnit::addLabel(DIEBlock *Die, dwarf::Form Form,
248 const MCSymbol *Label) {
249 addLabel(Die, (dwarf::Attribute)0, Form, Label);
252 /// addSectionLabel - Add a Dwarf section label attribute data and value.
254 void DwarfUnit::addSectionLabel(DIE *Die, dwarf::Attribute Attribute,
255 const MCSymbol *Label) {
256 if (DD->getDwarfVersion() >= 4)
257 addLabel(Die, Attribute, dwarf::DW_FORM_sec_offset, Label);
259 addLabel(Die, Attribute, dwarf::DW_FORM_data4, Label);
262 /// addSectionOffset - Add an offset into a section attribute data and value.
264 void DwarfUnit::addSectionOffset(DIE *Die, dwarf::Attribute Attribute,
266 if (DD->getDwarfVersion() >= 4)
267 addUInt(Die, Attribute, dwarf::DW_FORM_sec_offset, Integer);
269 addUInt(Die, Attribute, dwarf::DW_FORM_data4, Integer);
272 /// addLabelAddress - Add a dwarf label attribute data and value using
273 /// DW_FORM_addr or DW_FORM_GNU_addr_index.
275 void DwarfCompileUnit::addLabelAddress(DIE *Die, dwarf::Attribute Attribute,
278 DD->addArangeLabel(SymbolCU(this, Label));
280 if (!DD->useSplitDwarf()) {
282 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
283 Die->addValue(Attribute, dwarf::DW_FORM_addr, Value);
285 DIEValue *Value = new (DIEValueAllocator) DIEInteger(0);
286 Die->addValue(Attribute, dwarf::DW_FORM_addr, Value);
289 unsigned idx = DU->getAddrPoolIndex(Label);
290 DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
291 Die->addValue(Attribute, dwarf::DW_FORM_GNU_addr_index, Value);
295 /// addOpAddress - Add a dwarf op address data and value using the
296 /// form given and an op of either DW_FORM_addr or DW_FORM_GNU_addr_index.
298 void DwarfUnit::addOpAddress(DIEBlock *Die, const MCSymbol *Sym) {
299 if (!DD->useSplitDwarf()) {
300 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
301 addLabel(Die, dwarf::DW_FORM_udata, Sym);
303 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index);
304 addUInt(Die, dwarf::DW_FORM_GNU_addr_index, DU->getAddrPoolIndex(Sym));
308 /// addSectionDelta - Add a section label delta attribute data and value.
310 void DwarfUnit::addSectionDelta(DIE *Die, dwarf::Attribute Attribute,
311 const MCSymbol *Hi, const MCSymbol *Lo) {
312 DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
313 if (DD->getDwarfVersion() >= 4)
314 Die->addValue(Attribute, dwarf::DW_FORM_sec_offset, Value);
316 Die->addValue(Attribute, dwarf::DW_FORM_data4, Value);
319 /// addDIEEntry - Add a DIE attribute data and value.
321 void DwarfUnit::addDIEEntry(DIE *Die, dwarf::Attribute Attribute, DIE *Entry) {
322 addDIEEntry(Die, Attribute, createDIEEntry(Entry));
325 void DwarfUnit::addDIETypeSignature(DIE *Die, const DwarfTypeUnit &Type) {
326 Die->addValue(dwarf::DW_AT_signature, dwarf::DW_FORM_ref_sig8,
327 new (DIEValueAllocator) DIETypeSignature(Type));
330 void DwarfUnit::addDIEEntry(DIE *Die, dwarf::Attribute Attribute,
332 const DIE *DieCU = Die->getUnitOrNull();
333 const DIE *EntryCU = Entry->getEntry()->getUnitOrNull();
335 // We assume that Die belongs to this CU, if it is not linked to any CU yet.
336 DieCU = getUnitDie();
338 EntryCU = getUnitDie();
339 Die->addValue(Attribute, EntryCU == DieCU ? dwarf::DW_FORM_ref4
340 : dwarf::DW_FORM_ref_addr,
344 /// Create a DIE with the given Tag, add the DIE to its parent, and
345 /// call insertDIE if MD is not null.
346 DIE *DwarfUnit::createAndAddDIE(unsigned Tag, DIE &Parent, DIDescriptor N) {
347 DIE *Die = new DIE(Tag);
348 Parent.addChild(Die);
354 /// addBlock - Add block data.
356 void DwarfUnit::addBlock(DIE *Die, dwarf::Attribute Attribute,
358 Block->ComputeSize(Asm);
359 DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
360 Die->addValue(Attribute, Block->BestForm(), Block);
363 /// addSourceLine - Add location information to specified debug information
365 void DwarfUnit::addSourceLine(DIE *Die, DIVariable V) {
370 unsigned Line = V.getLineNumber();
374 DD->getOrCreateSourceID(V.getContext().getFilename(),
375 V.getContext().getDirectory(), getUniqueID());
376 assert(FileID && "Invalid file id");
377 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
378 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
381 /// addSourceLine - Add location information to specified debug information
383 void DwarfUnit::addSourceLine(DIE *Die, DIGlobalVariable G) {
384 // Verify global variable.
385 if (!G.isGlobalVariable())
388 unsigned Line = G.getLineNumber();
392 DD->getOrCreateSourceID(G.getFilename(), G.getDirectory(), getUniqueID());
393 assert(FileID && "Invalid file id");
394 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
395 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
398 /// addSourceLine - Add location information to specified debug information
400 void DwarfUnit::addSourceLine(DIE *Die, DISubprogram SP) {
401 // Verify subprogram.
402 if (!SP.isSubprogram())
405 // If the line number is 0, don't add it.
406 unsigned Line = SP.getLineNumber();
410 unsigned FileID = DD->getOrCreateSourceID(SP.getFilename(), SP.getDirectory(),
412 assert(FileID && "Invalid file id");
413 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
414 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
417 /// addSourceLine - Add location information to specified debug information
419 void DwarfUnit::addSourceLine(DIE *Die, DIType Ty) {
424 unsigned Line = Ty.getLineNumber();
427 unsigned FileID = DD->getOrCreateSourceID(Ty.getFilename(), Ty.getDirectory(),
429 assert(FileID && "Invalid file id");
430 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
431 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
434 /// addSourceLine - Add location information to specified debug information
436 void DwarfUnit::addSourceLine(DIE *Die, DIObjCProperty Ty) {
438 if (!Ty.isObjCProperty())
441 unsigned Line = Ty.getLineNumber();
444 DIFile File = Ty.getFile();
445 unsigned FileID = DD->getOrCreateSourceID(File.getFilename(),
446 File.getDirectory(), getUniqueID());
447 assert(FileID && "Invalid file id");
448 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
449 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
452 /// addSourceLine - Add location information to specified debug information
454 void DwarfUnit::addSourceLine(DIE *Die, DINameSpace NS) {
459 unsigned Line = NS.getLineNumber();
462 StringRef FN = NS.getFilename();
465 DD->getOrCreateSourceID(FN, NS.getDirectory(), getUniqueID());
466 assert(FileID && "Invalid file id");
467 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
468 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
471 /// addVariableAddress - Add DW_AT_location attribute for a
472 /// DbgVariable based on provided MachineLocation.
473 void DwarfUnit::addVariableAddress(const DbgVariable &DV, DIE *Die,
474 MachineLocation Location) {
475 if (DV.variableHasComplexAddress())
476 addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
477 else if (DV.isBlockByrefVariable())
478 addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location);
480 addAddress(Die, dwarf::DW_AT_location, Location,
481 DV.getVariable().isIndirect());
484 /// addRegisterOp - Add register operand.
485 void DwarfUnit::addRegisterOp(DIEBlock *TheDie, unsigned Reg) {
486 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
487 unsigned DWReg = RI->getDwarfRegNum(Reg, false);
489 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + DWReg);
491 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
492 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
496 /// addRegisterOffset - Add register offset.
497 void DwarfUnit::addRegisterOffset(DIEBlock *TheDie, unsigned Reg,
499 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
500 unsigned DWReg = RI->getDwarfRegNum(Reg, false);
501 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
502 if (Reg == TRI->getFrameRegister(*Asm->MF))
503 // If variable offset is based in frame register then use fbreg.
504 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_fbreg);
506 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + DWReg);
508 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
509 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
511 addSInt(TheDie, dwarf::DW_FORM_sdata, Offset);
514 /// addAddress - Add an address attribute to a die based on the location
516 void DwarfUnit::addAddress(DIE *Die, dwarf::Attribute Attribute,
517 const MachineLocation &Location, bool Indirect) {
518 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
520 if (Location.isReg() && !Indirect)
521 addRegisterOp(Block, Location.getReg());
523 addRegisterOffset(Block, Location.getReg(), Location.getOffset());
524 if (Indirect && !Location.isReg()) {
525 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
529 // Now attach the location information to the DIE.
530 addBlock(Die, Attribute, Block);
533 /// addComplexAddress - Start with the address based on the location provided,
534 /// and generate the DWARF information necessary to find the actual variable
535 /// given the extra address information encoded in the DbgVariable, starting
536 /// from the starting location. Add the DWARF information to the die.
538 void DwarfUnit::addComplexAddress(const DbgVariable &DV, DIE *Die,
539 dwarf::Attribute Attribute,
540 const MachineLocation &Location) {
541 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
542 unsigned N = DV.getNumAddrElements();
544 if (Location.isReg()) {
545 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
546 // If first address element is OpPlus then emit
547 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
548 addRegisterOffset(Block, Location.getReg(), DV.getAddrElement(1));
551 addRegisterOp(Block, Location.getReg());
553 addRegisterOffset(Block, Location.getReg(), Location.getOffset());
556 uint64_t Element = DV.getAddrElement(i);
557 if (Element == DIBuilder::OpPlus) {
558 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
559 addUInt(Block, dwarf::DW_FORM_udata, DV.getAddrElement(++i));
560 } else if (Element == DIBuilder::OpDeref) {
561 if (!Location.isReg())
562 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
564 llvm_unreachable("unknown DIBuilder Opcode");
567 // Now attach the location information to the DIE.
568 addBlock(Die, Attribute, Block);
571 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
572 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
573 gives the variable VarName either the struct, or a pointer to the struct, as
574 its type. This is necessary for various behind-the-scenes things the
575 compiler needs to do with by-reference variables in Blocks.
577 However, as far as the original *programmer* is concerned, the variable
578 should still have type 'SomeType', as originally declared.
580 The function getBlockByrefType dives into the __Block_byref_x_VarName
581 struct to find the original type of the variable, which is then assigned to
582 the variable's Debug Information Entry as its real type. So far, so good.
583 However now the debugger will expect the variable VarName to have the type
584 SomeType. So we need the location attribute for the variable to be an
585 expression that explains to the debugger how to navigate through the
586 pointers and struct to find the actual variable of type SomeType.
588 The following function does just that. We start by getting
589 the "normal" location for the variable. This will be the location
590 of either the struct __Block_byref_x_VarName or the pointer to the
591 struct __Block_byref_x_VarName.
593 The struct will look something like:
595 struct __Block_byref_x_VarName {
597 struct __Block_byref_x_VarName *forwarding;
598 ... <various other fields>
600 ... <maybe more fields>
603 If we are given the struct directly (as our starting point) we
604 need to tell the debugger to:
606 1). Add the offset of the forwarding field.
608 2). Follow that pointer to get the real __Block_byref_x_VarName
609 struct to use (the real one may have been copied onto the heap).
611 3). Add the offset for the field VarName, to find the actual variable.
613 If we started with a pointer to the struct, then we need to
614 dereference that pointer first, before the other steps.
615 Translating this into DWARF ops, we will need to append the following
616 to the current location description for the variable:
618 DW_OP_deref -- optional, if we start with a pointer
619 DW_OP_plus_uconst <forward_fld_offset>
621 DW_OP_plus_uconst <varName_fld_offset>
623 That is what this function does. */
625 /// addBlockByrefAddress - Start with the address based on the location
626 /// provided, and generate the DWARF information necessary to find the
627 /// actual Block variable (navigating the Block struct) based on the
628 /// starting location. Add the DWARF information to the die. For
629 /// more information, read large comment just above here.
631 void DwarfUnit::addBlockByrefAddress(const DbgVariable &DV, DIE *Die,
632 dwarf::Attribute Attribute,
633 const MachineLocation &Location) {
634 DIType Ty = DV.getType();
636 uint16_t Tag = Ty.getTag();
637 bool isPointer = false;
639 StringRef varName = DV.getName();
641 if (Tag == dwarf::DW_TAG_pointer_type) {
642 DIDerivedType DTy(Ty);
643 TmpTy = resolve(DTy.getTypeDerivedFrom());
647 DICompositeType blockStruct(TmpTy);
649 // Find the __forwarding field and the variable field in the __Block_byref
651 DIArray Fields = blockStruct.getTypeArray();
652 DIDerivedType varField;
653 DIDerivedType forwardingField;
655 for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
656 DIDerivedType DT(Fields.getElement(i));
657 StringRef fieldName = DT.getName();
658 if (fieldName == "__forwarding")
659 forwardingField = DT;
660 else if (fieldName == varName)
664 // Get the offsets for the forwarding field and the variable field.
665 unsigned forwardingFieldOffset = forwardingField.getOffsetInBits() >> 3;
666 unsigned varFieldOffset = varField.getOffsetInBits() >> 2;
668 // Decode the original location, and use that as the start of the byref
669 // variable's location.
670 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
672 if (Location.isReg())
673 addRegisterOp(Block, Location.getReg());
675 addRegisterOffset(Block, Location.getReg(), Location.getOffset());
677 // If we started with a pointer to the __Block_byref... struct, then
678 // the first thing we need to do is dereference the pointer (DW_OP_deref).
680 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
682 // Next add the offset for the '__forwarding' field:
683 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
684 // adding the offset if it's 0.
685 if (forwardingFieldOffset > 0) {
686 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
687 addUInt(Block, dwarf::DW_FORM_udata, forwardingFieldOffset);
690 // Now dereference the __forwarding field to get to the real __Block_byref
691 // struct: DW_OP_deref.
692 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
694 // Now that we've got the real __Block_byref... struct, add the offset
695 // for the variable's field to get to the location of the actual variable:
696 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
697 if (varFieldOffset > 0) {
698 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
699 addUInt(Block, dwarf::DW_FORM_udata, varFieldOffset);
702 // Now attach the location information to the DIE.
703 addBlock(Die, Attribute, Block);
706 /// isTypeSigned - Return true if the type is signed.
707 static bool isTypeSigned(DwarfDebug *DD, DIType Ty, int *SizeInBits) {
708 if (Ty.isDerivedType())
709 return isTypeSigned(DD, DD->resolve(DIDerivedType(Ty).getTypeDerivedFrom()),
711 if (Ty.isBasicType())
712 if (DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed ||
713 DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed_char) {
714 *SizeInBits = Ty.getSizeInBits();
720 /// Return true if type encoding is unsigned.
721 static bool isUnsignedDIType(DwarfDebug *DD, DIType Ty) {
722 DIDerivedType DTy(Ty);
723 if (DTy.isDerivedType())
724 return isUnsignedDIType(DD, DD->resolve(DTy.getTypeDerivedFrom()));
727 if (BTy.isBasicType()) {
728 unsigned Encoding = BTy.getEncoding();
729 if (Encoding == dwarf::DW_ATE_unsigned ||
730 Encoding == dwarf::DW_ATE_unsigned_char ||
731 Encoding == dwarf::DW_ATE_boolean)
737 /// If this type is derived from a base type then return base type size.
738 static uint64_t getBaseTypeSize(DwarfDebug *DD, DIDerivedType Ty) {
739 unsigned Tag = Ty.getTag();
741 if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef &&
742 Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type &&
743 Tag != dwarf::DW_TAG_restrict_type)
744 return Ty.getSizeInBits();
746 DIType BaseType = DD->resolve(Ty.getTypeDerivedFrom());
748 // If this type is not derived from any type then take conservative approach.
749 if (!BaseType.isValid())
750 return Ty.getSizeInBits();
752 // If this is a derived type, go ahead and get the base type, unless it's a
753 // reference then it's just the size of the field. Pointer types have no need
754 // of this since they're a different type of qualification on the type.
755 if (BaseType.getTag() == dwarf::DW_TAG_reference_type ||
756 BaseType.getTag() == dwarf::DW_TAG_rvalue_reference_type)
757 return Ty.getSizeInBits();
759 if (BaseType.isDerivedType())
760 return getBaseTypeSize(DD, DIDerivedType(BaseType));
762 return BaseType.getSizeInBits();
765 /// addConstantValue - Add constant value entry in variable DIE.
766 void DwarfUnit::addConstantValue(DIE *Die, const MachineOperand &MO,
768 // FIXME: This is a bit conservative/simple - it emits negative values at
769 // their maximum bit width which is a bit unfortunate (& doesn't prefer
770 // udata/sdata over dataN as suggested by the DWARF spec)
771 assert(MO.isImm() && "Invalid machine operand!");
773 bool SignedConstant = isTypeSigned(DD, Ty, &SizeInBits);
776 // If we're a signed constant definitely use sdata.
777 if (SignedConstant) {
778 addSInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, MO.getImm());
782 // Else use data for now unless it's larger than we can deal with.
783 switch (SizeInBits) {
785 Form = dwarf::DW_FORM_data1;
788 Form = dwarf::DW_FORM_data2;
791 Form = dwarf::DW_FORM_data4;
794 Form = dwarf::DW_FORM_data8;
797 Form = dwarf::DW_FORM_udata;
798 addUInt(Die, dwarf::DW_AT_const_value, Form, MO.getImm());
801 addUInt(Die, dwarf::DW_AT_const_value, Form, MO.getImm());
804 /// addConstantFPValue - Add constant value entry in variable DIE.
805 void DwarfUnit::addConstantFPValue(DIE *Die, const MachineOperand &MO) {
806 assert(MO.isFPImm() && "Invalid machine operand!");
807 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
808 APFloat FPImm = MO.getFPImm()->getValueAPF();
810 // Get the raw data form of the floating point.
811 const APInt FltVal = FPImm.bitcastToAPInt();
812 const char *FltPtr = (const char *)FltVal.getRawData();
814 int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
815 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
816 int Incr = (LittleEndian ? 1 : -1);
817 int Start = (LittleEndian ? 0 : NumBytes - 1);
818 int Stop = (LittleEndian ? NumBytes : -1);
820 // Output the constant to DWARF one byte at a time.
821 for (; Start != Stop; Start += Incr)
822 addUInt(Block, dwarf::DW_FORM_data1, (unsigned char)0xFF & FltPtr[Start]);
824 addBlock(Die, dwarf::DW_AT_const_value, Block);
827 /// addConstantFPValue - Add constant value entry in variable DIE.
828 void DwarfUnit::addConstantFPValue(DIE *Die, const ConstantFP *CFP) {
829 // Pass this down to addConstantValue as an unsigned bag of bits.
830 addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true);
833 /// addConstantValue - Add constant value entry in variable DIE.
834 void DwarfUnit::addConstantValue(DIE *Die, const ConstantInt *CI,
836 addConstantValue(Die, CI->getValue(), Unsigned);
839 // addConstantValue - Add constant value entry in variable DIE.
840 void DwarfUnit::addConstantValue(DIE *Die, const APInt &Val, bool Unsigned) {
841 unsigned CIBitWidth = Val.getBitWidth();
842 if (CIBitWidth <= 64) {
843 // If we're a signed constant definitely use sdata.
845 addSInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
850 // Else use data for now unless it's larger than we can deal with.
852 switch (CIBitWidth) {
854 Form = dwarf::DW_FORM_data1;
857 Form = dwarf::DW_FORM_data2;
860 Form = dwarf::DW_FORM_data4;
863 Form = dwarf::DW_FORM_data8;
866 addUInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_udata,
870 addUInt(Die, dwarf::DW_AT_const_value, Form, Val.getZExtValue());
874 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
876 // Get the raw data form of the large APInt.
877 const uint64_t *Ptr64 = Val.getRawData();
879 int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
880 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
882 // Output the constant to DWARF one byte at a time.
883 for (int i = 0; i < NumBytes; i++) {
886 c = Ptr64[i / 8] >> (8 * (i & 7));
888 c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
889 addUInt(Block, dwarf::DW_FORM_data1, c);
892 addBlock(Die, dwarf::DW_AT_const_value, Block);
895 /// addTemplateParams - Add template parameters into buffer.
896 void DwarfUnit::addTemplateParams(DIE &Buffer, DIArray TParams) {
897 // Add template parameters.
898 for (unsigned i = 0, e = TParams.getNumElements(); i != e; ++i) {
899 DIDescriptor Element = TParams.getElement(i);
900 if (Element.isTemplateTypeParameter())
901 constructTemplateTypeParameterDIE(Buffer,
902 DITemplateTypeParameter(Element));
903 else if (Element.isTemplateValueParameter())
904 constructTemplateValueParameterDIE(Buffer,
905 DITemplateValueParameter(Element));
909 /// getOrCreateContextDIE - Get context owner's DIE.
910 DIE *DwarfUnit::getOrCreateContextDIE(DIScope Context) {
911 if (!Context || Context.isFile())
913 if (Context.isType())
914 return getOrCreateTypeDIE(DIType(Context));
915 if (Context.isNameSpace())
916 return getOrCreateNameSpace(DINameSpace(Context));
917 if (Context.isSubprogram())
918 return getOrCreateSubprogramDIE(DISubprogram(Context));
919 return getDIE(Context);
922 DIE *DwarfUnit::createTypeDIE(DICompositeType Ty) {
923 DIScope Context = resolve(Ty.getContext());
924 DIE *ContextDIE = getOrCreateContextDIE(Context);
926 DIE *TyDIE = getDIE(Ty);
931 TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
933 constructTypeDIE(*TyDIE, Ty);
935 updateAcceleratorTables(Context, Ty, TyDIE);
939 /// Return true if the type is appropriately scoped to be contained inside
940 /// its own type unit.
941 static bool isDwarfTypeUnitScoped(DIType Ty, const DwarfDebug *DD) {
942 DIScope Parent = DD->resolve(Ty.getContext());
944 // Don't generate a hash for anything scoped inside a function.
945 if (Parent.isSubprogram())
947 Parent = DD->resolve(Parent.getContext());
952 /// Return true if the type should be split out into a type unit.
953 static bool shouldCreateDwarfTypeUnit(DICompositeType CTy,
954 const DwarfDebug *DD) {
955 if (!GenerateDwarfTypeUnits)
958 uint16_t Tag = CTy.getTag();
961 case dwarf::DW_TAG_structure_type:
962 case dwarf::DW_TAG_union_type:
963 case dwarf::DW_TAG_enumeration_type:
964 case dwarf::DW_TAG_class_type:
965 // If this is a class, structure, union, or enumeration type
966 // that is a definition (not a declaration), and not scoped
967 // inside a function then separate this out as a type unit.
968 return !CTy.isForwardDecl() && isDwarfTypeUnitScoped(CTy, DD);
974 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
976 DIE *DwarfUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
983 // Construct the context before querying for the existence of the DIE in case
984 // such construction creates the DIE.
985 DIScope Context = resolve(Ty.getContext());
986 DIE *ContextDIE = getOrCreateContextDIE(Context);
989 DIE *TyDIE = getDIE(Ty);
994 TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
996 if (Ty.isBasicType())
997 constructTypeDIE(*TyDIE, DIBasicType(Ty));
998 else if (Ty.isCompositeType()) {
999 DICompositeType CTy(Ty);
1000 if (shouldCreateDwarfTypeUnit(CTy, DD)) {
1001 DD->addDwarfTypeUnitType(getLanguage(), TyDIE, CTy);
1002 // Skip updating the accellerator tables since this is not the full type
1005 constructTypeDIE(*TyDIE, CTy);
1007 assert(Ty.isDerivedType() && "Unknown kind of DIType");
1008 constructTypeDIE(*TyDIE, DIDerivedType(Ty));
1011 updateAcceleratorTables(Context, Ty, TyDIE);
1016 void DwarfUnit::updateAcceleratorTables(DIScope Context, DIType Ty,
1018 if (!Ty.getName().empty() && !Ty.isForwardDecl()) {
1019 bool IsImplementation = 0;
1020 if (Ty.isCompositeType()) {
1021 DICompositeType CT(Ty);
1022 // A runtime language of 0 actually means C/C++ and that any
1023 // non-negative value is some version of Objective-C/C++.
1024 IsImplementation = (CT.getRunTimeLang() == 0) || CT.isObjcClassComplete();
1026 unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0;
1027 addAccelType(Ty.getName(), std::make_pair(TyDIE, Flags));
1029 if (!Context || Context.isCompileUnit() || Context.isFile() ||
1030 Context.isNameSpace())
1031 GlobalTypes[getParentContextString(Context) + Ty.getName().str()] = TyDIE;
1035 /// addType - Add a new type attribute to the specified entity.
1036 void DwarfUnit::addType(DIE *Entity, DIType Ty, dwarf::Attribute Attribute) {
1037 assert(Ty && "Trying to add a type that doesn't exist?");
1039 // Check for pre-existence.
1040 DIEEntry *Entry = getDIEEntry(Ty);
1041 // If it exists then use the existing value.
1043 addDIEEntry(Entity, Attribute, Entry);
1048 DIE *Buffer = getOrCreateTypeDIE(Ty);
1051 Entry = createDIEEntry(Buffer);
1052 insertDIEEntry(Ty, Entry);
1053 addDIEEntry(Entity, Attribute, Entry);
1056 // Accelerator table mutators - add each name along with its companion
1057 // DIE to the proper table while ensuring that the name that we're going
1058 // to reference is in the string table. We do this since the names we
1059 // add may not only be identical to the names in the DIE.
1060 void DwarfUnit::addAccelName(StringRef Name, const DIE *Die) {
1061 DU->getStringPoolEntry(Name);
1062 std::vector<const DIE *> &DIEs = AccelNames[Name];
1063 DIEs.push_back(Die);
1066 void DwarfUnit::addAccelObjC(StringRef Name, const DIE *Die) {
1067 DU->getStringPoolEntry(Name);
1068 std::vector<const DIE *> &DIEs = AccelObjC[Name];
1069 DIEs.push_back(Die);
1072 void DwarfUnit::addAccelNamespace(StringRef Name, const DIE *Die) {
1073 DU->getStringPoolEntry(Name);
1074 std::vector<const DIE *> &DIEs = AccelNamespace[Name];
1075 DIEs.push_back(Die);
1078 void DwarfUnit::addAccelType(StringRef Name,
1079 std::pair<const DIE *, unsigned> Die) {
1080 DU->getStringPoolEntry(Name);
1081 std::vector<std::pair<const DIE *, unsigned> > &DIEs = AccelTypes[Name];
1082 DIEs.push_back(Die);
1085 /// addGlobalName - Add a new global name to the compile unit.
1086 void DwarfUnit::addGlobalName(StringRef Name, DIE *Die, DIScope Context) {
1087 std::string FullName = getParentContextString(Context) + Name.str();
1088 GlobalNames[FullName] = Die;
1091 /// getParentContextString - Walks the metadata parent chain in a language
1092 /// specific manner (using the compile unit language) and returns
1093 /// it as a string. This is done at the metadata level because DIEs may
1094 /// not currently have been added to the parent context and walking the
1095 /// DIEs looking for names is more expensive than walking the metadata.
1096 std::string DwarfUnit::getParentContextString(DIScope Context) const {
1100 // FIXME: Decide whether to implement this for non-C++ languages.
1101 if (getLanguage() != dwarf::DW_LANG_C_plus_plus)
1105 SmallVector<DIScope, 1> Parents;
1106 while (!Context.isCompileUnit()) {
1107 Parents.push_back(Context);
1108 if (Context.getContext())
1109 Context = resolve(Context.getContext());
1111 // Structure, etc types will have a NULL context if they're at the top
1116 // Reverse iterate over our list to go from the outermost construct to the
1118 for (SmallVectorImpl<DIScope>::reverse_iterator I = Parents.rbegin(),
1122 StringRef Name = Ctx.getName();
1123 if (!Name.empty()) {
1131 /// constructTypeDIE - Construct basic type die from DIBasicType.
1132 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
1133 // Get core information.
1134 StringRef Name = BTy.getName();
1135 // Add name if not anonymous or intermediate type.
1137 addString(&Buffer, dwarf::DW_AT_name, Name);
1139 // An unspecified type only has a name attribute.
1140 if (BTy.getTag() == dwarf::DW_TAG_unspecified_type)
1143 addUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1146 uint64_t Size = BTy.getSizeInBits() >> 3;
1147 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1150 /// constructTypeDIE - Construct derived type die from DIDerivedType.
1151 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
1152 // Get core information.
1153 StringRef Name = DTy.getName();
1154 uint64_t Size = DTy.getSizeInBits() >> 3;
1155 uint16_t Tag = Buffer.getTag();
1157 // Map to main type, void will not have a type.
1158 DIType FromTy = resolve(DTy.getTypeDerivedFrom());
1160 addType(&Buffer, FromTy);
1162 // Add name if not anonymous or intermediate type.
1164 addString(&Buffer, dwarf::DW_AT_name, Name);
1166 // Add size if non-zero (derived types might be zero-sized.)
1167 if (Size && Tag != dwarf::DW_TAG_pointer_type)
1168 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1170 if (Tag == dwarf::DW_TAG_ptr_to_member_type)
1171 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type,
1172 getOrCreateTypeDIE(resolve(DTy.getClassType())));
1173 // Add source line info if available and TyDesc is not a forward declaration.
1174 if (!DTy.isForwardDecl())
1175 addSourceLine(&Buffer, DTy);
1178 /// constructTypeDIE - Construct type DIE from DICompositeType.
1179 void DwarfUnit::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
1180 // Add name if not anonymous or intermediate type.
1181 StringRef Name = CTy.getName();
1183 uint64_t Size = CTy.getSizeInBits() >> 3;
1184 uint16_t Tag = Buffer.getTag();
1187 case dwarf::DW_TAG_array_type:
1188 constructArrayTypeDIE(Buffer, CTy);
1190 case dwarf::DW_TAG_enumeration_type:
1191 constructEnumTypeDIE(Buffer, CTy);
1193 case dwarf::DW_TAG_subroutine_type: {
1194 // Add return type. A void return won't have a type.
1195 DIArray Elements = CTy.getTypeArray();
1196 DIType RTy(Elements.getElement(0));
1198 addType(&Buffer, RTy);
1200 bool isPrototyped = true;
1202 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
1203 DIDescriptor Ty = Elements.getElement(i);
1204 if (Ty.isUnspecifiedParameter()) {
1205 createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
1206 isPrototyped = false;
1208 DIE *Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
1209 addType(Arg, DIType(Ty));
1210 if (DIType(Ty).isArtificial())
1211 addFlag(Arg, dwarf::DW_AT_artificial);
1214 // Add prototype flag if we're dealing with a C language and the
1215 // function has been prototyped.
1216 uint16_t Language = getLanguage();
1218 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1219 Language == dwarf::DW_LANG_ObjC))
1220 addFlag(&Buffer, dwarf::DW_AT_prototyped);
1222 if (CTy.isLValueReference())
1223 addFlag(&Buffer, dwarf::DW_AT_reference);
1225 if (CTy.isRValueReference())
1226 addFlag(&Buffer, dwarf::DW_AT_rvalue_reference);
1228 case dwarf::DW_TAG_structure_type:
1229 case dwarf::DW_TAG_union_type:
1230 case dwarf::DW_TAG_class_type: {
1231 // Add elements to structure type.
1232 DIArray Elements = CTy.getTypeArray();
1233 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1234 DIDescriptor Element = Elements.getElement(i);
1235 DIE *ElemDie = NULL;
1236 if (Element.isSubprogram()) {
1237 DISubprogram SP(Element);
1238 ElemDie = getOrCreateSubprogramDIE(SP);
1239 if (SP.isProtected())
1240 addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1241 dwarf::DW_ACCESS_protected);
1242 else if (SP.isPrivate())
1243 addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1244 dwarf::DW_ACCESS_private);
1246 addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1247 dwarf::DW_ACCESS_public);
1248 if (SP.isExplicit())
1249 addFlag(ElemDie, dwarf::DW_AT_explicit);
1250 } else if (Element.isDerivedType()) {
1251 DIDerivedType DDTy(Element);
1252 if (DDTy.getTag() == dwarf::DW_TAG_friend) {
1253 ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
1254 addType(ElemDie, resolve(DDTy.getTypeDerivedFrom()),
1255 dwarf::DW_AT_friend);
1256 } else if (DDTy.isStaticMember()) {
1257 getOrCreateStaticMemberDIE(DDTy);
1259 constructMemberDIE(Buffer, DDTy);
1261 } else if (Element.isObjCProperty()) {
1262 DIObjCProperty Property(Element);
1263 ElemDie = createAndAddDIE(Property.getTag(), Buffer);
1264 StringRef PropertyName = Property.getObjCPropertyName();
1265 addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
1266 addType(ElemDie, Property.getType());
1267 addSourceLine(ElemDie, Property);
1268 StringRef GetterName = Property.getObjCPropertyGetterName();
1269 if (!GetterName.empty())
1270 addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
1271 StringRef SetterName = Property.getObjCPropertySetterName();
1272 if (!SetterName.empty())
1273 addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
1274 unsigned PropertyAttributes = 0;
1275 if (Property.isReadOnlyObjCProperty())
1276 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readonly;
1277 if (Property.isReadWriteObjCProperty())
1278 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readwrite;
1279 if (Property.isAssignObjCProperty())
1280 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_assign;
1281 if (Property.isRetainObjCProperty())
1282 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_retain;
1283 if (Property.isCopyObjCProperty())
1284 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_copy;
1285 if (Property.isNonAtomicObjCProperty())
1286 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_nonatomic;
1287 if (PropertyAttributes)
1288 addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None,
1289 PropertyAttributes);
1291 DIEEntry *Entry = getDIEEntry(Element);
1293 Entry = createDIEEntry(ElemDie);
1294 insertDIEEntry(Element, Entry);
1300 if (CTy.isAppleBlockExtension())
1301 addFlag(&Buffer, dwarf::DW_AT_APPLE_block);
1303 DICompositeType ContainingType(resolve(CTy.getContainingType()));
1305 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type,
1306 getOrCreateTypeDIE(ContainingType));
1308 if (CTy.isObjcClassComplete())
1309 addFlag(&Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
1311 // Add template parameters to a class, structure or union types.
1312 // FIXME: The support isn't in the metadata for this yet.
1313 if (Tag == dwarf::DW_TAG_class_type ||
1314 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
1315 addTemplateParams(Buffer, CTy.getTemplateParams());
1323 // Add name if not anonymous or intermediate type.
1325 addString(&Buffer, dwarf::DW_AT_name, Name);
1327 if (Tag == dwarf::DW_TAG_enumeration_type ||
1328 Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
1329 Tag == dwarf::DW_TAG_union_type) {
1330 // Add size if non-zero (derived types might be zero-sized.)
1331 // TODO: Do we care about size for enum forward declarations?
1333 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1334 else if (!CTy.isForwardDecl())
1335 // Add zero size if it is not a forward declaration.
1336 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, 0);
1338 // If we're a forward decl, say so.
1339 if (CTy.isForwardDecl())
1340 addFlag(&Buffer, dwarf::DW_AT_declaration);
1342 // Add source line info if available.
1343 if (!CTy.isForwardDecl())
1344 addSourceLine(&Buffer, CTy);
1346 // No harm in adding the runtime language to the declaration.
1347 unsigned RLang = CTy.getRunTimeLang();
1349 addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
1354 /// constructTemplateTypeParameterDIE - Construct new DIE for the given
1355 /// DITemplateTypeParameter.
1356 void DwarfUnit::constructTemplateTypeParameterDIE(DIE &Buffer,
1357 DITemplateTypeParameter TP) {
1359 createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
1360 // Add the type if it exists, it could be void and therefore no type.
1362 addType(ParamDIE, resolve(TP.getType()));
1363 if (!TP.getName().empty())
1364 addString(ParamDIE, dwarf::DW_AT_name, TP.getName());
1367 /// constructTemplateValueParameterDIE - Construct new DIE for the given
1368 /// DITemplateValueParameter.
1370 DwarfUnit::constructTemplateValueParameterDIE(DIE &Buffer,
1371 DITemplateValueParameter VP) {
1372 DIE *ParamDIE = createAndAddDIE(VP.getTag(), Buffer);
1374 // Add the type if there is one, template template and template parameter
1375 // packs will not have a type.
1376 if (VP.getTag() == dwarf::DW_TAG_template_value_parameter)
1377 addType(ParamDIE, resolve(VP.getType()));
1378 if (!VP.getName().empty())
1379 addString(ParamDIE, dwarf::DW_AT_name, VP.getName());
1380 if (Value *Val = VP.getValue()) {
1381 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val))
1382 addConstantValue(ParamDIE, CI,
1383 isUnsignedDIType(DD, resolve(VP.getType())));
1384 else if (GlobalValue *GV = dyn_cast<GlobalValue>(Val)) {
1385 // For declaration non-type template parameters (such as global values and
1387 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1388 addOpAddress(Block, Asm->getSymbol(GV));
1389 // Emit DW_OP_stack_value to use the address as the immediate value of the
1390 // parameter, rather than a pointer to it.
1391 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
1392 addBlock(ParamDIE, dwarf::DW_AT_location, Block);
1393 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1394 assert(isa<MDString>(Val));
1395 addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
1396 cast<MDString>(Val)->getString());
1397 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1398 assert(isa<MDNode>(Val));
1399 DIArray A(cast<MDNode>(Val));
1400 addTemplateParams(*ParamDIE, A);
1405 /// getOrCreateNameSpace - Create a DIE for DINameSpace.
1406 DIE *DwarfUnit::getOrCreateNameSpace(DINameSpace NS) {
1407 // Construct the context before querying for the existence of the DIE in case
1408 // such construction creates the DIE.
1409 DIE *ContextDIE = getOrCreateContextDIE(NS.getContext());
1411 DIE *NDie = getDIE(NS);
1414 NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS);
1416 if (!NS.getName().empty()) {
1417 addString(NDie, dwarf::DW_AT_name, NS.getName());
1418 addAccelNamespace(NS.getName(), NDie);
1419 addGlobalName(NS.getName(), NDie, NS.getContext());
1421 addAccelNamespace("(anonymous namespace)", NDie);
1422 addSourceLine(NDie, NS);
1426 /// getOrCreateSubprogramDIE - Create new DIE using SP.
1427 DIE *DwarfUnit::getOrCreateSubprogramDIE(DISubprogram SP) {
1428 // Construct the context before querying for the existence of the DIE in case
1429 // such construction creates the DIE (as is the case for member function
1431 DIE *ContextDIE = getOrCreateContextDIE(resolve(SP.getContext()));
1433 DIE *SPDie = getDIE(SP);
1437 DISubprogram SPDecl = SP.getFunctionDeclaration();
1438 if (SPDecl.isSubprogram())
1439 // Add subprogram definitions to the CU die directly.
1440 ContextDIE = UnitDie.get();
1442 // DW_TAG_inlined_subroutine may refer to this DIE.
1443 SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
1445 DIE *DeclDie = NULL;
1446 if (SPDecl.isSubprogram())
1447 DeclDie = getOrCreateSubprogramDIE(SPDecl);
1449 // Add function template parameters.
1450 addTemplateParams(*SPDie, SP.getTemplateParams());
1452 // If this DIE is going to refer declaration info using AT_specification
1453 // then there is no need to add other attributes.
1455 // Refer function declaration directly.
1456 addDIEEntry(SPDie, dwarf::DW_AT_specification, DeclDie);
1461 // Add the linkage name if we have one.
1462 StringRef LinkageName = SP.getLinkageName();
1463 if (!LinkageName.empty())
1464 addString(SPDie, dwarf::DW_AT_MIPS_linkage_name,
1465 GlobalValue::getRealLinkageName(LinkageName));
1467 // Constructors and operators for anonymous aggregates do not have names.
1468 if (!SP.getName().empty())
1469 addString(SPDie, dwarf::DW_AT_name, SP.getName());
1471 addSourceLine(SPDie, SP);
1473 // Add the prototype if we have a prototype and we have a C like
1475 uint16_t Language = getLanguage();
1476 if (SP.isPrototyped() &&
1477 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1478 Language == dwarf::DW_LANG_ObjC))
1479 addFlag(SPDie, dwarf::DW_AT_prototyped);
1481 DICompositeType SPTy = SP.getType();
1482 assert(SPTy.getTag() == dwarf::DW_TAG_subroutine_type &&
1483 "the type of a subprogram should be a subroutine");
1485 DIArray Args = SPTy.getTypeArray();
1486 // Add a return type. If this is a type like a C/C++ void type we don't add a
1488 if (Args.getElement(0))
1489 addType(SPDie, DIType(Args.getElement(0)));
1491 unsigned VK = SP.getVirtuality();
1493 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1494 DIEBlock *Block = getDIEBlock();
1495 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1496 addUInt(Block, dwarf::DW_FORM_udata, SP.getVirtualIndex());
1497 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
1498 ContainingTypeMap.insert(
1499 std::make_pair(SPDie, resolve(SP.getContainingType())));
1502 if (!SP.isDefinition()) {
1503 addFlag(SPDie, dwarf::DW_AT_declaration);
1505 // Add arguments. Do not add arguments for subprogram definition. They will
1506 // be handled while processing variables.
1507 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1508 DIE *Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, *SPDie);
1509 DIType ATy(Args.getElement(i));
1511 if (ATy.isArtificial())
1512 addFlag(Arg, dwarf::DW_AT_artificial);
1516 if (SP.isArtificial())
1517 addFlag(SPDie, dwarf::DW_AT_artificial);
1519 if (!SP.isLocalToUnit())
1520 addFlag(SPDie, dwarf::DW_AT_external);
1522 if (SP.isOptimized())
1523 addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1525 if (unsigned isa = Asm->getISAEncoding()) {
1526 addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1529 if (SP.isLValueReference())
1530 addFlag(SPDie, dwarf::DW_AT_reference);
1532 if (SP.isRValueReference())
1533 addFlag(SPDie, dwarf::DW_AT_rvalue_reference);
1538 // Return const expression if value is a GEP to access merged global
1540 // i8* getelementptr ({ i8, i8, i8, i8 }* @_MergedGlobals, i32 0, i32 0)
1541 static const ConstantExpr *getMergedGlobalExpr(const Value *V) {
1542 const ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(V);
1543 if (!CE || CE->getNumOperands() != 3 ||
1544 CE->getOpcode() != Instruction::GetElementPtr)
1547 // First operand points to a global struct.
1548 Value *Ptr = CE->getOperand(0);
1549 if (!isa<GlobalValue>(Ptr) ||
1550 !isa<StructType>(cast<PointerType>(Ptr->getType())->getElementType()))
1553 // Second operand is zero.
1554 const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(CE->getOperand(1));
1555 if (!CI || !CI->isZero())
1558 // Third operand is offset.
1559 if (!isa<ConstantInt>(CE->getOperand(2)))
1565 /// createGlobalVariableDIE - create global variable DIE.
1566 void DwarfCompileUnit::createGlobalVariableDIE(DIGlobalVariable GV) {
1567 // Check for pre-existence.
1571 if (!GV.isGlobalVariable())
1574 DIScope GVContext = GV.getContext();
1575 DIType GTy = GV.getType();
1577 // If this is a static data member definition, some attributes belong
1578 // to the declaration DIE.
1579 DIE *VariableDIE = NULL;
1580 bool IsStaticMember = false;
1581 DIDerivedType SDMDecl = GV.getStaticDataMemberDeclaration();
1582 if (SDMDecl.Verify()) {
1583 assert(SDMDecl.isStaticMember() && "Expected static member decl");
1584 // We need the declaration DIE that is in the static member's class.
1585 VariableDIE = getOrCreateStaticMemberDIE(SDMDecl);
1586 IsStaticMember = true;
1589 // If this is not a static data member definition, create the variable
1590 // DIE and add the initial set of attributes to it.
1592 // Construct the context before querying for the existence of the DIE in
1593 // case such construction creates the DIE.
1594 DIE *ContextDIE = getOrCreateContextDIE(GVContext);
1597 VariableDIE = createAndAddDIE(GV.getTag(), *ContextDIE, GV);
1599 // Add name and type.
1600 addString(VariableDIE, dwarf::DW_AT_name, GV.getDisplayName());
1601 addType(VariableDIE, GTy);
1603 // Add scoping info.
1604 if (!GV.isLocalToUnit())
1605 addFlag(VariableDIE, dwarf::DW_AT_external);
1607 // Add line number info.
1608 addSourceLine(VariableDIE, GV);
1612 bool addToAccelTable = false;
1613 DIE *VariableSpecDIE = NULL;
1614 bool isGlobalVariable = GV.getGlobal() != NULL;
1615 if (isGlobalVariable) {
1616 addToAccelTable = true;
1617 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1618 const MCSymbol *Sym = Asm->getSymbol(GV.getGlobal());
1619 if (GV.getGlobal()->isThreadLocal()) {
1620 // FIXME: Make this work with -gsplit-dwarf.
1621 unsigned PointerSize = Asm->getDataLayout().getPointerSize();
1622 assert((PointerSize == 4 || PointerSize == 8) &&
1623 "Add support for other sizes if necessary");
1624 const MCExpr *Expr =
1625 Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym);
1626 // Based on GCC's support for TLS:
1627 if (!DD->useSplitDwarf()) {
1628 // 1) Start with a constNu of the appropriate pointer size
1629 addUInt(Block, dwarf::DW_FORM_data1,
1630 PointerSize == 4 ? dwarf::DW_OP_const4u : dwarf::DW_OP_const8u);
1631 // 2) containing the (relocated) offset of the TLS variable
1632 // within the module's TLS block.
1633 addExpr(Block, dwarf::DW_FORM_udata, Expr);
1635 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
1636 addUInt(Block, dwarf::DW_FORM_udata, DU->getAddrPoolIndex(Expr));
1638 // 3) followed by a custom OP to make the debugger do a TLS lookup.
1639 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_push_tls_address);
1641 DD->addArangeLabel(SymbolCU(this, Sym));
1642 addOpAddress(Block, Sym);
1644 // Do not create specification DIE if context is either compile unit
1646 if (GVContext && GV.isDefinition() && !GVContext.isCompileUnit() &&
1647 !GVContext.isFile() && !DD->isSubprogramContext(GVContext)) {
1648 // Create specification DIE.
1649 VariableSpecDIE = createAndAddDIE(dwarf::DW_TAG_variable, *UnitDie);
1650 addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification, VariableDIE);
1651 addBlock(VariableSpecDIE, dwarf::DW_AT_location, Block);
1652 // A static member's declaration is already flagged as such.
1653 if (!SDMDecl.Verify())
1654 addFlag(VariableDIE, dwarf::DW_AT_declaration);
1656 addBlock(VariableDIE, dwarf::DW_AT_location, Block);
1658 // Add the linkage name.
1659 StringRef LinkageName = GV.getLinkageName();
1660 if (!LinkageName.empty())
1661 // From DWARF4: DIEs to which DW_AT_linkage_name may apply include:
1662 // TAG_common_block, TAG_constant, TAG_entry_point, TAG_subprogram and
1664 addString(IsStaticMember && VariableSpecDIE ? VariableSpecDIE
1666 dwarf::DW_AT_MIPS_linkage_name,
1667 GlobalValue::getRealLinkageName(LinkageName));
1668 } else if (const ConstantInt *CI =
1669 dyn_cast_or_null<ConstantInt>(GV.getConstant())) {
1670 // AT_const_value was added when the static member was created. To avoid
1671 // emitting AT_const_value multiple times, we only add AT_const_value when
1672 // it is not a static member.
1673 if (!IsStaticMember)
1674 addConstantValue(VariableDIE, CI, isUnsignedDIType(DD, GTy));
1675 } else if (const ConstantExpr *CE = getMergedGlobalExpr(GV->getOperand(11))) {
1676 addToAccelTable = true;
1677 // GV is a merged global.
1678 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1679 Value *Ptr = CE->getOperand(0);
1680 MCSymbol *Sym = Asm->getSymbol(cast<GlobalValue>(Ptr));
1681 DD->addArangeLabel(SymbolCU(this, Sym));
1682 addOpAddress(Block, Sym);
1683 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1684 SmallVector<Value *, 3> Idx(CE->op_begin() + 1, CE->op_end());
1685 addUInt(Block, dwarf::DW_FORM_udata,
1686 Asm->getDataLayout().getIndexedOffset(Ptr->getType(), Idx));
1687 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1688 addBlock(VariableDIE, dwarf::DW_AT_location, Block);
1691 if (addToAccelTable) {
1692 DIE *AddrDIE = VariableSpecDIE ? VariableSpecDIE : VariableDIE;
1693 addAccelName(GV.getName(), AddrDIE);
1695 // If the linkage name is different than the name, go ahead and output
1696 // that as well into the name table.
1697 if (GV.getLinkageName() != "" && GV.getName() != GV.getLinkageName())
1698 addAccelName(GV.getLinkageName(), AddrDIE);
1701 if (!GV.isLocalToUnit())
1702 addGlobalName(GV.getName(), VariableSpecDIE ? VariableSpecDIE : VariableDIE,
1706 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
1707 void DwarfUnit::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy) {
1708 DIE *DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
1709 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, IndexTy);
1711 // The LowerBound value defines the lower bounds which is typically zero for
1712 // C/C++. The Count value is the number of elements. Values are 64 bit. If
1713 // Count == -1 then the array is unbounded and we do not emit
1714 // DW_AT_lower_bound and DW_AT_upper_bound attributes. If LowerBound == 0 and
1715 // Count == 0, then the array has zero elements in which case we do not emit
1717 int64_t LowerBound = SR.getLo();
1718 int64_t DefaultLowerBound = getDefaultLowerBound();
1719 int64_t Count = SR.getCount();
1721 if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
1722 addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound);
1724 if (Count != -1 && Count != 0)
1725 // FIXME: An unbounded array should reference the expression that defines
1727 addUInt(DW_Subrange, dwarf::DW_AT_upper_bound, None,
1728 LowerBound + Count - 1);
1731 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
1732 void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, DICompositeType CTy) {
1734 addFlag(&Buffer, dwarf::DW_AT_GNU_vector);
1736 // Emit the element type.
1737 addType(&Buffer, resolve(CTy.getTypeDerivedFrom()));
1739 // Get an anonymous type for index type.
1740 // FIXME: This type should be passed down from the front end
1741 // as different languages may have different sizes for indexes.
1742 DIE *IdxTy = getIndexTyDie();
1744 // Construct an anonymous type for index type.
1745 IdxTy = createAndAddDIE(dwarf::DW_TAG_base_type, *UnitDie);
1746 addString(IdxTy, dwarf::DW_AT_name, "int");
1747 addUInt(IdxTy, dwarf::DW_AT_byte_size, None, sizeof(int32_t));
1748 addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1749 dwarf::DW_ATE_signed);
1750 setIndexTyDie(IdxTy);
1753 // Add subranges to array type.
1754 DIArray Elements = CTy.getTypeArray();
1755 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1756 DIDescriptor Element = Elements.getElement(i);
1757 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1758 constructSubrangeDIE(Buffer, DISubrange(Element), IdxTy);
1762 /// constructEnumTypeDIE - Construct an enum type DIE from DICompositeType.
1763 void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, DICompositeType CTy) {
1764 DIArray Elements = CTy.getTypeArray();
1766 // Add enumerators to enumeration type.
1767 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1768 DIEnumerator Enum(Elements.getElement(i));
1769 if (Enum.isEnumerator()) {
1770 DIE *Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
1771 StringRef Name = Enum.getName();
1772 addString(Enumerator, dwarf::DW_AT_name, Name);
1773 int64_t Value = Enum.getEnumValue();
1774 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
1777 // Add the enumerator to the __apple_names accelerator table.
1778 addAccelName(Name, Enumerator);
1781 DIType DTy = resolve(CTy.getTypeDerivedFrom());
1783 addType(&Buffer, DTy);
1784 addFlag(&Buffer, dwarf::DW_AT_enum_class);
1788 /// constructContainingTypeDIEs - Construct DIEs for types that contain
1790 void DwarfUnit::constructContainingTypeDIEs() {
1791 for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(),
1792 CE = ContainingTypeMap.end();
1794 DIE *SPDie = CI->first;
1795 DIDescriptor D(CI->second);
1798 DIE *NDie = getDIE(D);
1801 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, NDie);
1805 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
1806 DIE *DwarfUnit::constructVariableDIE(DbgVariable &DV, bool isScopeAbstract) {
1807 StringRef Name = DV.getName();
1809 // Define variable debug information entry.
1810 DIE *VariableDie = new DIE(DV.getTag());
1811 DbgVariable *AbsVar = DV.getAbstractVariable();
1812 DIE *AbsDIE = AbsVar ? AbsVar->getDIE() : NULL;
1814 addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin, AbsDIE);
1817 addString(VariableDie, dwarf::DW_AT_name, Name);
1818 addSourceLine(VariableDie, DV.getVariable());
1819 addType(VariableDie, DV.getType());
1822 if (DV.isArtificial())
1823 addFlag(VariableDie, dwarf::DW_AT_artificial);
1825 if (isScopeAbstract) {
1826 DV.setDIE(VariableDie);
1830 // Add variable address.
1832 unsigned Offset = DV.getDotDebugLocOffset();
1833 if (Offset != ~0U) {
1834 addSectionLabel(VariableDie, dwarf::DW_AT_location,
1835 Asm->GetTempSymbol("debug_loc", Offset));
1836 DV.setDIE(VariableDie);
1840 // Check if variable is described by a DBG_VALUE instruction.
1841 if (const MachineInstr *DVInsn = DV.getMInsn()) {
1842 assert(DVInsn->getNumOperands() == 3);
1843 if (DVInsn->getOperand(0).isReg()) {
1844 const MachineOperand RegOp = DVInsn->getOperand(0);
1845 // If the second operand is an immediate, this is an indirect value.
1846 if (DVInsn->getOperand(1).isImm()) {
1847 MachineLocation Location(RegOp.getReg(),
1848 DVInsn->getOperand(1).getImm());
1849 addVariableAddress(DV, VariableDie, Location);
1850 } else if (RegOp.getReg())
1851 addVariableAddress(DV, VariableDie, MachineLocation(RegOp.getReg()));
1852 } else if (DVInsn->getOperand(0).isImm())
1853 addConstantValue(VariableDie, DVInsn->getOperand(0), DV.getType());
1854 else if (DVInsn->getOperand(0).isFPImm())
1855 addConstantFPValue(VariableDie, DVInsn->getOperand(0));
1856 else if (DVInsn->getOperand(0).isCImm())
1857 addConstantValue(VariableDie, DVInsn->getOperand(0).getCImm(),
1858 isUnsignedDIType(DD, DV.getType()));
1860 DV.setDIE(VariableDie);
1863 // .. else use frame index.
1864 int FI = DV.getFrameIndex();
1866 unsigned FrameReg = 0;
1867 const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
1868 int Offset = TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
1869 MachineLocation Location(FrameReg, Offset);
1870 addVariableAddress(DV, VariableDie, Location);
1874 DV.setDIE(VariableDie);
1878 /// constructMemberDIE - Construct member DIE from DIDerivedType.
1879 void DwarfUnit::constructMemberDIE(DIE &Buffer, DIDerivedType DT) {
1880 DIE *MemberDie = createAndAddDIE(DT.getTag(), Buffer);
1881 StringRef Name = DT.getName();
1883 addString(MemberDie, dwarf::DW_AT_name, Name);
1885 addType(MemberDie, resolve(DT.getTypeDerivedFrom()));
1887 addSourceLine(MemberDie, DT);
1889 DIEBlock *MemLocationDie = new (DIEValueAllocator) DIEBlock();
1890 addUInt(MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1892 if (DT.getTag() == dwarf::DW_TAG_inheritance && DT.isVirtual()) {
1894 // For C++, virtual base classes are not at fixed offset. Use following
1895 // expression to extract appropriate offset from vtable.
1896 // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1898 DIEBlock *VBaseLocationDie = new (DIEValueAllocator) DIEBlock();
1899 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1900 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1901 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1902 addUInt(VBaseLocationDie, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1903 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1904 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1905 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1907 addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
1909 uint64_t Size = DT.getSizeInBits();
1910 uint64_t FieldSize = getBaseTypeSize(DD, DT);
1911 uint64_t OffsetInBytes;
1913 if (Size != FieldSize) {
1915 addUInt(MemberDie, dwarf::DW_AT_byte_size, None,
1916 getBaseTypeSize(DD, DT) >> 3);
1917 addUInt(MemberDie, dwarf::DW_AT_bit_size, None, DT.getSizeInBits());
1919 uint64_t Offset = DT.getOffsetInBits();
1920 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1921 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1922 uint64_t FieldOffset = (HiMark - FieldSize);
1923 Offset -= FieldOffset;
1925 // Maybe we need to work from the other end.
1926 if (Asm->getDataLayout().isLittleEndian())
1927 Offset = FieldSize - (Offset + Size);
1928 addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset);
1930 // Here WD_AT_data_member_location points to the anonymous
1931 // field that includes this bit field.
1932 OffsetInBytes = FieldOffset >> 3;
1934 // This is not a bitfield.
1935 OffsetInBytes = DT.getOffsetInBits() >> 3;
1936 addUInt(MemberDie, dwarf::DW_AT_data_member_location, None, OffsetInBytes);
1939 if (DT.isProtected())
1940 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1941 dwarf::DW_ACCESS_protected);
1942 else if (DT.isPrivate())
1943 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1944 dwarf::DW_ACCESS_private);
1945 // Otherwise C++ member and base classes are considered public.
1947 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1948 dwarf::DW_ACCESS_public);
1950 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1951 dwarf::DW_VIRTUALITY_virtual);
1953 // Objective-C properties.
1954 if (MDNode *PNode = DT.getObjCProperty())
1955 if (DIEEntry *PropertyDie = getDIEEntry(PNode))
1956 MemberDie->addValue(dwarf::DW_AT_APPLE_property, dwarf::DW_FORM_ref4,
1959 if (DT.isArtificial())
1960 addFlag(MemberDie, dwarf::DW_AT_artificial);
1963 /// getOrCreateStaticMemberDIE - Create new DIE for C++ static member.
1964 DIE *DwarfUnit::getOrCreateStaticMemberDIE(DIDerivedType DT) {
1968 // Construct the context before querying for the existence of the DIE in case
1969 // such construction creates the DIE.
1970 DIE *ContextDIE = getOrCreateContextDIE(resolve(DT.getContext()));
1971 assert(dwarf::isType(ContextDIE->getTag()) &&
1972 "Static member should belong to a type.");
1974 DIE *StaticMemberDIE = getDIE(DT);
1975 if (StaticMemberDIE)
1976 return StaticMemberDIE;
1978 StaticMemberDIE = createAndAddDIE(DT.getTag(), *ContextDIE, DT);
1980 DIType Ty = resolve(DT.getTypeDerivedFrom());
1982 addString(StaticMemberDIE, dwarf::DW_AT_name, DT.getName());
1983 addType(StaticMemberDIE, Ty);
1984 addSourceLine(StaticMemberDIE, DT);
1985 addFlag(StaticMemberDIE, dwarf::DW_AT_external);
1986 addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
1988 // FIXME: We could omit private if the parent is a class_type, and
1989 // public if the parent is something else.
1990 if (DT.isProtected())
1991 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1992 dwarf::DW_ACCESS_protected);
1993 else if (DT.isPrivate())
1994 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1995 dwarf::DW_ACCESS_private);
1997 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1998 dwarf::DW_ACCESS_public);
2000 if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT.getConstant()))
2001 addConstantValue(StaticMemberDIE, CI, isUnsignedDIType(DD, Ty));
2002 if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT.getConstant()))
2003 addConstantFPValue(StaticMemberDIE, CFP);
2005 return StaticMemberDIE;
2008 void DwarfUnit::emitHeader(const MCSection *ASection,
2009 const MCSymbol *ASectionSym) const {
2010 Asm->OutStreamer.AddComment("DWARF version number");
2011 Asm->EmitInt16(DD->getDwarfVersion());
2012 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
2013 // We share one abbreviations table across all units so it's always at the
2014 // start of the section. Use a relocatable offset where needed to ensure
2015 // linking doesn't invalidate that offset.
2016 Asm->EmitSectionOffset(ASectionSym, ASectionSym);
2017 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2018 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
2021 DwarfCompileUnit::~DwarfCompileUnit() {}
2022 DwarfTypeUnit::~DwarfTypeUnit() {}
2024 void DwarfTypeUnit::emitHeader(const MCSection *ASection,
2025 const MCSymbol *ASectionSym) const {
2026 DwarfUnit::emitHeader(ASection, ASectionSym);
2027 Asm->OutStreamer.AddComment("Type Signature");
2028 Asm->OutStreamer.EmitIntValue(TypeSignature, sizeof(TypeSignature));
2029 Asm->OutStreamer.AddComment("Type DIE Offset");
2030 Asm->OutStreamer.EmitIntValue(Ty->getOffset(), sizeof(Ty->getOffset()));
2033 void DwarfTypeUnit::initSection(const MCSection *Section) {
2034 assert(!this->Section);
2035 this->Section = Section;
2036 // Since each type unit is contained in its own COMDAT section, the begin
2037 // label and the section label are the same. Using the begin label emission in
2038 // DwarfDebug to emit the section label as well is slightly subtle/sneaky, but
2039 // the only other alternative of lazily constructing start-of-section labels
2040 // and storing a mapping in DwarfDebug (or AsmPrinter).
2041 this->SectionSym = this->LabelBegin =
2042 Asm->GetTempSymbol(Section->getLabelBeginName(), getUniqueID());
2044 Asm->GetTempSymbol(Section->getLabelEndName(), getUniqueID());
2045 this->LabelRange = Asm->GetTempSymbol("gnu_ranges", getUniqueID());