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, DICompileUnit CUNode,
59 AsmPrinter *A, DwarfDebug *DW, DwarfFile *DWU)
60 : DwarfUnit(UID, D, CUNode, A, DW, DWU) {}
62 /// ~Unit - Destructor for compile unit.
63 DwarfUnit::~DwarfUnit() {
64 for (unsigned j = 0, M = DIEBlocks.size(); j < M; ++j)
65 DIEBlocks[j]->~DIEBlock();
68 /// createDIEEntry - Creates a new DIEEntry to be a proxy for a debug
69 /// information entry.
70 DIEEntry *DwarfUnit::createDIEEntry(DIE *Entry) {
71 DIEEntry *Value = new (DIEValueAllocator) DIEEntry(Entry);
75 /// getDefaultLowerBound - Return the default lower bound for an array. If the
76 /// DWARF version doesn't handle the language, return -1.
77 int64_t DwarfUnit::getDefaultLowerBound() const {
78 switch (getLanguage()) {
82 case dwarf::DW_LANG_C89:
83 case dwarf::DW_LANG_C99:
84 case dwarf::DW_LANG_C:
85 case dwarf::DW_LANG_C_plus_plus:
86 case dwarf::DW_LANG_ObjC:
87 case dwarf::DW_LANG_ObjC_plus_plus:
90 case dwarf::DW_LANG_Fortran77:
91 case dwarf::DW_LANG_Fortran90:
92 case dwarf::DW_LANG_Fortran95:
95 // The languages below have valid values only if the DWARF version >= 4.
96 case dwarf::DW_LANG_Java:
97 case dwarf::DW_LANG_Python:
98 case dwarf::DW_LANG_UPC:
99 case dwarf::DW_LANG_D:
100 if (dwarf::DWARF_VERSION >= 4)
104 case dwarf::DW_LANG_Ada83:
105 case dwarf::DW_LANG_Ada95:
106 case dwarf::DW_LANG_Cobol74:
107 case dwarf::DW_LANG_Cobol85:
108 case dwarf::DW_LANG_Modula2:
109 case dwarf::DW_LANG_Pascal83:
110 case dwarf::DW_LANG_PLI:
111 if (dwarf::DWARF_VERSION >= 4)
119 /// Check whether the DIE for this MDNode can be shared across CUs.
120 static bool isShareableAcrossCUs(DIDescriptor D) {
121 // When the MDNode can be part of the type system, the DIE can be shared
123 // Combining type units and cross-CU DIE sharing is lower value (since
124 // cross-CU DIE sharing is used in LTO and removes type redundancy at that
125 // level already) but may be implementable for some value in projects
126 // building multiple independent libraries with LTO and then linking those
128 return (D.isType() ||
129 (D.isSubprogram() && !DISubprogram(D).isDefinition())) &&
130 !GenerateDwarfTypeUnits;
133 /// getDIE - Returns the debug information entry map slot for the
134 /// specified debug variable. We delegate the request to DwarfDebug
135 /// when the DIE for this MDNode can be shared across CUs. The mappings
136 /// will be kept in DwarfDebug for shareable DIEs.
137 DIE *DwarfUnit::getDIE(DIDescriptor D) const {
138 if (isShareableAcrossCUs(D))
139 return DD->getDIE(D);
140 return MDNodeToDieMap.lookup(D);
143 /// insertDIE - Insert DIE into the map. We delegate the request to DwarfDebug
144 /// when the DIE for this MDNode can be shared across CUs. The mappings
145 /// will be kept in DwarfDebug for shareable DIEs.
146 void DwarfUnit::insertDIE(DIDescriptor Desc, DIE *D) {
147 if (isShareableAcrossCUs(Desc)) {
148 DD->insertDIE(Desc, D);
151 MDNodeToDieMap.insert(std::make_pair(Desc, D));
154 /// addFlag - Add a flag that is true.
155 void DwarfUnit::addFlag(DIE *Die, dwarf::Attribute Attribute) {
156 if (DD->getDwarfVersion() >= 4)
157 Die->addValue(Attribute, dwarf::DW_FORM_flag_present, DIEIntegerOne);
159 Die->addValue(Attribute, dwarf::DW_FORM_flag, DIEIntegerOne);
162 /// addUInt - Add an unsigned integer attribute data and value.
164 void DwarfUnit::addUInt(DIE *Die, dwarf::Attribute Attribute,
165 Optional<dwarf::Form> Form, uint64_t Integer) {
167 Form = DIEInteger::BestForm(false, Integer);
168 DIEValue *Value = Integer == 1 ? DIEIntegerOne : new (DIEValueAllocator)
170 Die->addValue(Attribute, *Form, Value);
173 void DwarfUnit::addUInt(DIEBlock *Block, dwarf::Form Form, uint64_t Integer) {
174 addUInt(Block, (dwarf::Attribute)0, Form, Integer);
177 /// addSInt - Add an signed integer attribute data and value.
179 void DwarfUnit::addSInt(DIE *Die, dwarf::Attribute Attribute,
180 Optional<dwarf::Form> Form, int64_t Integer) {
182 Form = DIEInteger::BestForm(true, Integer);
183 DIEValue *Value = new (DIEValueAllocator) DIEInteger(Integer);
184 Die->addValue(Attribute, *Form, Value);
187 void DwarfUnit::addSInt(DIEBlock *Die, Optional<dwarf::Form> Form,
189 addSInt(Die, (dwarf::Attribute)0, Form, Integer);
192 /// addString - Add a string attribute data and value. We always emit a
193 /// reference to the string pool instead of immediate strings so that DIEs have
194 /// more predictable sizes. In the case of split dwarf we emit an index
195 /// into another table which gets us the static offset into the string
197 void DwarfUnit::addString(DIE *Die, dwarf::Attribute Attribute,
200 if (!DD->useSplitDwarf())
201 return addLocalString(Die, Attribute, String);
203 unsigned idx = DU->getStringPoolIndex(String);
204 DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
205 DIEValue *Str = new (DIEValueAllocator) DIEString(Value, String);
206 Die->addValue(Attribute, dwarf::DW_FORM_GNU_str_index, Str);
209 /// addLocalString - Add a string attribute data and value. This is guaranteed
210 /// to be in the local string pool instead of indirected.
211 void DwarfUnit::addLocalString(DIE *Die, dwarf::Attribute Attribute,
213 MCSymbol *Symb = DU->getStringPoolEntry(String);
215 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
216 Value = new (DIEValueAllocator) DIELabel(Symb);
218 MCSymbol *StringPool = DU->getStringPoolSym();
219 Value = new (DIEValueAllocator) DIEDelta(Symb, StringPool);
221 DIEValue *Str = new (DIEValueAllocator) DIEString(Value, String);
222 Die->addValue(Attribute, dwarf::DW_FORM_strp, Str);
225 /// addExpr - Add a Dwarf expression attribute data and value.
227 void DwarfUnit::addExpr(DIEBlock *Die, dwarf::Form Form, const MCExpr *Expr) {
228 DIEValue *Value = new (DIEValueAllocator) DIEExpr(Expr);
229 Die->addValue((dwarf::Attribute)0, Form, Value);
232 /// addLabel - Add a Dwarf label attribute data and value.
234 void DwarfUnit::addLabel(DIE *Die, dwarf::Attribute Attribute, dwarf::Form Form,
235 const MCSymbol *Label) {
236 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
237 Die->addValue(Attribute, Form, Value);
240 void DwarfUnit::addLabel(DIEBlock *Die, dwarf::Form Form,
241 const MCSymbol *Label) {
242 addLabel(Die, (dwarf::Attribute)0, Form, Label);
245 /// addSectionLabel - Add a Dwarf section label attribute data and value.
247 void DwarfUnit::addSectionLabel(DIE *Die, dwarf::Attribute Attribute,
248 const MCSymbol *Label) {
249 if (DD->getDwarfVersion() >= 4)
250 addLabel(Die, Attribute, dwarf::DW_FORM_sec_offset, Label);
252 addLabel(Die, Attribute, dwarf::DW_FORM_data4, Label);
255 /// addSectionOffset - Add an offset into a section attribute data and value.
257 void DwarfUnit::addSectionOffset(DIE *Die, dwarf::Attribute Attribute,
259 if (DD->getDwarfVersion() >= 4)
260 addUInt(Die, Attribute, dwarf::DW_FORM_sec_offset, Integer);
262 addUInt(Die, Attribute, dwarf::DW_FORM_data4, Integer);
265 /// addLabelAddress - Add a dwarf label attribute data and value using
266 /// DW_FORM_addr or DW_FORM_GNU_addr_index.
268 void DwarfCompileUnit::addLabelAddress(DIE *Die, dwarf::Attribute Attribute,
271 DD->addArangeLabel(SymbolCU(this, Label));
273 if (!DD->useSplitDwarf()) {
275 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
276 Die->addValue(Attribute, dwarf::DW_FORM_addr, Value);
278 DIEValue *Value = new (DIEValueAllocator) DIEInteger(0);
279 Die->addValue(Attribute, dwarf::DW_FORM_addr, Value);
282 unsigned idx = DU->getAddrPoolIndex(Label);
283 DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
284 Die->addValue(Attribute, dwarf::DW_FORM_GNU_addr_index, Value);
288 /// addOpAddress - Add a dwarf op address data and value using the
289 /// form given and an op of either DW_FORM_addr or DW_FORM_GNU_addr_index.
291 void DwarfUnit::addOpAddress(DIEBlock *Die, const MCSymbol *Sym) {
292 if (!DD->useSplitDwarf()) {
293 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
294 addLabel(Die, dwarf::DW_FORM_udata, Sym);
296 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index);
297 addUInt(Die, dwarf::DW_FORM_GNU_addr_index, DU->getAddrPoolIndex(Sym));
301 /// addSectionDelta - Add a section label delta attribute data and value.
303 void DwarfUnit::addSectionDelta(DIE *Die, dwarf::Attribute Attribute,
304 const MCSymbol *Hi, const MCSymbol *Lo) {
305 DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
306 if (DD->getDwarfVersion() >= 4)
307 Die->addValue(Attribute, dwarf::DW_FORM_sec_offset, Value);
309 Die->addValue(Attribute, dwarf::DW_FORM_data4, Value);
312 /// addDIEEntry - Add a DIE attribute data and value.
314 void DwarfUnit::addDIEEntry(DIE *Die, dwarf::Attribute Attribute, DIE *Entry) {
315 addDIEEntry(Die, Attribute, createDIEEntry(Entry));
318 void DwarfUnit::addDIETypeSignature(DIE *Die, const DwarfTypeUnit &Type) {
319 Die->addValue(dwarf::DW_AT_signature, dwarf::DW_FORM_ref_sig8,
320 new (DIEValueAllocator) DIETypeSignature(Type));
323 void DwarfUnit::addDIEEntry(DIE *Die, dwarf::Attribute Attribute,
325 const DIE *DieCU = Die->getUnitOrNull();
326 const DIE *EntryCU = Entry->getEntry()->getUnitOrNull();
328 // We assume that Die belongs to this CU, if it is not linked to any CU yet.
329 DieCU = getUnitDie();
331 EntryCU = getUnitDie();
332 Die->addValue(Attribute, EntryCU == DieCU ? dwarf::DW_FORM_ref4
333 : dwarf::DW_FORM_ref_addr,
337 /// Create a DIE with the given Tag, add the DIE to its parent, and
338 /// call insertDIE if MD is not null.
339 DIE *DwarfUnit::createAndAddDIE(unsigned Tag, DIE &Parent, DIDescriptor N) {
340 DIE *Die = new DIE(Tag);
341 Parent.addChild(Die);
347 /// addBlock - Add block data.
349 void DwarfUnit::addBlock(DIE *Die, dwarf::Attribute Attribute,
351 Block->ComputeSize(Asm);
352 DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
353 Die->addValue(Attribute, Block->BestForm(), Block);
356 /// addSourceLine - Add location information to specified debug information
358 void DwarfUnit::addSourceLine(DIE *Die, unsigned Line, StringRef File,
359 StringRef Directory) {
363 unsigned FileID = DD->getOrCreateSourceID(File, Directory, getUniqueID());
364 assert(FileID && "Invalid file id");
365 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
366 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
369 /// addSourceLine - Add location information to specified debug information
371 void DwarfUnit::addSourceLine(DIE *Die, DIVariable V) {
372 assert(V.isVariable());
374 addSourceLine(Die, V.getLineNumber(), V.getContext().getFilename(), V.getContext().getDirectory());
377 /// addSourceLine - Add location information to specified debug information
379 void DwarfUnit::addSourceLine(DIE *Die, DIGlobalVariable G) {
380 assert(G.isGlobalVariable());
382 addSourceLine(Die, G.getLineNumber(), G.getFilename(), G.getDirectory());
385 /// addSourceLine - Add location information to specified debug information
387 void DwarfUnit::addSourceLine(DIE *Die, DISubprogram SP) {
388 assert(SP.isSubprogram());
390 addSourceLine(Die, SP.getLineNumber(), SP.getFilename(), SP.getDirectory());
393 /// addSourceLine - Add location information to specified debug information
395 void DwarfUnit::addSourceLine(DIE *Die, DIType Ty) {
398 addSourceLine(Die, Ty.getLineNumber(), Ty.getFilename(), Ty.getDirectory());
401 /// addSourceLine - Add location information to specified debug information
403 void DwarfUnit::addSourceLine(DIE *Die, DIObjCProperty Ty) {
404 assert(Ty.isObjCProperty());
406 DIFile File = Ty.getFile();
407 addSourceLine(Die, Ty.getLineNumber(), File.getFilename(),
408 File.getDirectory());
411 /// addSourceLine - Add location information to specified debug information
413 void DwarfUnit::addSourceLine(DIE *Die, DINameSpace NS) {
416 addSourceLine(Die, NS.getLineNumber(), NS.getFilename(), NS.getDirectory());
419 /// addVariableAddress - Add DW_AT_location attribute for a
420 /// DbgVariable based on provided MachineLocation.
421 void DwarfUnit::addVariableAddress(const DbgVariable &DV, DIE *Die,
422 MachineLocation Location) {
423 if (DV.variableHasComplexAddress())
424 addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
425 else if (DV.isBlockByrefVariable())
426 addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location);
428 addAddress(Die, dwarf::DW_AT_location, Location,
429 DV.getVariable().isIndirect());
432 /// addRegisterOp - Add register operand.
433 void DwarfUnit::addRegisterOp(DIEBlock *TheDie, unsigned Reg) {
434 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
435 int DWReg = RI->getDwarfRegNum(Reg, false);
436 bool isSubRegister = DWReg < 0;
440 // Go up the super-register chain until we hit a valid dwarf register number.
441 for (MCSuperRegIterator SR(Reg, RI); SR.isValid() && DWReg < 0; ++SR) {
442 DWReg = RI->getDwarfRegNum(*SR, false);
444 Idx = RI->getSubRegIndex(*SR, Reg);
448 DEBUG(llvm::dbgs() << "Invalid Dwarf register number.\n");
449 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_nop);
455 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + DWReg);
457 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
458 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
463 unsigned Size = RI->getSubRegIdxSize(Idx);
464 unsigned Offset = RI->getSubRegIdxOffset(Idx);
466 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_bit_piece);
467 addUInt(TheDie, dwarf::DW_FORM_data1, Size);
468 addUInt(TheDie, dwarf::DW_FORM_data1, Offset);
470 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_piece);
471 addUInt(TheDie, dwarf::DW_FORM_data1, Size);
476 /// addRegisterOffset - Add register offset.
477 void DwarfUnit::addRegisterOffset(DIEBlock *TheDie, unsigned Reg,
479 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
480 unsigned DWReg = RI->getDwarfRegNum(Reg, false);
481 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
482 if (Reg == TRI->getFrameRegister(*Asm->MF))
483 // If variable offset is based in frame register then use fbreg.
484 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_fbreg);
486 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + DWReg);
488 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
489 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
491 addSInt(TheDie, dwarf::DW_FORM_sdata, Offset);
494 /// addAddress - Add an address attribute to a die based on the location
496 void DwarfUnit::addAddress(DIE *Die, dwarf::Attribute Attribute,
497 const MachineLocation &Location, bool Indirect) {
498 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
500 if (Location.isReg() && !Indirect)
501 addRegisterOp(Block, Location.getReg());
503 addRegisterOffset(Block, Location.getReg(), Location.getOffset());
504 if (Indirect && !Location.isReg()) {
505 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
509 // Now attach the location information to the DIE.
510 addBlock(Die, Attribute, Block);
513 /// addComplexAddress - Start with the address based on the location provided,
514 /// and generate the DWARF information necessary to find the actual variable
515 /// given the extra address information encoded in the DbgVariable, starting
516 /// from the starting location. Add the DWARF information to the die.
518 void DwarfUnit::addComplexAddress(const DbgVariable &DV, DIE *Die,
519 dwarf::Attribute Attribute,
520 const MachineLocation &Location) {
521 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
522 unsigned N = DV.getNumAddrElements();
524 if (Location.isReg()) {
525 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
526 // If first address element is OpPlus then emit
527 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
528 addRegisterOffset(Block, Location.getReg(), DV.getAddrElement(1));
531 addRegisterOp(Block, Location.getReg());
533 addRegisterOffset(Block, Location.getReg(), Location.getOffset());
536 uint64_t Element = DV.getAddrElement(i);
537 if (Element == DIBuilder::OpPlus) {
538 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
539 addUInt(Block, dwarf::DW_FORM_udata, DV.getAddrElement(++i));
540 } else if (Element == DIBuilder::OpDeref) {
541 if (!Location.isReg())
542 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
544 llvm_unreachable("unknown DIBuilder Opcode");
547 // Now attach the location information to the DIE.
548 addBlock(Die, Attribute, Block);
551 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
552 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
553 gives the variable VarName either the struct, or a pointer to the struct, as
554 its type. This is necessary for various behind-the-scenes things the
555 compiler needs to do with by-reference variables in Blocks.
557 However, as far as the original *programmer* is concerned, the variable
558 should still have type 'SomeType', as originally declared.
560 The function getBlockByrefType dives into the __Block_byref_x_VarName
561 struct to find the original type of the variable, which is then assigned to
562 the variable's Debug Information Entry as its real type. So far, so good.
563 However now the debugger will expect the variable VarName to have the type
564 SomeType. So we need the location attribute for the variable to be an
565 expression that explains to the debugger how to navigate through the
566 pointers and struct to find the actual variable of type SomeType.
568 The following function does just that. We start by getting
569 the "normal" location for the variable. This will be the location
570 of either the struct __Block_byref_x_VarName or the pointer to the
571 struct __Block_byref_x_VarName.
573 The struct will look something like:
575 struct __Block_byref_x_VarName {
577 struct __Block_byref_x_VarName *forwarding;
578 ... <various other fields>
580 ... <maybe more fields>
583 If we are given the struct directly (as our starting point) we
584 need to tell the debugger to:
586 1). Add the offset of the forwarding field.
588 2). Follow that pointer to get the real __Block_byref_x_VarName
589 struct to use (the real one may have been copied onto the heap).
591 3). Add the offset for the field VarName, to find the actual variable.
593 If we started with a pointer to the struct, then we need to
594 dereference that pointer first, before the other steps.
595 Translating this into DWARF ops, we will need to append the following
596 to the current location description for the variable:
598 DW_OP_deref -- optional, if we start with a pointer
599 DW_OP_plus_uconst <forward_fld_offset>
601 DW_OP_plus_uconst <varName_fld_offset>
603 That is what this function does. */
605 /// addBlockByrefAddress - Start with the address based on the location
606 /// provided, and generate the DWARF information necessary to find the
607 /// actual Block variable (navigating the Block struct) based on the
608 /// starting location. Add the DWARF information to the die. For
609 /// more information, read large comment just above here.
611 void DwarfUnit::addBlockByrefAddress(const DbgVariable &DV, DIE *Die,
612 dwarf::Attribute Attribute,
613 const MachineLocation &Location) {
614 DIType Ty = DV.getType();
616 uint16_t Tag = Ty.getTag();
617 bool isPointer = false;
619 StringRef varName = DV.getName();
621 if (Tag == dwarf::DW_TAG_pointer_type) {
622 DIDerivedType DTy(Ty);
623 TmpTy = resolve(DTy.getTypeDerivedFrom());
627 DICompositeType blockStruct(TmpTy);
629 // Find the __forwarding field and the variable field in the __Block_byref
631 DIArray Fields = blockStruct.getTypeArray();
632 DIDerivedType varField;
633 DIDerivedType forwardingField;
635 for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
636 DIDerivedType DT(Fields.getElement(i));
637 StringRef fieldName = DT.getName();
638 if (fieldName == "__forwarding")
639 forwardingField = DT;
640 else if (fieldName == varName)
644 // Get the offsets for the forwarding field and the variable field.
645 unsigned forwardingFieldOffset = forwardingField.getOffsetInBits() >> 3;
646 unsigned varFieldOffset = varField.getOffsetInBits() >> 2;
648 // Decode the original location, and use that as the start of the byref
649 // variable's location.
650 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
652 if (Location.isReg())
653 addRegisterOp(Block, Location.getReg());
655 addRegisterOffset(Block, Location.getReg(), Location.getOffset());
657 // If we started with a pointer to the __Block_byref... struct, then
658 // the first thing we need to do is dereference the pointer (DW_OP_deref).
660 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
662 // Next add the offset for the '__forwarding' field:
663 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
664 // adding the offset if it's 0.
665 if (forwardingFieldOffset > 0) {
666 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
667 addUInt(Block, dwarf::DW_FORM_udata, forwardingFieldOffset);
670 // Now dereference the __forwarding field to get to the real __Block_byref
671 // struct: DW_OP_deref.
672 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
674 // Now that we've got the real __Block_byref... struct, add the offset
675 // for the variable's field to get to the location of the actual variable:
676 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
677 if (varFieldOffset > 0) {
678 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
679 addUInt(Block, dwarf::DW_FORM_udata, varFieldOffset);
682 // Now attach the location information to the DIE.
683 addBlock(Die, Attribute, Block);
686 /// isTypeSigned - Return true if the type is signed.
687 static bool isTypeSigned(DwarfDebug *DD, DIType Ty, int *SizeInBits) {
688 if (Ty.isDerivedType())
689 return isTypeSigned(DD, DD->resolve(DIDerivedType(Ty).getTypeDerivedFrom()),
691 if (Ty.isBasicType())
692 if (DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed ||
693 DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed_char) {
694 *SizeInBits = Ty.getSizeInBits();
700 /// Return true if type encoding is unsigned.
701 static bool isUnsignedDIType(DwarfDebug *DD, DIType Ty) {
702 DIDerivedType DTy(Ty);
703 if (DTy.isDerivedType())
704 return isUnsignedDIType(DD, DD->resolve(DTy.getTypeDerivedFrom()));
707 if (BTy.isBasicType()) {
708 unsigned Encoding = BTy.getEncoding();
709 if (Encoding == dwarf::DW_ATE_unsigned ||
710 Encoding == dwarf::DW_ATE_unsigned_char ||
711 Encoding == dwarf::DW_ATE_boolean)
717 /// If this type is derived from a base type then return base type size.
718 static uint64_t getBaseTypeSize(DwarfDebug *DD, DIDerivedType Ty) {
719 unsigned Tag = Ty.getTag();
721 if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef &&
722 Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type &&
723 Tag != dwarf::DW_TAG_restrict_type)
724 return Ty.getSizeInBits();
726 DIType BaseType = DD->resolve(Ty.getTypeDerivedFrom());
728 // If this type is not derived from any type then take conservative approach.
729 if (!BaseType.isValid())
730 return Ty.getSizeInBits();
732 // If this is a derived type, go ahead and get the base type, unless it's a
733 // reference then it's just the size of the field. Pointer types have no need
734 // of this since they're a different type of qualification on the type.
735 if (BaseType.getTag() == dwarf::DW_TAG_reference_type ||
736 BaseType.getTag() == dwarf::DW_TAG_rvalue_reference_type)
737 return Ty.getSizeInBits();
739 if (BaseType.isDerivedType())
740 return getBaseTypeSize(DD, DIDerivedType(BaseType));
742 return BaseType.getSizeInBits();
745 /// addConstantValue - Add constant value entry in variable DIE.
746 void DwarfUnit::addConstantValue(DIE *Die, const MachineOperand &MO,
748 // FIXME: This is a bit conservative/simple - it emits negative values at
749 // their maximum bit width which is a bit unfortunate (& doesn't prefer
750 // udata/sdata over dataN as suggested by the DWARF spec)
751 assert(MO.isImm() && "Invalid machine operand!");
753 bool SignedConstant = isTypeSigned(DD, Ty, &SizeInBits);
756 // If we're a signed constant definitely use sdata.
757 if (SignedConstant) {
758 addSInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, MO.getImm());
762 // Else use data for now unless it's larger than we can deal with.
763 switch (SizeInBits) {
765 Form = dwarf::DW_FORM_data1;
768 Form = dwarf::DW_FORM_data2;
771 Form = dwarf::DW_FORM_data4;
774 Form = dwarf::DW_FORM_data8;
777 Form = dwarf::DW_FORM_udata;
778 addUInt(Die, dwarf::DW_AT_const_value, Form, MO.getImm());
781 addUInt(Die, dwarf::DW_AT_const_value, Form, MO.getImm());
784 /// addConstantFPValue - Add constant value entry in variable DIE.
785 void DwarfUnit::addConstantFPValue(DIE *Die, const MachineOperand &MO) {
786 assert(MO.isFPImm() && "Invalid machine operand!");
787 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
788 APFloat FPImm = MO.getFPImm()->getValueAPF();
790 // Get the raw data form of the floating point.
791 const APInt FltVal = FPImm.bitcastToAPInt();
792 const char *FltPtr = (const char *)FltVal.getRawData();
794 int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
795 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
796 int Incr = (LittleEndian ? 1 : -1);
797 int Start = (LittleEndian ? 0 : NumBytes - 1);
798 int Stop = (LittleEndian ? NumBytes : -1);
800 // Output the constant to DWARF one byte at a time.
801 for (; Start != Stop; Start += Incr)
802 addUInt(Block, dwarf::DW_FORM_data1, (unsigned char)0xFF & FltPtr[Start]);
804 addBlock(Die, dwarf::DW_AT_const_value, Block);
807 /// addConstantFPValue - Add constant value entry in variable DIE.
808 void DwarfUnit::addConstantFPValue(DIE *Die, const ConstantFP *CFP) {
809 // Pass this down to addConstantValue as an unsigned bag of bits.
810 addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true);
813 /// addConstantValue - Add constant value entry in variable DIE.
814 void DwarfUnit::addConstantValue(DIE *Die, const ConstantInt *CI,
816 addConstantValue(Die, CI->getValue(), Unsigned);
819 // addConstantValue - Add constant value entry in variable DIE.
820 void DwarfUnit::addConstantValue(DIE *Die, const APInt &Val, bool Unsigned) {
821 unsigned CIBitWidth = Val.getBitWidth();
822 if (CIBitWidth <= 64) {
823 // If we're a signed constant definitely use sdata.
825 addSInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
830 // Else use data for now unless it's larger than we can deal with.
832 switch (CIBitWidth) {
834 Form = dwarf::DW_FORM_data1;
837 Form = dwarf::DW_FORM_data2;
840 Form = dwarf::DW_FORM_data4;
843 Form = dwarf::DW_FORM_data8;
846 addUInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_udata,
850 addUInt(Die, dwarf::DW_AT_const_value, Form, Val.getZExtValue());
854 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
856 // Get the raw data form of the large APInt.
857 const uint64_t *Ptr64 = Val.getRawData();
859 int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
860 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
862 // Output the constant to DWARF one byte at a time.
863 for (int i = 0; i < NumBytes; i++) {
866 c = Ptr64[i / 8] >> (8 * (i & 7));
868 c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
869 addUInt(Block, dwarf::DW_FORM_data1, c);
872 addBlock(Die, dwarf::DW_AT_const_value, Block);
875 /// addTemplateParams - Add template parameters into buffer.
876 void DwarfUnit::addTemplateParams(DIE &Buffer, DIArray TParams) {
877 // Add template parameters.
878 for (unsigned i = 0, e = TParams.getNumElements(); i != e; ++i) {
879 DIDescriptor Element = TParams.getElement(i);
880 if (Element.isTemplateTypeParameter())
881 constructTemplateTypeParameterDIE(Buffer,
882 DITemplateTypeParameter(Element));
883 else if (Element.isTemplateValueParameter())
884 constructTemplateValueParameterDIE(Buffer,
885 DITemplateValueParameter(Element));
889 /// getOrCreateContextDIE - Get context owner's DIE.
890 DIE *DwarfUnit::getOrCreateContextDIE(DIScope Context) {
891 if (!Context || Context.isFile())
893 if (Context.isType())
894 return getOrCreateTypeDIE(DIType(Context));
895 if (Context.isNameSpace())
896 return getOrCreateNameSpace(DINameSpace(Context));
897 if (Context.isSubprogram())
898 return getOrCreateSubprogramDIE(DISubprogram(Context));
899 return getDIE(Context);
902 DIE *DwarfUnit::createTypeDIE(DICompositeType Ty) {
903 DIScope Context = resolve(Ty.getContext());
904 DIE *ContextDIE = getOrCreateContextDIE(Context);
906 DIE *TyDIE = getDIE(Ty);
911 TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
913 constructTypeDIE(*TyDIE, Ty);
915 updateAcceleratorTables(Context, Ty, TyDIE);
919 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
921 DIE *DwarfUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
928 // Construct the context before querying for the existence of the DIE in case
929 // such construction creates the DIE.
930 DIScope Context = resolve(Ty.getContext());
931 DIE *ContextDIE = getOrCreateContextDIE(Context);
934 DIE *TyDIE = getDIE(Ty);
939 TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
941 if (Ty.isBasicType())
942 constructTypeDIE(*TyDIE, DIBasicType(Ty));
943 else if (Ty.isCompositeType()) {
944 DICompositeType CTy(Ty);
945 if (GenerateDwarfTypeUnits && !Ty.isForwardDecl())
946 if (MDString *TypeId = CTy.getIdentifier()) {
947 DD->addDwarfTypeUnitType(getCUNode(), TypeId->getString(), TyDIE, CTy);
948 // Skip updating the accellerator tables since this is not the full type
951 constructTypeDIE(*TyDIE, CTy);
953 assert(Ty.isDerivedType() && "Unknown kind of DIType");
954 constructTypeDIE(*TyDIE, DIDerivedType(Ty));
957 updateAcceleratorTables(Context, Ty, TyDIE);
962 void DwarfUnit::updateAcceleratorTables(DIScope Context, DIType Ty,
964 if (!Ty.getName().empty() && !Ty.isForwardDecl()) {
965 bool IsImplementation = 0;
966 if (Ty.isCompositeType()) {
967 DICompositeType CT(Ty);
968 // A runtime language of 0 actually means C/C++ and that any
969 // non-negative value is some version of Objective-C/C++.
970 IsImplementation = (CT.getRunTimeLang() == 0) || CT.isObjcClassComplete();
972 unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0;
973 addAccelType(Ty.getName(), std::make_pair(TyDIE, Flags));
975 if (!Context || Context.isCompileUnit() || Context.isFile() ||
976 Context.isNameSpace())
977 GlobalTypes[getParentContextString(Context) + Ty.getName().str()] = TyDIE;
981 /// addType - Add a new type attribute to the specified entity.
982 void DwarfUnit::addType(DIE *Entity, DIType Ty, dwarf::Attribute Attribute) {
983 assert(Ty && "Trying to add a type that doesn't exist?");
985 // Check for pre-existence.
986 DIEEntry *Entry = getDIEEntry(Ty);
987 // If it exists then use the existing value.
989 addDIEEntry(Entity, Attribute, Entry);
994 DIE *Buffer = getOrCreateTypeDIE(Ty);
997 Entry = createDIEEntry(Buffer);
998 insertDIEEntry(Ty, Entry);
999 addDIEEntry(Entity, Attribute, Entry);
1002 // Accelerator table mutators - add each name along with its companion
1003 // DIE to the proper table while ensuring that the name that we're going
1004 // to reference is in the string table. We do this since the names we
1005 // add may not only be identical to the names in the DIE.
1006 void DwarfUnit::addAccelName(StringRef Name, const DIE *Die) {
1007 if (!DD->useDwarfAccelTables()) return;
1008 DU->getStringPoolEntry(Name);
1009 std::vector<const DIE *> &DIEs = AccelNames[Name];
1010 DIEs.push_back(Die);
1013 void DwarfUnit::addAccelObjC(StringRef Name, const DIE *Die) {
1014 if (!DD->useDwarfAccelTables()) return;
1015 DU->getStringPoolEntry(Name);
1016 std::vector<const DIE *> &DIEs = AccelObjC[Name];
1017 DIEs.push_back(Die);
1020 void DwarfUnit::addAccelNamespace(StringRef Name, const DIE *Die) {
1021 if (!DD->useDwarfAccelTables()) return;
1022 DU->getStringPoolEntry(Name);
1023 std::vector<const DIE *> &DIEs = AccelNamespace[Name];
1024 DIEs.push_back(Die);
1027 void DwarfUnit::addAccelType(StringRef Name,
1028 std::pair<const DIE *, unsigned> Die) {
1029 if (!DD->useDwarfAccelTables()) return;
1030 DU->getStringPoolEntry(Name);
1031 std::vector<std::pair<const DIE *, unsigned> > &DIEs = AccelTypes[Name];
1032 DIEs.push_back(Die);
1035 /// addGlobalName - Add a new global name to the compile unit.
1036 void DwarfUnit::addGlobalName(StringRef Name, DIE *Die, DIScope Context) {
1037 std::string FullName = getParentContextString(Context) + Name.str();
1038 GlobalNames[FullName] = Die;
1041 /// getParentContextString - Walks the metadata parent chain in a language
1042 /// specific manner (using the compile unit language) and returns
1043 /// it as a string. This is done at the metadata level because DIEs may
1044 /// not currently have been added to the parent context and walking the
1045 /// DIEs looking for names is more expensive than walking the metadata.
1046 std::string DwarfUnit::getParentContextString(DIScope Context) const {
1050 // FIXME: Decide whether to implement this for non-C++ languages.
1051 if (getLanguage() != dwarf::DW_LANG_C_plus_plus)
1055 SmallVector<DIScope, 1> Parents;
1056 while (!Context.isCompileUnit()) {
1057 Parents.push_back(Context);
1058 if (Context.getContext())
1059 Context = resolve(Context.getContext());
1061 // Structure, etc types will have a NULL context if they're at the top
1066 // Reverse iterate over our list to go from the outermost construct to the
1068 for (SmallVectorImpl<DIScope>::reverse_iterator I = Parents.rbegin(),
1072 StringRef Name = Ctx.getName();
1073 if (!Name.empty()) {
1081 /// constructTypeDIE - Construct basic type die from DIBasicType.
1082 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
1083 // Get core information.
1084 StringRef Name = BTy.getName();
1085 // Add name if not anonymous or intermediate type.
1087 addString(&Buffer, dwarf::DW_AT_name, Name);
1089 // An unspecified type only has a name attribute.
1090 if (BTy.getTag() == dwarf::DW_TAG_unspecified_type)
1093 addUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1096 uint64_t Size = BTy.getSizeInBits() >> 3;
1097 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1100 /// constructTypeDIE - Construct derived type die from DIDerivedType.
1101 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
1102 // Get core information.
1103 StringRef Name = DTy.getName();
1104 uint64_t Size = DTy.getSizeInBits() >> 3;
1105 uint16_t Tag = Buffer.getTag();
1107 // Map to main type, void will not have a type.
1108 DIType FromTy = resolve(DTy.getTypeDerivedFrom());
1110 addType(&Buffer, FromTy);
1112 // Add name if not anonymous or intermediate type.
1114 addString(&Buffer, dwarf::DW_AT_name, Name);
1116 // Add size if non-zero (derived types might be zero-sized.)
1117 if (Size && Tag != dwarf::DW_TAG_pointer_type)
1118 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1120 if (Tag == dwarf::DW_TAG_ptr_to_member_type)
1121 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type,
1122 getOrCreateTypeDIE(resolve(DTy.getClassType())));
1123 // Add source line info if available and TyDesc is not a forward declaration.
1124 if (!DTy.isForwardDecl())
1125 addSourceLine(&Buffer, DTy);
1128 /// constructTypeDIE - Construct type DIE from DICompositeType.
1129 void DwarfUnit::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
1130 // Add name if not anonymous or intermediate type.
1131 StringRef Name = CTy.getName();
1133 uint64_t Size = CTy.getSizeInBits() >> 3;
1134 uint16_t Tag = Buffer.getTag();
1137 case dwarf::DW_TAG_array_type:
1138 constructArrayTypeDIE(Buffer, CTy);
1140 case dwarf::DW_TAG_enumeration_type:
1141 constructEnumTypeDIE(Buffer, CTy);
1143 case dwarf::DW_TAG_subroutine_type: {
1144 // Add return type. A void return won't have a type.
1145 DIArray Elements = CTy.getTypeArray();
1146 DIType RTy(Elements.getElement(0));
1148 addType(&Buffer, RTy);
1150 bool isPrototyped = true;
1152 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
1153 DIDescriptor Ty = Elements.getElement(i);
1154 if (Ty.isUnspecifiedParameter()) {
1155 createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
1156 isPrototyped = false;
1158 DIE *Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
1159 addType(Arg, DIType(Ty));
1160 if (DIType(Ty).isArtificial())
1161 addFlag(Arg, dwarf::DW_AT_artificial);
1164 // Add prototype flag if we're dealing with a C language and the
1165 // function has been prototyped.
1166 uint16_t Language = getLanguage();
1168 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1169 Language == dwarf::DW_LANG_ObjC))
1170 addFlag(&Buffer, dwarf::DW_AT_prototyped);
1172 if (CTy.isLValueReference())
1173 addFlag(&Buffer, dwarf::DW_AT_reference);
1175 if (CTy.isRValueReference())
1176 addFlag(&Buffer, dwarf::DW_AT_rvalue_reference);
1178 case dwarf::DW_TAG_structure_type:
1179 case dwarf::DW_TAG_union_type:
1180 case dwarf::DW_TAG_class_type: {
1181 // Add elements to structure type.
1182 DIArray Elements = CTy.getTypeArray();
1183 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1184 DIDescriptor Element = Elements.getElement(i);
1185 DIE *ElemDie = NULL;
1186 if (Element.isSubprogram())
1187 ElemDie = getOrCreateSubprogramDIE(DISubprogram(Element));
1188 else if (Element.isDerivedType()) {
1189 DIDerivedType DDTy(Element);
1190 if (DDTy.getTag() == dwarf::DW_TAG_friend) {
1191 ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
1192 addType(ElemDie, resolve(DDTy.getTypeDerivedFrom()),
1193 dwarf::DW_AT_friend);
1194 } else if (DDTy.isStaticMember()) {
1195 getOrCreateStaticMemberDIE(DDTy);
1197 constructMemberDIE(Buffer, DDTy);
1199 } else if (Element.isObjCProperty()) {
1200 DIObjCProperty Property(Element);
1201 ElemDie = createAndAddDIE(Property.getTag(), Buffer);
1202 StringRef PropertyName = Property.getObjCPropertyName();
1203 addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
1204 if (Property.getType())
1205 addType(ElemDie, Property.getType());
1206 addSourceLine(ElemDie, Property);
1207 StringRef GetterName = Property.getObjCPropertyGetterName();
1208 if (!GetterName.empty())
1209 addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
1210 StringRef SetterName = Property.getObjCPropertySetterName();
1211 if (!SetterName.empty())
1212 addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
1213 unsigned PropertyAttributes = 0;
1214 if (Property.isReadOnlyObjCProperty())
1215 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readonly;
1216 if (Property.isReadWriteObjCProperty())
1217 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readwrite;
1218 if (Property.isAssignObjCProperty())
1219 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_assign;
1220 if (Property.isRetainObjCProperty())
1221 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_retain;
1222 if (Property.isCopyObjCProperty())
1223 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_copy;
1224 if (Property.isNonAtomicObjCProperty())
1225 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_nonatomic;
1226 if (PropertyAttributes)
1227 addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None,
1228 PropertyAttributes);
1230 DIEEntry *Entry = getDIEEntry(Element);
1232 Entry = createDIEEntry(ElemDie);
1233 insertDIEEntry(Element, Entry);
1239 if (CTy.isAppleBlockExtension())
1240 addFlag(&Buffer, dwarf::DW_AT_APPLE_block);
1242 DICompositeType ContainingType(resolve(CTy.getContainingType()));
1244 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type,
1245 getOrCreateTypeDIE(ContainingType));
1247 if (CTy.isObjcClassComplete())
1248 addFlag(&Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
1250 // Add template parameters to a class, structure or union types.
1251 // FIXME: The support isn't in the metadata for this yet.
1252 if (Tag == dwarf::DW_TAG_class_type ||
1253 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
1254 addTemplateParams(Buffer, CTy.getTemplateParams());
1262 // Add name if not anonymous or intermediate type.
1264 addString(&Buffer, dwarf::DW_AT_name, Name);
1266 if (Tag == dwarf::DW_TAG_enumeration_type ||
1267 Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
1268 Tag == dwarf::DW_TAG_union_type) {
1269 // Add size if non-zero (derived types might be zero-sized.)
1270 // TODO: Do we care about size for enum forward declarations?
1272 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1273 else if (!CTy.isForwardDecl())
1274 // Add zero size if it is not a forward declaration.
1275 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, 0);
1277 // If we're a forward decl, say so.
1278 if (CTy.isForwardDecl())
1279 addFlag(&Buffer, dwarf::DW_AT_declaration);
1281 // Add source line info if available.
1282 if (!CTy.isForwardDecl())
1283 addSourceLine(&Buffer, CTy);
1285 // No harm in adding the runtime language to the declaration.
1286 unsigned RLang = CTy.getRunTimeLang();
1288 addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
1293 /// constructTemplateTypeParameterDIE - Construct new DIE for the given
1294 /// DITemplateTypeParameter.
1295 void DwarfUnit::constructTemplateTypeParameterDIE(DIE &Buffer,
1296 DITemplateTypeParameter TP) {
1298 createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
1299 // Add the type if it exists, it could be void and therefore no type.
1301 addType(ParamDIE, resolve(TP.getType()));
1302 if (!TP.getName().empty())
1303 addString(ParamDIE, dwarf::DW_AT_name, TP.getName());
1306 /// constructTemplateValueParameterDIE - Construct new DIE for the given
1307 /// DITemplateValueParameter.
1309 DwarfUnit::constructTemplateValueParameterDIE(DIE &Buffer,
1310 DITemplateValueParameter VP) {
1311 DIE *ParamDIE = createAndAddDIE(VP.getTag(), Buffer);
1313 // Add the type if there is one, template template and template parameter
1314 // packs will not have a type.
1315 if (VP.getTag() == dwarf::DW_TAG_template_value_parameter)
1316 addType(ParamDIE, resolve(VP.getType()));
1317 if (!VP.getName().empty())
1318 addString(ParamDIE, dwarf::DW_AT_name, VP.getName());
1319 if (Value *Val = VP.getValue()) {
1320 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val))
1321 addConstantValue(ParamDIE, CI,
1322 isUnsignedDIType(DD, resolve(VP.getType())));
1323 else if (GlobalValue *GV = dyn_cast<GlobalValue>(Val)) {
1324 // For declaration non-type template parameters (such as global values and
1326 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1327 addOpAddress(Block, Asm->getSymbol(GV));
1328 // Emit DW_OP_stack_value to use the address as the immediate value of the
1329 // parameter, rather than a pointer to it.
1330 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
1331 addBlock(ParamDIE, dwarf::DW_AT_location, Block);
1332 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1333 assert(isa<MDString>(Val));
1334 addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
1335 cast<MDString>(Val)->getString());
1336 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1337 assert(isa<MDNode>(Val));
1338 DIArray A(cast<MDNode>(Val));
1339 addTemplateParams(*ParamDIE, A);
1344 /// getOrCreateNameSpace - Create a DIE for DINameSpace.
1345 DIE *DwarfUnit::getOrCreateNameSpace(DINameSpace NS) {
1346 // Construct the context before querying for the existence of the DIE in case
1347 // such construction creates the DIE.
1348 DIE *ContextDIE = getOrCreateContextDIE(NS.getContext());
1350 DIE *NDie = getDIE(NS);
1353 NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS);
1355 if (!NS.getName().empty()) {
1356 addString(NDie, dwarf::DW_AT_name, NS.getName());
1357 addAccelNamespace(NS.getName(), NDie);
1358 addGlobalName(NS.getName(), NDie, NS.getContext());
1360 addAccelNamespace("(anonymous namespace)", NDie);
1361 addSourceLine(NDie, NS);
1365 /// getOrCreateSubprogramDIE - Create new DIE using SP.
1366 DIE *DwarfUnit::getOrCreateSubprogramDIE(DISubprogram SP) {
1367 // Construct the context before querying for the existence of the DIE in case
1368 // such construction creates the DIE (as is the case for member function
1370 DIE *ContextDIE = getOrCreateContextDIE(resolve(SP.getContext()));
1372 DIE *SPDie = getDIE(SP);
1376 DISubprogram SPDecl = SP.getFunctionDeclaration();
1377 if (SPDecl.isSubprogram())
1378 // Add subprogram definitions to the CU die directly.
1379 ContextDIE = UnitDie.get();
1381 // DW_TAG_inlined_subroutine may refer to this DIE.
1382 SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
1384 DIE *DeclDie = NULL;
1385 if (SPDecl.isSubprogram())
1386 DeclDie = getOrCreateSubprogramDIE(SPDecl);
1388 // Add function template parameters.
1389 addTemplateParams(*SPDie, SP.getTemplateParams());
1391 // If this DIE is going to refer declaration info using AT_specification
1392 // then there is no need to add other attributes.
1394 // Refer function declaration directly.
1395 addDIEEntry(SPDie, dwarf::DW_AT_specification, DeclDie);
1400 // Add the linkage name if we have one.
1401 StringRef LinkageName = SP.getLinkageName();
1402 if (!LinkageName.empty())
1403 addString(SPDie, dwarf::DW_AT_MIPS_linkage_name,
1404 GlobalValue::getRealLinkageName(LinkageName));
1406 // Constructors and operators for anonymous aggregates do not have names.
1407 if (!SP.getName().empty())
1408 addString(SPDie, dwarf::DW_AT_name, SP.getName());
1410 addSourceLine(SPDie, SP);
1412 // Add the prototype if we have a prototype and we have a C like
1414 uint16_t Language = getLanguage();
1415 if (SP.isPrototyped() &&
1416 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1417 Language == dwarf::DW_LANG_ObjC))
1418 addFlag(SPDie, dwarf::DW_AT_prototyped);
1420 DICompositeType SPTy = SP.getType();
1421 assert(SPTy.getTag() == dwarf::DW_TAG_subroutine_type &&
1422 "the type of a subprogram should be a subroutine");
1424 DIArray Args = SPTy.getTypeArray();
1425 // Add a return type. If this is a type like a C/C++ void type we don't add a
1427 if (Args.getElement(0))
1428 addType(SPDie, DIType(Args.getElement(0)));
1430 unsigned VK = SP.getVirtuality();
1432 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1433 DIEBlock *Block = getDIEBlock();
1434 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1435 addUInt(Block, dwarf::DW_FORM_udata, SP.getVirtualIndex());
1436 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
1437 ContainingTypeMap.insert(
1438 std::make_pair(SPDie, resolve(SP.getContainingType())));
1441 if (!SP.isDefinition()) {
1442 addFlag(SPDie, dwarf::DW_AT_declaration);
1444 // Add arguments. Do not add arguments for subprogram definition. They will
1445 // be handled while processing variables.
1446 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1447 DIE *Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, *SPDie);
1448 DIType ATy(Args.getElement(i));
1450 if (ATy.isArtificial())
1451 addFlag(Arg, dwarf::DW_AT_artificial);
1455 if (SP.isArtificial())
1456 addFlag(SPDie, dwarf::DW_AT_artificial);
1458 if (!SP.isLocalToUnit())
1459 addFlag(SPDie, dwarf::DW_AT_external);
1461 if (SP.isOptimized())
1462 addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1464 if (unsigned isa = Asm->getISAEncoding()) {
1465 addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1468 if (SP.isLValueReference())
1469 addFlag(SPDie, dwarf::DW_AT_reference);
1471 if (SP.isRValueReference())
1472 addFlag(SPDie, dwarf::DW_AT_rvalue_reference);
1474 if (SP.isProtected())
1475 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1476 dwarf::DW_ACCESS_protected);
1477 else if (SP.isPrivate())
1478 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1479 dwarf::DW_ACCESS_private);
1481 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1482 dwarf::DW_ACCESS_public);
1484 if (SP.isExplicit())
1485 addFlag(SPDie, dwarf::DW_AT_explicit);
1490 // Return const expression if value is a GEP to access merged global
1492 // i8* getelementptr ({ i8, i8, i8, i8 }* @_MergedGlobals, i32 0, i32 0)
1493 static const ConstantExpr *getMergedGlobalExpr(const Value *V) {
1494 const ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(V);
1495 if (!CE || CE->getNumOperands() != 3 ||
1496 CE->getOpcode() != Instruction::GetElementPtr)
1499 // First operand points to a global struct.
1500 Value *Ptr = CE->getOperand(0);
1501 if (!isa<GlobalValue>(Ptr) ||
1502 !isa<StructType>(cast<PointerType>(Ptr->getType())->getElementType()))
1505 // Second operand is zero.
1506 const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(CE->getOperand(1));
1507 if (!CI || !CI->isZero())
1510 // Third operand is offset.
1511 if (!isa<ConstantInt>(CE->getOperand(2)))
1517 /// createGlobalVariableDIE - create global variable DIE.
1518 void DwarfCompileUnit::createGlobalVariableDIE(DIGlobalVariable GV) {
1519 // Check for pre-existence.
1523 assert(GV.isGlobalVariable());
1525 DIScope GVContext = GV.getContext();
1526 DIType GTy = GV.getType();
1528 // If this is a static data member definition, some attributes belong
1529 // to the declaration DIE.
1530 DIE *VariableDIE = NULL;
1531 bool IsStaticMember = false;
1532 DIDerivedType SDMDecl = GV.getStaticDataMemberDeclaration();
1533 if (SDMDecl.Verify()) {
1534 assert(SDMDecl.isStaticMember() && "Expected static member decl");
1535 // We need the declaration DIE that is in the static member's class.
1536 VariableDIE = getOrCreateStaticMemberDIE(SDMDecl);
1537 IsStaticMember = true;
1540 // If this is not a static data member definition, create the variable
1541 // DIE and add the initial set of attributes to it.
1543 // Construct the context before querying for the existence of the DIE in
1544 // case such construction creates the DIE.
1545 DIE *ContextDIE = getOrCreateContextDIE(GVContext);
1548 VariableDIE = createAndAddDIE(GV.getTag(), *ContextDIE, GV);
1550 // Add name and type.
1551 addString(VariableDIE, dwarf::DW_AT_name, GV.getDisplayName());
1552 addType(VariableDIE, GTy);
1554 // Add scoping info.
1555 if (!GV.isLocalToUnit())
1556 addFlag(VariableDIE, dwarf::DW_AT_external);
1558 // Add line number info.
1559 addSourceLine(VariableDIE, GV);
1563 bool addToAccelTable = false;
1564 DIE *VariableSpecDIE = NULL;
1565 bool isGlobalVariable = GV.getGlobal() != NULL;
1566 if (isGlobalVariable) {
1567 addToAccelTable = true;
1568 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1569 const MCSymbol *Sym = Asm->getSymbol(GV.getGlobal());
1570 if (GV.getGlobal()->isThreadLocal()) {
1571 // FIXME: Make this work with -gsplit-dwarf.
1572 unsigned PointerSize = Asm->getDataLayout().getPointerSize();
1573 assert((PointerSize == 4 || PointerSize == 8) &&
1574 "Add support for other sizes if necessary");
1575 const MCExpr *Expr =
1576 Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym);
1577 // Based on GCC's support for TLS:
1578 if (!DD->useSplitDwarf()) {
1579 // 1) Start with a constNu of the appropriate pointer size
1580 addUInt(Block, dwarf::DW_FORM_data1,
1581 PointerSize == 4 ? dwarf::DW_OP_const4u : dwarf::DW_OP_const8u);
1582 // 2) containing the (relocated) offset of the TLS variable
1583 // within the module's TLS block.
1584 addExpr(Block, dwarf::DW_FORM_udata, Expr);
1586 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
1587 addUInt(Block, dwarf::DW_FORM_udata, DU->getAddrPoolIndex(Expr));
1589 // 3) followed by a custom OP to make the debugger do a TLS lookup.
1590 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_push_tls_address);
1592 DD->addArangeLabel(SymbolCU(this, Sym));
1593 addOpAddress(Block, Sym);
1595 // Do not create specification DIE if context is either compile unit
1597 if (GVContext && GV.isDefinition() && !GVContext.isCompileUnit() &&
1598 !GVContext.isFile() && !DD->isSubprogramContext(GVContext)) {
1599 // Create specification DIE.
1600 VariableSpecDIE = createAndAddDIE(dwarf::DW_TAG_variable, *UnitDie);
1601 addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification, VariableDIE);
1602 addBlock(VariableSpecDIE, dwarf::DW_AT_location, Block);
1603 // A static member's declaration is already flagged as such.
1604 if (!SDMDecl.Verify())
1605 addFlag(VariableDIE, dwarf::DW_AT_declaration);
1607 addBlock(VariableDIE, dwarf::DW_AT_location, Block);
1609 // Add the linkage name.
1610 StringRef LinkageName = GV.getLinkageName();
1611 if (!LinkageName.empty())
1612 // From DWARF4: DIEs to which DW_AT_linkage_name may apply include:
1613 // TAG_common_block, TAG_constant, TAG_entry_point, TAG_subprogram and
1615 addString(IsStaticMember && VariableSpecDIE ? VariableSpecDIE
1617 dwarf::DW_AT_MIPS_linkage_name,
1618 GlobalValue::getRealLinkageName(LinkageName));
1619 } else if (const ConstantInt *CI =
1620 dyn_cast_or_null<ConstantInt>(GV.getConstant())) {
1621 // AT_const_value was added when the static member was created. To avoid
1622 // emitting AT_const_value multiple times, we only add AT_const_value when
1623 // it is not a static member.
1624 if (!IsStaticMember)
1625 addConstantValue(VariableDIE, CI, isUnsignedDIType(DD, GTy));
1626 } else if (const ConstantExpr *CE = getMergedGlobalExpr(GV->getOperand(11))) {
1627 addToAccelTable = true;
1628 // GV is a merged global.
1629 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1630 Value *Ptr = CE->getOperand(0);
1631 MCSymbol *Sym = Asm->getSymbol(cast<GlobalValue>(Ptr));
1632 DD->addArangeLabel(SymbolCU(this, Sym));
1633 addOpAddress(Block, Sym);
1634 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1635 SmallVector<Value *, 3> Idx(CE->op_begin() + 1, CE->op_end());
1636 addUInt(Block, dwarf::DW_FORM_udata,
1637 Asm->getDataLayout().getIndexedOffset(Ptr->getType(), Idx));
1638 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1639 addBlock(VariableDIE, dwarf::DW_AT_location, Block);
1642 if (addToAccelTable) {
1643 DIE *AddrDIE = VariableSpecDIE ? VariableSpecDIE : VariableDIE;
1644 addAccelName(GV.getName(), AddrDIE);
1646 // If the linkage name is different than the name, go ahead and output
1647 // that as well into the name table.
1648 if (GV.getLinkageName() != "" && GV.getName() != GV.getLinkageName())
1649 addAccelName(GV.getLinkageName(), AddrDIE);
1652 if (!GV.isLocalToUnit())
1653 addGlobalName(GV.getName(), VariableSpecDIE ? VariableSpecDIE : VariableDIE,
1657 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
1658 void DwarfUnit::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy) {
1659 DIE *DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
1660 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, IndexTy);
1662 // The LowerBound value defines the lower bounds which is typically zero for
1663 // C/C++. The Count value is the number of elements. Values are 64 bit. If
1664 // Count == -1 then the array is unbounded and we do not emit
1665 // DW_AT_lower_bound and DW_AT_upper_bound attributes. If LowerBound == 0 and
1666 // Count == 0, then the array has zero elements in which case we do not emit
1668 int64_t LowerBound = SR.getLo();
1669 int64_t DefaultLowerBound = getDefaultLowerBound();
1670 int64_t Count = SR.getCount();
1672 if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
1673 addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound);
1675 if (Count != -1 && Count != 0)
1676 // FIXME: An unbounded array should reference the expression that defines
1678 addUInt(DW_Subrange, dwarf::DW_AT_upper_bound, None,
1679 LowerBound + Count - 1);
1682 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
1683 void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, DICompositeType CTy) {
1685 addFlag(&Buffer, dwarf::DW_AT_GNU_vector);
1687 // Emit the element type.
1688 addType(&Buffer, resolve(CTy.getTypeDerivedFrom()));
1690 // Get an anonymous type for index type.
1691 // FIXME: This type should be passed down from the front end
1692 // as different languages may have different sizes for indexes.
1693 DIE *IdxTy = getIndexTyDie();
1695 // Construct an anonymous type for index type.
1696 IdxTy = createAndAddDIE(dwarf::DW_TAG_base_type, *UnitDie);
1697 addString(IdxTy, dwarf::DW_AT_name, "int");
1698 addUInt(IdxTy, dwarf::DW_AT_byte_size, None, sizeof(int32_t));
1699 addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1700 dwarf::DW_ATE_signed);
1701 setIndexTyDie(IdxTy);
1704 // Add subranges to array type.
1705 DIArray Elements = CTy.getTypeArray();
1706 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1707 DIDescriptor Element = Elements.getElement(i);
1708 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1709 constructSubrangeDIE(Buffer, DISubrange(Element), IdxTy);
1713 /// constructEnumTypeDIE - Construct an enum type DIE from DICompositeType.
1714 void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, DICompositeType CTy) {
1715 DIArray Elements = CTy.getTypeArray();
1717 // Add enumerators to enumeration type.
1718 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1719 DIEnumerator Enum(Elements.getElement(i));
1720 if (Enum.isEnumerator()) {
1721 DIE *Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
1722 StringRef Name = Enum.getName();
1723 addString(Enumerator, dwarf::DW_AT_name, Name);
1724 int64_t Value = Enum.getEnumValue();
1725 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
1729 DIType DTy = resolve(CTy.getTypeDerivedFrom());
1731 addType(&Buffer, DTy);
1732 addFlag(&Buffer, dwarf::DW_AT_enum_class);
1736 /// constructContainingTypeDIEs - Construct DIEs for types that contain
1738 void DwarfUnit::constructContainingTypeDIEs() {
1739 for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(),
1740 CE = ContainingTypeMap.end();
1742 DIE *SPDie = CI->first;
1743 DIDescriptor D(CI->second);
1746 DIE *NDie = getDIE(D);
1749 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, NDie);
1753 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
1754 DIE *DwarfUnit::constructVariableDIE(DbgVariable &DV, bool isScopeAbstract) {
1755 StringRef Name = DV.getName();
1757 // Define variable debug information entry.
1758 DIE *VariableDie = new DIE(DV.getTag());
1759 DbgVariable *AbsVar = DV.getAbstractVariable();
1760 DIE *AbsDIE = AbsVar ? AbsVar->getDIE() : NULL;
1762 addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin, AbsDIE);
1765 addString(VariableDie, dwarf::DW_AT_name, Name);
1766 addSourceLine(VariableDie, DV.getVariable());
1767 addType(VariableDie, DV.getType());
1770 if (DV.isArtificial())
1771 addFlag(VariableDie, dwarf::DW_AT_artificial);
1773 if (isScopeAbstract) {
1774 DV.setDIE(VariableDie);
1778 // Add variable address.
1780 unsigned Offset = DV.getDotDebugLocOffset();
1781 if (Offset != ~0U) {
1782 addSectionLabel(VariableDie, dwarf::DW_AT_location,
1783 Asm->GetTempSymbol("debug_loc", Offset));
1784 DV.setDIE(VariableDie);
1788 // Check if variable is described by a DBG_VALUE instruction.
1789 if (const MachineInstr *DVInsn = DV.getMInsn()) {
1790 assert(DVInsn->getNumOperands() == 3);
1791 if (DVInsn->getOperand(0).isReg()) {
1792 const MachineOperand RegOp = DVInsn->getOperand(0);
1793 // If the second operand is an immediate, this is an indirect value.
1794 if (DVInsn->getOperand(1).isImm()) {
1795 MachineLocation Location(RegOp.getReg(),
1796 DVInsn->getOperand(1).getImm());
1797 addVariableAddress(DV, VariableDie, Location);
1798 } else if (RegOp.getReg())
1799 addVariableAddress(DV, VariableDie, MachineLocation(RegOp.getReg()));
1800 } else if (DVInsn->getOperand(0).isImm())
1801 addConstantValue(VariableDie, DVInsn->getOperand(0), DV.getType());
1802 else if (DVInsn->getOperand(0).isFPImm())
1803 addConstantFPValue(VariableDie, DVInsn->getOperand(0));
1804 else if (DVInsn->getOperand(0).isCImm())
1805 addConstantValue(VariableDie, DVInsn->getOperand(0).getCImm(),
1806 isUnsignedDIType(DD, DV.getType()));
1808 DV.setDIE(VariableDie);
1811 // .. else use frame index.
1812 int FI = DV.getFrameIndex();
1814 unsigned FrameReg = 0;
1815 const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
1816 int Offset = TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
1817 MachineLocation Location(FrameReg, Offset);
1818 addVariableAddress(DV, VariableDie, Location);
1822 DV.setDIE(VariableDie);
1826 /// constructMemberDIE - Construct member DIE from DIDerivedType.
1827 void DwarfUnit::constructMemberDIE(DIE &Buffer, DIDerivedType DT) {
1828 DIE *MemberDie = createAndAddDIE(DT.getTag(), Buffer);
1829 StringRef Name = DT.getName();
1831 addString(MemberDie, dwarf::DW_AT_name, Name);
1833 addType(MemberDie, resolve(DT.getTypeDerivedFrom()));
1835 addSourceLine(MemberDie, DT);
1837 if (DT.getTag() == dwarf::DW_TAG_inheritance && DT.isVirtual()) {
1839 // For C++, virtual base classes are not at fixed offset. Use following
1840 // expression to extract appropriate offset from vtable.
1841 // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1843 DIEBlock *VBaseLocationDie = new (DIEValueAllocator) DIEBlock();
1844 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1845 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1846 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1847 addUInt(VBaseLocationDie, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1848 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1849 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1850 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1852 addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
1854 uint64_t Size = DT.getSizeInBits();
1855 uint64_t FieldSize = getBaseTypeSize(DD, DT);
1856 uint64_t OffsetInBytes;
1858 if (Size != FieldSize) {
1860 addUInt(MemberDie, dwarf::DW_AT_byte_size, None,
1861 getBaseTypeSize(DD, DT) >> 3);
1862 addUInt(MemberDie, dwarf::DW_AT_bit_size, None, DT.getSizeInBits());
1864 uint64_t Offset = DT.getOffsetInBits();
1865 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1866 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1867 uint64_t FieldOffset = (HiMark - FieldSize);
1868 Offset -= FieldOffset;
1870 // Maybe we need to work from the other end.
1871 if (Asm->getDataLayout().isLittleEndian())
1872 Offset = FieldSize - (Offset + Size);
1873 addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset);
1875 // Here DW_AT_data_member_location points to the anonymous
1876 // field that includes this bit field.
1877 OffsetInBytes = FieldOffset >> 3;
1879 // This is not a bitfield.
1880 OffsetInBytes = DT.getOffsetInBits() >> 3;
1882 if (DD->getDwarfVersion() <= 2) {
1883 DIEBlock *MemLocationDie = new (DIEValueAllocator) DIEBlock();
1884 addUInt(MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1885 addUInt(MemLocationDie, dwarf::DW_FORM_udata, OffsetInBytes);
1886 addBlock(MemberDie, dwarf::DW_AT_data_member_location, MemLocationDie);
1888 addUInt(MemberDie, dwarf::DW_AT_data_member_location, None,
1892 if (DT.isProtected())
1893 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1894 dwarf::DW_ACCESS_protected);
1895 else if (DT.isPrivate())
1896 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1897 dwarf::DW_ACCESS_private);
1898 // Otherwise C++ member and base classes are considered public.
1900 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1901 dwarf::DW_ACCESS_public);
1903 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1904 dwarf::DW_VIRTUALITY_virtual);
1906 // Objective-C properties.
1907 if (MDNode *PNode = DT.getObjCProperty())
1908 if (DIEEntry *PropertyDie = getDIEEntry(PNode))
1909 MemberDie->addValue(dwarf::DW_AT_APPLE_property, dwarf::DW_FORM_ref4,
1912 if (DT.isArtificial())
1913 addFlag(MemberDie, dwarf::DW_AT_artificial);
1916 /// getOrCreateStaticMemberDIE - Create new DIE for C++ static member.
1917 DIE *DwarfUnit::getOrCreateStaticMemberDIE(DIDerivedType DT) {
1921 // Construct the context before querying for the existence of the DIE in case
1922 // such construction creates the DIE.
1923 DIE *ContextDIE = getOrCreateContextDIE(resolve(DT.getContext()));
1924 assert(dwarf::isType(ContextDIE->getTag()) &&
1925 "Static member should belong to a type.");
1927 DIE *StaticMemberDIE = getDIE(DT);
1928 if (StaticMemberDIE)
1929 return StaticMemberDIE;
1931 StaticMemberDIE = createAndAddDIE(DT.getTag(), *ContextDIE, DT);
1933 DIType Ty = resolve(DT.getTypeDerivedFrom());
1935 addString(StaticMemberDIE, dwarf::DW_AT_name, DT.getName());
1936 addType(StaticMemberDIE, Ty);
1937 addSourceLine(StaticMemberDIE, DT);
1938 addFlag(StaticMemberDIE, dwarf::DW_AT_external);
1939 addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
1941 // FIXME: We could omit private if the parent is a class_type, and
1942 // public if the parent is something else.
1943 if (DT.isProtected())
1944 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1945 dwarf::DW_ACCESS_protected);
1946 else if (DT.isPrivate())
1947 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1948 dwarf::DW_ACCESS_private);
1950 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1951 dwarf::DW_ACCESS_public);
1953 if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT.getConstant()))
1954 addConstantValue(StaticMemberDIE, CI, isUnsignedDIType(DD, Ty));
1955 if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT.getConstant()))
1956 addConstantFPValue(StaticMemberDIE, CFP);
1958 return StaticMemberDIE;
1961 void DwarfUnit::emitHeader(const MCSection *ASection,
1962 const MCSymbol *ASectionSym) const {
1963 Asm->OutStreamer.AddComment("DWARF version number");
1964 Asm->EmitInt16(DD->getDwarfVersion());
1965 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
1966 // We share one abbreviations table across all units so it's always at the
1967 // start of the section. Use a relocatable offset where needed to ensure
1968 // linking doesn't invalidate that offset.
1969 Asm->EmitSectionOffset(ASectionSym, ASectionSym);
1970 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1971 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
1974 DwarfCompileUnit::~DwarfCompileUnit() {}
1975 DwarfTypeUnit::~DwarfTypeUnit() {}
1977 void DwarfTypeUnit::emitHeader(const MCSection *ASection,
1978 const MCSymbol *ASectionSym) const {
1979 DwarfUnit::emitHeader(ASection, ASectionSym);
1980 Asm->OutStreamer.AddComment("Type Signature");
1981 Asm->OutStreamer.EmitIntValue(TypeSignature, sizeof(TypeSignature));
1982 Asm->OutStreamer.AddComment("Type DIE Offset");
1983 // In a skeleton type unit there is no type DIE so emit a zero offset.
1984 Asm->OutStreamer.EmitIntValue(Ty ? Ty->getOffset() : 0,
1985 sizeof(Ty->getOffset()));
1988 void DwarfTypeUnit::initSection(const MCSection *Section) {
1989 assert(!this->Section);
1990 this->Section = Section;
1991 // Since each type unit is contained in its own COMDAT section, the begin
1992 // label and the section label are the same. Using the begin label emission in
1993 // DwarfDebug to emit the section label as well is slightly subtle/sneaky, but
1994 // the only other alternative of lazily constructing start-of-section labels
1995 // and storing a mapping in DwarfDebug (or AsmPrinter).
1996 this->SectionSym = this->LabelBegin =
1997 Asm->GetTempSymbol(Section->getLabelBeginName(), getUniqueID());
1999 Asm->GetTempSymbol(Section->getLabelEndName(), getUniqueID());
2000 this->LabelRange = Asm->GetTempSymbol("gnu_ranges", getUniqueID());