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) {
365 unsigned FileID = DD->getOrCreateSourceID(File, Directory, getUniqueID());
366 assert(FileID && "Invalid file id");
367 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
368 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
371 /// addSourceLine - Add location information to specified debug information
373 void DwarfUnit::addSourceLine(DIE *Die, DIVariable V) {
374 assert(V.isVariable());
376 addSourceLine(Die, V.getLineNumber(), V.getContext().getFilename(), V.getContext().getDirectory());
379 /// addSourceLine - Add location information to specified debug information
381 void DwarfUnit::addSourceLine(DIE *Die, DIGlobalVariable G) {
382 assert(G.isGlobalVariable());
384 addSourceLine(Die, G.getLineNumber(), G.getFilename(), G.getDirectory());
387 /// addSourceLine - Add location information to specified debug information
389 void DwarfUnit::addSourceLine(DIE *Die, DISubprogram SP) {
390 assert(SP.isSubprogram());
392 addSourceLine(Die, SP.getLineNumber(), SP.getFilename(), SP.getDirectory());
395 /// addSourceLine - Add location information to specified debug information
397 void DwarfUnit::addSourceLine(DIE *Die, DIType Ty) {
400 addSourceLine(Die, Ty.getLineNumber(), Ty.getFilename(), Ty.getDirectory());
403 /// addSourceLine - Add location information to specified debug information
405 void DwarfUnit::addSourceLine(DIE *Die, DIObjCProperty Ty) {
406 assert(Ty.isObjCProperty());
408 DIFile File = Ty.getFile();
409 addSourceLine(Die, Ty.getLineNumber(), File.getFilename(),
410 File.getDirectory());
413 /// addSourceLine - Add location information to specified debug information
415 void DwarfUnit::addSourceLine(DIE *Die, DINameSpace NS) {
418 addSourceLine(Die, NS.getLineNumber(), NS.getFilename(), NS.getDirectory());
421 /// addVariableAddress - Add DW_AT_location attribute for a
422 /// DbgVariable based on provided MachineLocation.
423 void DwarfUnit::addVariableAddress(const DbgVariable &DV, DIE *Die,
424 MachineLocation Location) {
425 if (DV.variableHasComplexAddress())
426 addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
427 else if (DV.isBlockByrefVariable())
428 addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location);
430 addAddress(Die, dwarf::DW_AT_location, Location,
431 DV.getVariable().isIndirect());
434 /// addRegisterOp - Add register operand.
435 void DwarfUnit::addRegisterOp(DIEBlock *TheDie, unsigned Reg) {
436 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
437 int DWReg = RI->getDwarfRegNum(Reg, false);
438 bool isSubRegister = DWReg < 0;
442 // Go up the super-register chain until we hit a valid dwarf register number.
443 for (MCSuperRegIterator SR(Reg, RI); SR.isValid() && DWReg < 0; ++SR) {
444 DWReg = RI->getDwarfRegNum(*SR, false);
446 Idx = RI->getSubRegIndex(*SR, Reg);
450 DEBUG(llvm::dbgs() << "Invalid Dwarf register number.\n");
451 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_nop);
457 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + DWReg);
459 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
460 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
465 unsigned Size = RI->getSubRegIdxSize(Idx);
466 unsigned Offset = RI->getSubRegIdxOffset(Idx);
468 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_bit_piece);
469 addUInt(TheDie, dwarf::DW_FORM_data1, Size);
470 addUInt(TheDie, dwarf::DW_FORM_data1, Offset);
472 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_piece);
473 addUInt(TheDie, dwarf::DW_FORM_data1, Size);
478 /// addRegisterOffset - Add register offset.
479 void DwarfUnit::addRegisterOffset(DIEBlock *TheDie, unsigned Reg,
481 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
482 unsigned DWReg = RI->getDwarfRegNum(Reg, false);
483 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
484 if (Reg == TRI->getFrameRegister(*Asm->MF))
485 // If variable offset is based in frame register then use fbreg.
486 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_fbreg);
488 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + DWReg);
490 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
491 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
493 addSInt(TheDie, dwarf::DW_FORM_sdata, Offset);
496 /// addAddress - Add an address attribute to a die based on the location
498 void DwarfUnit::addAddress(DIE *Die, dwarf::Attribute Attribute,
499 const MachineLocation &Location, bool Indirect) {
500 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
502 if (Location.isReg() && !Indirect)
503 addRegisterOp(Block, Location.getReg());
505 addRegisterOffset(Block, Location.getReg(), Location.getOffset());
506 if (Indirect && !Location.isReg()) {
507 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
511 // Now attach the location information to the DIE.
512 addBlock(Die, Attribute, Block);
515 /// addComplexAddress - Start with the address based on the location provided,
516 /// and generate the DWARF information necessary to find the actual variable
517 /// given the extra address information encoded in the DbgVariable, starting
518 /// from the starting location. Add the DWARF information to the die.
520 void DwarfUnit::addComplexAddress(const DbgVariable &DV, DIE *Die,
521 dwarf::Attribute Attribute,
522 const MachineLocation &Location) {
523 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
524 unsigned N = DV.getNumAddrElements();
526 if (Location.isReg()) {
527 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
528 // If first address element is OpPlus then emit
529 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
530 addRegisterOffset(Block, Location.getReg(), DV.getAddrElement(1));
533 addRegisterOp(Block, Location.getReg());
535 addRegisterOffset(Block, Location.getReg(), Location.getOffset());
538 uint64_t Element = DV.getAddrElement(i);
539 if (Element == DIBuilder::OpPlus) {
540 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
541 addUInt(Block, dwarf::DW_FORM_udata, DV.getAddrElement(++i));
542 } else if (Element == DIBuilder::OpDeref) {
543 if (!Location.isReg())
544 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
546 llvm_unreachable("unknown DIBuilder Opcode");
549 // Now attach the location information to the DIE.
550 addBlock(Die, Attribute, Block);
553 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
554 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
555 gives the variable VarName either the struct, or a pointer to the struct, as
556 its type. This is necessary for various behind-the-scenes things the
557 compiler needs to do with by-reference variables in Blocks.
559 However, as far as the original *programmer* is concerned, the variable
560 should still have type 'SomeType', as originally declared.
562 The function getBlockByrefType dives into the __Block_byref_x_VarName
563 struct to find the original type of the variable, which is then assigned to
564 the variable's Debug Information Entry as its real type. So far, so good.
565 However now the debugger will expect the variable VarName to have the type
566 SomeType. So we need the location attribute for the variable to be an
567 expression that explains to the debugger how to navigate through the
568 pointers and struct to find the actual variable of type SomeType.
570 The following function does just that. We start by getting
571 the "normal" location for the variable. This will be the location
572 of either the struct __Block_byref_x_VarName or the pointer to the
573 struct __Block_byref_x_VarName.
575 The struct will look something like:
577 struct __Block_byref_x_VarName {
579 struct __Block_byref_x_VarName *forwarding;
580 ... <various other fields>
582 ... <maybe more fields>
585 If we are given the struct directly (as our starting point) we
586 need to tell the debugger to:
588 1). Add the offset of the forwarding field.
590 2). Follow that pointer to get the real __Block_byref_x_VarName
591 struct to use (the real one may have been copied onto the heap).
593 3). Add the offset for the field VarName, to find the actual variable.
595 If we started with a pointer to the struct, then we need to
596 dereference that pointer first, before the other steps.
597 Translating this into DWARF ops, we will need to append the following
598 to the current location description for the variable:
600 DW_OP_deref -- optional, if we start with a pointer
601 DW_OP_plus_uconst <forward_fld_offset>
603 DW_OP_plus_uconst <varName_fld_offset>
605 That is what this function does. */
607 /// addBlockByrefAddress - Start with the address based on the location
608 /// provided, and generate the DWARF information necessary to find the
609 /// actual Block variable (navigating the Block struct) based on the
610 /// starting location. Add the DWARF information to the die. For
611 /// more information, read large comment just above here.
613 void DwarfUnit::addBlockByrefAddress(const DbgVariable &DV, DIE *Die,
614 dwarf::Attribute Attribute,
615 const MachineLocation &Location) {
616 DIType Ty = DV.getType();
618 uint16_t Tag = Ty.getTag();
619 bool isPointer = false;
621 StringRef varName = DV.getName();
623 if (Tag == dwarf::DW_TAG_pointer_type) {
624 DIDerivedType DTy(Ty);
625 TmpTy = resolve(DTy.getTypeDerivedFrom());
629 DICompositeType blockStruct(TmpTy);
631 // Find the __forwarding field and the variable field in the __Block_byref
633 DIArray Fields = blockStruct.getTypeArray();
634 DIDerivedType varField;
635 DIDerivedType forwardingField;
637 for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
638 DIDerivedType DT(Fields.getElement(i));
639 StringRef fieldName = DT.getName();
640 if (fieldName == "__forwarding")
641 forwardingField = DT;
642 else if (fieldName == varName)
646 // Get the offsets for the forwarding field and the variable field.
647 unsigned forwardingFieldOffset = forwardingField.getOffsetInBits() >> 3;
648 unsigned varFieldOffset = varField.getOffsetInBits() >> 2;
650 // Decode the original location, and use that as the start of the byref
651 // variable's location.
652 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
654 if (Location.isReg())
655 addRegisterOp(Block, Location.getReg());
657 addRegisterOffset(Block, Location.getReg(), Location.getOffset());
659 // If we started with a pointer to the __Block_byref... struct, then
660 // the first thing we need to do is dereference the pointer (DW_OP_deref).
662 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
664 // Next add the offset for the '__forwarding' field:
665 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
666 // adding the offset if it's 0.
667 if (forwardingFieldOffset > 0) {
668 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
669 addUInt(Block, dwarf::DW_FORM_udata, forwardingFieldOffset);
672 // Now dereference the __forwarding field to get to the real __Block_byref
673 // struct: DW_OP_deref.
674 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
676 // Now that we've got the real __Block_byref... struct, add the offset
677 // for the variable's field to get to the location of the actual variable:
678 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
679 if (varFieldOffset > 0) {
680 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
681 addUInt(Block, dwarf::DW_FORM_udata, varFieldOffset);
684 // Now attach the location information to the DIE.
685 addBlock(Die, Attribute, Block);
688 /// isTypeSigned - Return true if the type is signed.
689 static bool isTypeSigned(DwarfDebug *DD, DIType Ty, int *SizeInBits) {
690 if (Ty.isDerivedType())
691 return isTypeSigned(DD, DD->resolve(DIDerivedType(Ty).getTypeDerivedFrom()),
693 if (Ty.isBasicType())
694 if (DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed ||
695 DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed_char) {
696 *SizeInBits = Ty.getSizeInBits();
702 /// Return true if type encoding is unsigned.
703 static bool isUnsignedDIType(DwarfDebug *DD, DIType Ty) {
704 DIDerivedType DTy(Ty);
705 if (DTy.isDerivedType())
706 return isUnsignedDIType(DD, DD->resolve(DTy.getTypeDerivedFrom()));
709 if (BTy.isBasicType()) {
710 unsigned Encoding = BTy.getEncoding();
711 if (Encoding == dwarf::DW_ATE_unsigned ||
712 Encoding == dwarf::DW_ATE_unsigned_char ||
713 Encoding == dwarf::DW_ATE_boolean)
719 /// If this type is derived from a base type then return base type size.
720 static uint64_t getBaseTypeSize(DwarfDebug *DD, DIDerivedType Ty) {
721 unsigned Tag = Ty.getTag();
723 if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef &&
724 Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type &&
725 Tag != dwarf::DW_TAG_restrict_type)
726 return Ty.getSizeInBits();
728 DIType BaseType = DD->resolve(Ty.getTypeDerivedFrom());
730 // If this type is not derived from any type then take conservative approach.
731 if (!BaseType.isValid())
732 return Ty.getSizeInBits();
734 // If this is a derived type, go ahead and get the base type, unless it's a
735 // reference then it's just the size of the field. Pointer types have no need
736 // of this since they're a different type of qualification on the type.
737 if (BaseType.getTag() == dwarf::DW_TAG_reference_type ||
738 BaseType.getTag() == dwarf::DW_TAG_rvalue_reference_type)
739 return Ty.getSizeInBits();
741 if (BaseType.isDerivedType())
742 return getBaseTypeSize(DD, DIDerivedType(BaseType));
744 return BaseType.getSizeInBits();
747 /// addConstantValue - Add constant value entry in variable DIE.
748 void DwarfUnit::addConstantValue(DIE *Die, const MachineOperand &MO,
750 // FIXME: This is a bit conservative/simple - it emits negative values at
751 // their maximum bit width which is a bit unfortunate (& doesn't prefer
752 // udata/sdata over dataN as suggested by the DWARF spec)
753 assert(MO.isImm() && "Invalid machine operand!");
755 bool SignedConstant = isTypeSigned(DD, Ty, &SizeInBits);
758 // If we're a signed constant definitely use sdata.
759 if (SignedConstant) {
760 addSInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, MO.getImm());
764 // Else use data for now unless it's larger than we can deal with.
765 switch (SizeInBits) {
767 Form = dwarf::DW_FORM_data1;
770 Form = dwarf::DW_FORM_data2;
773 Form = dwarf::DW_FORM_data4;
776 Form = dwarf::DW_FORM_data8;
779 Form = dwarf::DW_FORM_udata;
780 addUInt(Die, dwarf::DW_AT_const_value, Form, MO.getImm());
783 addUInt(Die, dwarf::DW_AT_const_value, Form, MO.getImm());
786 /// addConstantFPValue - Add constant value entry in variable DIE.
787 void DwarfUnit::addConstantFPValue(DIE *Die, const MachineOperand &MO) {
788 assert(MO.isFPImm() && "Invalid machine operand!");
789 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
790 APFloat FPImm = MO.getFPImm()->getValueAPF();
792 // Get the raw data form of the floating point.
793 const APInt FltVal = FPImm.bitcastToAPInt();
794 const char *FltPtr = (const char *)FltVal.getRawData();
796 int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
797 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
798 int Incr = (LittleEndian ? 1 : -1);
799 int Start = (LittleEndian ? 0 : NumBytes - 1);
800 int Stop = (LittleEndian ? NumBytes : -1);
802 // Output the constant to DWARF one byte at a time.
803 for (; Start != Stop; Start += Incr)
804 addUInt(Block, dwarf::DW_FORM_data1, (unsigned char)0xFF & FltPtr[Start]);
806 addBlock(Die, dwarf::DW_AT_const_value, Block);
809 /// addConstantFPValue - Add constant value entry in variable DIE.
810 void DwarfUnit::addConstantFPValue(DIE *Die, const ConstantFP *CFP) {
811 // Pass this down to addConstantValue as an unsigned bag of bits.
812 addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true);
815 /// addConstantValue - Add constant value entry in variable DIE.
816 void DwarfUnit::addConstantValue(DIE *Die, const ConstantInt *CI,
818 addConstantValue(Die, CI->getValue(), Unsigned);
821 // addConstantValue - Add constant value entry in variable DIE.
822 void DwarfUnit::addConstantValue(DIE *Die, const APInt &Val, bool Unsigned) {
823 unsigned CIBitWidth = Val.getBitWidth();
824 if (CIBitWidth <= 64) {
825 // If we're a signed constant definitely use sdata.
827 addSInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
832 // Else use data for now unless it's larger than we can deal with.
834 switch (CIBitWidth) {
836 Form = dwarf::DW_FORM_data1;
839 Form = dwarf::DW_FORM_data2;
842 Form = dwarf::DW_FORM_data4;
845 Form = dwarf::DW_FORM_data8;
848 addUInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_udata,
852 addUInt(Die, dwarf::DW_AT_const_value, Form, Val.getZExtValue());
856 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
858 // Get the raw data form of the large APInt.
859 const uint64_t *Ptr64 = Val.getRawData();
861 int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
862 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
864 // Output the constant to DWARF one byte at a time.
865 for (int i = 0; i < NumBytes; i++) {
868 c = Ptr64[i / 8] >> (8 * (i & 7));
870 c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
871 addUInt(Block, dwarf::DW_FORM_data1, c);
874 addBlock(Die, dwarf::DW_AT_const_value, Block);
877 /// addTemplateParams - Add template parameters into buffer.
878 void DwarfUnit::addTemplateParams(DIE &Buffer, DIArray TParams) {
879 // Add template parameters.
880 for (unsigned i = 0, e = TParams.getNumElements(); i != e; ++i) {
881 DIDescriptor Element = TParams.getElement(i);
882 if (Element.isTemplateTypeParameter())
883 constructTemplateTypeParameterDIE(Buffer,
884 DITemplateTypeParameter(Element));
885 else if (Element.isTemplateValueParameter())
886 constructTemplateValueParameterDIE(Buffer,
887 DITemplateValueParameter(Element));
891 /// getOrCreateContextDIE - Get context owner's DIE.
892 DIE *DwarfUnit::getOrCreateContextDIE(DIScope Context) {
893 if (!Context || Context.isFile())
895 if (Context.isType())
896 return getOrCreateTypeDIE(DIType(Context));
897 if (Context.isNameSpace())
898 return getOrCreateNameSpace(DINameSpace(Context));
899 if (Context.isSubprogram())
900 return getOrCreateSubprogramDIE(DISubprogram(Context));
901 return getDIE(Context);
904 DIE *DwarfUnit::createTypeDIE(DICompositeType Ty) {
905 DIScope Context = resolve(Ty.getContext());
906 DIE *ContextDIE = getOrCreateContextDIE(Context);
908 DIE *TyDIE = getDIE(Ty);
913 TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
915 constructTypeDIE(*TyDIE, Ty);
917 updateAcceleratorTables(Context, Ty, TyDIE);
921 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
923 DIE *DwarfUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
930 // Construct the context before querying for the existence of the DIE in case
931 // such construction creates the DIE.
932 DIScope Context = resolve(Ty.getContext());
933 DIE *ContextDIE = getOrCreateContextDIE(Context);
936 DIE *TyDIE = getDIE(Ty);
941 TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
943 if (Ty.isBasicType())
944 constructTypeDIE(*TyDIE, DIBasicType(Ty));
945 else if (Ty.isCompositeType()) {
946 DICompositeType CTy(Ty);
947 if (GenerateDwarfTypeUnits && !Ty.isForwardDecl())
948 if (MDString *TypeId = CTy.getIdentifier()) {
949 DD->addDwarfTypeUnitType(getCU(), TypeId->getString(), TyDIE, CTy);
950 // Skip updating the accellerator tables since this is not the full type
953 constructTypeDIE(*TyDIE, CTy);
955 assert(Ty.isDerivedType() && "Unknown kind of DIType");
956 constructTypeDIE(*TyDIE, DIDerivedType(Ty));
959 updateAcceleratorTables(Context, Ty, TyDIE);
964 void DwarfUnit::updateAcceleratorTables(DIScope Context, DIType Ty,
966 if (!Ty.getName().empty() && !Ty.isForwardDecl()) {
967 bool IsImplementation = 0;
968 if (Ty.isCompositeType()) {
969 DICompositeType CT(Ty);
970 // A runtime language of 0 actually means C/C++ and that any
971 // non-negative value is some version of Objective-C/C++.
972 IsImplementation = (CT.getRunTimeLang() == 0) || CT.isObjcClassComplete();
974 unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0;
975 addAccelType(Ty.getName(), std::make_pair(TyDIE, Flags));
977 if (!Context || Context.isCompileUnit() || Context.isFile() ||
978 Context.isNameSpace())
979 GlobalTypes[getParentContextString(Context) + Ty.getName().str()] = TyDIE;
983 /// addType - Add a new type attribute to the specified entity.
984 void DwarfUnit::addType(DIE *Entity, DIType Ty, dwarf::Attribute Attribute) {
985 assert(Ty && "Trying to add a type that doesn't exist?");
987 // Check for pre-existence.
988 DIEEntry *Entry = getDIEEntry(Ty);
989 // If it exists then use the existing value.
991 addDIEEntry(Entity, Attribute, Entry);
996 DIE *Buffer = getOrCreateTypeDIE(Ty);
999 Entry = createDIEEntry(Buffer);
1000 insertDIEEntry(Ty, Entry);
1001 addDIEEntry(Entity, Attribute, Entry);
1004 // Accelerator table mutators - add each name along with its companion
1005 // DIE to the proper table while ensuring that the name that we're going
1006 // to reference is in the string table. We do this since the names we
1007 // add may not only be identical to the names in the DIE.
1008 void DwarfUnit::addAccelName(StringRef Name, const DIE *Die) {
1009 if (!DD->useDwarfAccelTables()) return;
1010 DU->getStringPoolEntry(Name);
1011 std::vector<const DIE *> &DIEs = AccelNames[Name];
1012 DIEs.push_back(Die);
1015 void DwarfUnit::addAccelObjC(StringRef Name, const DIE *Die) {
1016 if (!DD->useDwarfAccelTables()) return;
1017 DU->getStringPoolEntry(Name);
1018 std::vector<const DIE *> &DIEs = AccelObjC[Name];
1019 DIEs.push_back(Die);
1022 void DwarfUnit::addAccelNamespace(StringRef Name, const DIE *Die) {
1023 if (!DD->useDwarfAccelTables()) return;
1024 DU->getStringPoolEntry(Name);
1025 std::vector<const DIE *> &DIEs = AccelNamespace[Name];
1026 DIEs.push_back(Die);
1029 void DwarfUnit::addAccelType(StringRef Name,
1030 std::pair<const DIE *, unsigned> Die) {
1031 if (!DD->useDwarfAccelTables()) return;
1032 DU->getStringPoolEntry(Name);
1033 std::vector<std::pair<const DIE *, unsigned> > &DIEs = AccelTypes[Name];
1034 DIEs.push_back(Die);
1037 /// addGlobalName - Add a new global name to the compile unit.
1038 void DwarfUnit::addGlobalName(StringRef Name, DIE *Die, DIScope Context) {
1039 std::string FullName = getParentContextString(Context) + Name.str();
1040 GlobalNames[FullName] = Die;
1043 /// getParentContextString - Walks the metadata parent chain in a language
1044 /// specific manner (using the compile unit language) and returns
1045 /// it as a string. This is done at the metadata level because DIEs may
1046 /// not currently have been added to the parent context and walking the
1047 /// DIEs looking for names is more expensive than walking the metadata.
1048 std::string DwarfUnit::getParentContextString(DIScope Context) const {
1052 // FIXME: Decide whether to implement this for non-C++ languages.
1053 if (getLanguage() != dwarf::DW_LANG_C_plus_plus)
1057 SmallVector<DIScope, 1> Parents;
1058 while (!Context.isCompileUnit()) {
1059 Parents.push_back(Context);
1060 if (Context.getContext())
1061 Context = resolve(Context.getContext());
1063 // Structure, etc types will have a NULL context if they're at the top
1068 // Reverse iterate over our list to go from the outermost construct to the
1070 for (SmallVectorImpl<DIScope>::reverse_iterator I = Parents.rbegin(),
1074 StringRef Name = Ctx.getName();
1075 if (!Name.empty()) {
1083 /// constructTypeDIE - Construct basic type die from DIBasicType.
1084 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
1085 // Get core information.
1086 StringRef Name = BTy.getName();
1087 // Add name if not anonymous or intermediate type.
1089 addString(&Buffer, dwarf::DW_AT_name, Name);
1091 // An unspecified type only has a name attribute.
1092 if (BTy.getTag() == dwarf::DW_TAG_unspecified_type)
1095 addUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1098 uint64_t Size = BTy.getSizeInBits() >> 3;
1099 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1102 /// constructTypeDIE - Construct derived type die from DIDerivedType.
1103 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
1104 // Get core information.
1105 StringRef Name = DTy.getName();
1106 uint64_t Size = DTy.getSizeInBits() >> 3;
1107 uint16_t Tag = Buffer.getTag();
1109 // Map to main type, void will not have a type.
1110 DIType FromTy = resolve(DTy.getTypeDerivedFrom());
1112 addType(&Buffer, FromTy);
1114 // Add name if not anonymous or intermediate type.
1116 addString(&Buffer, dwarf::DW_AT_name, Name);
1118 // Add size if non-zero (derived types might be zero-sized.)
1119 if (Size && Tag != dwarf::DW_TAG_pointer_type)
1120 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1122 if (Tag == dwarf::DW_TAG_ptr_to_member_type)
1123 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type,
1124 getOrCreateTypeDIE(resolve(DTy.getClassType())));
1125 // Add source line info if available and TyDesc is not a forward declaration.
1126 if (!DTy.isForwardDecl())
1127 addSourceLine(&Buffer, DTy);
1130 /// constructTypeDIE - Construct type DIE from DICompositeType.
1131 void DwarfUnit::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
1132 // Add name if not anonymous or intermediate type.
1133 StringRef Name = CTy.getName();
1135 uint64_t Size = CTy.getSizeInBits() >> 3;
1136 uint16_t Tag = Buffer.getTag();
1139 case dwarf::DW_TAG_array_type:
1140 constructArrayTypeDIE(Buffer, CTy);
1142 case dwarf::DW_TAG_enumeration_type:
1143 constructEnumTypeDIE(Buffer, CTy);
1145 case dwarf::DW_TAG_subroutine_type: {
1146 // Add return type. A void return won't have a type.
1147 DIArray Elements = CTy.getTypeArray();
1148 DIType RTy(Elements.getElement(0));
1150 addType(&Buffer, RTy);
1152 bool isPrototyped = true;
1154 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
1155 DIDescriptor Ty = Elements.getElement(i);
1156 if (Ty.isUnspecifiedParameter()) {
1157 createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
1158 isPrototyped = false;
1160 DIE *Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
1161 addType(Arg, DIType(Ty));
1162 if (DIType(Ty).isArtificial())
1163 addFlag(Arg, dwarf::DW_AT_artificial);
1166 // Add prototype flag if we're dealing with a C language and the
1167 // function has been prototyped.
1168 uint16_t Language = getLanguage();
1170 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1171 Language == dwarf::DW_LANG_ObjC))
1172 addFlag(&Buffer, dwarf::DW_AT_prototyped);
1174 if (CTy.isLValueReference())
1175 addFlag(&Buffer, dwarf::DW_AT_reference);
1177 if (CTy.isRValueReference())
1178 addFlag(&Buffer, dwarf::DW_AT_rvalue_reference);
1180 case dwarf::DW_TAG_structure_type:
1181 case dwarf::DW_TAG_union_type:
1182 case dwarf::DW_TAG_class_type: {
1183 // Add elements to structure type.
1184 DIArray Elements = CTy.getTypeArray();
1185 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1186 DIDescriptor Element = Elements.getElement(i);
1187 DIE *ElemDie = NULL;
1188 if (Element.isSubprogram())
1189 ElemDie = getOrCreateSubprogramDIE(DISubprogram(Element));
1190 else if (Element.isDerivedType()) {
1191 DIDerivedType DDTy(Element);
1192 if (DDTy.getTag() == dwarf::DW_TAG_friend) {
1193 ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
1194 addType(ElemDie, resolve(DDTy.getTypeDerivedFrom()),
1195 dwarf::DW_AT_friend);
1196 } else if (DDTy.isStaticMember()) {
1197 getOrCreateStaticMemberDIE(DDTy);
1199 constructMemberDIE(Buffer, DDTy);
1201 } else if (Element.isObjCProperty()) {
1202 DIObjCProperty Property(Element);
1203 ElemDie = createAndAddDIE(Property.getTag(), Buffer);
1204 StringRef PropertyName = Property.getObjCPropertyName();
1205 addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
1206 if (Property.getType())
1207 addType(ElemDie, Property.getType());
1208 addSourceLine(ElemDie, Property);
1209 StringRef GetterName = Property.getObjCPropertyGetterName();
1210 if (!GetterName.empty())
1211 addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
1212 StringRef SetterName = Property.getObjCPropertySetterName();
1213 if (!SetterName.empty())
1214 addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
1215 unsigned PropertyAttributes = 0;
1216 if (Property.isReadOnlyObjCProperty())
1217 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readonly;
1218 if (Property.isReadWriteObjCProperty())
1219 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readwrite;
1220 if (Property.isAssignObjCProperty())
1221 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_assign;
1222 if (Property.isRetainObjCProperty())
1223 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_retain;
1224 if (Property.isCopyObjCProperty())
1225 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_copy;
1226 if (Property.isNonAtomicObjCProperty())
1227 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_nonatomic;
1228 if (PropertyAttributes)
1229 addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None,
1230 PropertyAttributes);
1232 DIEEntry *Entry = getDIEEntry(Element);
1234 Entry = createDIEEntry(ElemDie);
1235 insertDIEEntry(Element, Entry);
1241 if (CTy.isAppleBlockExtension())
1242 addFlag(&Buffer, dwarf::DW_AT_APPLE_block);
1244 DICompositeType ContainingType(resolve(CTy.getContainingType()));
1246 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type,
1247 getOrCreateTypeDIE(ContainingType));
1249 if (CTy.isObjcClassComplete())
1250 addFlag(&Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
1252 // Add template parameters to a class, structure or union types.
1253 // FIXME: The support isn't in the metadata for this yet.
1254 if (Tag == dwarf::DW_TAG_class_type ||
1255 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
1256 addTemplateParams(Buffer, CTy.getTemplateParams());
1264 // Add name if not anonymous or intermediate type.
1266 addString(&Buffer, dwarf::DW_AT_name, Name);
1268 if (Tag == dwarf::DW_TAG_enumeration_type ||
1269 Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
1270 Tag == dwarf::DW_TAG_union_type) {
1271 // Add size if non-zero (derived types might be zero-sized.)
1272 // TODO: Do we care about size for enum forward declarations?
1274 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1275 else if (!CTy.isForwardDecl())
1276 // Add zero size if it is not a forward declaration.
1277 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, 0);
1279 // If we're a forward decl, say so.
1280 if (CTy.isForwardDecl())
1281 addFlag(&Buffer, dwarf::DW_AT_declaration);
1283 // Add source line info if available.
1284 if (!CTy.isForwardDecl())
1285 addSourceLine(&Buffer, CTy);
1287 // No harm in adding the runtime language to the declaration.
1288 unsigned RLang = CTy.getRunTimeLang();
1290 addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
1295 /// constructTemplateTypeParameterDIE - Construct new DIE for the given
1296 /// DITemplateTypeParameter.
1297 void DwarfUnit::constructTemplateTypeParameterDIE(DIE &Buffer,
1298 DITemplateTypeParameter TP) {
1300 createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
1301 // Add the type if it exists, it could be void and therefore no type.
1303 addType(ParamDIE, resolve(TP.getType()));
1304 if (!TP.getName().empty())
1305 addString(ParamDIE, dwarf::DW_AT_name, TP.getName());
1308 /// constructTemplateValueParameterDIE - Construct new DIE for the given
1309 /// DITemplateValueParameter.
1311 DwarfUnit::constructTemplateValueParameterDIE(DIE &Buffer,
1312 DITemplateValueParameter VP) {
1313 DIE *ParamDIE = createAndAddDIE(VP.getTag(), Buffer);
1315 // Add the type if there is one, template template and template parameter
1316 // packs will not have a type.
1317 if (VP.getTag() == dwarf::DW_TAG_template_value_parameter)
1318 addType(ParamDIE, resolve(VP.getType()));
1319 if (!VP.getName().empty())
1320 addString(ParamDIE, dwarf::DW_AT_name, VP.getName());
1321 if (Value *Val = VP.getValue()) {
1322 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val))
1323 addConstantValue(ParamDIE, CI,
1324 isUnsignedDIType(DD, resolve(VP.getType())));
1325 else if (GlobalValue *GV = dyn_cast<GlobalValue>(Val)) {
1326 // For declaration non-type template parameters (such as global values and
1328 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1329 addOpAddress(Block, Asm->getSymbol(GV));
1330 // Emit DW_OP_stack_value to use the address as the immediate value of the
1331 // parameter, rather than a pointer to it.
1332 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
1333 addBlock(ParamDIE, dwarf::DW_AT_location, Block);
1334 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1335 assert(isa<MDString>(Val));
1336 addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
1337 cast<MDString>(Val)->getString());
1338 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1339 assert(isa<MDNode>(Val));
1340 DIArray A(cast<MDNode>(Val));
1341 addTemplateParams(*ParamDIE, A);
1346 /// getOrCreateNameSpace - Create a DIE for DINameSpace.
1347 DIE *DwarfUnit::getOrCreateNameSpace(DINameSpace NS) {
1348 // Construct the context before querying for the existence of the DIE in case
1349 // such construction creates the DIE.
1350 DIE *ContextDIE = getOrCreateContextDIE(NS.getContext());
1352 DIE *NDie = getDIE(NS);
1355 NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS);
1357 if (!NS.getName().empty()) {
1358 addString(NDie, dwarf::DW_AT_name, NS.getName());
1359 addAccelNamespace(NS.getName(), NDie);
1360 addGlobalName(NS.getName(), NDie, NS.getContext());
1362 addAccelNamespace("(anonymous namespace)", NDie);
1363 addSourceLine(NDie, NS);
1367 /// getOrCreateSubprogramDIE - Create new DIE using SP.
1368 DIE *DwarfUnit::getOrCreateSubprogramDIE(DISubprogram SP) {
1369 // Construct the context before querying for the existence of the DIE in case
1370 // such construction creates the DIE (as is the case for member function
1372 DIE *ContextDIE = getOrCreateContextDIE(resolve(SP.getContext()));
1374 DIE *SPDie = getDIE(SP);
1378 DISubprogram SPDecl = SP.getFunctionDeclaration();
1379 if (SPDecl.isSubprogram())
1380 // Add subprogram definitions to the CU die directly.
1381 ContextDIE = UnitDie.get();
1383 // DW_TAG_inlined_subroutine may refer to this DIE.
1384 SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
1386 DIE *DeclDie = NULL;
1387 if (SPDecl.isSubprogram())
1388 DeclDie = getOrCreateSubprogramDIE(SPDecl);
1390 // Add function template parameters.
1391 addTemplateParams(*SPDie, SP.getTemplateParams());
1393 // If this DIE is going to refer declaration info using AT_specification
1394 // then there is no need to add other attributes.
1396 // Refer function declaration directly.
1397 addDIEEntry(SPDie, dwarf::DW_AT_specification, DeclDie);
1402 // Add the linkage name if we have one.
1403 StringRef LinkageName = SP.getLinkageName();
1404 if (!LinkageName.empty())
1405 addString(SPDie, dwarf::DW_AT_MIPS_linkage_name,
1406 GlobalValue::getRealLinkageName(LinkageName));
1408 // Constructors and operators for anonymous aggregates do not have names.
1409 if (!SP.getName().empty())
1410 addString(SPDie, dwarf::DW_AT_name, SP.getName());
1412 addSourceLine(SPDie, SP);
1414 // Add the prototype if we have a prototype and we have a C like
1416 uint16_t Language = getLanguage();
1417 if (SP.isPrototyped() &&
1418 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1419 Language == dwarf::DW_LANG_ObjC))
1420 addFlag(SPDie, dwarf::DW_AT_prototyped);
1422 DICompositeType SPTy = SP.getType();
1423 assert(SPTy.getTag() == dwarf::DW_TAG_subroutine_type &&
1424 "the type of a subprogram should be a subroutine");
1426 DIArray Args = SPTy.getTypeArray();
1427 // Add a return type. If this is a type like a C/C++ void type we don't add a
1429 if (Args.getElement(0))
1430 addType(SPDie, DIType(Args.getElement(0)));
1432 unsigned VK = SP.getVirtuality();
1434 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1435 DIEBlock *Block = getDIEBlock();
1436 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1437 addUInt(Block, dwarf::DW_FORM_udata, SP.getVirtualIndex());
1438 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
1439 ContainingTypeMap.insert(
1440 std::make_pair(SPDie, resolve(SP.getContainingType())));
1443 if (!SP.isDefinition()) {
1444 addFlag(SPDie, dwarf::DW_AT_declaration);
1446 // Add arguments. Do not add arguments for subprogram definition. They will
1447 // be handled while processing variables.
1448 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1449 DIE *Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, *SPDie);
1450 DIType ATy(Args.getElement(i));
1452 if (ATy.isArtificial())
1453 addFlag(Arg, dwarf::DW_AT_artificial);
1457 if (SP.isArtificial())
1458 addFlag(SPDie, dwarf::DW_AT_artificial);
1460 if (!SP.isLocalToUnit())
1461 addFlag(SPDie, dwarf::DW_AT_external);
1463 if (SP.isOptimized())
1464 addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1466 if (unsigned isa = Asm->getISAEncoding()) {
1467 addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1470 if (SP.isLValueReference())
1471 addFlag(SPDie, dwarf::DW_AT_reference);
1473 if (SP.isRValueReference())
1474 addFlag(SPDie, dwarf::DW_AT_rvalue_reference);
1476 if (SP.isProtected())
1477 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1478 dwarf::DW_ACCESS_protected);
1479 else if (SP.isPrivate())
1480 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1481 dwarf::DW_ACCESS_private);
1483 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1484 dwarf::DW_ACCESS_public);
1486 if (SP.isExplicit())
1487 addFlag(SPDie, dwarf::DW_AT_explicit);
1492 // Return const expression if value is a GEP to access merged global
1494 // i8* getelementptr ({ i8, i8, i8, i8 }* @_MergedGlobals, i32 0, i32 0)
1495 static const ConstantExpr *getMergedGlobalExpr(const Value *V) {
1496 const ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(V);
1497 if (!CE || CE->getNumOperands() != 3 ||
1498 CE->getOpcode() != Instruction::GetElementPtr)
1501 // First operand points to a global struct.
1502 Value *Ptr = CE->getOperand(0);
1503 if (!isa<GlobalValue>(Ptr) ||
1504 !isa<StructType>(cast<PointerType>(Ptr->getType())->getElementType()))
1507 // Second operand is zero.
1508 const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(CE->getOperand(1));
1509 if (!CI || !CI->isZero())
1512 // Third operand is offset.
1513 if (!isa<ConstantInt>(CE->getOperand(2)))
1519 /// createGlobalVariableDIE - create global variable DIE.
1520 void DwarfCompileUnit::createGlobalVariableDIE(DIGlobalVariable GV) {
1521 // Check for pre-existence.
1525 assert(GV.isGlobalVariable());
1527 DIScope GVContext = GV.getContext();
1528 DIType GTy = GV.getType();
1530 // If this is a static data member definition, some attributes belong
1531 // to the declaration DIE.
1532 DIE *VariableDIE = NULL;
1533 bool IsStaticMember = false;
1534 DIDerivedType SDMDecl = GV.getStaticDataMemberDeclaration();
1535 if (SDMDecl.Verify()) {
1536 assert(SDMDecl.isStaticMember() && "Expected static member decl");
1537 // We need the declaration DIE that is in the static member's class.
1538 VariableDIE = getOrCreateStaticMemberDIE(SDMDecl);
1539 IsStaticMember = true;
1542 // If this is not a static data member definition, create the variable
1543 // DIE and add the initial set of attributes to it.
1545 // Construct the context before querying for the existence of the DIE in
1546 // case such construction creates the DIE.
1547 DIE *ContextDIE = getOrCreateContextDIE(GVContext);
1550 VariableDIE = createAndAddDIE(GV.getTag(), *ContextDIE, GV);
1552 // Add name and type.
1553 addString(VariableDIE, dwarf::DW_AT_name, GV.getDisplayName());
1554 addType(VariableDIE, GTy);
1556 // Add scoping info.
1557 if (!GV.isLocalToUnit())
1558 addFlag(VariableDIE, dwarf::DW_AT_external);
1560 // Add line number info.
1561 addSourceLine(VariableDIE, GV);
1565 bool addToAccelTable = false;
1566 DIE *VariableSpecDIE = NULL;
1567 bool isGlobalVariable = GV.getGlobal() != NULL;
1568 if (isGlobalVariable) {
1569 addToAccelTable = true;
1570 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1571 const MCSymbol *Sym = Asm->getSymbol(GV.getGlobal());
1572 if (GV.getGlobal()->isThreadLocal()) {
1573 // FIXME: Make this work with -gsplit-dwarf.
1574 unsigned PointerSize = Asm->getDataLayout().getPointerSize();
1575 assert((PointerSize == 4 || PointerSize == 8) &&
1576 "Add support for other sizes if necessary");
1577 const MCExpr *Expr =
1578 Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym);
1579 // Based on GCC's support for TLS:
1580 if (!DD->useSplitDwarf()) {
1581 // 1) Start with a constNu of the appropriate pointer size
1582 addUInt(Block, dwarf::DW_FORM_data1,
1583 PointerSize == 4 ? dwarf::DW_OP_const4u : dwarf::DW_OP_const8u);
1584 // 2) containing the (relocated) offset of the TLS variable
1585 // within the module's TLS block.
1586 addExpr(Block, dwarf::DW_FORM_udata, Expr);
1588 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
1589 addUInt(Block, dwarf::DW_FORM_udata, DU->getAddrPoolIndex(Expr));
1591 // 3) followed by a custom OP to make the debugger do a TLS lookup.
1592 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_push_tls_address);
1594 DD->addArangeLabel(SymbolCU(this, Sym));
1595 addOpAddress(Block, Sym);
1597 // Do not create specification DIE if context is either compile unit
1599 if (GVContext && GV.isDefinition() && !GVContext.isCompileUnit() &&
1600 !GVContext.isFile() && !DD->isSubprogramContext(GVContext)) {
1601 // Create specification DIE.
1602 VariableSpecDIE = createAndAddDIE(dwarf::DW_TAG_variable, *UnitDie);
1603 addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification, VariableDIE);
1604 addBlock(VariableSpecDIE, dwarf::DW_AT_location, Block);
1605 // A static member's declaration is already flagged as such.
1606 if (!SDMDecl.Verify())
1607 addFlag(VariableDIE, dwarf::DW_AT_declaration);
1609 addBlock(VariableDIE, dwarf::DW_AT_location, Block);
1611 // Add the linkage name.
1612 StringRef LinkageName = GV.getLinkageName();
1613 if (!LinkageName.empty())
1614 // From DWARF4: DIEs to which DW_AT_linkage_name may apply include:
1615 // TAG_common_block, TAG_constant, TAG_entry_point, TAG_subprogram and
1617 addString(IsStaticMember && VariableSpecDIE ? VariableSpecDIE
1619 dwarf::DW_AT_MIPS_linkage_name,
1620 GlobalValue::getRealLinkageName(LinkageName));
1621 } else if (const ConstantInt *CI =
1622 dyn_cast_or_null<ConstantInt>(GV.getConstant())) {
1623 // AT_const_value was added when the static member was created. To avoid
1624 // emitting AT_const_value multiple times, we only add AT_const_value when
1625 // it is not a static member.
1626 if (!IsStaticMember)
1627 addConstantValue(VariableDIE, CI, isUnsignedDIType(DD, GTy));
1628 } else if (const ConstantExpr *CE = getMergedGlobalExpr(GV->getOperand(11))) {
1629 addToAccelTable = true;
1630 // GV is a merged global.
1631 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1632 Value *Ptr = CE->getOperand(0);
1633 MCSymbol *Sym = Asm->getSymbol(cast<GlobalValue>(Ptr));
1634 DD->addArangeLabel(SymbolCU(this, Sym));
1635 addOpAddress(Block, Sym);
1636 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1637 SmallVector<Value *, 3> Idx(CE->op_begin() + 1, CE->op_end());
1638 addUInt(Block, dwarf::DW_FORM_udata,
1639 Asm->getDataLayout().getIndexedOffset(Ptr->getType(), Idx));
1640 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1641 addBlock(VariableDIE, dwarf::DW_AT_location, Block);
1644 if (addToAccelTable) {
1645 DIE *AddrDIE = VariableSpecDIE ? VariableSpecDIE : VariableDIE;
1646 addAccelName(GV.getName(), AddrDIE);
1648 // If the linkage name is different than the name, go ahead and output
1649 // that as well into the name table.
1650 if (GV.getLinkageName() != "" && GV.getName() != GV.getLinkageName())
1651 addAccelName(GV.getLinkageName(), AddrDIE);
1654 if (!GV.isLocalToUnit())
1655 addGlobalName(GV.getName(), VariableSpecDIE ? VariableSpecDIE : VariableDIE,
1659 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
1660 void DwarfUnit::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy) {
1661 DIE *DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
1662 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, IndexTy);
1664 // The LowerBound value defines the lower bounds which is typically zero for
1665 // C/C++. The Count value is the number of elements. Values are 64 bit. If
1666 // Count == -1 then the array is unbounded and we do not emit
1667 // DW_AT_lower_bound and DW_AT_upper_bound attributes. If LowerBound == 0 and
1668 // Count == 0, then the array has zero elements in which case we do not emit
1670 int64_t LowerBound = SR.getLo();
1671 int64_t DefaultLowerBound = getDefaultLowerBound();
1672 int64_t Count = SR.getCount();
1674 if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
1675 addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound);
1677 if (Count != -1 && Count != 0)
1678 // FIXME: An unbounded array should reference the expression that defines
1680 addUInt(DW_Subrange, dwarf::DW_AT_upper_bound, None,
1681 LowerBound + Count - 1);
1684 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
1685 void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, DICompositeType CTy) {
1687 addFlag(&Buffer, dwarf::DW_AT_GNU_vector);
1689 // Emit the element type.
1690 addType(&Buffer, resolve(CTy.getTypeDerivedFrom()));
1692 // Get an anonymous type for index type.
1693 // FIXME: This type should be passed down from the front end
1694 // as different languages may have different sizes for indexes.
1695 DIE *IdxTy = getIndexTyDie();
1697 // Construct an anonymous type for index type.
1698 IdxTy = createAndAddDIE(dwarf::DW_TAG_base_type, *UnitDie);
1699 addString(IdxTy, dwarf::DW_AT_name, "int");
1700 addUInt(IdxTy, dwarf::DW_AT_byte_size, None, sizeof(int32_t));
1701 addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1702 dwarf::DW_ATE_signed);
1703 setIndexTyDie(IdxTy);
1706 // Add subranges to array type.
1707 DIArray Elements = CTy.getTypeArray();
1708 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1709 DIDescriptor Element = Elements.getElement(i);
1710 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1711 constructSubrangeDIE(Buffer, DISubrange(Element), IdxTy);
1715 /// constructEnumTypeDIE - Construct an enum type DIE from DICompositeType.
1716 void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, DICompositeType CTy) {
1717 DIArray Elements = CTy.getTypeArray();
1719 // Add enumerators to enumeration type.
1720 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1721 DIEnumerator Enum(Elements.getElement(i));
1722 if (Enum.isEnumerator()) {
1723 DIE *Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
1724 StringRef Name = Enum.getName();
1725 addString(Enumerator, dwarf::DW_AT_name, Name);
1726 int64_t Value = Enum.getEnumValue();
1727 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
1731 DIType DTy = resolve(CTy.getTypeDerivedFrom());
1733 addType(&Buffer, DTy);
1734 addFlag(&Buffer, dwarf::DW_AT_enum_class);
1738 /// constructContainingTypeDIEs - Construct DIEs for types that contain
1740 void DwarfUnit::constructContainingTypeDIEs() {
1741 for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(),
1742 CE = ContainingTypeMap.end();
1744 DIE *SPDie = CI->first;
1745 DIDescriptor D(CI->second);
1748 DIE *NDie = getDIE(D);
1751 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, NDie);
1755 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
1756 DIE *DwarfUnit::constructVariableDIE(DbgVariable &DV, bool isScopeAbstract) {
1757 StringRef Name = DV.getName();
1759 // Define variable debug information entry.
1760 DIE *VariableDie = new DIE(DV.getTag());
1761 DbgVariable *AbsVar = DV.getAbstractVariable();
1762 DIE *AbsDIE = AbsVar ? AbsVar->getDIE() : NULL;
1764 addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin, AbsDIE);
1767 addString(VariableDie, dwarf::DW_AT_name, Name);
1768 addSourceLine(VariableDie, DV.getVariable());
1769 addType(VariableDie, DV.getType());
1772 if (DV.isArtificial())
1773 addFlag(VariableDie, dwarf::DW_AT_artificial);
1775 if (isScopeAbstract) {
1776 DV.setDIE(VariableDie);
1780 // Add variable address.
1782 unsigned Offset = DV.getDotDebugLocOffset();
1783 if (Offset != ~0U) {
1784 addSectionLabel(VariableDie, dwarf::DW_AT_location,
1785 Asm->GetTempSymbol("debug_loc", Offset));
1786 DV.setDIE(VariableDie);
1790 // Check if variable is described by a DBG_VALUE instruction.
1791 if (const MachineInstr *DVInsn = DV.getMInsn()) {
1792 assert(DVInsn->getNumOperands() == 3);
1793 if (DVInsn->getOperand(0).isReg()) {
1794 const MachineOperand RegOp = DVInsn->getOperand(0);
1795 // If the second operand is an immediate, this is an indirect value.
1796 if (DVInsn->getOperand(1).isImm()) {
1797 MachineLocation Location(RegOp.getReg(),
1798 DVInsn->getOperand(1).getImm());
1799 addVariableAddress(DV, VariableDie, Location);
1800 } else if (RegOp.getReg())
1801 addVariableAddress(DV, VariableDie, MachineLocation(RegOp.getReg()));
1802 } else if (DVInsn->getOperand(0).isImm())
1803 addConstantValue(VariableDie, DVInsn->getOperand(0), DV.getType());
1804 else if (DVInsn->getOperand(0).isFPImm())
1805 addConstantFPValue(VariableDie, DVInsn->getOperand(0));
1806 else if (DVInsn->getOperand(0).isCImm())
1807 addConstantValue(VariableDie, DVInsn->getOperand(0).getCImm(),
1808 isUnsignedDIType(DD, DV.getType()));
1810 DV.setDIE(VariableDie);
1813 // .. else use frame index.
1814 int FI = DV.getFrameIndex();
1816 unsigned FrameReg = 0;
1817 const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
1818 int Offset = TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
1819 MachineLocation Location(FrameReg, Offset);
1820 addVariableAddress(DV, VariableDie, Location);
1824 DV.setDIE(VariableDie);
1828 /// constructMemberDIE - Construct member DIE from DIDerivedType.
1829 void DwarfUnit::constructMemberDIE(DIE &Buffer, DIDerivedType DT) {
1830 DIE *MemberDie = createAndAddDIE(DT.getTag(), Buffer);
1831 StringRef Name = DT.getName();
1833 addString(MemberDie, dwarf::DW_AT_name, Name);
1835 addType(MemberDie, resolve(DT.getTypeDerivedFrom()));
1837 addSourceLine(MemberDie, DT);
1839 if (DT.getTag() == dwarf::DW_TAG_inheritance && DT.isVirtual()) {
1841 // For C++, virtual base classes are not at fixed offset. Use following
1842 // expression to extract appropriate offset from vtable.
1843 // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1845 DIEBlock *VBaseLocationDie = new (DIEValueAllocator) DIEBlock();
1846 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1847 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1848 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1849 addUInt(VBaseLocationDie, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1850 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1851 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1852 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1854 addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
1856 uint64_t Size = DT.getSizeInBits();
1857 uint64_t FieldSize = getBaseTypeSize(DD, DT);
1858 uint64_t OffsetInBytes;
1860 if (Size != FieldSize) {
1862 addUInt(MemberDie, dwarf::DW_AT_byte_size, None,
1863 getBaseTypeSize(DD, DT) >> 3);
1864 addUInt(MemberDie, dwarf::DW_AT_bit_size, None, DT.getSizeInBits());
1866 uint64_t Offset = DT.getOffsetInBits();
1867 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1868 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1869 uint64_t FieldOffset = (HiMark - FieldSize);
1870 Offset -= FieldOffset;
1872 // Maybe we need to work from the other end.
1873 if (Asm->getDataLayout().isLittleEndian())
1874 Offset = FieldSize - (Offset + Size);
1875 addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset);
1877 // Here DW_AT_data_member_location points to the anonymous
1878 // field that includes this bit field.
1879 OffsetInBytes = FieldOffset >> 3;
1881 // This is not a bitfield.
1882 OffsetInBytes = DT.getOffsetInBits() >> 3;
1884 if (DD->getDwarfVersion() <= 2) {
1885 DIEBlock *MemLocationDie = new (DIEValueAllocator) DIEBlock();
1886 addUInt(MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1887 addUInt(MemLocationDie, dwarf::DW_FORM_udata, OffsetInBytes);
1888 addBlock(MemberDie, dwarf::DW_AT_data_member_location, MemLocationDie);
1890 addUInt(MemberDie, dwarf::DW_AT_data_member_location, None,
1894 if (DT.isProtected())
1895 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1896 dwarf::DW_ACCESS_protected);
1897 else if (DT.isPrivate())
1898 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1899 dwarf::DW_ACCESS_private);
1900 // Otherwise C++ member and base classes are considered public.
1902 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1903 dwarf::DW_ACCESS_public);
1905 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1906 dwarf::DW_VIRTUALITY_virtual);
1908 // Objective-C properties.
1909 if (MDNode *PNode = DT.getObjCProperty())
1910 if (DIEEntry *PropertyDie = getDIEEntry(PNode))
1911 MemberDie->addValue(dwarf::DW_AT_APPLE_property, dwarf::DW_FORM_ref4,
1914 if (DT.isArtificial())
1915 addFlag(MemberDie, dwarf::DW_AT_artificial);
1918 /// getOrCreateStaticMemberDIE - Create new DIE for C++ static member.
1919 DIE *DwarfUnit::getOrCreateStaticMemberDIE(DIDerivedType DT) {
1923 // Construct the context before querying for the existence of the DIE in case
1924 // such construction creates the DIE.
1925 DIE *ContextDIE = getOrCreateContextDIE(resolve(DT.getContext()));
1926 assert(dwarf::isType(ContextDIE->getTag()) &&
1927 "Static member should belong to a type.");
1929 DIE *StaticMemberDIE = getDIE(DT);
1930 if (StaticMemberDIE)
1931 return StaticMemberDIE;
1933 StaticMemberDIE = createAndAddDIE(DT.getTag(), *ContextDIE, DT);
1935 DIType Ty = resolve(DT.getTypeDerivedFrom());
1937 addString(StaticMemberDIE, dwarf::DW_AT_name, DT.getName());
1938 addType(StaticMemberDIE, Ty);
1939 addSourceLine(StaticMemberDIE, DT);
1940 addFlag(StaticMemberDIE, dwarf::DW_AT_external);
1941 addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
1943 // FIXME: We could omit private if the parent is a class_type, and
1944 // public if the parent is something else.
1945 if (DT.isProtected())
1946 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1947 dwarf::DW_ACCESS_protected);
1948 else if (DT.isPrivate())
1949 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1950 dwarf::DW_ACCESS_private);
1952 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1953 dwarf::DW_ACCESS_public);
1955 if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT.getConstant()))
1956 addConstantValue(StaticMemberDIE, CI, isUnsignedDIType(DD, Ty));
1957 if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT.getConstant()))
1958 addConstantFPValue(StaticMemberDIE, CFP);
1960 return StaticMemberDIE;
1963 void DwarfUnit::emitHeader(const MCSection *ASection,
1964 const MCSymbol *ASectionSym) const {
1965 Asm->OutStreamer.AddComment("DWARF version number");
1966 Asm->EmitInt16(DD->getDwarfVersion());
1967 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
1968 // We share one abbreviations table across all units so it's always at the
1969 // start of the section. Use a relocatable offset where needed to ensure
1970 // linking doesn't invalidate that offset.
1971 Asm->EmitSectionOffset(ASectionSym, ASectionSym);
1972 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1973 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
1976 DwarfCompileUnit::~DwarfCompileUnit() {}
1977 DwarfTypeUnit::~DwarfTypeUnit() {}
1979 void DwarfTypeUnit::emitHeader(const MCSection *ASection,
1980 const MCSymbol *ASectionSym) const {
1981 DwarfUnit::emitHeader(ASection, ASectionSym);
1982 Asm->OutStreamer.AddComment("Type Signature");
1983 Asm->OutStreamer.EmitIntValue(TypeSignature, sizeof(TypeSignature));
1984 Asm->OutStreamer.AddComment("Type DIE Offset");
1985 // In a skeleton type unit there is no type DIE so emit a zero offset.
1986 Asm->OutStreamer.EmitIntValue(Ty ? Ty->getOffset() : 0,
1987 sizeof(Ty->getOffset()));
1990 void DwarfTypeUnit::initSection(const MCSection *Section) {
1991 assert(!this->Section);
1992 this->Section = Section;
1993 // Since each type unit is contained in its own COMDAT section, the begin
1994 // label and the section label are the same. Using the begin label emission in
1995 // DwarfDebug to emit the section label as well is slightly subtle/sneaky, but
1996 // the only other alternative of lazily constructing start-of-section labels
1997 // and storing a mapping in DwarfDebug (or AsmPrinter).
1998 this->SectionSym = this->LabelBegin =
1999 Asm->GetTempSymbol(Section->getLabelBeginName(), getUniqueID());
2001 Asm->GetTempSymbol(Section->getLabelEndName(), getUniqueID());
2002 this->LabelRange = Asm->GetTempSymbol("gnu_ranges", getUniqueID());