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/IR/Constants.h"
21 #include "llvm/IR/DIBuilder.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/GlobalVariable.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/IR/Mangler.h"
26 #include "llvm/MC/MCAsmInfo.h"
27 #include "llvm/MC/MCContext.h"
28 #include "llvm/MC/MCSection.h"
29 #include "llvm/MC/MCStreamer.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Target/TargetFrameLowering.h"
32 #include "llvm/Target/TargetLoweringObjectFile.h"
33 #include "llvm/Target/TargetMachine.h"
34 #include "llvm/Target/TargetRegisterInfo.h"
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) {}
62 /// ~Unit - Destructor for compile unit.
63 DwarfUnit::~DwarfUnit() {
64 for (unsigned j = 0, M = DIEBlocks.size(); j < M; ++j)
65 DIEBlocks[j]->~DIEBlock();
66 for (unsigned j = 0, M = DIELocs.size(); j < M; ++j)
67 DIELocs[j]->~DIELoc();
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(DIE *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(DIELoc *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(DIELoc *Die, dwarf::Form Form, const MCExpr *Expr) {
230 DIEValue *Value = new (DIEValueAllocator) DIEExpr(Expr);
231 Die->addValue((dwarf::Attribute)0, Form, Value);
234 /// addLocationList - Add a Dwarf loclistptr attribute data and value.
236 void DwarfUnit::addLocationList(DIE *Die, dwarf::Attribute Attribute,
238 DIEValue *Value = new (DIEValueAllocator) DIELocList(Index);
239 dwarf::Form Form = DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
240 : dwarf::DW_FORM_data4;
241 Die->addValue(Attribute, Form, Value);
244 /// addLabel - Add a Dwarf label attribute data and value.
246 void DwarfUnit::addLabel(DIE *Die, dwarf::Attribute Attribute, dwarf::Form Form,
247 const MCSymbol *Label) {
248 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
249 Die->addValue(Attribute, Form, Value);
252 void DwarfUnit::addLabel(DIELoc *Die, dwarf::Form Form, const MCSymbol *Label) {
253 addLabel(Die, (dwarf::Attribute)0, Form, Label);
256 /// addSectionLabel - Add a Dwarf section label attribute data and value.
258 void DwarfUnit::addSectionLabel(DIE *Die, dwarf::Attribute Attribute,
259 const MCSymbol *Label) {
260 if (DD->getDwarfVersion() >= 4)
261 addLabel(Die, Attribute, dwarf::DW_FORM_sec_offset, Label);
263 addLabel(Die, Attribute, dwarf::DW_FORM_data4, Label);
266 /// addSectionOffset - Add an offset into a section attribute data and value.
268 void DwarfUnit::addSectionOffset(DIE *Die, dwarf::Attribute Attribute,
270 if (DD->getDwarfVersion() >= 4)
271 addUInt(Die, Attribute, dwarf::DW_FORM_sec_offset, Integer);
273 addUInt(Die, Attribute, dwarf::DW_FORM_data4, Integer);
276 /// addLabelAddress - Add a dwarf label attribute data and value using
277 /// DW_FORM_addr or DW_FORM_GNU_addr_index.
279 void DwarfCompileUnit::addLabelAddress(DIE *Die, dwarf::Attribute Attribute,
282 DD->addArangeLabel(SymbolCU(this, Label));
284 if (!DD->useSplitDwarf()) {
286 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
287 Die->addValue(Attribute, dwarf::DW_FORM_addr, Value);
289 DIEValue *Value = new (DIEValueAllocator) DIEInteger(0);
290 Die->addValue(Attribute, dwarf::DW_FORM_addr, Value);
293 unsigned idx = DU->getAddrPoolIndex(Label);
294 DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
295 Die->addValue(Attribute, dwarf::DW_FORM_GNU_addr_index, Value);
299 /// addOpAddress - Add a dwarf op address data and value using the
300 /// form given and an op of either DW_FORM_addr or DW_FORM_GNU_addr_index.
302 void DwarfUnit::addOpAddress(DIELoc *Die, const MCSymbol *Sym) {
303 if (!DD->useSplitDwarf()) {
304 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
305 addLabel(Die, dwarf::DW_FORM_udata, Sym);
307 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index);
308 addUInt(Die, dwarf::DW_FORM_GNU_addr_index, DU->getAddrPoolIndex(Sym));
312 /// addSectionDelta - Add a section label delta attribute data and value.
314 void DwarfUnit::addSectionDelta(DIE *Die, dwarf::Attribute Attribute,
315 const MCSymbol *Hi, const MCSymbol *Lo) {
316 DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
317 if (DD->getDwarfVersion() >= 4)
318 Die->addValue(Attribute, dwarf::DW_FORM_sec_offset, Value);
320 Die->addValue(Attribute, dwarf::DW_FORM_data4, Value);
323 void DwarfUnit::addLabelDelta(DIE *Die, dwarf::Attribute Attribute,
324 const MCSymbol *Hi, const MCSymbol *Lo) {
325 DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
326 Die->addValue(Attribute, dwarf::DW_FORM_data4, Value);
329 /// addDIEEntry - Add a DIE attribute data and value.
331 void DwarfUnit::addDIEEntry(DIE *Die, dwarf::Attribute Attribute, DIE *Entry) {
332 addDIEEntry(Die, Attribute, createDIEEntry(Entry));
335 void DwarfUnit::addDIETypeSignature(DIE *Die, const DwarfTypeUnit &Type) {
336 Die->addValue(dwarf::DW_AT_signature, dwarf::DW_FORM_ref_sig8,
337 new (DIEValueAllocator) DIETypeSignature(Type));
340 void DwarfUnit::addDIEEntry(DIE *Die, dwarf::Attribute Attribute,
342 const DIE *DieCU = Die->getUnitOrNull();
343 const DIE *EntryCU = Entry->getEntry()->getUnitOrNull();
345 // We assume that Die belongs to this CU, if it is not linked to any CU yet.
346 DieCU = getUnitDie();
348 EntryCU = getUnitDie();
349 Die->addValue(Attribute, EntryCU == DieCU ? dwarf::DW_FORM_ref4
350 : dwarf::DW_FORM_ref_addr,
354 /// Create a DIE with the given Tag, add the DIE to its parent, and
355 /// call insertDIE if MD is not null.
356 DIE *DwarfUnit::createAndAddDIE(unsigned Tag, DIE &Parent, DIDescriptor N) {
357 DIE *Die = new DIE(Tag);
358 Parent.addChild(Die);
364 /// addBlock - Add block data.
366 void DwarfUnit::addBlock(DIE *Die, dwarf::Attribute Attribute, DIELoc *Loc) {
367 Loc->ComputeSize(Asm);
368 DIELocs.push_back(Loc); // Memoize so we can call the destructor later on.
369 Die->addValue(Attribute, Loc->BestForm(DD->getDwarfVersion()), Loc);
372 void DwarfUnit::addBlock(DIE *Die, dwarf::Attribute Attribute,
374 Block->ComputeSize(Asm);
375 DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
376 Die->addValue(Attribute, Block->BestForm(), Block);
379 /// addSourceLine - Add location information to specified debug information
381 void DwarfUnit::addSourceLine(DIE *Die, unsigned Line, StringRef File,
382 StringRef Directory) {
387 DD->getOrCreateSourceID(File, Directory, getCU().getUniqueID());
388 assert(FileID && "Invalid file id");
389 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
390 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
393 /// addSourceLine - Add location information to specified debug information
395 void DwarfUnit::addSourceLine(DIE *Die, DIVariable V) {
396 assert(V.isVariable());
398 addSourceLine(Die, V.getLineNumber(), V.getContext().getFilename(),
399 V.getContext().getDirectory());
402 /// addSourceLine - Add location information to specified debug information
404 void DwarfUnit::addSourceLine(DIE *Die, DIGlobalVariable G) {
405 assert(G.isGlobalVariable());
407 addSourceLine(Die, G.getLineNumber(), G.getFilename(), G.getDirectory());
410 /// addSourceLine - Add location information to specified debug information
412 void DwarfUnit::addSourceLine(DIE *Die, DISubprogram SP) {
413 assert(SP.isSubprogram());
415 addSourceLine(Die, SP.getLineNumber(), SP.getFilename(), SP.getDirectory());
418 /// addSourceLine - Add location information to specified debug information
420 void DwarfUnit::addSourceLine(DIE *Die, DIType Ty) {
423 addSourceLine(Die, Ty.getLineNumber(), Ty.getFilename(), Ty.getDirectory());
426 /// addSourceLine - Add location information to specified debug information
428 void DwarfUnit::addSourceLine(DIE *Die, DIObjCProperty Ty) {
429 assert(Ty.isObjCProperty());
431 DIFile File = Ty.getFile();
432 addSourceLine(Die, Ty.getLineNumber(), File.getFilename(),
433 File.getDirectory());
436 /// addSourceLine - Add location information to specified debug information
438 void DwarfUnit::addSourceLine(DIE *Die, DINameSpace NS) {
441 addSourceLine(Die, NS.getLineNumber(), NS.getFilename(), NS.getDirectory());
444 /// addVariableAddress - Add DW_AT_location attribute for a
445 /// DbgVariable based on provided MachineLocation.
446 void DwarfUnit::addVariableAddress(const DbgVariable &DV, DIE *Die,
447 MachineLocation Location) {
448 if (DV.variableHasComplexAddress())
449 addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
450 else if (DV.isBlockByrefVariable())
451 addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location);
453 addAddress(Die, dwarf::DW_AT_location, Location,
454 DV.getVariable().isIndirect());
457 /// addRegisterOp - Add register operand.
458 void DwarfUnit::addRegisterOp(DIELoc *TheDie, unsigned Reg) {
459 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
460 int DWReg = RI->getDwarfRegNum(Reg, false);
461 bool isSubRegister = DWReg < 0;
465 // Go up the super-register chain until we hit a valid dwarf register number.
466 for (MCSuperRegIterator SR(Reg, RI); SR.isValid() && DWReg < 0; ++SR) {
467 DWReg = RI->getDwarfRegNum(*SR, false);
469 Idx = RI->getSubRegIndex(*SR, Reg);
473 DEBUG(dbgs() << "Invalid Dwarf register number.\n");
474 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_nop);
480 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + DWReg);
482 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
483 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
488 unsigned Size = RI->getSubRegIdxSize(Idx);
489 unsigned Offset = RI->getSubRegIdxOffset(Idx);
491 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_bit_piece);
492 addUInt(TheDie, dwarf::DW_FORM_data1, Size);
493 addUInt(TheDie, dwarf::DW_FORM_data1, Offset);
495 unsigned ByteSize = Size / 8; // Assuming 8 bits per byte.
496 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_piece);
497 addUInt(TheDie, dwarf::DW_FORM_data1, ByteSize);
502 /// addRegisterOffset - Add register offset.
503 void DwarfUnit::addRegisterOffset(DIELoc *TheDie, unsigned Reg,
505 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
506 unsigned DWReg = RI->getDwarfRegNum(Reg, false);
507 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
508 if (Reg == TRI->getFrameRegister(*Asm->MF))
509 // If variable offset is based in frame register then use fbreg.
510 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_fbreg);
512 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + DWReg);
514 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
515 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
517 addSInt(TheDie, dwarf::DW_FORM_sdata, Offset);
520 /// addAddress - Add an address attribute to a die based on the location
522 void DwarfUnit::addAddress(DIE *Die, dwarf::Attribute Attribute,
523 const MachineLocation &Location, bool Indirect) {
524 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
526 if (Location.isReg() && !Indirect)
527 addRegisterOp(Loc, Location.getReg());
529 addRegisterOffset(Loc, Location.getReg(), Location.getOffset());
530 if (Indirect && !Location.isReg()) {
531 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
535 // Now attach the location information to the DIE.
536 addBlock(Die, Attribute, Loc);
539 /// addComplexAddress - Start with the address based on the location provided,
540 /// and generate the DWARF information necessary to find the actual variable
541 /// given the extra address information encoded in the DbgVariable, starting
542 /// from the starting location. Add the DWARF information to the die.
544 void DwarfUnit::addComplexAddress(const DbgVariable &DV, DIE *Die,
545 dwarf::Attribute Attribute,
546 const MachineLocation &Location) {
547 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
548 unsigned N = DV.getNumAddrElements();
550 if (Location.isReg()) {
551 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
552 // If first address element is OpPlus then emit
553 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
554 addRegisterOffset(Loc, Location.getReg(), DV.getAddrElement(1));
557 addRegisterOp(Loc, Location.getReg());
559 addRegisterOffset(Loc, Location.getReg(), Location.getOffset());
562 uint64_t Element = DV.getAddrElement(i);
563 if (Element == DIBuilder::OpPlus) {
564 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
565 addUInt(Loc, dwarf::DW_FORM_udata, DV.getAddrElement(++i));
566 } else if (Element == DIBuilder::OpDeref) {
567 if (!Location.isReg())
568 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
570 llvm_unreachable("unknown DIBuilder Opcode");
573 // Now attach the location information to the DIE.
574 addBlock(Die, Attribute, Loc);
577 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
578 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
579 gives the variable VarName either the struct, or a pointer to the struct, as
580 its type. This is necessary for various behind-the-scenes things the
581 compiler needs to do with by-reference variables in Blocks.
583 However, as far as the original *programmer* is concerned, the variable
584 should still have type 'SomeType', as originally declared.
586 The function getBlockByrefType dives into the __Block_byref_x_VarName
587 struct to find the original type of the variable, which is then assigned to
588 the variable's Debug Information Entry as its real type. So far, so good.
589 However now the debugger will expect the variable VarName to have the type
590 SomeType. So we need the location attribute for the variable to be an
591 expression that explains to the debugger how to navigate through the
592 pointers and struct to find the actual variable of type SomeType.
594 The following function does just that. We start by getting
595 the "normal" location for the variable. This will be the location
596 of either the struct __Block_byref_x_VarName or the pointer to the
597 struct __Block_byref_x_VarName.
599 The struct will look something like:
601 struct __Block_byref_x_VarName {
603 struct __Block_byref_x_VarName *forwarding;
604 ... <various other fields>
606 ... <maybe more fields>
609 If we are given the struct directly (as our starting point) we
610 need to tell the debugger to:
612 1). Add the offset of the forwarding field.
614 2). Follow that pointer to get the real __Block_byref_x_VarName
615 struct to use (the real one may have been copied onto the heap).
617 3). Add the offset for the field VarName, to find the actual variable.
619 If we started with a pointer to the struct, then we need to
620 dereference that pointer first, before the other steps.
621 Translating this into DWARF ops, we will need to append the following
622 to the current location description for the variable:
624 DW_OP_deref -- optional, if we start with a pointer
625 DW_OP_plus_uconst <forward_fld_offset>
627 DW_OP_plus_uconst <varName_fld_offset>
629 That is what this function does. */
631 /// addBlockByrefAddress - Start with the address based on the location
632 /// provided, and generate the DWARF information necessary to find the
633 /// actual Block variable (navigating the Block struct) based on the
634 /// starting location. Add the DWARF information to the die. For
635 /// more information, read large comment just above here.
637 void DwarfUnit::addBlockByrefAddress(const DbgVariable &DV, DIE *Die,
638 dwarf::Attribute Attribute,
639 const MachineLocation &Location) {
640 DIType Ty = DV.getType();
642 uint16_t Tag = Ty.getTag();
643 bool isPointer = false;
645 StringRef varName = DV.getName();
647 if (Tag == dwarf::DW_TAG_pointer_type) {
648 DIDerivedType DTy(Ty);
649 TmpTy = resolve(DTy.getTypeDerivedFrom());
653 DICompositeType blockStruct(TmpTy);
655 // Find the __forwarding field and the variable field in the __Block_byref
657 DIArray Fields = blockStruct.getTypeArray();
658 DIDerivedType varField;
659 DIDerivedType forwardingField;
661 for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
662 DIDerivedType DT(Fields.getElement(i));
663 StringRef fieldName = DT.getName();
664 if (fieldName == "__forwarding")
665 forwardingField = DT;
666 else if (fieldName == varName)
670 // Get the offsets for the forwarding field and the variable field.
671 unsigned forwardingFieldOffset = forwardingField.getOffsetInBits() >> 3;
672 unsigned varFieldOffset = varField.getOffsetInBits() >> 2;
674 // Decode the original location, and use that as the start of the byref
675 // variable's location.
676 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
678 if (Location.isReg())
679 addRegisterOp(Loc, Location.getReg());
681 addRegisterOffset(Loc, Location.getReg(), Location.getOffset());
683 // If we started with a pointer to the __Block_byref... struct, then
684 // the first thing we need to do is dereference the pointer (DW_OP_deref).
686 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
688 // Next add the offset for the '__forwarding' field:
689 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
690 // adding the offset if it's 0.
691 if (forwardingFieldOffset > 0) {
692 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
693 addUInt(Loc, dwarf::DW_FORM_udata, forwardingFieldOffset);
696 // Now dereference the __forwarding field to get to the real __Block_byref
697 // struct: DW_OP_deref.
698 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
700 // Now that we've got the real __Block_byref... struct, add the offset
701 // for the variable's field to get to the location of the actual variable:
702 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
703 if (varFieldOffset > 0) {
704 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
705 addUInt(Loc, dwarf::DW_FORM_udata, varFieldOffset);
708 // Now attach the location information to the DIE.
709 addBlock(Die, Attribute, Loc);
712 /// isTypeSigned - Return true if the type is signed.
713 static bool isTypeSigned(DwarfDebug *DD, DIType Ty, int *SizeInBits) {
714 if (Ty.isDerivedType())
715 return isTypeSigned(DD, DD->resolve(DIDerivedType(Ty).getTypeDerivedFrom()),
717 if (Ty.isBasicType())
718 if (DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed ||
719 DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed_char) {
720 *SizeInBits = Ty.getSizeInBits();
726 /// Return true if type encoding is unsigned.
727 static bool isUnsignedDIType(DwarfDebug *DD, DIType Ty) {
728 DIDerivedType DTy(Ty);
729 if (DTy.isDerivedType())
730 return isUnsignedDIType(DD, DD->resolve(DTy.getTypeDerivedFrom()));
733 if (BTy.isBasicType()) {
734 unsigned Encoding = BTy.getEncoding();
735 if (Encoding == dwarf::DW_ATE_unsigned ||
736 Encoding == dwarf::DW_ATE_unsigned_char ||
737 Encoding == dwarf::DW_ATE_boolean)
743 /// If this type is derived from a base type then return base type size.
744 static uint64_t getBaseTypeSize(DwarfDebug *DD, DIDerivedType Ty) {
745 unsigned Tag = Ty.getTag();
747 if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef &&
748 Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type &&
749 Tag != dwarf::DW_TAG_restrict_type)
750 return Ty.getSizeInBits();
752 DIType BaseType = DD->resolve(Ty.getTypeDerivedFrom());
754 // If this type is not derived from any type or the type is a declaration then
755 // take conservative approach.
756 if (!BaseType.isValid() || BaseType.isForwardDecl())
757 return Ty.getSizeInBits();
759 // If this is a derived type, go ahead and get the base type, unless it's a
760 // reference then it's just the size of the field. Pointer types have no need
761 // of this since they're a different type of qualification on the type.
762 if (BaseType.getTag() == dwarf::DW_TAG_reference_type ||
763 BaseType.getTag() == dwarf::DW_TAG_rvalue_reference_type)
764 return Ty.getSizeInBits();
766 if (BaseType.isDerivedType())
767 return getBaseTypeSize(DD, DIDerivedType(BaseType));
769 return BaseType.getSizeInBits();
772 /// addConstantValue - Add constant value entry in variable DIE.
773 void DwarfUnit::addConstantValue(DIE *Die, const MachineOperand &MO,
775 // FIXME: This is a bit conservative/simple - it emits negative values at
776 // their maximum bit width which is a bit unfortunate (& doesn't prefer
777 // udata/sdata over dataN as suggested by the DWARF spec)
778 assert(MO.isImm() && "Invalid machine operand!");
780 bool SignedConstant = isTypeSigned(DD, Ty, &SizeInBits);
783 // If we're a signed constant definitely use sdata.
784 if (SignedConstant) {
785 addSInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, MO.getImm());
789 // Else use data for now unless it's larger than we can deal with.
790 switch (SizeInBits) {
792 Form = dwarf::DW_FORM_data1;
795 Form = dwarf::DW_FORM_data2;
798 Form = dwarf::DW_FORM_data4;
801 Form = dwarf::DW_FORM_data8;
804 Form = dwarf::DW_FORM_udata;
805 addUInt(Die, dwarf::DW_AT_const_value, Form, MO.getImm());
808 addUInt(Die, dwarf::DW_AT_const_value, Form, MO.getImm());
811 /// addConstantFPValue - Add constant value entry in variable DIE.
812 void DwarfUnit::addConstantFPValue(DIE *Die, const MachineOperand &MO) {
813 assert(MO.isFPImm() && "Invalid machine operand!");
814 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
815 APFloat FPImm = MO.getFPImm()->getValueAPF();
817 // Get the raw data form of the floating point.
818 const APInt FltVal = FPImm.bitcastToAPInt();
819 const char *FltPtr = (const char *)FltVal.getRawData();
821 int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
822 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
823 int Incr = (LittleEndian ? 1 : -1);
824 int Start = (LittleEndian ? 0 : NumBytes - 1);
825 int Stop = (LittleEndian ? NumBytes : -1);
827 // Output the constant to DWARF one byte at a time.
828 for (; Start != Stop; Start += Incr)
829 addUInt(Block, dwarf::DW_FORM_data1, (unsigned char)0xFF & FltPtr[Start]);
831 addBlock(Die, dwarf::DW_AT_const_value, Block);
834 /// addConstantFPValue - Add constant value entry in variable DIE.
835 void DwarfUnit::addConstantFPValue(DIE *Die, const ConstantFP *CFP) {
836 // Pass this down to addConstantValue as an unsigned bag of bits.
837 addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true);
840 /// addConstantValue - Add constant value entry in variable DIE.
841 void DwarfUnit::addConstantValue(DIE *Die, const ConstantInt *CI,
843 addConstantValue(Die, CI->getValue(), Unsigned);
846 // addConstantValue - Add constant value entry in variable DIE.
847 void DwarfUnit::addConstantValue(DIE *Die, const APInt &Val, bool Unsigned) {
848 unsigned CIBitWidth = Val.getBitWidth();
849 if (CIBitWidth <= 64) {
850 // If we're a signed constant definitely use sdata.
852 addSInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
857 // Else use data for now unless it's larger than we can deal with.
859 switch (CIBitWidth) {
861 Form = dwarf::DW_FORM_data1;
864 Form = dwarf::DW_FORM_data2;
867 Form = dwarf::DW_FORM_data4;
870 Form = dwarf::DW_FORM_data8;
873 addUInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_udata,
877 addUInt(Die, dwarf::DW_AT_const_value, Form, Val.getZExtValue());
881 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
883 // Get the raw data form of the large APInt.
884 const uint64_t *Ptr64 = Val.getRawData();
886 int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
887 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
889 // Output the constant to DWARF one byte at a time.
890 for (int i = 0; i < NumBytes; i++) {
893 c = Ptr64[i / 8] >> (8 * (i & 7));
895 c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
896 addUInt(Block, dwarf::DW_FORM_data1, c);
899 addBlock(Die, dwarf::DW_AT_const_value, Block);
902 /// addTemplateParams - Add template parameters into buffer.
903 void DwarfUnit::addTemplateParams(DIE &Buffer, DIArray TParams) {
904 // Add template parameters.
905 for (unsigned i = 0, e = TParams.getNumElements(); i != e; ++i) {
906 DIDescriptor Element = TParams.getElement(i);
907 if (Element.isTemplateTypeParameter())
908 constructTemplateTypeParameterDIE(Buffer,
909 DITemplateTypeParameter(Element));
910 else if (Element.isTemplateValueParameter())
911 constructTemplateValueParameterDIE(Buffer,
912 DITemplateValueParameter(Element));
916 /// getOrCreateContextDIE - Get context owner's DIE.
917 DIE *DwarfUnit::getOrCreateContextDIE(DIScope Context) {
918 if (!Context || Context.isFile())
920 if (Context.isType())
921 return getOrCreateTypeDIE(DIType(Context));
922 if (Context.isNameSpace())
923 return getOrCreateNameSpace(DINameSpace(Context));
924 if (Context.isSubprogram())
925 return getOrCreateSubprogramDIE(DISubprogram(Context));
926 return getDIE(Context);
929 DIE *DwarfUnit::createTypeDIE(DICompositeType Ty) {
930 DIScope Context = resolve(Ty.getContext());
931 DIE *ContextDIE = getOrCreateContextDIE(Context);
933 DIE *TyDIE = getDIE(Ty);
938 TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
940 constructTypeDIE(*TyDIE, Ty);
942 updateAcceleratorTables(Context, Ty, TyDIE);
946 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
948 DIE *DwarfUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
955 // Construct the context before querying for the existence of the DIE in case
956 // such construction creates the DIE.
957 DIScope Context = resolve(Ty.getContext());
958 DIE *ContextDIE = getOrCreateContextDIE(Context);
961 DIE *TyDIE = getDIE(Ty);
966 TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
968 updateAcceleratorTables(Context, Ty, TyDIE);
970 if (Ty.isBasicType())
971 constructTypeDIE(*TyDIE, DIBasicType(Ty));
972 else if (Ty.isCompositeType()) {
973 DICompositeType CTy(Ty);
974 if (GenerateDwarfTypeUnits && !Ty.isForwardDecl())
975 if (MDString *TypeId = CTy.getIdentifier()) {
976 DD->addDwarfTypeUnitType(getCU(), TypeId->getString(), TyDIE, CTy);
977 // Skip updating the accellerator tables since this is not the full type
980 constructTypeDIE(*TyDIE, CTy);
982 assert(Ty.isDerivedType() && "Unknown kind of DIType");
983 constructTypeDIE(*TyDIE, DIDerivedType(Ty));
989 void DwarfUnit::updateAcceleratorTables(DIScope Context, DIType Ty,
991 if (!Ty.getName().empty() && !Ty.isForwardDecl()) {
992 bool IsImplementation = 0;
993 if (Ty.isCompositeType()) {
994 DICompositeType CT(Ty);
995 // A runtime language of 0 actually means C/C++ and that any
996 // non-negative value is some version of Objective-C/C++.
997 IsImplementation = (CT.getRunTimeLang() == 0) || CT.isObjcClassComplete();
999 unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0;
1000 addAccelType(Ty.getName(), std::make_pair(TyDIE, Flags));
1002 if ((!Context || Context.isCompileUnit() || Context.isFile() ||
1003 Context.isNameSpace()) &&
1004 getCUNode().getEmissionKind() != DIBuilder::LineTablesOnly)
1005 GlobalTypes[getParentContextString(Context) + Ty.getName().str()] = TyDIE;
1009 /// addType - Add a new type attribute to the specified entity.
1010 void DwarfUnit::addType(DIE *Entity, DIType Ty, dwarf::Attribute Attribute) {
1011 assert(Ty && "Trying to add a type that doesn't exist?");
1013 // Check for pre-existence.
1014 DIEEntry *Entry = getDIEEntry(Ty);
1015 // If it exists then use the existing value.
1017 addDIEEntry(Entity, Attribute, Entry);
1022 DIE *Buffer = getOrCreateTypeDIE(Ty);
1025 Entry = createDIEEntry(Buffer);
1026 insertDIEEntry(Ty, Entry);
1027 addDIEEntry(Entity, Attribute, Entry);
1030 // Accelerator table mutators - add each name along with its companion
1031 // DIE to the proper table while ensuring that the name that we're going
1032 // to reference is in the string table. We do this since the names we
1033 // add may not only be identical to the names in the DIE.
1034 void DwarfUnit::addAccelName(StringRef Name, const DIE *Die) {
1035 if (!DD->useDwarfAccelTables())
1037 DU->getStringPoolEntry(Name);
1038 std::vector<const DIE *> &DIEs = AccelNames[Name];
1039 DIEs.push_back(Die);
1042 void DwarfUnit::addAccelObjC(StringRef Name, const DIE *Die) {
1043 if (!DD->useDwarfAccelTables())
1045 DU->getStringPoolEntry(Name);
1046 std::vector<const DIE *> &DIEs = AccelObjC[Name];
1047 DIEs.push_back(Die);
1050 void DwarfUnit::addAccelNamespace(StringRef Name, const DIE *Die) {
1051 if (!DD->useDwarfAccelTables())
1053 DU->getStringPoolEntry(Name);
1054 std::vector<const DIE *> &DIEs = AccelNamespace[Name];
1055 DIEs.push_back(Die);
1058 void DwarfUnit::addAccelType(StringRef Name,
1059 std::pair<const DIE *, unsigned> Die) {
1060 if (!DD->useDwarfAccelTables())
1062 DU->getStringPoolEntry(Name);
1063 std::vector<std::pair<const DIE *, unsigned> > &DIEs = AccelTypes[Name];
1064 DIEs.push_back(Die);
1067 /// addGlobalName - Add a new global name to the compile unit.
1068 void DwarfUnit::addGlobalName(StringRef Name, DIE *Die, DIScope Context) {
1069 if (getCUNode().getEmissionKind() == DIBuilder::LineTablesOnly)
1071 std::string FullName = getParentContextString(Context) + Name.str();
1072 GlobalNames[FullName] = Die;
1075 /// getParentContextString - Walks the metadata parent chain in a language
1076 /// specific manner (using the compile unit language) and returns
1077 /// it as a string. This is done at the metadata level because DIEs may
1078 /// not currently have been added to the parent context and walking the
1079 /// DIEs looking for names is more expensive than walking the metadata.
1080 std::string DwarfUnit::getParentContextString(DIScope Context) const {
1084 // FIXME: Decide whether to implement this for non-C++ languages.
1085 if (getLanguage() != dwarf::DW_LANG_C_plus_plus)
1089 SmallVector<DIScope, 1> Parents;
1090 while (!Context.isCompileUnit()) {
1091 Parents.push_back(Context);
1092 if (Context.getContext())
1093 Context = resolve(Context.getContext());
1095 // Structure, etc types will have a NULL context if they're at the top
1100 // Reverse iterate over our list to go from the outermost construct to the
1102 for (SmallVectorImpl<DIScope>::reverse_iterator I = Parents.rbegin(),
1106 StringRef Name = Ctx.getName();
1107 if (!Name.empty()) {
1115 /// constructTypeDIE - Construct basic type die from DIBasicType.
1116 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
1117 // Get core information.
1118 StringRef Name = BTy.getName();
1119 // Add name if not anonymous or intermediate type.
1121 addString(&Buffer, dwarf::DW_AT_name, Name);
1123 // An unspecified type only has a name attribute.
1124 if (BTy.getTag() == dwarf::DW_TAG_unspecified_type)
1127 addUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1130 uint64_t Size = BTy.getSizeInBits() >> 3;
1131 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1134 /// constructTypeDIE - Construct derived type die from DIDerivedType.
1135 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
1136 // Get core information.
1137 StringRef Name = DTy.getName();
1138 uint64_t Size = DTy.getSizeInBits() >> 3;
1139 uint16_t Tag = Buffer.getTag();
1141 // Map to main type, void will not have a type.
1142 DIType FromTy = resolve(DTy.getTypeDerivedFrom());
1144 addType(&Buffer, FromTy);
1146 // Add name if not anonymous or intermediate type.
1148 addString(&Buffer, dwarf::DW_AT_name, Name);
1150 // Add size if non-zero (derived types might be zero-sized.)
1151 if (Size && Tag != dwarf::DW_TAG_pointer_type)
1152 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1154 if (Tag == dwarf::DW_TAG_ptr_to_member_type)
1155 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type,
1156 getOrCreateTypeDIE(resolve(DTy.getClassType())));
1157 // Add source line info if available and TyDesc is not a forward declaration.
1158 if (!DTy.isForwardDecl())
1159 addSourceLine(&Buffer, DTy);
1162 /// constructSubprogramArguments - Construct function argument DIEs.
1163 void DwarfUnit::constructSubprogramArguments(DIE &Buffer, DIArray Args) {
1164 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1165 DIDescriptor Ty = Args.getElement(i);
1166 if (Ty.isUnspecifiedParameter()) {
1167 assert(i == N-1 && "Unspecified parameter must be the last argument");
1168 createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
1170 DIE *Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
1171 addType(Arg, DIType(Ty));
1172 if (DIType(Ty).isArtificial())
1173 addFlag(Arg, dwarf::DW_AT_artificial);
1178 /// constructTypeDIE - Construct type DIE from DICompositeType.
1179 void DwarfUnit::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
1180 // Add name if not anonymous or intermediate type.
1181 StringRef Name = CTy.getName();
1183 uint64_t Size = CTy.getSizeInBits() >> 3;
1184 uint16_t Tag = Buffer.getTag();
1187 case dwarf::DW_TAG_array_type:
1188 constructArrayTypeDIE(Buffer, CTy);
1190 case dwarf::DW_TAG_enumeration_type:
1191 constructEnumTypeDIE(Buffer, CTy);
1193 case dwarf::DW_TAG_subroutine_type: {
1194 // Add return type. A void return won't have a type.
1195 DIArray Elements = CTy.getTypeArray();
1196 DIType RTy(Elements.getElement(0));
1198 addType(&Buffer, RTy);
1200 bool isPrototyped = true;
1201 if (Elements.getNumElements() == 2 &&
1202 Elements.getElement(1).isUnspecifiedParameter())
1203 isPrototyped = false;
1205 constructSubprogramArguments(Buffer, Elements);
1207 // Add prototype flag if we're dealing with a C language and the
1208 // function has been prototyped.
1209 uint16_t Language = getLanguage();
1211 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1212 Language == dwarf::DW_LANG_ObjC))
1213 addFlag(&Buffer, dwarf::DW_AT_prototyped);
1215 if (CTy.isLValueReference())
1216 addFlag(&Buffer, dwarf::DW_AT_reference);
1218 if (CTy.isRValueReference())
1219 addFlag(&Buffer, dwarf::DW_AT_rvalue_reference);
1221 case dwarf::DW_TAG_structure_type:
1222 case dwarf::DW_TAG_union_type:
1223 case dwarf::DW_TAG_class_type: {
1224 // Add elements to structure type.
1225 DIArray Elements = CTy.getTypeArray();
1226 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1227 DIDescriptor Element = Elements.getElement(i);
1228 DIE *ElemDie = NULL;
1229 if (Element.isSubprogram())
1230 ElemDie = getOrCreateSubprogramDIE(DISubprogram(Element));
1231 else if (Element.isDerivedType()) {
1232 DIDerivedType DDTy(Element);
1233 if (DDTy.getTag() == dwarf::DW_TAG_friend) {
1234 ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
1235 addType(ElemDie, resolve(DDTy.getTypeDerivedFrom()),
1236 dwarf::DW_AT_friend);
1237 } else if (DDTy.isStaticMember()) {
1238 getOrCreateStaticMemberDIE(DDTy);
1240 constructMemberDIE(Buffer, DDTy);
1242 } else if (Element.isObjCProperty()) {
1243 DIObjCProperty Property(Element);
1244 ElemDie = createAndAddDIE(Property.getTag(), Buffer);
1245 StringRef PropertyName = Property.getObjCPropertyName();
1246 addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
1247 if (Property.getType())
1248 addType(ElemDie, Property.getType());
1249 addSourceLine(ElemDie, Property);
1250 StringRef GetterName = Property.getObjCPropertyGetterName();
1251 if (!GetterName.empty())
1252 addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
1253 StringRef SetterName = Property.getObjCPropertySetterName();
1254 if (!SetterName.empty())
1255 addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
1256 unsigned PropertyAttributes = 0;
1257 if (Property.isReadOnlyObjCProperty())
1258 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readonly;
1259 if (Property.isReadWriteObjCProperty())
1260 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readwrite;
1261 if (Property.isAssignObjCProperty())
1262 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_assign;
1263 if (Property.isRetainObjCProperty())
1264 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_retain;
1265 if (Property.isCopyObjCProperty())
1266 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_copy;
1267 if (Property.isNonAtomicObjCProperty())
1268 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_nonatomic;
1269 if (PropertyAttributes)
1270 addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None,
1271 PropertyAttributes);
1273 DIEEntry *Entry = getDIEEntry(Element);
1275 Entry = createDIEEntry(ElemDie);
1276 insertDIEEntry(Element, Entry);
1282 if (CTy.isAppleBlockExtension())
1283 addFlag(&Buffer, dwarf::DW_AT_APPLE_block);
1285 DICompositeType ContainingType(resolve(CTy.getContainingType()));
1287 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type,
1288 getOrCreateTypeDIE(ContainingType));
1290 if (CTy.isObjcClassComplete())
1291 addFlag(&Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
1293 // Add template parameters to a class, structure or union types.
1294 // FIXME: The support isn't in the metadata for this yet.
1295 if (Tag == dwarf::DW_TAG_class_type ||
1296 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
1297 addTemplateParams(Buffer, CTy.getTemplateParams());
1305 // Add name if not anonymous or intermediate type.
1307 addString(&Buffer, dwarf::DW_AT_name, Name);
1309 if (Tag == dwarf::DW_TAG_enumeration_type ||
1310 Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
1311 Tag == dwarf::DW_TAG_union_type) {
1312 // Add size if non-zero (derived types might be zero-sized.)
1313 // TODO: Do we care about size for enum forward declarations?
1315 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1316 else if (!CTy.isForwardDecl())
1317 // Add zero size if it is not a forward declaration.
1318 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, 0);
1320 // If we're a forward decl, say so.
1321 if (CTy.isForwardDecl())
1322 addFlag(&Buffer, dwarf::DW_AT_declaration);
1324 // Add source line info if available.
1325 if (!CTy.isForwardDecl())
1326 addSourceLine(&Buffer, CTy);
1328 // No harm in adding the runtime language to the declaration.
1329 unsigned RLang = CTy.getRunTimeLang();
1331 addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
1336 /// constructTemplateTypeParameterDIE - Construct new DIE for the given
1337 /// DITemplateTypeParameter.
1338 void DwarfUnit::constructTemplateTypeParameterDIE(DIE &Buffer,
1339 DITemplateTypeParameter TP) {
1341 createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
1342 // Add the type if it exists, it could be void and therefore no type.
1344 addType(ParamDIE, resolve(TP.getType()));
1345 if (!TP.getName().empty())
1346 addString(ParamDIE, dwarf::DW_AT_name, TP.getName());
1349 /// constructTemplateValueParameterDIE - Construct new DIE for the given
1350 /// DITemplateValueParameter.
1352 DwarfUnit::constructTemplateValueParameterDIE(DIE &Buffer,
1353 DITemplateValueParameter VP) {
1354 DIE *ParamDIE = createAndAddDIE(VP.getTag(), Buffer);
1356 // Add the type if there is one, template template and template parameter
1357 // packs will not have a type.
1358 if (VP.getTag() == dwarf::DW_TAG_template_value_parameter)
1359 addType(ParamDIE, resolve(VP.getType()));
1360 if (!VP.getName().empty())
1361 addString(ParamDIE, dwarf::DW_AT_name, VP.getName());
1362 if (Value *Val = VP.getValue()) {
1363 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val))
1364 addConstantValue(ParamDIE, CI,
1365 isUnsignedDIType(DD, resolve(VP.getType())));
1366 else if (GlobalValue *GV = dyn_cast<GlobalValue>(Val)) {
1367 // For declaration non-type template parameters (such as global values and
1369 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
1370 addOpAddress(Loc, Asm->getSymbol(GV));
1371 // Emit DW_OP_stack_value to use the address as the immediate value of the
1372 // parameter, rather than a pointer to it.
1373 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
1374 addBlock(ParamDIE, dwarf::DW_AT_location, Loc);
1375 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1376 assert(isa<MDString>(Val));
1377 addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
1378 cast<MDString>(Val)->getString());
1379 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1380 assert(isa<MDNode>(Val));
1381 DIArray A(cast<MDNode>(Val));
1382 addTemplateParams(*ParamDIE, A);
1387 /// getOrCreateNameSpace - Create a DIE for DINameSpace.
1388 DIE *DwarfUnit::getOrCreateNameSpace(DINameSpace NS) {
1389 // Construct the context before querying for the existence of the DIE in case
1390 // such construction creates the DIE.
1391 DIE *ContextDIE = getOrCreateContextDIE(NS.getContext());
1393 DIE *NDie = getDIE(NS);
1396 NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS);
1398 if (!NS.getName().empty()) {
1399 addString(NDie, dwarf::DW_AT_name, NS.getName());
1400 addAccelNamespace(NS.getName(), NDie);
1401 addGlobalName(NS.getName(), NDie, NS.getContext());
1403 addAccelNamespace("(anonymous namespace)", NDie);
1404 addSourceLine(NDie, NS);
1408 /// getOrCreateSubprogramDIE - Create new DIE using SP.
1409 DIE *DwarfUnit::getOrCreateSubprogramDIE(DISubprogram SP) {
1410 // Construct the context before querying for the existence of the DIE in case
1411 // such construction creates the DIE (as is the case for member function
1413 DIE *ContextDIE = getOrCreateContextDIE(resolve(SP.getContext()));
1415 DIE *SPDie = getDIE(SP);
1419 DISubprogram SPDecl = SP.getFunctionDeclaration();
1420 if (SPDecl.isSubprogram())
1421 // Add subprogram definitions to the CU die directly.
1422 ContextDIE = UnitDie.get();
1424 // DW_TAG_inlined_subroutine may refer to this DIE.
1425 SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
1427 DIE *DeclDie = NULL;
1428 if (SPDecl.isSubprogram())
1429 DeclDie = getOrCreateSubprogramDIE(SPDecl);
1431 // Add function template parameters.
1432 addTemplateParams(*SPDie, SP.getTemplateParams());
1434 // If this DIE is going to refer declaration info using AT_specification
1435 // then there is no need to add other attributes.
1437 // Refer function declaration directly.
1438 addDIEEntry(SPDie, dwarf::DW_AT_specification, DeclDie);
1443 // Add the linkage name if we have one.
1444 StringRef LinkageName = SP.getLinkageName();
1445 if (!LinkageName.empty())
1446 addString(SPDie, dwarf::DW_AT_MIPS_linkage_name,
1447 GlobalValue::getRealLinkageName(LinkageName));
1449 // Constructors and operators for anonymous aggregates do not have names.
1450 if (!SP.getName().empty())
1451 addString(SPDie, dwarf::DW_AT_name, SP.getName());
1453 addSourceLine(SPDie, SP);
1455 // Add the prototype if we have a prototype and we have a C like
1457 uint16_t Language = getLanguage();
1458 if (SP.isPrototyped() &&
1459 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1460 Language == dwarf::DW_LANG_ObjC))
1461 addFlag(SPDie, dwarf::DW_AT_prototyped);
1463 DICompositeType SPTy = SP.getType();
1464 assert(SPTy.getTag() == dwarf::DW_TAG_subroutine_type &&
1465 "the type of a subprogram should be a subroutine");
1467 DIArray Args = SPTy.getTypeArray();
1468 // Add a return type. If this is a type like a C/C++ void type we don't add a
1470 if (Args.getElement(0))
1471 addType(SPDie, DIType(Args.getElement(0)));
1473 unsigned VK = SP.getVirtuality();
1475 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1476 DIELoc *Block = getDIELoc();
1477 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1478 addUInt(Block, dwarf::DW_FORM_udata, SP.getVirtualIndex());
1479 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
1480 ContainingTypeMap.insert(
1481 std::make_pair(SPDie, resolve(SP.getContainingType())));
1484 if (!SP.isDefinition()) {
1485 addFlag(SPDie, dwarf::DW_AT_declaration);
1487 // Add arguments. Do not add arguments for subprogram definition. They will
1488 // be handled while processing variables.
1489 constructSubprogramArguments(*SPDie, Args);
1492 if (SP.isArtificial())
1493 addFlag(SPDie, dwarf::DW_AT_artificial);
1495 if (!SP.isLocalToUnit())
1496 addFlag(SPDie, dwarf::DW_AT_external);
1498 if (SP.isOptimized())
1499 addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1501 if (unsigned isa = Asm->getISAEncoding()) {
1502 addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1505 if (SP.isLValueReference())
1506 addFlag(SPDie, dwarf::DW_AT_reference);
1508 if (SP.isRValueReference())
1509 addFlag(SPDie, dwarf::DW_AT_rvalue_reference);
1511 if (SP.isProtected())
1512 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1513 dwarf::DW_ACCESS_protected);
1514 else if (SP.isPrivate())
1515 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1516 dwarf::DW_ACCESS_private);
1518 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1519 dwarf::DW_ACCESS_public);
1521 if (SP.isExplicit())
1522 addFlag(SPDie, dwarf::DW_AT_explicit);
1527 // Return const expression if value is a GEP to access merged global
1529 // i8* getelementptr ({ i8, i8, i8, i8 }* @_MergedGlobals, i32 0, i32 0)
1530 static const ConstantExpr *getMergedGlobalExpr(const Value *V) {
1531 const ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(V);
1532 if (!CE || CE->getNumOperands() != 3 ||
1533 CE->getOpcode() != Instruction::GetElementPtr)
1536 // First operand points to a global struct.
1537 Value *Ptr = CE->getOperand(0);
1538 if (!isa<GlobalValue>(Ptr) ||
1539 !isa<StructType>(cast<PointerType>(Ptr->getType())->getElementType()))
1542 // Second operand is zero.
1543 const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(CE->getOperand(1));
1544 if (!CI || !CI->isZero())
1547 // Third operand is offset.
1548 if (!isa<ConstantInt>(CE->getOperand(2)))
1554 /// createGlobalVariableDIE - create global variable DIE.
1555 void DwarfCompileUnit::createGlobalVariableDIE(DIGlobalVariable GV) {
1556 // Check for pre-existence.
1560 assert(GV.isGlobalVariable());
1562 DIScope GVContext = GV.getContext();
1563 DIType GTy = GV.getType();
1565 // If this is a static data member definition, some attributes belong
1566 // to the declaration DIE.
1567 DIE *VariableDIE = NULL;
1568 bool IsStaticMember = false;
1569 DIDerivedType SDMDecl = GV.getStaticDataMemberDeclaration();
1570 if (SDMDecl.Verify()) {
1571 assert(SDMDecl.isStaticMember() && "Expected static member decl");
1572 // We need the declaration DIE that is in the static member's class.
1573 VariableDIE = getOrCreateStaticMemberDIE(SDMDecl);
1574 IsStaticMember = true;
1577 // If this is not a static data member definition, create the variable
1578 // DIE and add the initial set of attributes to it.
1580 // Construct the context before querying for the existence of the DIE in
1581 // case such construction creates the DIE.
1582 DIE *ContextDIE = getOrCreateContextDIE(GVContext);
1585 VariableDIE = createAndAddDIE(GV.getTag(), *ContextDIE, GV);
1587 // Add name and type.
1588 addString(VariableDIE, dwarf::DW_AT_name, GV.getDisplayName());
1589 addType(VariableDIE, GTy);
1591 // Add scoping info.
1592 if (!GV.isLocalToUnit())
1593 addFlag(VariableDIE, dwarf::DW_AT_external);
1595 // Add line number info.
1596 addSourceLine(VariableDIE, GV);
1600 bool addToAccelTable = false;
1601 DIE *VariableSpecDIE = NULL;
1602 bool isGlobalVariable = GV.getGlobal() != NULL;
1603 if (isGlobalVariable) {
1604 addToAccelTable = true;
1605 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
1606 const MCSymbol *Sym = Asm->getSymbol(GV.getGlobal());
1607 if (GV.getGlobal()->isThreadLocal()) {
1608 // FIXME: Make this work with -gsplit-dwarf.
1609 unsigned PointerSize = Asm->getDataLayout().getPointerSize();
1610 assert((PointerSize == 4 || PointerSize == 8) &&
1611 "Add support for other sizes if necessary");
1612 // Based on GCC's support for TLS:
1613 if (!DD->useSplitDwarf()) {
1614 // 1) Start with a constNu of the appropriate pointer size
1615 addUInt(Loc, dwarf::DW_FORM_data1,
1616 PointerSize == 4 ? dwarf::DW_OP_const4u : dwarf::DW_OP_const8u);
1617 // 2) containing the (relocated) offset of the TLS variable
1618 // within the module's TLS block.
1619 addExpr(Loc, dwarf::DW_FORM_udata,
1620 Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym));
1622 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
1623 addUInt(Loc, dwarf::DW_FORM_udata,
1624 DU->getAddrPoolIndex(Sym, /* TLS */ true));
1626 // 3) followed by a custom OP to make the debugger do a TLS lookup.
1627 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_push_tls_address);
1629 DD->addArangeLabel(SymbolCU(this, Sym));
1630 addOpAddress(Loc, Sym);
1632 // Do not create specification DIE if context is either compile unit
1634 if (GVContext && GV.isDefinition() && !GVContext.isCompileUnit() &&
1635 !GVContext.isFile() && !DD->isSubprogramContext(GVContext)) {
1636 // Create specification DIE.
1637 VariableSpecDIE = createAndAddDIE(dwarf::DW_TAG_variable, *UnitDie);
1638 addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification, VariableDIE);
1639 addBlock(VariableSpecDIE, dwarf::DW_AT_location, Loc);
1640 // A static member's declaration is already flagged as such.
1641 if (!SDMDecl.Verify())
1642 addFlag(VariableDIE, dwarf::DW_AT_declaration);
1644 addBlock(VariableDIE, dwarf::DW_AT_location, Loc);
1646 // Add the linkage name.
1647 StringRef LinkageName = GV.getLinkageName();
1648 if (!LinkageName.empty())
1649 // From DWARF4: DIEs to which DW_AT_linkage_name may apply include:
1650 // TAG_common_block, TAG_constant, TAG_entry_point, TAG_subprogram and
1652 addString(IsStaticMember && VariableSpecDIE ? VariableSpecDIE
1654 DD->getDwarfVersion() >= 4 ? dwarf::DW_AT_linkage_name
1655 : dwarf::DW_AT_MIPS_linkage_name,
1656 GlobalValue::getRealLinkageName(LinkageName));
1657 } else if (const ConstantInt *CI =
1658 dyn_cast_or_null<ConstantInt>(GV.getConstant())) {
1659 // AT_const_value was added when the static member was created. To avoid
1660 // emitting AT_const_value multiple times, we only add AT_const_value when
1661 // it is not a static member.
1662 if (!IsStaticMember)
1663 addConstantValue(VariableDIE, CI, isUnsignedDIType(DD, GTy));
1664 } else if (const ConstantExpr *CE = getMergedGlobalExpr(GV->getOperand(11))) {
1665 addToAccelTable = true;
1666 // GV is a merged global.
1667 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
1668 Value *Ptr = CE->getOperand(0);
1669 MCSymbol *Sym = Asm->getSymbol(cast<GlobalValue>(Ptr));
1670 DD->addArangeLabel(SymbolCU(this, Sym));
1671 addOpAddress(Loc, Sym);
1672 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1673 SmallVector<Value *, 3> Idx(CE->op_begin() + 1, CE->op_end());
1674 addUInt(Loc, dwarf::DW_FORM_udata,
1675 Asm->getDataLayout().getIndexedOffset(Ptr->getType(), Idx));
1676 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1677 addBlock(VariableDIE, dwarf::DW_AT_location, Loc);
1680 if (addToAccelTable) {
1681 DIE *AddrDIE = VariableSpecDIE ? VariableSpecDIE : VariableDIE;
1682 addAccelName(GV.getName(), AddrDIE);
1684 // If the linkage name is different than the name, go ahead and output
1685 // that as well into the name table.
1686 if (GV.getLinkageName() != "" && GV.getName() != GV.getLinkageName())
1687 addAccelName(GV.getLinkageName(), AddrDIE);
1690 if (!GV.isLocalToUnit())
1691 addGlobalName(GV.getName(), VariableSpecDIE ? VariableSpecDIE : VariableDIE,
1695 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
1696 void DwarfUnit::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy) {
1697 DIE *DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
1698 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, IndexTy);
1700 // The LowerBound value defines the lower bounds which is typically zero for
1701 // C/C++. The Count value is the number of elements. Values are 64 bit. If
1702 // Count == -1 then the array is unbounded and we do not emit
1703 // DW_AT_lower_bound and DW_AT_upper_bound attributes. If LowerBound == 0 and
1704 // Count == 0, then the array has zero elements in which case we do not emit
1706 int64_t LowerBound = SR.getLo();
1707 int64_t DefaultLowerBound = getDefaultLowerBound();
1708 int64_t Count = SR.getCount();
1710 if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
1711 addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound);
1713 if (Count != -1 && Count != 0)
1714 // FIXME: An unbounded array should reference the expression that defines
1716 addUInt(DW_Subrange, dwarf::DW_AT_upper_bound, None,
1717 LowerBound + Count - 1);
1720 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
1721 void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, DICompositeType CTy) {
1723 addFlag(&Buffer, dwarf::DW_AT_GNU_vector);
1725 // Emit the element type.
1726 addType(&Buffer, resolve(CTy.getTypeDerivedFrom()));
1728 // Get an anonymous type for index type.
1729 // FIXME: This type should be passed down from the front end
1730 // as different languages may have different sizes for indexes.
1731 DIE *IdxTy = getIndexTyDie();
1733 // Construct an anonymous type for index type.
1734 IdxTy = createAndAddDIE(dwarf::DW_TAG_base_type, *UnitDie);
1735 addString(IdxTy, dwarf::DW_AT_name, "int");
1736 addUInt(IdxTy, dwarf::DW_AT_byte_size, None, sizeof(int32_t));
1737 addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1738 dwarf::DW_ATE_signed);
1739 setIndexTyDie(IdxTy);
1742 // Add subranges to array type.
1743 DIArray Elements = CTy.getTypeArray();
1744 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1745 DIDescriptor Element = Elements.getElement(i);
1746 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1747 constructSubrangeDIE(Buffer, DISubrange(Element), IdxTy);
1751 /// constructEnumTypeDIE - Construct an enum type DIE from DICompositeType.
1752 void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, DICompositeType CTy) {
1753 DIArray Elements = CTy.getTypeArray();
1755 // Add enumerators to enumeration type.
1756 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1757 DIEnumerator Enum(Elements.getElement(i));
1758 if (Enum.isEnumerator()) {
1759 DIE *Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
1760 StringRef Name = Enum.getName();
1761 addString(Enumerator, dwarf::DW_AT_name, Name);
1762 int64_t Value = Enum.getEnumValue();
1763 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
1767 DIType DTy = resolve(CTy.getTypeDerivedFrom());
1769 addType(&Buffer, DTy);
1770 addFlag(&Buffer, dwarf::DW_AT_enum_class);
1774 /// constructContainingTypeDIEs - Construct DIEs for types that contain
1776 void DwarfUnit::constructContainingTypeDIEs() {
1777 for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(),
1778 CE = ContainingTypeMap.end();
1780 DIE *SPDie = CI->first;
1781 DIDescriptor D(CI->second);
1784 DIE *NDie = getDIE(D);
1787 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, NDie);
1791 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
1792 DIE *DwarfUnit::constructVariableDIE(DbgVariable &DV, bool isScopeAbstract) {
1793 StringRef Name = DV.getName();
1795 // Define variable debug information entry.
1796 DIE *VariableDie = new DIE(DV.getTag());
1797 DbgVariable *AbsVar = DV.getAbstractVariable();
1798 DIE *AbsDIE = AbsVar ? AbsVar->getDIE() : NULL;
1800 addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin, AbsDIE);
1803 addString(VariableDie, dwarf::DW_AT_name, Name);
1804 addSourceLine(VariableDie, DV.getVariable());
1805 addType(VariableDie, DV.getType());
1808 if (DV.isArtificial())
1809 addFlag(VariableDie, dwarf::DW_AT_artificial);
1811 if (isScopeAbstract) {
1812 DV.setDIE(VariableDie);
1816 // Add variable address.
1818 unsigned Offset = DV.getDotDebugLocOffset();
1819 if (Offset != ~0U) {
1820 addLocationList(VariableDie, dwarf::DW_AT_location, Offset);
1821 DV.setDIE(VariableDie);
1825 // Check if variable is described by a DBG_VALUE instruction.
1826 if (const MachineInstr *DVInsn = DV.getMInsn()) {
1827 assert(DVInsn->getNumOperands() == 3);
1828 if (DVInsn->getOperand(0).isReg()) {
1829 const MachineOperand RegOp = DVInsn->getOperand(0);
1830 // If the second operand is an immediate, this is an indirect value.
1831 if (DVInsn->getOperand(1).isImm()) {
1832 MachineLocation Location(RegOp.getReg(),
1833 DVInsn->getOperand(1).getImm());
1834 addVariableAddress(DV, VariableDie, Location);
1835 } else if (RegOp.getReg())
1836 addVariableAddress(DV, VariableDie, MachineLocation(RegOp.getReg()));
1837 } else if (DVInsn->getOperand(0).isImm())
1838 addConstantValue(VariableDie, DVInsn->getOperand(0), DV.getType());
1839 else if (DVInsn->getOperand(0).isFPImm())
1840 addConstantFPValue(VariableDie, DVInsn->getOperand(0));
1841 else if (DVInsn->getOperand(0).isCImm())
1842 addConstantValue(VariableDie, DVInsn->getOperand(0).getCImm(),
1843 isUnsignedDIType(DD, DV.getType()));
1845 DV.setDIE(VariableDie);
1848 // .. else use frame index.
1849 int FI = DV.getFrameIndex();
1851 unsigned FrameReg = 0;
1852 const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
1853 int Offset = TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
1854 MachineLocation Location(FrameReg, Offset);
1855 addVariableAddress(DV, VariableDie, Location);
1859 DV.setDIE(VariableDie);
1863 /// constructMemberDIE - Construct member DIE from DIDerivedType.
1864 void DwarfUnit::constructMemberDIE(DIE &Buffer, DIDerivedType DT) {
1865 DIE *MemberDie = createAndAddDIE(DT.getTag(), Buffer);
1866 StringRef Name = DT.getName();
1868 addString(MemberDie, dwarf::DW_AT_name, Name);
1870 addType(MemberDie, resolve(DT.getTypeDerivedFrom()));
1872 addSourceLine(MemberDie, DT);
1874 if (DT.getTag() == dwarf::DW_TAG_inheritance && DT.isVirtual()) {
1876 // For C++, virtual base classes are not at fixed offset. Use following
1877 // expression to extract appropriate offset from vtable.
1878 // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1880 DIELoc *VBaseLocationDie = new (DIEValueAllocator) DIELoc();
1881 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1882 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1883 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1884 addUInt(VBaseLocationDie, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1885 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1886 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1887 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1889 addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
1891 uint64_t Size = DT.getSizeInBits();
1892 uint64_t FieldSize = getBaseTypeSize(DD, DT);
1893 uint64_t OffsetInBytes;
1895 if (Size != FieldSize) {
1896 // Handle bitfield, assume bytes are 8 bits.
1897 addUInt(MemberDie, dwarf::DW_AT_byte_size, None, FieldSize/8);
1898 addUInt(MemberDie, dwarf::DW_AT_bit_size, None, Size);
1900 uint64_t Offset = DT.getOffsetInBits();
1901 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1902 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1903 uint64_t FieldOffset = (HiMark - FieldSize);
1904 Offset -= FieldOffset;
1906 // Maybe we need to work from the other end.
1907 if (Asm->getDataLayout().isLittleEndian())
1908 Offset = FieldSize - (Offset + Size);
1909 addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset);
1911 // Here DW_AT_data_member_location points to the anonymous
1912 // field that includes this bit field.
1913 OffsetInBytes = FieldOffset >> 3;
1915 // This is not a bitfield.
1916 OffsetInBytes = DT.getOffsetInBits() >> 3;
1918 if (DD->getDwarfVersion() <= 2) {
1919 DIELoc *MemLocationDie = new (DIEValueAllocator) DIELoc();
1920 addUInt(MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1921 addUInt(MemLocationDie, dwarf::DW_FORM_udata, OffsetInBytes);
1922 addBlock(MemberDie, dwarf::DW_AT_data_member_location, MemLocationDie);
1924 addUInt(MemberDie, dwarf::DW_AT_data_member_location, None,
1928 if (DT.isProtected())
1929 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1930 dwarf::DW_ACCESS_protected);
1931 else if (DT.isPrivate())
1932 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1933 dwarf::DW_ACCESS_private);
1934 // Otherwise C++ member and base classes are considered public.
1936 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1937 dwarf::DW_ACCESS_public);
1939 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1940 dwarf::DW_VIRTUALITY_virtual);
1942 // Objective-C properties.
1943 if (MDNode *PNode = DT.getObjCProperty())
1944 if (DIEEntry *PropertyDie = getDIEEntry(PNode))
1945 MemberDie->addValue(dwarf::DW_AT_APPLE_property, dwarf::DW_FORM_ref4,
1948 if (DT.isArtificial())
1949 addFlag(MemberDie, dwarf::DW_AT_artificial);
1952 /// getOrCreateStaticMemberDIE - Create new DIE for C++ static member.
1953 DIE *DwarfUnit::getOrCreateStaticMemberDIE(DIDerivedType DT) {
1957 // Construct the context before querying for the existence of the DIE in case
1958 // such construction creates the DIE.
1959 DIE *ContextDIE = getOrCreateContextDIE(resolve(DT.getContext()));
1960 assert(dwarf::isType(ContextDIE->getTag()) &&
1961 "Static member should belong to a type.");
1963 DIE *StaticMemberDIE = getDIE(DT);
1964 if (StaticMemberDIE)
1965 return StaticMemberDIE;
1967 StaticMemberDIE = createAndAddDIE(DT.getTag(), *ContextDIE, DT);
1969 DIType Ty = resolve(DT.getTypeDerivedFrom());
1971 addString(StaticMemberDIE, dwarf::DW_AT_name, DT.getName());
1972 addType(StaticMemberDIE, Ty);
1973 addSourceLine(StaticMemberDIE, DT);
1974 addFlag(StaticMemberDIE, dwarf::DW_AT_external);
1975 addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
1977 // FIXME: We could omit private if the parent is a class_type, and
1978 // public if the parent is something else.
1979 if (DT.isProtected())
1980 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1981 dwarf::DW_ACCESS_protected);
1982 else if (DT.isPrivate())
1983 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1984 dwarf::DW_ACCESS_private);
1986 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1987 dwarf::DW_ACCESS_public);
1989 if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT.getConstant()))
1990 addConstantValue(StaticMemberDIE, CI, isUnsignedDIType(DD, Ty));
1991 if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT.getConstant()))
1992 addConstantFPValue(StaticMemberDIE, CFP);
1994 return StaticMemberDIE;
1997 void DwarfUnit::emitHeader(const MCSection *ASection,
1998 const MCSymbol *ASectionSym) const {
1999 Asm->OutStreamer.AddComment("DWARF version number");
2000 Asm->EmitInt16(DD->getDwarfVersion());
2001 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
2002 // We share one abbreviations table across all units so it's always at the
2003 // start of the section. Use a relocatable offset where needed to ensure
2004 // linking doesn't invalidate that offset.
2005 Asm->EmitSectionOffset(ASectionSym, ASectionSym);
2006 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2007 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
2010 void DwarfCompileUnit::initStmtList(MCSymbol *DwarfLineSectionSym) {
2011 // Define start line table label for each Compile Unit.
2012 MCSymbol *LineTableStartSym =
2013 Asm->GetTempSymbol("line_table_start", getUniqueID());
2014 Asm->OutStreamer.getContext().setMCLineTableSymbol(LineTableStartSym,
2017 // Use a single line table if we are generating assembly.
2018 bool UseTheFirstCU =
2019 Asm->OutStreamer.hasRawTextSupport() || (getUniqueID() == 0);
2021 stmtListIndex = UnitDie->getValues().size();
2023 // DW_AT_stmt_list is a offset of line number information for this
2024 // compile unit in debug_line section. For split dwarf this is
2025 // left in the skeleton CU and so not included.
2026 // The line table entries are not always emitted in assembly, so it
2027 // is not okay to use line_table_start here.
2028 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2029 addSectionLabel(UnitDie.get(), dwarf::DW_AT_stmt_list,
2030 UseTheFirstCU ? DwarfLineSectionSym : LineTableStartSym);
2031 else if (UseTheFirstCU)
2032 addSectionOffset(UnitDie.get(), dwarf::DW_AT_stmt_list, 0);
2034 addSectionDelta(UnitDie.get(), dwarf::DW_AT_stmt_list, LineTableStartSym,
2035 DwarfLineSectionSym);
2038 void DwarfCompileUnit::applyStmtList(DIE &D) {
2039 D.addValue(dwarf::DW_AT_stmt_list,
2040 UnitDie->getAbbrev().getData()[stmtListIndex].getForm(),
2041 UnitDie->getValues()[stmtListIndex]);
2044 void DwarfTypeUnit::emitHeader(const MCSection *ASection,
2045 const MCSymbol *ASectionSym) const {
2046 DwarfUnit::emitHeader(ASection, ASectionSym);
2047 Asm->OutStreamer.AddComment("Type Signature");
2048 Asm->OutStreamer.EmitIntValue(TypeSignature, sizeof(TypeSignature));
2049 Asm->OutStreamer.AddComment("Type DIE Offset");
2050 // In a skeleton type unit there is no type DIE so emit a zero offset.
2051 Asm->OutStreamer.EmitIntValue(Ty ? Ty->getOffset() : 0,
2052 sizeof(Ty->getOffset()));
2055 void DwarfTypeUnit::initSection(const MCSection *Section) {
2056 assert(!this->Section);
2057 this->Section = Section;
2058 // Since each type unit is contained in its own COMDAT section, the begin
2059 // label and the section label are the same. Using the begin label emission in
2060 // DwarfDebug to emit the section label as well is slightly subtle/sneaky, but
2061 // the only other alternative of lazily constructing start-of-section labels
2062 // and storing a mapping in DwarfDebug (or AsmPrinter).
2063 this->SectionSym = this->LabelBegin =
2064 Asm->GetTempSymbol(Section->getLabelBeginName(), getUniqueID());
2066 Asm->GetTempSymbol(Section->getLabelEndName(), getUniqueID());
2067 this->LabelRange = Asm->GetTempSymbol("gnu_ranges", getUniqueID());