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/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"
39 GenerateDwarfTypeUnits("generate-type-units", cl::Hidden,
40 cl::desc("Generate DWARF4 type units."),
43 /// Unit - Unit constructor.
44 DwarfUnit::DwarfUnit(unsigned UID, DIE *D, DICompileUnit Node, AsmPrinter *A,
45 DwarfDebug *DW, DwarfFile *DWU)
46 : UniqueID(UID), CUNode(Node), UnitDie(D), DebugInfoOffset(0), Asm(A),
47 DD(DW), DU(DWU), IndexTyDie(0), Section(0), Skeleton(0) {
48 DIEIntegerOne = new (DIEValueAllocator) DIEInteger(1);
51 DwarfCompileUnit::DwarfCompileUnit(unsigned UID, DIE *D, DICompileUnit Node,
52 AsmPrinter *A, DwarfDebug *DW,
54 : DwarfUnit(UID, D, Node, A, DW, DWU) {
58 DwarfTypeUnit::DwarfTypeUnit(unsigned UID, DIE *D, DwarfCompileUnit &CU,
59 AsmPrinter *A, DwarfDebug *DW, DwarfFile *DWU)
60 : DwarfUnit(UID, D, CU.getCUNode(), A, DW, DWU), CU(CU) {
64 /// ~Unit - Destructor for compile unit.
65 DwarfUnit::~DwarfUnit() {
66 for (unsigned j = 0, M = DIEBlocks.size(); j < M; ++j)
67 DIEBlocks[j]->~DIEBlock();
70 /// createDIEEntry - Creates a new DIEEntry to be a proxy for a debug
71 /// information entry.
72 DIEEntry *DwarfUnit::createDIEEntry(DIE *Entry) {
73 DIEEntry *Value = new (DIEValueAllocator) DIEEntry(Entry);
77 /// getDefaultLowerBound - Return the default lower bound for an array. If the
78 /// DWARF version doesn't handle the language, return -1.
79 int64_t DwarfUnit::getDefaultLowerBound() const {
80 switch (getLanguage()) {
84 case dwarf::DW_LANG_C89:
85 case dwarf::DW_LANG_C99:
86 case dwarf::DW_LANG_C:
87 case dwarf::DW_LANG_C_plus_plus:
88 case dwarf::DW_LANG_ObjC:
89 case dwarf::DW_LANG_ObjC_plus_plus:
92 case dwarf::DW_LANG_Fortran77:
93 case dwarf::DW_LANG_Fortran90:
94 case dwarf::DW_LANG_Fortran95:
97 // The languages below have valid values only if the DWARF version >= 4.
98 case dwarf::DW_LANG_Java:
99 case dwarf::DW_LANG_Python:
100 case dwarf::DW_LANG_UPC:
101 case dwarf::DW_LANG_D:
102 if (dwarf::DWARF_VERSION >= 4)
106 case dwarf::DW_LANG_Ada83:
107 case dwarf::DW_LANG_Ada95:
108 case dwarf::DW_LANG_Cobol74:
109 case dwarf::DW_LANG_Cobol85:
110 case dwarf::DW_LANG_Modula2:
111 case dwarf::DW_LANG_Pascal83:
112 case dwarf::DW_LANG_PLI:
113 if (dwarf::DWARF_VERSION >= 4)
121 /// Check whether the DIE for this MDNode can be shared across CUs.
122 static bool isShareableAcrossCUs(DIDescriptor D) {
123 // When the MDNode can be part of the type system, the DIE can be shared
125 // Combining type units and cross-CU DIE sharing is lower value (since
126 // cross-CU DIE sharing is used in LTO and removes type redundancy at that
127 // level already) but may be implementable for some value in projects
128 // building multiple independent libraries with LTO and then linking those
130 return (D.isType() ||
131 (D.isSubprogram() && !DISubprogram(D).isDefinition())) &&
132 !GenerateDwarfTypeUnits;
135 /// getDIE - Returns the debug information entry map slot for the
136 /// specified debug variable. We delegate the request to DwarfDebug
137 /// when the DIE for this MDNode can be shared across CUs. The mappings
138 /// will be kept in DwarfDebug for shareable DIEs.
139 DIE *DwarfUnit::getDIE(DIDescriptor D) const {
140 if (isShareableAcrossCUs(D))
141 return DD->getDIE(D);
142 return MDNodeToDieMap.lookup(D);
145 /// insertDIE - Insert DIE into the map. We delegate the request to DwarfDebug
146 /// when the DIE for this MDNode can be shared across CUs. The mappings
147 /// will be kept in DwarfDebug for shareable DIEs.
148 void DwarfUnit::insertDIE(DIDescriptor Desc, DIE *D) {
149 if (isShareableAcrossCUs(Desc)) {
150 DD->insertDIE(Desc, D);
153 MDNodeToDieMap.insert(std::make_pair(Desc, D));
156 /// addFlag - Add a flag that is true.
157 void DwarfUnit::addFlag(DIE *Die, dwarf::Attribute Attribute) {
158 if (DD->getDwarfVersion() >= 4)
159 Die->addValue(Attribute, dwarf::DW_FORM_flag_present, DIEIntegerOne);
161 Die->addValue(Attribute, dwarf::DW_FORM_flag, DIEIntegerOne);
164 /// addUInt - Add an unsigned integer attribute data and value.
166 void DwarfUnit::addUInt(DIE *Die, dwarf::Attribute Attribute,
167 Optional<dwarf::Form> Form, uint64_t Integer) {
169 Form = DIEInteger::BestForm(false, Integer);
170 DIEValue *Value = Integer == 1 ? DIEIntegerOne : new (DIEValueAllocator)
172 Die->addValue(Attribute, *Form, Value);
175 void DwarfUnit::addUInt(DIEBlock *Block, dwarf::Form Form, uint64_t Integer) {
176 addUInt(Block, (dwarf::Attribute)0, Form, Integer);
179 /// addSInt - Add an signed integer attribute data and value.
181 void DwarfUnit::addSInt(DIE *Die, dwarf::Attribute Attribute,
182 Optional<dwarf::Form> Form, int64_t Integer) {
184 Form = DIEInteger::BestForm(true, Integer);
185 DIEValue *Value = new (DIEValueAllocator) DIEInteger(Integer);
186 Die->addValue(Attribute, *Form, Value);
189 void DwarfUnit::addSInt(DIEBlock *Die, Optional<dwarf::Form> Form,
191 addSInt(Die, (dwarf::Attribute)0, Form, Integer);
194 /// addString - Add a string attribute data and value. We always emit a
195 /// reference to the string pool instead of immediate strings so that DIEs have
196 /// more predictable sizes. In the case of split dwarf we emit an index
197 /// into another table which gets us the static offset into the string
199 void DwarfUnit::addString(DIE *Die, dwarf::Attribute Attribute,
202 if (!DD->useSplitDwarf())
203 return addLocalString(Die, Attribute, String);
205 unsigned idx = DU->getStringPoolIndex(String);
206 DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
207 DIEValue *Str = new (DIEValueAllocator) DIEString(Value, String);
208 Die->addValue(Attribute, dwarf::DW_FORM_GNU_str_index, Str);
211 /// addLocalString - Add a string attribute data and value. This is guaranteed
212 /// to be in the local string pool instead of indirected.
213 void DwarfUnit::addLocalString(DIE *Die, dwarf::Attribute Attribute,
215 MCSymbol *Symb = DU->getStringPoolEntry(String);
217 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
218 Value = new (DIEValueAllocator) DIELabel(Symb);
220 MCSymbol *StringPool = DU->getStringPoolSym();
221 Value = new (DIEValueAllocator) DIEDelta(Symb, StringPool);
223 DIEValue *Str = new (DIEValueAllocator) DIEString(Value, String);
224 Die->addValue(Attribute, dwarf::DW_FORM_strp, Str);
227 /// addExpr - Add a Dwarf expression attribute data and value.
229 void DwarfUnit::addExpr(DIEBlock *Die, dwarf::Form Form, const MCExpr *Expr) {
230 DIEValue *Value = new (DIEValueAllocator) DIEExpr(Expr);
231 Die->addValue((dwarf::Attribute)0, Form, Value);
234 /// addLabel - Add a Dwarf label attribute data and value.
236 void DwarfUnit::addLabel(DIE *Die, dwarf::Attribute Attribute, dwarf::Form Form,
237 const MCSymbol *Label) {
238 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
239 Die->addValue(Attribute, Form, Value);
242 void DwarfUnit::addLabel(DIEBlock *Die, dwarf::Form Form,
243 const MCSymbol *Label) {
244 addLabel(Die, (dwarf::Attribute)0, Form, Label);
247 /// addSectionLabel - Add a Dwarf section label attribute data and value.
249 void DwarfUnit::addSectionLabel(DIE *Die, dwarf::Attribute Attribute,
250 const MCSymbol *Label) {
251 if (DD->getDwarfVersion() >= 4)
252 addLabel(Die, Attribute, dwarf::DW_FORM_sec_offset, Label);
254 addLabel(Die, Attribute, dwarf::DW_FORM_data4, 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 /// addLabelAddress - Add a dwarf label attribute data and value using
268 /// DW_FORM_addr or DW_FORM_GNU_addr_index.
270 void DwarfCompileUnit::addLabelAddress(DIE *Die, dwarf::Attribute Attribute,
273 DD->addArangeLabel(SymbolCU(this, Label));
275 if (!DD->useSplitDwarf()) {
277 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
278 Die->addValue(Attribute, dwarf::DW_FORM_addr, Value);
280 DIEValue *Value = new (DIEValueAllocator) DIEInteger(0);
281 Die->addValue(Attribute, dwarf::DW_FORM_addr, Value);
284 unsigned idx = DU->getAddrPoolIndex(Label);
285 DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
286 Die->addValue(Attribute, dwarf::DW_FORM_GNU_addr_index, Value);
290 /// addOpAddress - Add a dwarf op address data and value using the
291 /// form given and an op of either DW_FORM_addr or DW_FORM_GNU_addr_index.
293 void DwarfUnit::addOpAddress(DIEBlock *Die, const MCSymbol *Sym) {
294 if (!DD->useSplitDwarf()) {
295 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
296 addLabel(Die, dwarf::DW_FORM_udata, Sym);
298 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index);
299 addUInt(Die, dwarf::DW_FORM_GNU_addr_index, DU->getAddrPoolIndex(Sym));
303 /// addSectionDelta - Add a section label delta attribute data and value.
305 void DwarfUnit::addSectionDelta(DIE *Die, dwarf::Attribute Attribute,
306 const MCSymbol *Hi, const MCSymbol *Lo) {
307 DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
308 if (DD->getDwarfVersion() >= 4)
309 Die->addValue(Attribute, dwarf::DW_FORM_sec_offset, Value);
311 Die->addValue(Attribute, dwarf::DW_FORM_data4, Value);
314 /// addDIEEntry - Add a DIE attribute data and value.
316 void DwarfUnit::addDIEEntry(DIE *Die, dwarf::Attribute Attribute, DIE *Entry) {
317 addDIEEntry(Die, Attribute, createDIEEntry(Entry));
320 void DwarfUnit::addDIETypeSignature(DIE *Die, const DwarfTypeUnit &Type) {
321 Die->addValue(dwarf::DW_AT_signature, dwarf::DW_FORM_ref_sig8,
322 new (DIEValueAllocator) DIETypeSignature(Type));
325 void DwarfUnit::addDIEEntry(DIE *Die, dwarf::Attribute Attribute,
327 const DIE *DieCU = Die->getUnitOrNull();
328 const DIE *EntryCU = Entry->getEntry()->getUnitOrNull();
330 // We assume that Die belongs to this CU, if it is not linked to any CU yet.
331 DieCU = getUnitDie();
333 EntryCU = getUnitDie();
334 Die->addValue(Attribute, EntryCU == DieCU ? dwarf::DW_FORM_ref4
335 : dwarf::DW_FORM_ref_addr,
339 /// Create a DIE with the given Tag, add the DIE to its parent, and
340 /// call insertDIE if MD is not null.
341 DIE *DwarfUnit::createAndAddDIE(unsigned Tag, DIE &Parent, DIDescriptor N) {
342 DIE *Die = new DIE(Tag);
343 Parent.addChild(Die);
349 /// addBlock - Add block data.
351 void DwarfUnit::addBlock(DIE *Die, dwarf::Attribute Attribute,
353 Block->ComputeSize(Asm);
354 DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
355 Die->addValue(Attribute, Block->BestForm(), Block);
358 /// addSourceLine - Add location information to specified debug information
360 void DwarfUnit::addSourceLine(DIE *Die, unsigned Line, StringRef File,
361 StringRef Directory) {
366 DD->getOrCreateSourceID(File, Directory, getCU().getUniqueID());
367 assert(FileID && "Invalid file id");
368 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
369 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
372 /// addSourceLine - Add location information to specified debug information
374 void DwarfUnit::addSourceLine(DIE *Die, DIVariable V) {
375 assert(V.isVariable());
377 addSourceLine(Die, V.getLineNumber(), V.getContext().getFilename(),
378 V.getContext().getDirectory());
381 /// addSourceLine - Add location information to specified debug information
383 void DwarfUnit::addSourceLine(DIE *Die, DIGlobalVariable G) {
384 assert(G.isGlobalVariable());
386 addSourceLine(Die, G.getLineNumber(), G.getFilename(), G.getDirectory());
389 /// addSourceLine - Add location information to specified debug information
391 void DwarfUnit::addSourceLine(DIE *Die, DISubprogram SP) {
392 assert(SP.isSubprogram());
394 addSourceLine(Die, SP.getLineNumber(), SP.getFilename(), SP.getDirectory());
397 /// addSourceLine - Add location information to specified debug information
399 void DwarfUnit::addSourceLine(DIE *Die, DIType Ty) {
402 addSourceLine(Die, Ty.getLineNumber(), Ty.getFilename(), Ty.getDirectory());
405 /// addSourceLine - Add location information to specified debug information
407 void DwarfUnit::addSourceLine(DIE *Die, DIObjCProperty Ty) {
408 assert(Ty.isObjCProperty());
410 DIFile File = Ty.getFile();
411 addSourceLine(Die, Ty.getLineNumber(), File.getFilename(),
412 File.getDirectory());
415 /// addSourceLine - Add location information to specified debug information
417 void DwarfUnit::addSourceLine(DIE *Die, DINameSpace NS) {
420 addSourceLine(Die, NS.getLineNumber(), NS.getFilename(), NS.getDirectory());
423 /// addVariableAddress - Add DW_AT_location attribute for a
424 /// DbgVariable based on provided MachineLocation.
425 void DwarfUnit::addVariableAddress(const DbgVariable &DV, DIE *Die,
426 MachineLocation Location) {
427 if (DV.variableHasComplexAddress())
428 addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
429 else if (DV.isBlockByrefVariable())
430 addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location);
432 addAddress(Die, dwarf::DW_AT_location, Location,
433 DV.getVariable().isIndirect());
436 /// addRegisterOp - Add register operand.
437 void DwarfUnit::addRegisterOp(DIEBlock *TheDie, unsigned Reg) {
438 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
439 int DWReg = RI->getDwarfRegNum(Reg, false);
440 bool isSubRegister = DWReg < 0;
444 // Go up the super-register chain until we hit a valid dwarf register number.
445 for (MCSuperRegIterator SR(Reg, RI); SR.isValid() && DWReg < 0; ++SR) {
446 DWReg = RI->getDwarfRegNum(*SR, false);
448 Idx = RI->getSubRegIndex(*SR, Reg);
452 DEBUG(llvm::dbgs() << "Invalid Dwarf register number.\n");
453 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_nop);
459 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + DWReg);
461 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
462 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
467 unsigned Size = RI->getSubRegIdxSize(Idx);
468 unsigned Offset = RI->getSubRegIdxOffset(Idx);
470 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_bit_piece);
471 addUInt(TheDie, dwarf::DW_FORM_data1, Size);
472 addUInt(TheDie, dwarf::DW_FORM_data1, Offset);
474 unsigned ByteSize = Size / 8; // Assuming 8 bits per byte.
475 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_piece);
476 addUInt(TheDie, dwarf::DW_FORM_data1, ByteSize);
481 /// addRegisterOffset - Add register offset.
482 void DwarfUnit::addRegisterOffset(DIEBlock *TheDie, unsigned Reg,
484 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
485 unsigned DWReg = RI->getDwarfRegNum(Reg, false);
486 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
487 if (Reg == TRI->getFrameRegister(*Asm->MF))
488 // If variable offset is based in frame register then use fbreg.
489 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_fbreg);
491 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + DWReg);
493 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
494 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
496 addSInt(TheDie, dwarf::DW_FORM_sdata, Offset);
499 /// addAddress - Add an address attribute to a die based on the location
501 void DwarfUnit::addAddress(DIE *Die, dwarf::Attribute Attribute,
502 const MachineLocation &Location, bool Indirect) {
503 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
505 if (Location.isReg() && !Indirect)
506 addRegisterOp(Block, Location.getReg());
508 addRegisterOffset(Block, Location.getReg(), Location.getOffset());
509 if (Indirect && !Location.isReg()) {
510 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
514 // Now attach the location information to the DIE.
515 addBlock(Die, Attribute, Block);
518 /// addComplexAddress - Start with the address based on the location provided,
519 /// and generate the DWARF information necessary to find the actual variable
520 /// given the extra address information encoded in the DbgVariable, starting
521 /// from the starting location. Add the DWARF information to the die.
523 void DwarfUnit::addComplexAddress(const DbgVariable &DV, DIE *Die,
524 dwarf::Attribute Attribute,
525 const MachineLocation &Location) {
526 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
527 unsigned N = DV.getNumAddrElements();
529 if (Location.isReg()) {
530 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
531 // If first address element is OpPlus then emit
532 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
533 addRegisterOffset(Block, Location.getReg(), DV.getAddrElement(1));
536 addRegisterOp(Block, Location.getReg());
538 addRegisterOffset(Block, Location.getReg(), Location.getOffset());
541 uint64_t Element = DV.getAddrElement(i);
542 if (Element == DIBuilder::OpPlus) {
543 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
544 addUInt(Block, dwarf::DW_FORM_udata, DV.getAddrElement(++i));
545 } else if (Element == DIBuilder::OpDeref) {
546 if (!Location.isReg())
547 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
549 llvm_unreachable("unknown DIBuilder Opcode");
552 // Now attach the location information to the DIE.
553 addBlock(Die, Attribute, Block);
556 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
557 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
558 gives the variable VarName either the struct, or a pointer to the struct, as
559 its type. This is necessary for various behind-the-scenes things the
560 compiler needs to do with by-reference variables in Blocks.
562 However, as far as the original *programmer* is concerned, the variable
563 should still have type 'SomeType', as originally declared.
565 The function getBlockByrefType dives into the __Block_byref_x_VarName
566 struct to find the original type of the variable, which is then assigned to
567 the variable's Debug Information Entry as its real type. So far, so good.
568 However now the debugger will expect the variable VarName to have the type
569 SomeType. So we need the location attribute for the variable to be an
570 expression that explains to the debugger how to navigate through the
571 pointers and struct to find the actual variable of type SomeType.
573 The following function does just that. We start by getting
574 the "normal" location for the variable. This will be the location
575 of either the struct __Block_byref_x_VarName or the pointer to the
576 struct __Block_byref_x_VarName.
578 The struct will look something like:
580 struct __Block_byref_x_VarName {
582 struct __Block_byref_x_VarName *forwarding;
583 ... <various other fields>
585 ... <maybe more fields>
588 If we are given the struct directly (as our starting point) we
589 need to tell the debugger to:
591 1). Add the offset of the forwarding field.
593 2). Follow that pointer to get the real __Block_byref_x_VarName
594 struct to use (the real one may have been copied onto the heap).
596 3). Add the offset for the field VarName, to find the actual variable.
598 If we started with a pointer to the struct, then we need to
599 dereference that pointer first, before the other steps.
600 Translating this into DWARF ops, we will need to append the following
601 to the current location description for the variable:
603 DW_OP_deref -- optional, if we start with a pointer
604 DW_OP_plus_uconst <forward_fld_offset>
606 DW_OP_plus_uconst <varName_fld_offset>
608 That is what this function does. */
610 /// addBlockByrefAddress - Start with the address based on the location
611 /// provided, and generate the DWARF information necessary to find the
612 /// actual Block variable (navigating the Block struct) based on the
613 /// starting location. Add the DWARF information to the die. For
614 /// more information, read large comment just above here.
616 void DwarfUnit::addBlockByrefAddress(const DbgVariable &DV, DIE *Die,
617 dwarf::Attribute Attribute,
618 const MachineLocation &Location) {
619 DIType Ty = DV.getType();
621 uint16_t Tag = Ty.getTag();
622 bool isPointer = false;
624 StringRef varName = DV.getName();
626 if (Tag == dwarf::DW_TAG_pointer_type) {
627 DIDerivedType DTy(Ty);
628 TmpTy = resolve(DTy.getTypeDerivedFrom());
632 DICompositeType blockStruct(TmpTy);
634 // Find the __forwarding field and the variable field in the __Block_byref
636 DIArray Fields = blockStruct.getTypeArray();
637 DIDerivedType varField;
638 DIDerivedType forwardingField;
640 for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
641 DIDerivedType DT(Fields.getElement(i));
642 StringRef fieldName = DT.getName();
643 if (fieldName == "__forwarding")
644 forwardingField = DT;
645 else if (fieldName == varName)
649 // Get the offsets for the forwarding field and the variable field.
650 unsigned forwardingFieldOffset = forwardingField.getOffsetInBits() >> 3;
651 unsigned varFieldOffset = varField.getOffsetInBits() >> 2;
653 // Decode the original location, and use that as the start of the byref
654 // variable's location.
655 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
657 if (Location.isReg())
658 addRegisterOp(Block, Location.getReg());
660 addRegisterOffset(Block, Location.getReg(), Location.getOffset());
662 // If we started with a pointer to the __Block_byref... struct, then
663 // the first thing we need to do is dereference the pointer (DW_OP_deref).
665 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
667 // Next add the offset for the '__forwarding' field:
668 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
669 // adding the offset if it's 0.
670 if (forwardingFieldOffset > 0) {
671 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
672 addUInt(Block, dwarf::DW_FORM_udata, forwardingFieldOffset);
675 // Now dereference the __forwarding field to get to the real __Block_byref
676 // struct: DW_OP_deref.
677 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
679 // Now that we've got the real __Block_byref... struct, add the offset
680 // for the variable's field to get to the location of the actual variable:
681 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
682 if (varFieldOffset > 0) {
683 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
684 addUInt(Block, dwarf::DW_FORM_udata, varFieldOffset);
687 // Now attach the location information to the DIE.
688 addBlock(Die, Attribute, Block);
691 /// isTypeSigned - Return true if the type is signed.
692 static bool isTypeSigned(DwarfDebug *DD, DIType Ty, int *SizeInBits) {
693 if (Ty.isDerivedType())
694 return isTypeSigned(DD, DD->resolve(DIDerivedType(Ty).getTypeDerivedFrom()),
696 if (Ty.isBasicType())
697 if (DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed ||
698 DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed_char) {
699 *SizeInBits = Ty.getSizeInBits();
705 /// Return true if type encoding is unsigned.
706 static bool isUnsignedDIType(DwarfDebug *DD, DIType Ty) {
707 DIDerivedType DTy(Ty);
708 if (DTy.isDerivedType())
709 return isUnsignedDIType(DD, DD->resolve(DTy.getTypeDerivedFrom()));
712 if (BTy.isBasicType()) {
713 unsigned Encoding = BTy.getEncoding();
714 if (Encoding == dwarf::DW_ATE_unsigned ||
715 Encoding == dwarf::DW_ATE_unsigned_char ||
716 Encoding == dwarf::DW_ATE_boolean)
722 /// If this type is derived from a base type then return base type size.
723 static uint64_t getBaseTypeSize(DwarfDebug *DD, DIDerivedType Ty) {
724 unsigned Tag = Ty.getTag();
726 if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef &&
727 Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type &&
728 Tag != dwarf::DW_TAG_restrict_type)
729 return Ty.getSizeInBits();
731 DIType BaseType = DD->resolve(Ty.getTypeDerivedFrom());
733 // If this type is not derived from any type then take conservative approach.
734 if (!BaseType.isValid())
735 return Ty.getSizeInBits();
737 // If this is a derived type, go ahead and get the base type, unless it's a
738 // reference then it's just the size of the field. Pointer types have no need
739 // of this since they're a different type of qualification on the type.
740 if (BaseType.getTag() == dwarf::DW_TAG_reference_type ||
741 BaseType.getTag() == dwarf::DW_TAG_rvalue_reference_type)
742 return Ty.getSizeInBits();
744 if (BaseType.isDerivedType())
745 return getBaseTypeSize(DD, DIDerivedType(BaseType));
747 return BaseType.getSizeInBits();
750 /// addConstantValue - Add constant value entry in variable DIE.
751 void DwarfUnit::addConstantValue(DIE *Die, const MachineOperand &MO,
753 // FIXME: This is a bit conservative/simple - it emits negative values at
754 // their maximum bit width which is a bit unfortunate (& doesn't prefer
755 // udata/sdata over dataN as suggested by the DWARF spec)
756 assert(MO.isImm() && "Invalid machine operand!");
758 bool SignedConstant = isTypeSigned(DD, Ty, &SizeInBits);
761 // If we're a signed constant definitely use sdata.
762 if (SignedConstant) {
763 addSInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, MO.getImm());
767 // Else use data for now unless it's larger than we can deal with.
768 switch (SizeInBits) {
770 Form = dwarf::DW_FORM_data1;
773 Form = dwarf::DW_FORM_data2;
776 Form = dwarf::DW_FORM_data4;
779 Form = dwarf::DW_FORM_data8;
782 Form = dwarf::DW_FORM_udata;
783 addUInt(Die, dwarf::DW_AT_const_value, Form, MO.getImm());
786 addUInt(Die, dwarf::DW_AT_const_value, Form, MO.getImm());
789 /// addConstantFPValue - Add constant value entry in variable DIE.
790 void DwarfUnit::addConstantFPValue(DIE *Die, const MachineOperand &MO) {
791 assert(MO.isFPImm() && "Invalid machine operand!");
792 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
793 APFloat FPImm = MO.getFPImm()->getValueAPF();
795 // Get the raw data form of the floating point.
796 const APInt FltVal = FPImm.bitcastToAPInt();
797 const char *FltPtr = (const char *)FltVal.getRawData();
799 int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
800 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
801 int Incr = (LittleEndian ? 1 : -1);
802 int Start = (LittleEndian ? 0 : NumBytes - 1);
803 int Stop = (LittleEndian ? NumBytes : -1);
805 // Output the constant to DWARF one byte at a time.
806 for (; Start != Stop; Start += Incr)
807 addUInt(Block, dwarf::DW_FORM_data1, (unsigned char)0xFF & FltPtr[Start]);
809 addBlock(Die, dwarf::DW_AT_const_value, Block);
812 /// addConstantFPValue - Add constant value entry in variable DIE.
813 void DwarfUnit::addConstantFPValue(DIE *Die, const ConstantFP *CFP) {
814 // Pass this down to addConstantValue as an unsigned bag of bits.
815 addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true);
818 /// addConstantValue - Add constant value entry in variable DIE.
819 void DwarfUnit::addConstantValue(DIE *Die, const ConstantInt *CI,
821 addConstantValue(Die, CI->getValue(), Unsigned);
824 // addConstantValue - Add constant value entry in variable DIE.
825 void DwarfUnit::addConstantValue(DIE *Die, const APInt &Val, bool Unsigned) {
826 unsigned CIBitWidth = Val.getBitWidth();
827 if (CIBitWidth <= 64) {
828 // If we're a signed constant definitely use sdata.
830 addSInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
835 // Else use data for now unless it's larger than we can deal with.
837 switch (CIBitWidth) {
839 Form = dwarf::DW_FORM_data1;
842 Form = dwarf::DW_FORM_data2;
845 Form = dwarf::DW_FORM_data4;
848 Form = dwarf::DW_FORM_data8;
851 addUInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_udata,
855 addUInt(Die, dwarf::DW_AT_const_value, Form, Val.getZExtValue());
859 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
861 // Get the raw data form of the large APInt.
862 const uint64_t *Ptr64 = Val.getRawData();
864 int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
865 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
867 // Output the constant to DWARF one byte at a time.
868 for (int i = 0; i < NumBytes; i++) {
871 c = Ptr64[i / 8] >> (8 * (i & 7));
873 c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
874 addUInt(Block, dwarf::DW_FORM_data1, c);
877 addBlock(Die, dwarf::DW_AT_const_value, Block);
880 /// addTemplateParams - Add template parameters into buffer.
881 void DwarfUnit::addTemplateParams(DIE &Buffer, DIArray TParams) {
882 // Add template parameters.
883 for (unsigned i = 0, e = TParams.getNumElements(); i != e; ++i) {
884 DIDescriptor Element = TParams.getElement(i);
885 if (Element.isTemplateTypeParameter())
886 constructTemplateTypeParameterDIE(Buffer,
887 DITemplateTypeParameter(Element));
888 else if (Element.isTemplateValueParameter())
889 constructTemplateValueParameterDIE(Buffer,
890 DITemplateValueParameter(Element));
894 /// getOrCreateContextDIE - Get context owner's DIE.
895 DIE *DwarfUnit::getOrCreateContextDIE(DIScope Context) {
896 if (!Context || Context.isFile())
898 if (Context.isType())
899 return getOrCreateTypeDIE(DIType(Context));
900 if (Context.isNameSpace())
901 return getOrCreateNameSpace(DINameSpace(Context));
902 if (Context.isSubprogram())
903 return getOrCreateSubprogramDIE(DISubprogram(Context));
904 return getDIE(Context);
907 DIE *DwarfUnit::createTypeDIE(DICompositeType Ty) {
908 DIScope Context = resolve(Ty.getContext());
909 DIE *ContextDIE = getOrCreateContextDIE(Context);
911 DIE *TyDIE = getDIE(Ty);
916 TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
918 constructTypeDIE(*TyDIE, Ty);
920 updateAcceleratorTables(Context, Ty, TyDIE);
924 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
926 DIE *DwarfUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
933 // Construct the context before querying for the existence of the DIE in case
934 // such construction creates the DIE.
935 DIScope Context = resolve(Ty.getContext());
936 DIE *ContextDIE = getOrCreateContextDIE(Context);
939 DIE *TyDIE = getDIE(Ty);
944 TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
946 if (Ty.isBasicType())
947 constructTypeDIE(*TyDIE, DIBasicType(Ty));
948 else if (Ty.isCompositeType()) {
949 DICompositeType CTy(Ty);
950 if (GenerateDwarfTypeUnits && !Ty.isForwardDecl())
951 if (MDString *TypeId = CTy.getIdentifier()) {
952 DD->addDwarfTypeUnitType(getCU(), TypeId->getString(), TyDIE, CTy);
953 // Skip updating the accellerator tables since this is not the full type
956 constructTypeDIE(*TyDIE, CTy);
958 assert(Ty.isDerivedType() && "Unknown kind of DIType");
959 constructTypeDIE(*TyDIE, DIDerivedType(Ty));
962 updateAcceleratorTables(Context, Ty, TyDIE);
967 void DwarfUnit::updateAcceleratorTables(DIScope Context, DIType Ty,
969 if (!Ty.getName().empty() && !Ty.isForwardDecl()) {
970 bool IsImplementation = 0;
971 if (Ty.isCompositeType()) {
972 DICompositeType CT(Ty);
973 // A runtime language of 0 actually means C/C++ and that any
974 // non-negative value is some version of Objective-C/C++.
975 IsImplementation = (CT.getRunTimeLang() == 0) || CT.isObjcClassComplete();
977 unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0;
978 addAccelType(Ty.getName(), std::make_pair(TyDIE, Flags));
980 if (!Context || Context.isCompileUnit() || Context.isFile() ||
981 Context.isNameSpace())
982 GlobalTypes[getParentContextString(Context) + Ty.getName().str()] = TyDIE;
986 /// addType - Add a new type attribute to the specified entity.
987 void DwarfUnit::addType(DIE *Entity, DIType Ty, dwarf::Attribute Attribute) {
988 assert(Ty && "Trying to add a type that doesn't exist?");
990 // Check for pre-existence.
991 DIEEntry *Entry = getDIEEntry(Ty);
992 // If it exists then use the existing value.
994 addDIEEntry(Entity, Attribute, Entry);
999 DIE *Buffer = getOrCreateTypeDIE(Ty);
1002 Entry = createDIEEntry(Buffer);
1003 insertDIEEntry(Ty, Entry);
1004 addDIEEntry(Entity, Attribute, Entry);
1007 // Accelerator table mutators - add each name along with its companion
1008 // DIE to the proper table while ensuring that the name that we're going
1009 // to reference is in the string table. We do this since the names we
1010 // add may not only be identical to the names in the DIE.
1011 void DwarfUnit::addAccelName(StringRef Name, const DIE *Die) {
1012 if (!DD->useDwarfAccelTables()) return;
1013 DU->getStringPoolEntry(Name);
1014 std::vector<const DIE *> &DIEs = AccelNames[Name];
1015 DIEs.push_back(Die);
1018 void DwarfUnit::addAccelObjC(StringRef Name, const DIE *Die) {
1019 if (!DD->useDwarfAccelTables()) return;
1020 DU->getStringPoolEntry(Name);
1021 std::vector<const DIE *> &DIEs = AccelObjC[Name];
1022 DIEs.push_back(Die);
1025 void DwarfUnit::addAccelNamespace(StringRef Name, const DIE *Die) {
1026 if (!DD->useDwarfAccelTables()) return;
1027 DU->getStringPoolEntry(Name);
1028 std::vector<const DIE *> &DIEs = AccelNamespace[Name];
1029 DIEs.push_back(Die);
1032 void DwarfUnit::addAccelType(StringRef Name,
1033 std::pair<const DIE *, unsigned> Die) {
1034 if (!DD->useDwarfAccelTables()) return;
1035 DU->getStringPoolEntry(Name);
1036 std::vector<std::pair<const DIE *, unsigned> > &DIEs = AccelTypes[Name];
1037 DIEs.push_back(Die);
1040 /// addGlobalName - Add a new global name to the compile unit.
1041 void DwarfUnit::addGlobalName(StringRef Name, DIE *Die, DIScope Context) {
1042 std::string FullName = getParentContextString(Context) + Name.str();
1043 GlobalNames[FullName] = Die;
1046 /// getParentContextString - Walks the metadata parent chain in a language
1047 /// specific manner (using the compile unit language) and returns
1048 /// it as a string. This is done at the metadata level because DIEs may
1049 /// not currently have been added to the parent context and walking the
1050 /// DIEs looking for names is more expensive than walking the metadata.
1051 std::string DwarfUnit::getParentContextString(DIScope Context) const {
1055 // FIXME: Decide whether to implement this for non-C++ languages.
1056 if (getLanguage() != dwarf::DW_LANG_C_plus_plus)
1060 SmallVector<DIScope, 1> Parents;
1061 while (!Context.isCompileUnit()) {
1062 Parents.push_back(Context);
1063 if (Context.getContext())
1064 Context = resolve(Context.getContext());
1066 // Structure, etc types will have a NULL context if they're at the top
1071 // Reverse iterate over our list to go from the outermost construct to the
1073 for (SmallVectorImpl<DIScope>::reverse_iterator I = Parents.rbegin(),
1077 StringRef Name = Ctx.getName();
1078 if (!Name.empty()) {
1086 /// constructTypeDIE - Construct basic type die from DIBasicType.
1087 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
1088 // Get core information.
1089 StringRef Name = BTy.getName();
1090 // Add name if not anonymous or intermediate type.
1092 addString(&Buffer, dwarf::DW_AT_name, Name);
1094 // An unspecified type only has a name attribute.
1095 if (BTy.getTag() == dwarf::DW_TAG_unspecified_type)
1098 addUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1101 uint64_t Size = BTy.getSizeInBits() >> 3;
1102 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1105 /// constructTypeDIE - Construct derived type die from DIDerivedType.
1106 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
1107 // Get core information.
1108 StringRef Name = DTy.getName();
1109 uint64_t Size = DTy.getSizeInBits() >> 3;
1110 uint16_t Tag = Buffer.getTag();
1112 // Map to main type, void will not have a type.
1113 DIType FromTy = resolve(DTy.getTypeDerivedFrom());
1115 addType(&Buffer, FromTy);
1117 // Add name if not anonymous or intermediate type.
1119 addString(&Buffer, dwarf::DW_AT_name, Name);
1121 // Add size if non-zero (derived types might be zero-sized.)
1122 if (Size && Tag != dwarf::DW_TAG_pointer_type)
1123 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1125 if (Tag == dwarf::DW_TAG_ptr_to_member_type)
1126 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type,
1127 getOrCreateTypeDIE(resolve(DTy.getClassType())));
1128 // Add source line info if available and TyDesc is not a forward declaration.
1129 if (!DTy.isForwardDecl())
1130 addSourceLine(&Buffer, DTy);
1133 /// constructTypeDIE - Construct type DIE from DICompositeType.
1134 void DwarfUnit::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
1135 // Add name if not anonymous or intermediate type.
1136 StringRef Name = CTy.getName();
1138 uint64_t Size = CTy.getSizeInBits() >> 3;
1139 uint16_t Tag = Buffer.getTag();
1142 case dwarf::DW_TAG_array_type:
1143 constructArrayTypeDIE(Buffer, CTy);
1145 case dwarf::DW_TAG_enumeration_type:
1146 constructEnumTypeDIE(Buffer, CTy);
1148 case dwarf::DW_TAG_subroutine_type: {
1149 // Add return type. A void return won't have a type.
1150 DIArray Elements = CTy.getTypeArray();
1151 DIType RTy(Elements.getElement(0));
1153 addType(&Buffer, RTy);
1155 bool isPrototyped = true;
1157 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
1158 DIDescriptor Ty = Elements.getElement(i);
1159 if (Ty.isUnspecifiedParameter()) {
1160 createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
1161 isPrototyped = false;
1163 DIE *Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
1164 addType(Arg, DIType(Ty));
1165 if (DIType(Ty).isArtificial())
1166 addFlag(Arg, dwarf::DW_AT_artificial);
1169 // Add prototype flag if we're dealing with a C language and the
1170 // function has been prototyped.
1171 uint16_t Language = getLanguage();
1173 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1174 Language == dwarf::DW_LANG_ObjC))
1175 addFlag(&Buffer, dwarf::DW_AT_prototyped);
1177 if (CTy.isLValueReference())
1178 addFlag(&Buffer, dwarf::DW_AT_reference);
1180 if (CTy.isRValueReference())
1181 addFlag(&Buffer, dwarf::DW_AT_rvalue_reference);
1183 case dwarf::DW_TAG_structure_type:
1184 case dwarf::DW_TAG_union_type:
1185 case dwarf::DW_TAG_class_type: {
1186 // Add elements to structure type.
1187 DIArray Elements = CTy.getTypeArray();
1188 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1189 DIDescriptor Element = Elements.getElement(i);
1190 DIE *ElemDie = NULL;
1191 if (Element.isSubprogram())
1192 ElemDie = getOrCreateSubprogramDIE(DISubprogram(Element));
1193 else if (Element.isDerivedType()) {
1194 DIDerivedType DDTy(Element);
1195 if (DDTy.getTag() == dwarf::DW_TAG_friend) {
1196 ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
1197 addType(ElemDie, resolve(DDTy.getTypeDerivedFrom()),
1198 dwarf::DW_AT_friend);
1199 } else if (DDTy.isStaticMember()) {
1200 getOrCreateStaticMemberDIE(DDTy);
1202 constructMemberDIE(Buffer, DDTy);
1204 } else if (Element.isObjCProperty()) {
1205 DIObjCProperty Property(Element);
1206 ElemDie = createAndAddDIE(Property.getTag(), Buffer);
1207 StringRef PropertyName = Property.getObjCPropertyName();
1208 addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
1209 if (Property.getType())
1210 addType(ElemDie, Property.getType());
1211 addSourceLine(ElemDie, Property);
1212 StringRef GetterName = Property.getObjCPropertyGetterName();
1213 if (!GetterName.empty())
1214 addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
1215 StringRef SetterName = Property.getObjCPropertySetterName();
1216 if (!SetterName.empty())
1217 addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
1218 unsigned PropertyAttributes = 0;
1219 if (Property.isReadOnlyObjCProperty())
1220 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readonly;
1221 if (Property.isReadWriteObjCProperty())
1222 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readwrite;
1223 if (Property.isAssignObjCProperty())
1224 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_assign;
1225 if (Property.isRetainObjCProperty())
1226 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_retain;
1227 if (Property.isCopyObjCProperty())
1228 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_copy;
1229 if (Property.isNonAtomicObjCProperty())
1230 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_nonatomic;
1231 if (PropertyAttributes)
1232 addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None,
1233 PropertyAttributes);
1235 DIEEntry *Entry = getDIEEntry(Element);
1237 Entry = createDIEEntry(ElemDie);
1238 insertDIEEntry(Element, Entry);
1244 if (CTy.isAppleBlockExtension())
1245 addFlag(&Buffer, dwarf::DW_AT_APPLE_block);
1247 DICompositeType ContainingType(resolve(CTy.getContainingType()));
1249 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type,
1250 getOrCreateTypeDIE(ContainingType));
1252 if (CTy.isObjcClassComplete())
1253 addFlag(&Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
1255 // Add template parameters to a class, structure or union types.
1256 // FIXME: The support isn't in the metadata for this yet.
1257 if (Tag == dwarf::DW_TAG_class_type ||
1258 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
1259 addTemplateParams(Buffer, CTy.getTemplateParams());
1267 // Add name if not anonymous or intermediate type.
1269 addString(&Buffer, dwarf::DW_AT_name, Name);
1271 if (Tag == dwarf::DW_TAG_enumeration_type ||
1272 Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
1273 Tag == dwarf::DW_TAG_union_type) {
1274 // Add size if non-zero (derived types might be zero-sized.)
1275 // TODO: Do we care about size for enum forward declarations?
1277 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1278 else if (!CTy.isForwardDecl())
1279 // Add zero size if it is not a forward declaration.
1280 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, 0);
1282 // If we're a forward decl, say so.
1283 if (CTy.isForwardDecl())
1284 addFlag(&Buffer, dwarf::DW_AT_declaration);
1286 // Add source line info if available.
1287 if (!CTy.isForwardDecl())
1288 addSourceLine(&Buffer, CTy);
1290 // No harm in adding the runtime language to the declaration.
1291 unsigned RLang = CTy.getRunTimeLang();
1293 addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
1298 /// constructTemplateTypeParameterDIE - Construct new DIE for the given
1299 /// DITemplateTypeParameter.
1300 void DwarfUnit::constructTemplateTypeParameterDIE(DIE &Buffer,
1301 DITemplateTypeParameter TP) {
1303 createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
1304 // Add the type if it exists, it could be void and therefore no type.
1306 addType(ParamDIE, resolve(TP.getType()));
1307 if (!TP.getName().empty())
1308 addString(ParamDIE, dwarf::DW_AT_name, TP.getName());
1311 /// constructTemplateValueParameterDIE - Construct new DIE for the given
1312 /// DITemplateValueParameter.
1314 DwarfUnit::constructTemplateValueParameterDIE(DIE &Buffer,
1315 DITemplateValueParameter VP) {
1316 DIE *ParamDIE = createAndAddDIE(VP.getTag(), Buffer);
1318 // Add the type if there is one, template template and template parameter
1319 // packs will not have a type.
1320 if (VP.getTag() == dwarf::DW_TAG_template_value_parameter)
1321 addType(ParamDIE, resolve(VP.getType()));
1322 if (!VP.getName().empty())
1323 addString(ParamDIE, dwarf::DW_AT_name, VP.getName());
1324 if (Value *Val = VP.getValue()) {
1325 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val))
1326 addConstantValue(ParamDIE, CI,
1327 isUnsignedDIType(DD, resolve(VP.getType())));
1328 else if (GlobalValue *GV = dyn_cast<GlobalValue>(Val)) {
1329 // For declaration non-type template parameters (such as global values and
1331 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1332 addOpAddress(Block, Asm->getSymbol(GV));
1333 // Emit DW_OP_stack_value to use the address as the immediate value of the
1334 // parameter, rather than a pointer to it.
1335 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
1336 addBlock(ParamDIE, dwarf::DW_AT_location, Block);
1337 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1338 assert(isa<MDString>(Val));
1339 addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
1340 cast<MDString>(Val)->getString());
1341 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1342 assert(isa<MDNode>(Val));
1343 DIArray A(cast<MDNode>(Val));
1344 addTemplateParams(*ParamDIE, A);
1349 /// getOrCreateNameSpace - Create a DIE for DINameSpace.
1350 DIE *DwarfUnit::getOrCreateNameSpace(DINameSpace NS) {
1351 // Construct the context before querying for the existence of the DIE in case
1352 // such construction creates the DIE.
1353 DIE *ContextDIE = getOrCreateContextDIE(NS.getContext());
1355 DIE *NDie = getDIE(NS);
1358 NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS);
1360 if (!NS.getName().empty()) {
1361 addString(NDie, dwarf::DW_AT_name, NS.getName());
1362 addAccelNamespace(NS.getName(), NDie);
1363 addGlobalName(NS.getName(), NDie, NS.getContext());
1365 addAccelNamespace("(anonymous namespace)", NDie);
1366 addSourceLine(NDie, NS);
1370 /// getOrCreateSubprogramDIE - Create new DIE using SP.
1371 DIE *DwarfUnit::getOrCreateSubprogramDIE(DISubprogram SP) {
1372 // Construct the context before querying for the existence of the DIE in case
1373 // such construction creates the DIE (as is the case for member function
1375 DIE *ContextDIE = getOrCreateContextDIE(resolve(SP.getContext()));
1377 DIE *SPDie = getDIE(SP);
1381 DISubprogram SPDecl = SP.getFunctionDeclaration();
1382 if (SPDecl.isSubprogram())
1383 // Add subprogram definitions to the CU die directly.
1384 ContextDIE = UnitDie.get();
1386 // DW_TAG_inlined_subroutine may refer to this DIE.
1387 SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
1389 DIE *DeclDie = NULL;
1390 if (SPDecl.isSubprogram())
1391 DeclDie = getOrCreateSubprogramDIE(SPDecl);
1393 // Add function template parameters.
1394 addTemplateParams(*SPDie, SP.getTemplateParams());
1396 // If this DIE is going to refer declaration info using AT_specification
1397 // then there is no need to add other attributes.
1399 // Refer function declaration directly.
1400 addDIEEntry(SPDie, dwarf::DW_AT_specification, DeclDie);
1405 // Add the linkage name if we have one.
1406 StringRef LinkageName = SP.getLinkageName();
1407 if (!LinkageName.empty())
1408 addString(SPDie, dwarf::DW_AT_MIPS_linkage_name,
1409 GlobalValue::getRealLinkageName(LinkageName));
1411 // Constructors and operators for anonymous aggregates do not have names.
1412 if (!SP.getName().empty())
1413 addString(SPDie, dwarf::DW_AT_name, SP.getName());
1415 addSourceLine(SPDie, SP);
1417 // Add the prototype if we have a prototype and we have a C like
1419 uint16_t Language = getLanguage();
1420 if (SP.isPrototyped() &&
1421 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1422 Language == dwarf::DW_LANG_ObjC))
1423 addFlag(SPDie, dwarf::DW_AT_prototyped);
1425 DICompositeType SPTy = SP.getType();
1426 assert(SPTy.getTag() == dwarf::DW_TAG_subroutine_type &&
1427 "the type of a subprogram should be a subroutine");
1429 DIArray Args = SPTy.getTypeArray();
1430 // Add a return type. If this is a type like a C/C++ void type we don't add a
1432 if (Args.getElement(0))
1433 addType(SPDie, DIType(Args.getElement(0)));
1435 unsigned VK = SP.getVirtuality();
1437 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1438 DIEBlock *Block = getDIEBlock();
1439 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1440 addUInt(Block, dwarf::DW_FORM_udata, SP.getVirtualIndex());
1441 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
1442 ContainingTypeMap.insert(
1443 std::make_pair(SPDie, resolve(SP.getContainingType())));
1446 if (!SP.isDefinition()) {
1447 addFlag(SPDie, dwarf::DW_AT_declaration);
1449 // Add arguments. Do not add arguments for subprogram definition. They will
1450 // be handled while processing variables.
1451 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1452 DIE *Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, *SPDie);
1453 DIType ATy(Args.getElement(i));
1455 if (ATy.isArtificial())
1456 addFlag(Arg, dwarf::DW_AT_artificial);
1460 if (SP.isArtificial())
1461 addFlag(SPDie, dwarf::DW_AT_artificial);
1463 if (!SP.isLocalToUnit())
1464 addFlag(SPDie, dwarf::DW_AT_external);
1466 if (SP.isOptimized())
1467 addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1469 if (unsigned isa = Asm->getISAEncoding()) {
1470 addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1473 if (SP.isLValueReference())
1474 addFlag(SPDie, dwarf::DW_AT_reference);
1476 if (SP.isRValueReference())
1477 addFlag(SPDie, dwarf::DW_AT_rvalue_reference);
1479 if (SP.isProtected())
1480 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1481 dwarf::DW_ACCESS_protected);
1482 else if (SP.isPrivate())
1483 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1484 dwarf::DW_ACCESS_private);
1486 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1487 dwarf::DW_ACCESS_public);
1489 if (SP.isExplicit())
1490 addFlag(SPDie, dwarf::DW_AT_explicit);
1495 // Return const expression if value is a GEP to access merged global
1497 // i8* getelementptr ({ i8, i8, i8, i8 }* @_MergedGlobals, i32 0, i32 0)
1498 static const ConstantExpr *getMergedGlobalExpr(const Value *V) {
1499 const ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(V);
1500 if (!CE || CE->getNumOperands() != 3 ||
1501 CE->getOpcode() != Instruction::GetElementPtr)
1504 // First operand points to a global struct.
1505 Value *Ptr = CE->getOperand(0);
1506 if (!isa<GlobalValue>(Ptr) ||
1507 !isa<StructType>(cast<PointerType>(Ptr->getType())->getElementType()))
1510 // Second operand is zero.
1511 const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(CE->getOperand(1));
1512 if (!CI || !CI->isZero())
1515 // Third operand is offset.
1516 if (!isa<ConstantInt>(CE->getOperand(2)))
1522 /// createGlobalVariableDIE - create global variable DIE.
1523 void DwarfCompileUnit::createGlobalVariableDIE(DIGlobalVariable GV) {
1524 // Check for pre-existence.
1528 assert(GV.isGlobalVariable());
1530 DIScope GVContext = GV.getContext();
1531 DIType GTy = GV.getType();
1533 // If this is a static data member definition, some attributes belong
1534 // to the declaration DIE.
1535 DIE *VariableDIE = NULL;
1536 bool IsStaticMember = false;
1537 DIDerivedType SDMDecl = GV.getStaticDataMemberDeclaration();
1538 if (SDMDecl.Verify()) {
1539 assert(SDMDecl.isStaticMember() && "Expected static member decl");
1540 // We need the declaration DIE that is in the static member's class.
1541 VariableDIE = getOrCreateStaticMemberDIE(SDMDecl);
1542 IsStaticMember = true;
1545 // If this is not a static data member definition, create the variable
1546 // DIE and add the initial set of attributes to it.
1548 // Construct the context before querying for the existence of the DIE in
1549 // case such construction creates the DIE.
1550 DIE *ContextDIE = getOrCreateContextDIE(GVContext);
1553 VariableDIE = createAndAddDIE(GV.getTag(), *ContextDIE, GV);
1555 // Add name and type.
1556 addString(VariableDIE, dwarf::DW_AT_name, GV.getDisplayName());
1557 addType(VariableDIE, GTy);
1559 // Add scoping info.
1560 if (!GV.isLocalToUnit())
1561 addFlag(VariableDIE, dwarf::DW_AT_external);
1563 // Add line number info.
1564 addSourceLine(VariableDIE, GV);
1568 bool addToAccelTable = false;
1569 DIE *VariableSpecDIE = NULL;
1570 bool isGlobalVariable = GV.getGlobal() != NULL;
1571 if (isGlobalVariable) {
1572 addToAccelTable = true;
1573 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1574 const MCSymbol *Sym = Asm->getSymbol(GV.getGlobal());
1575 if (GV.getGlobal()->isThreadLocal()) {
1576 // FIXME: Make this work with -gsplit-dwarf.
1577 unsigned PointerSize = Asm->getDataLayout().getPointerSize();
1578 assert((PointerSize == 4 || PointerSize == 8) &&
1579 "Add support for other sizes if necessary");
1580 const MCExpr *Expr =
1581 Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym);
1582 // Based on GCC's support for TLS:
1583 if (!DD->useSplitDwarf()) {
1584 // 1) Start with a constNu of the appropriate pointer size
1585 addUInt(Block, dwarf::DW_FORM_data1,
1586 PointerSize == 4 ? dwarf::DW_OP_const4u : dwarf::DW_OP_const8u);
1587 // 2) containing the (relocated) offset of the TLS variable
1588 // within the module's TLS block.
1589 addExpr(Block, dwarf::DW_FORM_udata, Expr);
1591 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
1592 addUInt(Block, dwarf::DW_FORM_udata, DU->getAddrPoolIndex(Expr));
1594 // 3) followed by a custom OP to make the debugger do a TLS lookup.
1595 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_push_tls_address);
1597 DD->addArangeLabel(SymbolCU(this, Sym));
1598 addOpAddress(Block, Sym);
1600 // Do not create specification DIE if context is either compile unit
1602 if (GVContext && GV.isDefinition() && !GVContext.isCompileUnit() &&
1603 !GVContext.isFile() && !DD->isSubprogramContext(GVContext)) {
1604 // Create specification DIE.
1605 VariableSpecDIE = createAndAddDIE(dwarf::DW_TAG_variable, *UnitDie);
1606 addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification, VariableDIE);
1607 addBlock(VariableSpecDIE, dwarf::DW_AT_location, Block);
1608 // A static member's declaration is already flagged as such.
1609 if (!SDMDecl.Verify())
1610 addFlag(VariableDIE, dwarf::DW_AT_declaration);
1612 addBlock(VariableDIE, dwarf::DW_AT_location, Block);
1614 // Add the linkage name.
1615 StringRef LinkageName = GV.getLinkageName();
1616 if (!LinkageName.empty())
1617 // From DWARF4: DIEs to which DW_AT_linkage_name may apply include:
1618 // TAG_common_block, TAG_constant, TAG_entry_point, TAG_subprogram and
1620 addString(IsStaticMember && VariableSpecDIE ? VariableSpecDIE
1622 dwarf::DW_AT_MIPS_linkage_name,
1623 GlobalValue::getRealLinkageName(LinkageName));
1624 } else if (const ConstantInt *CI =
1625 dyn_cast_or_null<ConstantInt>(GV.getConstant())) {
1626 // AT_const_value was added when the static member was created. To avoid
1627 // emitting AT_const_value multiple times, we only add AT_const_value when
1628 // it is not a static member.
1629 if (!IsStaticMember)
1630 addConstantValue(VariableDIE, CI, isUnsignedDIType(DD, GTy));
1631 } else if (const ConstantExpr *CE = getMergedGlobalExpr(GV->getOperand(11))) {
1632 addToAccelTable = true;
1633 // GV is a merged global.
1634 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1635 Value *Ptr = CE->getOperand(0);
1636 MCSymbol *Sym = Asm->getSymbol(cast<GlobalValue>(Ptr));
1637 DD->addArangeLabel(SymbolCU(this, Sym));
1638 addOpAddress(Block, Sym);
1639 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1640 SmallVector<Value *, 3> Idx(CE->op_begin() + 1, CE->op_end());
1641 addUInt(Block, dwarf::DW_FORM_udata,
1642 Asm->getDataLayout().getIndexedOffset(Ptr->getType(), Idx));
1643 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1644 addBlock(VariableDIE, dwarf::DW_AT_location, Block);
1647 if (addToAccelTable) {
1648 DIE *AddrDIE = VariableSpecDIE ? VariableSpecDIE : VariableDIE;
1649 addAccelName(GV.getName(), AddrDIE);
1651 // If the linkage name is different than the name, go ahead and output
1652 // that as well into the name table.
1653 if (GV.getLinkageName() != "" && GV.getName() != GV.getLinkageName())
1654 addAccelName(GV.getLinkageName(), AddrDIE);
1657 if (!GV.isLocalToUnit())
1658 addGlobalName(GV.getName(), VariableSpecDIE ? VariableSpecDIE : VariableDIE,
1662 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
1663 void DwarfUnit::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy) {
1664 DIE *DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
1665 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, IndexTy);
1667 // The LowerBound value defines the lower bounds which is typically zero for
1668 // C/C++. The Count value is the number of elements. Values are 64 bit. If
1669 // Count == -1 then the array is unbounded and we do not emit
1670 // DW_AT_lower_bound and DW_AT_upper_bound attributes. If LowerBound == 0 and
1671 // Count == 0, then the array has zero elements in which case we do not emit
1673 int64_t LowerBound = SR.getLo();
1674 int64_t DefaultLowerBound = getDefaultLowerBound();
1675 int64_t Count = SR.getCount();
1677 if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
1678 addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound);
1680 if (Count != -1 && Count != 0)
1681 // FIXME: An unbounded array should reference the expression that defines
1683 addUInt(DW_Subrange, dwarf::DW_AT_upper_bound, None,
1684 LowerBound + Count - 1);
1687 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
1688 void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, DICompositeType CTy) {
1690 addFlag(&Buffer, dwarf::DW_AT_GNU_vector);
1692 // Emit the element type.
1693 addType(&Buffer, resolve(CTy.getTypeDerivedFrom()));
1695 // Get an anonymous type for index type.
1696 // FIXME: This type should be passed down from the front end
1697 // as different languages may have different sizes for indexes.
1698 DIE *IdxTy = getIndexTyDie();
1700 // Construct an anonymous type for index type.
1701 IdxTy = createAndAddDIE(dwarf::DW_TAG_base_type, *UnitDie);
1702 addString(IdxTy, dwarf::DW_AT_name, "int");
1703 addUInt(IdxTy, dwarf::DW_AT_byte_size, None, sizeof(int32_t));
1704 addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1705 dwarf::DW_ATE_signed);
1706 setIndexTyDie(IdxTy);
1709 // Add subranges to array type.
1710 DIArray Elements = CTy.getTypeArray();
1711 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1712 DIDescriptor Element = Elements.getElement(i);
1713 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1714 constructSubrangeDIE(Buffer, DISubrange(Element), IdxTy);
1718 /// constructEnumTypeDIE - Construct an enum type DIE from DICompositeType.
1719 void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, DICompositeType CTy) {
1720 DIArray Elements = CTy.getTypeArray();
1722 // Add enumerators to enumeration type.
1723 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1724 DIEnumerator Enum(Elements.getElement(i));
1725 if (Enum.isEnumerator()) {
1726 DIE *Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
1727 StringRef Name = Enum.getName();
1728 addString(Enumerator, dwarf::DW_AT_name, Name);
1729 int64_t Value = Enum.getEnumValue();
1730 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
1734 DIType DTy = resolve(CTy.getTypeDerivedFrom());
1736 addType(&Buffer, DTy);
1737 addFlag(&Buffer, dwarf::DW_AT_enum_class);
1741 /// constructContainingTypeDIEs - Construct DIEs for types that contain
1743 void DwarfUnit::constructContainingTypeDIEs() {
1744 for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(),
1745 CE = ContainingTypeMap.end();
1747 DIE *SPDie = CI->first;
1748 DIDescriptor D(CI->second);
1751 DIE *NDie = getDIE(D);
1754 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, NDie);
1758 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
1759 DIE *DwarfUnit::constructVariableDIE(DbgVariable &DV, bool isScopeAbstract) {
1760 StringRef Name = DV.getName();
1762 // Define variable debug information entry.
1763 DIE *VariableDie = new DIE(DV.getTag());
1764 DbgVariable *AbsVar = DV.getAbstractVariable();
1765 DIE *AbsDIE = AbsVar ? AbsVar->getDIE() : NULL;
1767 addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin, AbsDIE);
1770 addString(VariableDie, dwarf::DW_AT_name, Name);
1771 addSourceLine(VariableDie, DV.getVariable());
1772 addType(VariableDie, DV.getType());
1775 if (DV.isArtificial())
1776 addFlag(VariableDie, dwarf::DW_AT_artificial);
1778 if (isScopeAbstract) {
1779 DV.setDIE(VariableDie);
1783 // Add variable address.
1785 unsigned Offset = DV.getDotDebugLocOffset();
1786 if (Offset != ~0U) {
1787 addSectionLabel(VariableDie, dwarf::DW_AT_location,
1788 Asm->GetTempSymbol("debug_loc", Offset));
1789 DV.setDIE(VariableDie);
1793 // Check if variable is described by a DBG_VALUE instruction.
1794 if (const MachineInstr *DVInsn = DV.getMInsn()) {
1795 assert(DVInsn->getNumOperands() == 3);
1796 if (DVInsn->getOperand(0).isReg()) {
1797 const MachineOperand RegOp = DVInsn->getOperand(0);
1798 // If the second operand is an immediate, this is an indirect value.
1799 if (DVInsn->getOperand(1).isImm()) {
1800 MachineLocation Location(RegOp.getReg(),
1801 DVInsn->getOperand(1).getImm());
1802 addVariableAddress(DV, VariableDie, Location);
1803 } else if (RegOp.getReg())
1804 addVariableAddress(DV, VariableDie, MachineLocation(RegOp.getReg()));
1805 } else if (DVInsn->getOperand(0).isImm())
1806 addConstantValue(VariableDie, DVInsn->getOperand(0), DV.getType());
1807 else if (DVInsn->getOperand(0).isFPImm())
1808 addConstantFPValue(VariableDie, DVInsn->getOperand(0));
1809 else if (DVInsn->getOperand(0).isCImm())
1810 addConstantValue(VariableDie, DVInsn->getOperand(0).getCImm(),
1811 isUnsignedDIType(DD, DV.getType()));
1813 DV.setDIE(VariableDie);
1816 // .. else use frame index.
1817 int FI = DV.getFrameIndex();
1819 unsigned FrameReg = 0;
1820 const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
1821 int Offset = TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
1822 MachineLocation Location(FrameReg, Offset);
1823 addVariableAddress(DV, VariableDie, Location);
1827 DV.setDIE(VariableDie);
1831 /// constructMemberDIE - Construct member DIE from DIDerivedType.
1832 void DwarfUnit::constructMemberDIE(DIE &Buffer, DIDerivedType DT) {
1833 DIE *MemberDie = createAndAddDIE(DT.getTag(), Buffer);
1834 StringRef Name = DT.getName();
1836 addString(MemberDie, dwarf::DW_AT_name, Name);
1838 addType(MemberDie, resolve(DT.getTypeDerivedFrom()));
1840 addSourceLine(MemberDie, DT);
1842 if (DT.getTag() == dwarf::DW_TAG_inheritance && DT.isVirtual()) {
1844 // For C++, virtual base classes are not at fixed offset. Use following
1845 // expression to extract appropriate offset from vtable.
1846 // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1848 DIEBlock *VBaseLocationDie = new (DIEValueAllocator) DIEBlock();
1849 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1850 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1851 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1852 addUInt(VBaseLocationDie, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1853 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1854 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1855 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1857 addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
1859 uint64_t Size = DT.getSizeInBits();
1860 uint64_t FieldSize = getBaseTypeSize(DD, DT);
1861 uint64_t OffsetInBytes;
1863 if (Size != FieldSize) {
1865 addUInt(MemberDie, dwarf::DW_AT_byte_size, None,
1866 getBaseTypeSize(DD, DT) >> 3);
1867 addUInt(MemberDie, dwarf::DW_AT_bit_size, None, DT.getSizeInBits());
1869 uint64_t Offset = DT.getOffsetInBits();
1870 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1871 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1872 uint64_t FieldOffset = (HiMark - FieldSize);
1873 Offset -= FieldOffset;
1875 // Maybe we need to work from the other end.
1876 if (Asm->getDataLayout().isLittleEndian())
1877 Offset = FieldSize - (Offset + Size);
1878 addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset);
1880 // Here DW_AT_data_member_location points to the anonymous
1881 // field that includes this bit field.
1882 OffsetInBytes = FieldOffset >> 3;
1884 // This is not a bitfield.
1885 OffsetInBytes = DT.getOffsetInBits() >> 3;
1887 if (DD->getDwarfVersion() <= 2) {
1888 DIEBlock *MemLocationDie = new (DIEValueAllocator) DIEBlock();
1889 addUInt(MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1890 addUInt(MemLocationDie, dwarf::DW_FORM_udata, OffsetInBytes);
1891 addBlock(MemberDie, dwarf::DW_AT_data_member_location, MemLocationDie);
1893 addUInt(MemberDie, dwarf::DW_AT_data_member_location, None,
1897 if (DT.isProtected())
1898 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1899 dwarf::DW_ACCESS_protected);
1900 else if (DT.isPrivate())
1901 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1902 dwarf::DW_ACCESS_private);
1903 // Otherwise C++ member and base classes are considered public.
1905 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1906 dwarf::DW_ACCESS_public);
1908 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1909 dwarf::DW_VIRTUALITY_virtual);
1911 // Objective-C properties.
1912 if (MDNode *PNode = DT.getObjCProperty())
1913 if (DIEEntry *PropertyDie = getDIEEntry(PNode))
1914 MemberDie->addValue(dwarf::DW_AT_APPLE_property, dwarf::DW_FORM_ref4,
1917 if (DT.isArtificial())
1918 addFlag(MemberDie, dwarf::DW_AT_artificial);
1921 /// getOrCreateStaticMemberDIE - Create new DIE for C++ static member.
1922 DIE *DwarfUnit::getOrCreateStaticMemberDIE(DIDerivedType DT) {
1926 // Construct the context before querying for the existence of the DIE in case
1927 // such construction creates the DIE.
1928 DIE *ContextDIE = getOrCreateContextDIE(resolve(DT.getContext()));
1929 assert(dwarf::isType(ContextDIE->getTag()) &&
1930 "Static member should belong to a type.");
1932 DIE *StaticMemberDIE = getDIE(DT);
1933 if (StaticMemberDIE)
1934 return StaticMemberDIE;
1936 StaticMemberDIE = createAndAddDIE(DT.getTag(), *ContextDIE, DT);
1938 DIType Ty = resolve(DT.getTypeDerivedFrom());
1940 addString(StaticMemberDIE, dwarf::DW_AT_name, DT.getName());
1941 addType(StaticMemberDIE, Ty);
1942 addSourceLine(StaticMemberDIE, DT);
1943 addFlag(StaticMemberDIE, dwarf::DW_AT_external);
1944 addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
1946 // FIXME: We could omit private if the parent is a class_type, and
1947 // public if the parent is something else.
1948 if (DT.isProtected())
1949 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1950 dwarf::DW_ACCESS_protected);
1951 else if (DT.isPrivate())
1952 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1953 dwarf::DW_ACCESS_private);
1955 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1956 dwarf::DW_ACCESS_public);
1958 if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT.getConstant()))
1959 addConstantValue(StaticMemberDIE, CI, isUnsignedDIType(DD, Ty));
1960 if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT.getConstant()))
1961 addConstantFPValue(StaticMemberDIE, CFP);
1963 return StaticMemberDIE;
1966 void DwarfUnit::emitHeader(const MCSection *ASection,
1967 const MCSymbol *ASectionSym) const {
1968 Asm->OutStreamer.AddComment("DWARF version number");
1969 Asm->EmitInt16(DD->getDwarfVersion());
1970 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
1971 // We share one abbreviations table across all units so it's always at the
1972 // start of the section. Use a relocatable offset where needed to ensure
1973 // linking doesn't invalidate that offset.
1974 Asm->EmitSectionOffset(ASectionSym, ASectionSym);
1975 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1976 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
1979 DwarfCompileUnit::~DwarfCompileUnit() {}
1980 DwarfTypeUnit::~DwarfTypeUnit() {}
1982 void DwarfTypeUnit::emitHeader(const MCSection *ASection,
1983 const MCSymbol *ASectionSym) const {
1984 DwarfUnit::emitHeader(ASection, ASectionSym);
1985 Asm->OutStreamer.AddComment("Type Signature");
1986 Asm->OutStreamer.EmitIntValue(TypeSignature, sizeof(TypeSignature));
1987 Asm->OutStreamer.AddComment("Type DIE Offset");
1988 // In a skeleton type unit there is no type DIE so emit a zero offset.
1989 Asm->OutStreamer.EmitIntValue(Ty ? Ty->getOffset() : 0,
1990 sizeof(Ty->getOffset()));
1993 void DwarfTypeUnit::initSection(const MCSection *Section) {
1994 assert(!this->Section);
1995 this->Section = Section;
1996 // Since each type unit is contained in its own COMDAT section, the begin
1997 // label and the section label are the same. Using the begin label emission in
1998 // DwarfDebug to emit the section label as well is slightly subtle/sneaky, but
1999 // the only other alternative of lazily constructing start-of-section labels
2000 // and storing a mapping in DwarfDebug (or AsmPrinter).
2001 this->SectionSym = this->LabelBegin =
2002 Asm->GetTempSymbol(Section->getLabelBeginName(), getUniqueID());
2004 Asm->GetTempSymbol(Section->getLabelEndName(), getUniqueID());
2005 this->LabelRange = Asm->GetTempSymbol("gnu_ranges", getUniqueID());