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) {}
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 /// 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(DIELoc *Die, dwarf::Form Form, const MCSymbol *Label) {
243 addLabel(Die, (dwarf::Attribute)0, Form, Label);
246 /// addSectionLabel - Add a Dwarf section label attribute data and value.
248 void DwarfUnit::addSectionLabel(DIE *Die, dwarf::Attribute Attribute,
249 const MCSymbol *Label) {
250 if (DD->getDwarfVersion() >= 4)
251 addLabel(Die, Attribute, dwarf::DW_FORM_sec_offset, Label);
253 addLabel(Die, Attribute, dwarf::DW_FORM_data4, Label);
256 /// addSectionOffset - Add an offset into a section attribute data and value.
258 void DwarfUnit::addSectionOffset(DIE *Die, dwarf::Attribute Attribute,
260 if (DD->getDwarfVersion() >= 4)
261 addUInt(Die, Attribute, dwarf::DW_FORM_sec_offset, Integer);
263 addUInt(Die, Attribute, dwarf::DW_FORM_data4, Integer);
266 /// addLabelAddress - Add a dwarf label attribute data and value using
267 /// DW_FORM_addr or DW_FORM_GNU_addr_index.
269 void DwarfCompileUnit::addLabelAddress(DIE *Die, dwarf::Attribute Attribute,
272 DD->addArangeLabel(SymbolCU(this, Label));
274 if (!DD->useSplitDwarf()) {
276 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
277 Die->addValue(Attribute, dwarf::DW_FORM_addr, Value);
279 DIEValue *Value = new (DIEValueAllocator) DIEInteger(0);
280 Die->addValue(Attribute, dwarf::DW_FORM_addr, Value);
283 unsigned idx = DU->getAddrPoolIndex(Label);
284 DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
285 Die->addValue(Attribute, dwarf::DW_FORM_GNU_addr_index, Value);
289 /// addOpAddress - Add a dwarf op address data and value using the
290 /// form given and an op of either DW_FORM_addr or DW_FORM_GNU_addr_index.
292 void DwarfUnit::addOpAddress(DIELoc *Die, const MCSymbol *Sym) {
293 if (!DD->useSplitDwarf()) {
294 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
295 addLabel(Die, dwarf::DW_FORM_udata, Sym);
297 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index);
298 addUInt(Die, dwarf::DW_FORM_GNU_addr_index, DU->getAddrPoolIndex(Sym));
302 /// addSectionDelta - Add a section label delta attribute data and value.
304 void DwarfUnit::addSectionDelta(DIE *Die, dwarf::Attribute Attribute,
305 const MCSymbol *Hi, const MCSymbol *Lo) {
306 DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
307 if (DD->getDwarfVersion() >= 4)
308 Die->addValue(Attribute, dwarf::DW_FORM_sec_offset, Value);
310 Die->addValue(Attribute, dwarf::DW_FORM_data4, Value);
313 /// addDIEEntry - Add a DIE attribute data and value.
315 void DwarfUnit::addDIEEntry(DIE *Die, dwarf::Attribute Attribute, DIE *Entry) {
316 addDIEEntry(Die, Attribute, createDIEEntry(Entry));
319 void DwarfUnit::addDIETypeSignature(DIE *Die, const DwarfTypeUnit &Type) {
320 Die->addValue(dwarf::DW_AT_signature, dwarf::DW_FORM_ref_sig8,
321 new (DIEValueAllocator) DIETypeSignature(Type));
324 void DwarfUnit::addDIEEntry(DIE *Die, dwarf::Attribute Attribute,
326 const DIE *DieCU = Die->getUnitOrNull();
327 const DIE *EntryCU = Entry->getEntry()->getUnitOrNull();
329 // We assume that Die belongs to this CU, if it is not linked to any CU yet.
330 DieCU = getUnitDie();
332 EntryCU = getUnitDie();
333 Die->addValue(Attribute, EntryCU == DieCU ? dwarf::DW_FORM_ref4
334 : dwarf::DW_FORM_ref_addr,
338 /// Create a DIE with the given Tag, add the DIE to its parent, and
339 /// call insertDIE if MD is not null.
340 DIE *DwarfUnit::createAndAddDIE(unsigned Tag, DIE &Parent, DIDescriptor N) {
341 DIE *Die = new DIE(Tag);
342 Parent.addChild(Die);
348 /// addBlock - Add block data.
350 void DwarfUnit::addBlock(DIE *Die, dwarf::Attribute Attribute, DIELoc *Loc) {
351 Loc->ComputeSize(Asm);
352 DIELocs.push_back(Loc); // Memoize so we can call the destructor later on.
353 Die->addValue(Attribute, Loc->BestForm(DD->getDwarfVersion()), Loc);
356 void DwarfUnit::addBlock(DIE *Die, dwarf::Attribute Attribute,
358 Block->ComputeSize(Asm);
359 DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
360 Die->addValue(Attribute, Block->BestForm(), Block);
363 /// addSourceLine - Add location information to specified debug information
365 void DwarfUnit::addSourceLine(DIE *Die, unsigned Line, StringRef File,
366 StringRef Directory) {
371 DD->getOrCreateSourceID(File, Directory, getCU().getUniqueID());
372 assert(FileID && "Invalid file id");
373 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
374 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
377 /// addSourceLine - Add location information to specified debug information
379 void DwarfUnit::addSourceLine(DIE *Die, DIVariable V) {
380 assert(V.isVariable());
382 addSourceLine(Die, V.getLineNumber(), V.getContext().getFilename(),
383 V.getContext().getDirectory());
386 /// addSourceLine - Add location information to specified debug information
388 void DwarfUnit::addSourceLine(DIE *Die, DIGlobalVariable G) {
389 assert(G.isGlobalVariable());
391 addSourceLine(Die, G.getLineNumber(), G.getFilename(), G.getDirectory());
394 /// addSourceLine - Add location information to specified debug information
396 void DwarfUnit::addSourceLine(DIE *Die, DISubprogram SP) {
397 assert(SP.isSubprogram());
399 addSourceLine(Die, SP.getLineNumber(), SP.getFilename(), SP.getDirectory());
402 /// addSourceLine - Add location information to specified debug information
404 void DwarfUnit::addSourceLine(DIE *Die, DIType Ty) {
407 addSourceLine(Die, Ty.getLineNumber(), Ty.getFilename(), Ty.getDirectory());
410 /// addSourceLine - Add location information to specified debug information
412 void DwarfUnit::addSourceLine(DIE *Die, DIObjCProperty Ty) {
413 assert(Ty.isObjCProperty());
415 DIFile File = Ty.getFile();
416 addSourceLine(Die, Ty.getLineNumber(), File.getFilename(),
417 File.getDirectory());
420 /// addSourceLine - Add location information to specified debug information
422 void DwarfUnit::addSourceLine(DIE *Die, DINameSpace NS) {
425 addSourceLine(Die, NS.getLineNumber(), NS.getFilename(), NS.getDirectory());
428 /// addVariableAddress - Add DW_AT_location attribute for a
429 /// DbgVariable based on provided MachineLocation.
430 void DwarfUnit::addVariableAddress(const DbgVariable &DV, DIE *Die,
431 MachineLocation Location) {
432 if (DV.variableHasComplexAddress())
433 addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
434 else if (DV.isBlockByrefVariable())
435 addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location);
437 addAddress(Die, dwarf::DW_AT_location, Location,
438 DV.getVariable().isIndirect());
441 /// addRegisterOp - Add register operand.
442 void DwarfUnit::addRegisterOp(DIELoc *TheDie, unsigned Reg) {
443 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
444 int DWReg = RI->getDwarfRegNum(Reg, false);
445 bool isSubRegister = DWReg < 0;
449 // Go up the super-register chain until we hit a valid dwarf register number.
450 for (MCSuperRegIterator SR(Reg, RI); SR.isValid() && DWReg < 0; ++SR) {
451 DWReg = RI->getDwarfRegNum(*SR, false);
453 Idx = RI->getSubRegIndex(*SR, Reg);
457 DEBUG(llvm::dbgs() << "Invalid Dwarf register number.\n");
458 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_nop);
464 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + DWReg);
466 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
467 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
472 unsigned Size = RI->getSubRegIdxSize(Idx);
473 unsigned Offset = RI->getSubRegIdxOffset(Idx);
475 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_bit_piece);
476 addUInt(TheDie, dwarf::DW_FORM_data1, Size);
477 addUInt(TheDie, dwarf::DW_FORM_data1, Offset);
479 unsigned ByteSize = Size / 8; // Assuming 8 bits per byte.
480 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_piece);
481 addUInt(TheDie, dwarf::DW_FORM_data1, ByteSize);
486 /// addRegisterOffset - Add register offset.
487 void DwarfUnit::addRegisterOffset(DIELoc *TheDie, unsigned Reg,
489 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
490 unsigned DWReg = RI->getDwarfRegNum(Reg, false);
491 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
492 if (Reg == TRI->getFrameRegister(*Asm->MF))
493 // If variable offset is based in frame register then use fbreg.
494 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_fbreg);
496 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + DWReg);
498 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
499 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
501 addSInt(TheDie, dwarf::DW_FORM_sdata, Offset);
504 /// addAddress - Add an address attribute to a die based on the location
506 void DwarfUnit::addAddress(DIE *Die, dwarf::Attribute Attribute,
507 const MachineLocation &Location, bool Indirect) {
508 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
510 if (Location.isReg() && !Indirect)
511 addRegisterOp(Loc, Location.getReg());
513 addRegisterOffset(Loc, Location.getReg(), Location.getOffset());
514 if (Indirect && !Location.isReg()) {
515 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
519 // Now attach the location information to the DIE.
520 addBlock(Die, Attribute, Loc);
523 /// addComplexAddress - Start with the address based on the location provided,
524 /// and generate the DWARF information necessary to find the actual variable
525 /// given the extra address information encoded in the DbgVariable, starting
526 /// from the starting location. Add the DWARF information to the die.
528 void DwarfUnit::addComplexAddress(const DbgVariable &DV, DIE *Die,
529 dwarf::Attribute Attribute,
530 const MachineLocation &Location) {
531 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
532 unsigned N = DV.getNumAddrElements();
534 if (Location.isReg()) {
535 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
536 // If first address element is OpPlus then emit
537 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
538 addRegisterOffset(Loc, Location.getReg(), DV.getAddrElement(1));
541 addRegisterOp(Loc, Location.getReg());
543 addRegisterOffset(Loc, Location.getReg(), Location.getOffset());
546 uint64_t Element = DV.getAddrElement(i);
547 if (Element == DIBuilder::OpPlus) {
548 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
549 addUInt(Loc, dwarf::DW_FORM_udata, DV.getAddrElement(++i));
550 } else if (Element == DIBuilder::OpDeref) {
551 if (!Location.isReg())
552 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
554 llvm_unreachable("unknown DIBuilder Opcode");
557 // Now attach the location information to the DIE.
558 addBlock(Die, Attribute, Loc);
561 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
562 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
563 gives the variable VarName either the struct, or a pointer to the struct, as
564 its type. This is necessary for various behind-the-scenes things the
565 compiler needs to do with by-reference variables in Blocks.
567 However, as far as the original *programmer* is concerned, the variable
568 should still have type 'SomeType', as originally declared.
570 The function getBlockByrefType dives into the __Block_byref_x_VarName
571 struct to find the original type of the variable, which is then assigned to
572 the variable's Debug Information Entry as its real type. So far, so good.
573 However now the debugger will expect the variable VarName to have the type
574 SomeType. So we need the location attribute for the variable to be an
575 expression that explains to the debugger how to navigate through the
576 pointers and struct to find the actual variable of type SomeType.
578 The following function does just that. We start by getting
579 the "normal" location for the variable. This will be the location
580 of either the struct __Block_byref_x_VarName or the pointer to the
581 struct __Block_byref_x_VarName.
583 The struct will look something like:
585 struct __Block_byref_x_VarName {
587 struct __Block_byref_x_VarName *forwarding;
588 ... <various other fields>
590 ... <maybe more fields>
593 If we are given the struct directly (as our starting point) we
594 need to tell the debugger to:
596 1). Add the offset of the forwarding field.
598 2). Follow that pointer to get the real __Block_byref_x_VarName
599 struct to use (the real one may have been copied onto the heap).
601 3). Add the offset for the field VarName, to find the actual variable.
603 If we started with a pointer to the struct, then we need to
604 dereference that pointer first, before the other steps.
605 Translating this into DWARF ops, we will need to append the following
606 to the current location description for the variable:
608 DW_OP_deref -- optional, if we start with a pointer
609 DW_OP_plus_uconst <forward_fld_offset>
611 DW_OP_plus_uconst <varName_fld_offset>
613 That is what this function does. */
615 /// addBlockByrefAddress - Start with the address based on the location
616 /// provided, and generate the DWARF information necessary to find the
617 /// actual Block variable (navigating the Block struct) based on the
618 /// starting location. Add the DWARF information to the die. For
619 /// more information, read large comment just above here.
621 void DwarfUnit::addBlockByrefAddress(const DbgVariable &DV, DIE *Die,
622 dwarf::Attribute Attribute,
623 const MachineLocation &Location) {
624 DIType Ty = DV.getType();
626 uint16_t Tag = Ty.getTag();
627 bool isPointer = false;
629 StringRef varName = DV.getName();
631 if (Tag == dwarf::DW_TAG_pointer_type) {
632 DIDerivedType DTy(Ty);
633 TmpTy = resolve(DTy.getTypeDerivedFrom());
637 DICompositeType blockStruct(TmpTy);
639 // Find the __forwarding field and the variable field in the __Block_byref
641 DIArray Fields = blockStruct.getTypeArray();
642 DIDerivedType varField;
643 DIDerivedType forwardingField;
645 for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
646 DIDerivedType DT(Fields.getElement(i));
647 StringRef fieldName = DT.getName();
648 if (fieldName == "__forwarding")
649 forwardingField = DT;
650 else if (fieldName == varName)
654 // Get the offsets for the forwarding field and the variable field.
655 unsigned forwardingFieldOffset = forwardingField.getOffsetInBits() >> 3;
656 unsigned varFieldOffset = varField.getOffsetInBits() >> 2;
658 // Decode the original location, and use that as the start of the byref
659 // variable's location.
660 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
662 if (Location.isReg())
663 addRegisterOp(Loc, Location.getReg());
665 addRegisterOffset(Loc, Location.getReg(), Location.getOffset());
667 // If we started with a pointer to the __Block_byref... struct, then
668 // the first thing we need to do is dereference the pointer (DW_OP_deref).
670 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
672 // Next add the offset for the '__forwarding' field:
673 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
674 // adding the offset if it's 0.
675 if (forwardingFieldOffset > 0) {
676 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
677 addUInt(Loc, dwarf::DW_FORM_udata, forwardingFieldOffset);
680 // Now dereference the __forwarding field to get to the real __Block_byref
681 // struct: DW_OP_deref.
682 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
684 // Now that we've got the real __Block_byref... struct, add the offset
685 // for the variable's field to get to the location of the actual variable:
686 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
687 if (varFieldOffset > 0) {
688 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
689 addUInt(Loc, dwarf::DW_FORM_udata, varFieldOffset);
692 // Now attach the location information to the DIE.
693 addBlock(Die, Attribute, Loc);
696 /// isTypeSigned - Return true if the type is signed.
697 static bool isTypeSigned(DwarfDebug *DD, DIType Ty, int *SizeInBits) {
698 if (Ty.isDerivedType())
699 return isTypeSigned(DD, DD->resolve(DIDerivedType(Ty).getTypeDerivedFrom()),
701 if (Ty.isBasicType())
702 if (DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed ||
703 DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed_char) {
704 *SizeInBits = Ty.getSizeInBits();
710 /// Return true if type encoding is unsigned.
711 static bool isUnsignedDIType(DwarfDebug *DD, DIType Ty) {
712 DIDerivedType DTy(Ty);
713 if (DTy.isDerivedType())
714 return isUnsignedDIType(DD, DD->resolve(DTy.getTypeDerivedFrom()));
717 if (BTy.isBasicType()) {
718 unsigned Encoding = BTy.getEncoding();
719 if (Encoding == dwarf::DW_ATE_unsigned ||
720 Encoding == dwarf::DW_ATE_unsigned_char ||
721 Encoding == dwarf::DW_ATE_boolean)
727 /// If this type is derived from a base type then return base type size.
728 static uint64_t getBaseTypeSize(DwarfDebug *DD, DIDerivedType Ty) {
729 unsigned Tag = Ty.getTag();
731 if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef &&
732 Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type &&
733 Tag != dwarf::DW_TAG_restrict_type)
734 return Ty.getSizeInBits();
736 DIType BaseType = DD->resolve(Ty.getTypeDerivedFrom());
738 // If this type is not derived from any type then take conservative approach.
739 if (!BaseType.isValid())
740 return Ty.getSizeInBits();
742 // If this is a derived type, go ahead and get the base type, unless it's a
743 // reference then it's just the size of the field. Pointer types have no need
744 // of this since they're a different type of qualification on the type.
745 if (BaseType.getTag() == dwarf::DW_TAG_reference_type ||
746 BaseType.getTag() == dwarf::DW_TAG_rvalue_reference_type)
747 return Ty.getSizeInBits();
749 if (BaseType.isDerivedType())
750 return getBaseTypeSize(DD, DIDerivedType(BaseType));
752 return BaseType.getSizeInBits();
755 /// addConstantValue - Add constant value entry in variable DIE.
756 void DwarfUnit::addConstantValue(DIE *Die, const MachineOperand &MO,
758 // FIXME: This is a bit conservative/simple - it emits negative values at
759 // their maximum bit width which is a bit unfortunate (& doesn't prefer
760 // udata/sdata over dataN as suggested by the DWARF spec)
761 assert(MO.isImm() && "Invalid machine operand!");
763 bool SignedConstant = isTypeSigned(DD, Ty, &SizeInBits);
766 // If we're a signed constant definitely use sdata.
767 if (SignedConstant) {
768 addSInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, MO.getImm());
772 // Else use data for now unless it's larger than we can deal with.
773 switch (SizeInBits) {
775 Form = dwarf::DW_FORM_data1;
778 Form = dwarf::DW_FORM_data2;
781 Form = dwarf::DW_FORM_data4;
784 Form = dwarf::DW_FORM_data8;
787 Form = dwarf::DW_FORM_udata;
788 addUInt(Die, dwarf::DW_AT_const_value, Form, MO.getImm());
791 addUInt(Die, dwarf::DW_AT_const_value, Form, MO.getImm());
794 /// addConstantFPValue - Add constant value entry in variable DIE.
795 void DwarfUnit::addConstantFPValue(DIE *Die, const MachineOperand &MO) {
796 assert(MO.isFPImm() && "Invalid machine operand!");
797 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
798 APFloat FPImm = MO.getFPImm()->getValueAPF();
800 // Get the raw data form of the floating point.
801 const APInt FltVal = FPImm.bitcastToAPInt();
802 const char *FltPtr = (const char *)FltVal.getRawData();
804 int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
805 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
806 int Incr = (LittleEndian ? 1 : -1);
807 int Start = (LittleEndian ? 0 : NumBytes - 1);
808 int Stop = (LittleEndian ? NumBytes : -1);
810 // Output the constant to DWARF one byte at a time.
811 for (; Start != Stop; Start += Incr)
812 addUInt(Block, dwarf::DW_FORM_data1, (unsigned char)0xFF & FltPtr[Start]);
814 addBlock(Die, dwarf::DW_AT_const_value, Block);
817 /// addConstantFPValue - Add constant value entry in variable DIE.
818 void DwarfUnit::addConstantFPValue(DIE *Die, const ConstantFP *CFP) {
819 // Pass this down to addConstantValue as an unsigned bag of bits.
820 addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true);
823 /// addConstantValue - Add constant value entry in variable DIE.
824 void DwarfUnit::addConstantValue(DIE *Die, const ConstantInt *CI,
826 addConstantValue(Die, CI->getValue(), Unsigned);
829 // addConstantValue - Add constant value entry in variable DIE.
830 void DwarfUnit::addConstantValue(DIE *Die, const APInt &Val, bool Unsigned) {
831 unsigned CIBitWidth = Val.getBitWidth();
832 if (CIBitWidth <= 64) {
833 // If we're a signed constant definitely use sdata.
835 addSInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
840 // Else use data for now unless it's larger than we can deal with.
842 switch (CIBitWidth) {
844 Form = dwarf::DW_FORM_data1;
847 Form = dwarf::DW_FORM_data2;
850 Form = dwarf::DW_FORM_data4;
853 Form = dwarf::DW_FORM_data8;
856 addUInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_udata,
860 addUInt(Die, dwarf::DW_AT_const_value, Form, Val.getZExtValue());
864 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
866 // Get the raw data form of the large APInt.
867 const uint64_t *Ptr64 = Val.getRawData();
869 int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
870 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
872 // Output the constant to DWARF one byte at a time.
873 for (int i = 0; i < NumBytes; i++) {
876 c = Ptr64[i / 8] >> (8 * (i & 7));
878 c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
879 addUInt(Block, dwarf::DW_FORM_data1, c);
882 addBlock(Die, dwarf::DW_AT_const_value, Block);
885 /// addTemplateParams - Add template parameters into buffer.
886 void DwarfUnit::addTemplateParams(DIE &Buffer, DIArray TParams) {
887 // Add template parameters.
888 for (unsigned i = 0, e = TParams.getNumElements(); i != e; ++i) {
889 DIDescriptor Element = TParams.getElement(i);
890 if (Element.isTemplateTypeParameter())
891 constructTemplateTypeParameterDIE(Buffer,
892 DITemplateTypeParameter(Element));
893 else if (Element.isTemplateValueParameter())
894 constructTemplateValueParameterDIE(Buffer,
895 DITemplateValueParameter(Element));
899 /// getOrCreateContextDIE - Get context owner's DIE.
900 DIE *DwarfUnit::getOrCreateContextDIE(DIScope Context) {
901 if (!Context || Context.isFile())
903 if (Context.isType())
904 return getOrCreateTypeDIE(DIType(Context));
905 if (Context.isNameSpace())
906 return getOrCreateNameSpace(DINameSpace(Context));
907 if (Context.isSubprogram())
908 return getOrCreateSubprogramDIE(DISubprogram(Context));
909 return getDIE(Context);
912 DIE *DwarfUnit::createTypeDIE(DICompositeType Ty) {
913 DIScope Context = resolve(Ty.getContext());
914 DIE *ContextDIE = getOrCreateContextDIE(Context);
916 DIE *TyDIE = getDIE(Ty);
921 TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
923 constructTypeDIE(*TyDIE, Ty);
925 updateAcceleratorTables(Context, Ty, TyDIE);
929 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
931 DIE *DwarfUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
938 // Construct the context before querying for the existence of the DIE in case
939 // such construction creates the DIE.
940 DIScope Context = resolve(Ty.getContext());
941 DIE *ContextDIE = getOrCreateContextDIE(Context);
944 DIE *TyDIE = getDIE(Ty);
949 TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
951 if (Ty.isBasicType())
952 constructTypeDIE(*TyDIE, DIBasicType(Ty));
953 else if (Ty.isCompositeType()) {
954 DICompositeType CTy(Ty);
955 if (GenerateDwarfTypeUnits && !Ty.isForwardDecl())
956 if (MDString *TypeId = CTy.getIdentifier()) {
957 DD->addDwarfTypeUnitType(getCU(), TypeId->getString(), TyDIE, CTy);
958 // Skip updating the accellerator tables since this is not the full type
961 constructTypeDIE(*TyDIE, CTy);
963 assert(Ty.isDerivedType() && "Unknown kind of DIType");
964 constructTypeDIE(*TyDIE, DIDerivedType(Ty));
967 updateAcceleratorTables(Context, Ty, TyDIE);
972 void DwarfUnit::updateAcceleratorTables(DIScope Context, DIType Ty,
974 if (!Ty.getName().empty() && !Ty.isForwardDecl()) {
975 bool IsImplementation = 0;
976 if (Ty.isCompositeType()) {
977 DICompositeType CT(Ty);
978 // A runtime language of 0 actually means C/C++ and that any
979 // non-negative value is some version of Objective-C/C++.
980 IsImplementation = (CT.getRunTimeLang() == 0) || CT.isObjcClassComplete();
982 unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0;
983 addAccelType(Ty.getName(), std::make_pair(TyDIE, Flags));
985 if (!Context || Context.isCompileUnit() || Context.isFile() ||
986 Context.isNameSpace())
987 GlobalTypes[getParentContextString(Context) + Ty.getName().str()] = TyDIE;
991 /// addType - Add a new type attribute to the specified entity.
992 void DwarfUnit::addType(DIE *Entity, DIType Ty, dwarf::Attribute Attribute) {
993 assert(Ty && "Trying to add a type that doesn't exist?");
995 // Check for pre-existence.
996 DIEEntry *Entry = getDIEEntry(Ty);
997 // If it exists then use the existing value.
999 addDIEEntry(Entity, Attribute, Entry);
1004 DIE *Buffer = getOrCreateTypeDIE(Ty);
1007 Entry = createDIEEntry(Buffer);
1008 insertDIEEntry(Ty, Entry);
1009 addDIEEntry(Entity, Attribute, Entry);
1012 // Accelerator table mutators - add each name along with its companion
1013 // DIE to the proper table while ensuring that the name that we're going
1014 // to reference is in the string table. We do this since the names we
1015 // add may not only be identical to the names in the DIE.
1016 void DwarfUnit::addAccelName(StringRef Name, const DIE *Die) {
1017 if (!DD->useDwarfAccelTables())
1019 DU->getStringPoolEntry(Name);
1020 std::vector<const DIE *> &DIEs = AccelNames[Name];
1021 DIEs.push_back(Die);
1024 void DwarfUnit::addAccelObjC(StringRef Name, const DIE *Die) {
1025 if (!DD->useDwarfAccelTables())
1027 DU->getStringPoolEntry(Name);
1028 std::vector<const DIE *> &DIEs = AccelObjC[Name];
1029 DIEs.push_back(Die);
1032 void DwarfUnit::addAccelNamespace(StringRef Name, const DIE *Die) {
1033 if (!DD->useDwarfAccelTables())
1035 DU->getStringPoolEntry(Name);
1036 std::vector<const DIE *> &DIEs = AccelNamespace[Name];
1037 DIEs.push_back(Die);
1040 void DwarfUnit::addAccelType(StringRef Name,
1041 std::pair<const DIE *, unsigned> Die) {
1042 if (!DD->useDwarfAccelTables())
1044 DU->getStringPoolEntry(Name);
1045 std::vector<std::pair<const DIE *, unsigned> > &DIEs = AccelTypes[Name];
1046 DIEs.push_back(Die);
1049 /// addGlobalName - Add a new global name to the compile unit.
1050 void DwarfUnit::addGlobalName(StringRef Name, DIE *Die, DIScope Context) {
1051 std::string FullName = getParentContextString(Context) + Name.str();
1052 GlobalNames[FullName] = Die;
1055 /// getParentContextString - Walks the metadata parent chain in a language
1056 /// specific manner (using the compile unit language) and returns
1057 /// it as a string. This is done at the metadata level because DIEs may
1058 /// not currently have been added to the parent context and walking the
1059 /// DIEs looking for names is more expensive than walking the metadata.
1060 std::string DwarfUnit::getParentContextString(DIScope Context) const {
1064 // FIXME: Decide whether to implement this for non-C++ languages.
1065 if (getLanguage() != dwarf::DW_LANG_C_plus_plus)
1069 SmallVector<DIScope, 1> Parents;
1070 while (!Context.isCompileUnit()) {
1071 Parents.push_back(Context);
1072 if (Context.getContext())
1073 Context = resolve(Context.getContext());
1075 // Structure, etc types will have a NULL context if they're at the top
1080 // Reverse iterate over our list to go from the outermost construct to the
1082 for (SmallVectorImpl<DIScope>::reverse_iterator I = Parents.rbegin(),
1086 StringRef Name = Ctx.getName();
1087 if (!Name.empty()) {
1095 /// constructTypeDIE - Construct basic type die from DIBasicType.
1096 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
1097 // Get core information.
1098 StringRef Name = BTy.getName();
1099 // Add name if not anonymous or intermediate type.
1101 addString(&Buffer, dwarf::DW_AT_name, Name);
1103 // An unspecified type only has a name attribute.
1104 if (BTy.getTag() == dwarf::DW_TAG_unspecified_type)
1107 addUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1110 uint64_t Size = BTy.getSizeInBits() >> 3;
1111 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1114 /// constructTypeDIE - Construct derived type die from DIDerivedType.
1115 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
1116 // Get core information.
1117 StringRef Name = DTy.getName();
1118 uint64_t Size = DTy.getSizeInBits() >> 3;
1119 uint16_t Tag = Buffer.getTag();
1121 // Map to main type, void will not have a type.
1122 DIType FromTy = resolve(DTy.getTypeDerivedFrom());
1124 addType(&Buffer, FromTy);
1126 // Add name if not anonymous or intermediate type.
1128 addString(&Buffer, dwarf::DW_AT_name, Name);
1130 // Add size if non-zero (derived types might be zero-sized.)
1131 if (Size && Tag != dwarf::DW_TAG_pointer_type)
1132 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1134 if (Tag == dwarf::DW_TAG_ptr_to_member_type)
1135 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type,
1136 getOrCreateTypeDIE(resolve(DTy.getClassType())));
1137 // Add source line info if available and TyDesc is not a forward declaration.
1138 if (!DTy.isForwardDecl())
1139 addSourceLine(&Buffer, DTy);
1142 /// constructTypeDIE - Construct type DIE from DICompositeType.
1143 void DwarfUnit::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
1144 // Add name if not anonymous or intermediate type.
1145 StringRef Name = CTy.getName();
1147 uint64_t Size = CTy.getSizeInBits() >> 3;
1148 uint16_t Tag = Buffer.getTag();
1151 case dwarf::DW_TAG_array_type:
1152 constructArrayTypeDIE(Buffer, CTy);
1154 case dwarf::DW_TAG_enumeration_type:
1155 constructEnumTypeDIE(Buffer, CTy);
1157 case dwarf::DW_TAG_subroutine_type: {
1158 // Add return type. A void return won't have a type.
1159 DIArray Elements = CTy.getTypeArray();
1160 DIType RTy(Elements.getElement(0));
1162 addType(&Buffer, RTy);
1164 bool isPrototyped = true;
1166 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
1167 DIDescriptor Ty = Elements.getElement(i);
1168 if (Ty.isUnspecifiedParameter()) {
1169 createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
1170 isPrototyped = false;
1172 DIE *Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
1173 addType(Arg, DIType(Ty));
1174 if (DIType(Ty).isArtificial())
1175 addFlag(Arg, dwarf::DW_AT_artificial);
1178 // Add prototype flag if we're dealing with a C language and the
1179 // function has been prototyped.
1180 uint16_t Language = getLanguage();
1182 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1183 Language == dwarf::DW_LANG_ObjC))
1184 addFlag(&Buffer, dwarf::DW_AT_prototyped);
1186 if (CTy.isLValueReference())
1187 addFlag(&Buffer, dwarf::DW_AT_reference);
1189 if (CTy.isRValueReference())
1190 addFlag(&Buffer, dwarf::DW_AT_rvalue_reference);
1192 case dwarf::DW_TAG_structure_type:
1193 case dwarf::DW_TAG_union_type:
1194 case dwarf::DW_TAG_class_type: {
1195 // Add elements to structure type.
1196 DIArray Elements = CTy.getTypeArray();
1197 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1198 DIDescriptor Element = Elements.getElement(i);
1199 DIE *ElemDie = NULL;
1200 if (Element.isSubprogram())
1201 ElemDie = getOrCreateSubprogramDIE(DISubprogram(Element));
1202 else if (Element.isDerivedType()) {
1203 DIDerivedType DDTy(Element);
1204 if (DDTy.getTag() == dwarf::DW_TAG_friend) {
1205 ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
1206 addType(ElemDie, resolve(DDTy.getTypeDerivedFrom()),
1207 dwarf::DW_AT_friend);
1208 } else if (DDTy.isStaticMember()) {
1209 getOrCreateStaticMemberDIE(DDTy);
1211 constructMemberDIE(Buffer, DDTy);
1213 } else if (Element.isObjCProperty()) {
1214 DIObjCProperty Property(Element);
1215 ElemDie = createAndAddDIE(Property.getTag(), Buffer);
1216 StringRef PropertyName = Property.getObjCPropertyName();
1217 addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
1218 if (Property.getType())
1219 addType(ElemDie, Property.getType());
1220 addSourceLine(ElemDie, Property);
1221 StringRef GetterName = Property.getObjCPropertyGetterName();
1222 if (!GetterName.empty())
1223 addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
1224 StringRef SetterName = Property.getObjCPropertySetterName();
1225 if (!SetterName.empty())
1226 addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
1227 unsigned PropertyAttributes = 0;
1228 if (Property.isReadOnlyObjCProperty())
1229 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readonly;
1230 if (Property.isReadWriteObjCProperty())
1231 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readwrite;
1232 if (Property.isAssignObjCProperty())
1233 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_assign;
1234 if (Property.isRetainObjCProperty())
1235 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_retain;
1236 if (Property.isCopyObjCProperty())
1237 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_copy;
1238 if (Property.isNonAtomicObjCProperty())
1239 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_nonatomic;
1240 if (PropertyAttributes)
1241 addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None,
1242 PropertyAttributes);
1244 DIEEntry *Entry = getDIEEntry(Element);
1246 Entry = createDIEEntry(ElemDie);
1247 insertDIEEntry(Element, Entry);
1253 if (CTy.isAppleBlockExtension())
1254 addFlag(&Buffer, dwarf::DW_AT_APPLE_block);
1256 DICompositeType ContainingType(resolve(CTy.getContainingType()));
1258 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type,
1259 getOrCreateTypeDIE(ContainingType));
1261 if (CTy.isObjcClassComplete())
1262 addFlag(&Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
1264 // Add template parameters to a class, structure or union types.
1265 // FIXME: The support isn't in the metadata for this yet.
1266 if (Tag == dwarf::DW_TAG_class_type ||
1267 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
1268 addTemplateParams(Buffer, CTy.getTemplateParams());
1276 // Add name if not anonymous or intermediate type.
1278 addString(&Buffer, dwarf::DW_AT_name, Name);
1280 if (Tag == dwarf::DW_TAG_enumeration_type ||
1281 Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
1282 Tag == dwarf::DW_TAG_union_type) {
1283 // Add size if non-zero (derived types might be zero-sized.)
1284 // TODO: Do we care about size for enum forward declarations?
1286 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1287 else if (!CTy.isForwardDecl())
1288 // Add zero size if it is not a forward declaration.
1289 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, 0);
1291 // If we're a forward decl, say so.
1292 if (CTy.isForwardDecl())
1293 addFlag(&Buffer, dwarf::DW_AT_declaration);
1295 // Add source line info if available.
1296 if (!CTy.isForwardDecl())
1297 addSourceLine(&Buffer, CTy);
1299 // No harm in adding the runtime language to the declaration.
1300 unsigned RLang = CTy.getRunTimeLang();
1302 addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
1307 /// constructTemplateTypeParameterDIE - Construct new DIE for the given
1308 /// DITemplateTypeParameter.
1309 void DwarfUnit::constructTemplateTypeParameterDIE(DIE &Buffer,
1310 DITemplateTypeParameter TP) {
1312 createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
1313 // Add the type if it exists, it could be void and therefore no type.
1315 addType(ParamDIE, resolve(TP.getType()));
1316 if (!TP.getName().empty())
1317 addString(ParamDIE, dwarf::DW_AT_name, TP.getName());
1320 /// constructTemplateValueParameterDIE - Construct new DIE for the given
1321 /// DITemplateValueParameter.
1323 DwarfUnit::constructTemplateValueParameterDIE(DIE &Buffer,
1324 DITemplateValueParameter VP) {
1325 DIE *ParamDIE = createAndAddDIE(VP.getTag(), Buffer);
1327 // Add the type if there is one, template template and template parameter
1328 // packs will not have a type.
1329 if (VP.getTag() == dwarf::DW_TAG_template_value_parameter)
1330 addType(ParamDIE, resolve(VP.getType()));
1331 if (!VP.getName().empty())
1332 addString(ParamDIE, dwarf::DW_AT_name, VP.getName());
1333 if (Value *Val = VP.getValue()) {
1334 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val))
1335 addConstantValue(ParamDIE, CI,
1336 isUnsignedDIType(DD, resolve(VP.getType())));
1337 else if (GlobalValue *GV = dyn_cast<GlobalValue>(Val)) {
1338 // For declaration non-type template parameters (such as global values and
1340 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
1341 addOpAddress(Loc, Asm->getSymbol(GV));
1342 // Emit DW_OP_stack_value to use the address as the immediate value of the
1343 // parameter, rather than a pointer to it.
1344 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
1345 addBlock(ParamDIE, dwarf::DW_AT_location, Loc);
1346 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1347 assert(isa<MDString>(Val));
1348 addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
1349 cast<MDString>(Val)->getString());
1350 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1351 assert(isa<MDNode>(Val));
1352 DIArray A(cast<MDNode>(Val));
1353 addTemplateParams(*ParamDIE, A);
1358 /// getOrCreateNameSpace - Create a DIE for DINameSpace.
1359 DIE *DwarfUnit::getOrCreateNameSpace(DINameSpace NS) {
1360 // Construct the context before querying for the existence of the DIE in case
1361 // such construction creates the DIE.
1362 DIE *ContextDIE = getOrCreateContextDIE(NS.getContext());
1364 DIE *NDie = getDIE(NS);
1367 NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS);
1369 if (!NS.getName().empty()) {
1370 addString(NDie, dwarf::DW_AT_name, NS.getName());
1371 addAccelNamespace(NS.getName(), NDie);
1372 addGlobalName(NS.getName(), NDie, NS.getContext());
1374 addAccelNamespace("(anonymous namespace)", NDie);
1375 addSourceLine(NDie, NS);
1379 /// getOrCreateSubprogramDIE - Create new DIE using SP.
1380 DIE *DwarfUnit::getOrCreateSubprogramDIE(DISubprogram SP) {
1381 // Construct the context before querying for the existence of the DIE in case
1382 // such construction creates the DIE (as is the case for member function
1384 DIE *ContextDIE = getOrCreateContextDIE(resolve(SP.getContext()));
1386 DIE *SPDie = getDIE(SP);
1390 DISubprogram SPDecl = SP.getFunctionDeclaration();
1391 if (SPDecl.isSubprogram())
1392 // Add subprogram definitions to the CU die directly.
1393 ContextDIE = UnitDie.get();
1395 // DW_TAG_inlined_subroutine may refer to this DIE.
1396 SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
1398 DIE *DeclDie = NULL;
1399 if (SPDecl.isSubprogram())
1400 DeclDie = getOrCreateSubprogramDIE(SPDecl);
1402 // Add function template parameters.
1403 addTemplateParams(*SPDie, SP.getTemplateParams());
1405 // If this DIE is going to refer declaration info using AT_specification
1406 // then there is no need to add other attributes.
1408 // Refer function declaration directly.
1409 addDIEEntry(SPDie, dwarf::DW_AT_specification, DeclDie);
1414 // Add the linkage name if we have one.
1415 StringRef LinkageName = SP.getLinkageName();
1416 if (!LinkageName.empty())
1417 addString(SPDie, dwarf::DW_AT_MIPS_linkage_name,
1418 GlobalValue::getRealLinkageName(LinkageName));
1420 // Constructors and operators for anonymous aggregates do not have names.
1421 if (!SP.getName().empty())
1422 addString(SPDie, dwarf::DW_AT_name, SP.getName());
1424 addSourceLine(SPDie, SP);
1426 // Add the prototype if we have a prototype and we have a C like
1428 uint16_t Language = getLanguage();
1429 if (SP.isPrototyped() &&
1430 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1431 Language == dwarf::DW_LANG_ObjC))
1432 addFlag(SPDie, dwarf::DW_AT_prototyped);
1434 DICompositeType SPTy = SP.getType();
1435 assert(SPTy.getTag() == dwarf::DW_TAG_subroutine_type &&
1436 "the type of a subprogram should be a subroutine");
1438 DIArray Args = SPTy.getTypeArray();
1439 // Add a return type. If this is a type like a C/C++ void type we don't add a
1441 if (Args.getElement(0))
1442 addType(SPDie, DIType(Args.getElement(0)));
1444 unsigned VK = SP.getVirtuality();
1446 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1447 DIELoc *Block = getDIELoc();
1448 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1449 addUInt(Block, dwarf::DW_FORM_udata, SP.getVirtualIndex());
1450 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
1451 ContainingTypeMap.insert(
1452 std::make_pair(SPDie, resolve(SP.getContainingType())));
1455 if (!SP.isDefinition()) {
1456 addFlag(SPDie, dwarf::DW_AT_declaration);
1458 // Add arguments. Do not add arguments for subprogram definition. They will
1459 // be handled while processing variables.
1460 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1461 DIE *Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, *SPDie);
1462 DIType ATy(Args.getElement(i));
1464 if (ATy.isArtificial())
1465 addFlag(Arg, dwarf::DW_AT_artificial);
1469 if (SP.isArtificial())
1470 addFlag(SPDie, dwarf::DW_AT_artificial);
1472 if (!SP.isLocalToUnit())
1473 addFlag(SPDie, dwarf::DW_AT_external);
1475 if (SP.isOptimized())
1476 addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1478 if (unsigned isa = Asm->getISAEncoding()) {
1479 addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1482 if (SP.isLValueReference())
1483 addFlag(SPDie, dwarf::DW_AT_reference);
1485 if (SP.isRValueReference())
1486 addFlag(SPDie, dwarf::DW_AT_rvalue_reference);
1488 if (SP.isProtected())
1489 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1490 dwarf::DW_ACCESS_protected);
1491 else if (SP.isPrivate())
1492 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1493 dwarf::DW_ACCESS_private);
1495 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1496 dwarf::DW_ACCESS_public);
1498 if (SP.isExplicit())
1499 addFlag(SPDie, dwarf::DW_AT_explicit);
1504 // Return const expression if value is a GEP to access merged global
1506 // i8* getelementptr ({ i8, i8, i8, i8 }* @_MergedGlobals, i32 0, i32 0)
1507 static const ConstantExpr *getMergedGlobalExpr(const Value *V) {
1508 const ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(V);
1509 if (!CE || CE->getNumOperands() != 3 ||
1510 CE->getOpcode() != Instruction::GetElementPtr)
1513 // First operand points to a global struct.
1514 Value *Ptr = CE->getOperand(0);
1515 if (!isa<GlobalValue>(Ptr) ||
1516 !isa<StructType>(cast<PointerType>(Ptr->getType())->getElementType()))
1519 // Second operand is zero.
1520 const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(CE->getOperand(1));
1521 if (!CI || !CI->isZero())
1524 // Third operand is offset.
1525 if (!isa<ConstantInt>(CE->getOperand(2)))
1531 /// createGlobalVariableDIE - create global variable DIE.
1532 void DwarfCompileUnit::createGlobalVariableDIE(DIGlobalVariable GV) {
1533 // Check for pre-existence.
1537 assert(GV.isGlobalVariable());
1539 DIScope GVContext = GV.getContext();
1540 DIType GTy = GV.getType();
1542 // If this is a static data member definition, some attributes belong
1543 // to the declaration DIE.
1544 DIE *VariableDIE = NULL;
1545 bool IsStaticMember = false;
1546 DIDerivedType SDMDecl = GV.getStaticDataMemberDeclaration();
1547 if (SDMDecl.Verify()) {
1548 assert(SDMDecl.isStaticMember() && "Expected static member decl");
1549 // We need the declaration DIE that is in the static member's class.
1550 VariableDIE = getOrCreateStaticMemberDIE(SDMDecl);
1551 IsStaticMember = true;
1554 // If this is not a static data member definition, create the variable
1555 // DIE and add the initial set of attributes to it.
1557 // Construct the context before querying for the existence of the DIE in
1558 // case such construction creates the DIE.
1559 DIE *ContextDIE = getOrCreateContextDIE(GVContext);
1562 VariableDIE = createAndAddDIE(GV.getTag(), *ContextDIE, GV);
1564 // Add name and type.
1565 addString(VariableDIE, dwarf::DW_AT_name, GV.getDisplayName());
1566 addType(VariableDIE, GTy);
1568 // Add scoping info.
1569 if (!GV.isLocalToUnit())
1570 addFlag(VariableDIE, dwarf::DW_AT_external);
1572 // Add line number info.
1573 addSourceLine(VariableDIE, GV);
1577 bool addToAccelTable = false;
1578 DIE *VariableSpecDIE = NULL;
1579 bool isGlobalVariable = GV.getGlobal() != NULL;
1580 if (isGlobalVariable) {
1581 addToAccelTable = true;
1582 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
1583 const MCSymbol *Sym = Asm->getSymbol(GV.getGlobal());
1584 if (GV.getGlobal()->isThreadLocal()) {
1585 // FIXME: Make this work with -gsplit-dwarf.
1586 unsigned PointerSize = Asm->getDataLayout().getPointerSize();
1587 assert((PointerSize == 4 || PointerSize == 8) &&
1588 "Add support for other sizes if necessary");
1589 // Based on GCC's support for TLS:
1590 if (!DD->useSplitDwarf()) {
1591 // 1) Start with a constNu of the appropriate pointer size
1592 addUInt(Loc, dwarf::DW_FORM_data1,
1593 PointerSize == 4 ? dwarf::DW_OP_const4u : dwarf::DW_OP_const8u);
1594 // 2) containing the (relocated) offset of the TLS variable
1595 // within the module's TLS block.
1596 addExpr(Loc, dwarf::DW_FORM_udata,
1597 Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym));
1599 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
1600 addUInt(Loc, dwarf::DW_FORM_udata,
1601 DU->getAddrPoolIndex(Sym, /* TLS */ true));
1603 // 3) followed by a custom OP to make the debugger do a TLS lookup.
1604 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_push_tls_address);
1606 DD->addArangeLabel(SymbolCU(this, Sym));
1607 addOpAddress(Loc, Sym);
1609 // Do not create specification DIE if context is either compile unit
1611 if (GVContext && GV.isDefinition() && !GVContext.isCompileUnit() &&
1612 !GVContext.isFile() && !DD->isSubprogramContext(GVContext)) {
1613 // Create specification DIE.
1614 VariableSpecDIE = createAndAddDIE(dwarf::DW_TAG_variable, *UnitDie);
1615 addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification, VariableDIE);
1616 addBlock(VariableSpecDIE, dwarf::DW_AT_location, Loc);
1617 // A static member's declaration is already flagged as such.
1618 if (!SDMDecl.Verify())
1619 addFlag(VariableDIE, dwarf::DW_AT_declaration);
1621 addBlock(VariableDIE, dwarf::DW_AT_location, Loc);
1623 // Add the linkage name.
1624 StringRef LinkageName = GV.getLinkageName();
1625 if (!LinkageName.empty())
1626 // From DWARF4: DIEs to which DW_AT_linkage_name may apply include:
1627 // TAG_common_block, TAG_constant, TAG_entry_point, TAG_subprogram and
1629 addString(IsStaticMember && VariableSpecDIE ? VariableSpecDIE
1631 dwarf::DW_AT_MIPS_linkage_name,
1632 GlobalValue::getRealLinkageName(LinkageName));
1633 } else if (const ConstantInt *CI =
1634 dyn_cast_or_null<ConstantInt>(GV.getConstant())) {
1635 // AT_const_value was added when the static member was created. To avoid
1636 // emitting AT_const_value multiple times, we only add AT_const_value when
1637 // it is not a static member.
1638 if (!IsStaticMember)
1639 addConstantValue(VariableDIE, CI, isUnsignedDIType(DD, GTy));
1640 } else if (const ConstantExpr *CE = getMergedGlobalExpr(GV->getOperand(11))) {
1641 addToAccelTable = true;
1642 // GV is a merged global.
1643 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
1644 Value *Ptr = CE->getOperand(0);
1645 MCSymbol *Sym = Asm->getSymbol(cast<GlobalValue>(Ptr));
1646 DD->addArangeLabel(SymbolCU(this, Sym));
1647 addOpAddress(Loc, Sym);
1648 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1649 SmallVector<Value *, 3> Idx(CE->op_begin() + 1, CE->op_end());
1650 addUInt(Loc, dwarf::DW_FORM_udata,
1651 Asm->getDataLayout().getIndexedOffset(Ptr->getType(), Idx));
1652 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1653 addBlock(VariableDIE, dwarf::DW_AT_location, Loc);
1656 if (addToAccelTable) {
1657 DIE *AddrDIE = VariableSpecDIE ? VariableSpecDIE : VariableDIE;
1658 addAccelName(GV.getName(), AddrDIE);
1660 // If the linkage name is different than the name, go ahead and output
1661 // that as well into the name table.
1662 if (GV.getLinkageName() != "" && GV.getName() != GV.getLinkageName())
1663 addAccelName(GV.getLinkageName(), AddrDIE);
1666 if (!GV.isLocalToUnit())
1667 addGlobalName(GV.getName(), VariableSpecDIE ? VariableSpecDIE : VariableDIE,
1671 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
1672 void DwarfUnit::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy) {
1673 DIE *DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
1674 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, IndexTy);
1676 // The LowerBound value defines the lower bounds which is typically zero for
1677 // C/C++. The Count value is the number of elements. Values are 64 bit. If
1678 // Count == -1 then the array is unbounded and we do not emit
1679 // DW_AT_lower_bound and DW_AT_upper_bound attributes. If LowerBound == 0 and
1680 // Count == 0, then the array has zero elements in which case we do not emit
1682 int64_t LowerBound = SR.getLo();
1683 int64_t DefaultLowerBound = getDefaultLowerBound();
1684 int64_t Count = SR.getCount();
1686 if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
1687 addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound);
1689 if (Count != -1 && Count != 0)
1690 // FIXME: An unbounded array should reference the expression that defines
1692 addUInt(DW_Subrange, dwarf::DW_AT_upper_bound, None,
1693 LowerBound + Count - 1);
1696 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
1697 void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, DICompositeType CTy) {
1699 addFlag(&Buffer, dwarf::DW_AT_GNU_vector);
1701 // Emit the element type.
1702 addType(&Buffer, resolve(CTy.getTypeDerivedFrom()));
1704 // Get an anonymous type for index type.
1705 // FIXME: This type should be passed down from the front end
1706 // as different languages may have different sizes for indexes.
1707 DIE *IdxTy = getIndexTyDie();
1709 // Construct an anonymous type for index type.
1710 IdxTy = createAndAddDIE(dwarf::DW_TAG_base_type, *UnitDie);
1711 addString(IdxTy, dwarf::DW_AT_name, "int");
1712 addUInt(IdxTy, dwarf::DW_AT_byte_size, None, sizeof(int32_t));
1713 addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1714 dwarf::DW_ATE_signed);
1715 setIndexTyDie(IdxTy);
1718 // Add subranges to array type.
1719 DIArray Elements = CTy.getTypeArray();
1720 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1721 DIDescriptor Element = Elements.getElement(i);
1722 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1723 constructSubrangeDIE(Buffer, DISubrange(Element), IdxTy);
1727 /// constructEnumTypeDIE - Construct an enum type DIE from DICompositeType.
1728 void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, DICompositeType CTy) {
1729 DIArray Elements = CTy.getTypeArray();
1731 // Add enumerators to enumeration type.
1732 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1733 DIEnumerator Enum(Elements.getElement(i));
1734 if (Enum.isEnumerator()) {
1735 DIE *Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
1736 StringRef Name = Enum.getName();
1737 addString(Enumerator, dwarf::DW_AT_name, Name);
1738 int64_t Value = Enum.getEnumValue();
1739 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
1743 DIType DTy = resolve(CTy.getTypeDerivedFrom());
1745 addType(&Buffer, DTy);
1746 addFlag(&Buffer, dwarf::DW_AT_enum_class);
1750 /// constructContainingTypeDIEs - Construct DIEs for types that contain
1752 void DwarfUnit::constructContainingTypeDIEs() {
1753 for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(),
1754 CE = ContainingTypeMap.end();
1756 DIE *SPDie = CI->first;
1757 DIDescriptor D(CI->second);
1760 DIE *NDie = getDIE(D);
1763 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, NDie);
1767 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
1768 DIE *DwarfUnit::constructVariableDIE(DbgVariable &DV, bool isScopeAbstract) {
1769 StringRef Name = DV.getName();
1771 // Define variable debug information entry.
1772 DIE *VariableDie = new DIE(DV.getTag());
1773 DbgVariable *AbsVar = DV.getAbstractVariable();
1774 DIE *AbsDIE = AbsVar ? AbsVar->getDIE() : NULL;
1776 addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin, AbsDIE);
1779 addString(VariableDie, dwarf::DW_AT_name, Name);
1780 addSourceLine(VariableDie, DV.getVariable());
1781 addType(VariableDie, DV.getType());
1784 if (DV.isArtificial())
1785 addFlag(VariableDie, dwarf::DW_AT_artificial);
1787 if (isScopeAbstract) {
1788 DV.setDIE(VariableDie);
1792 // Add variable address.
1794 unsigned Offset = DV.getDotDebugLocOffset();
1795 if (Offset != ~0U) {
1796 addSectionLabel(VariableDie, dwarf::DW_AT_location,
1797 Asm->GetTempSymbol("debug_loc", Offset));
1798 DV.setDIE(VariableDie);
1802 // Check if variable is described by a DBG_VALUE instruction.
1803 if (const MachineInstr *DVInsn = DV.getMInsn()) {
1804 assert(DVInsn->getNumOperands() == 3);
1805 if (DVInsn->getOperand(0).isReg()) {
1806 const MachineOperand RegOp = DVInsn->getOperand(0);
1807 // If the second operand is an immediate, this is an indirect value.
1808 if (DVInsn->getOperand(1).isImm()) {
1809 MachineLocation Location(RegOp.getReg(),
1810 DVInsn->getOperand(1).getImm());
1811 addVariableAddress(DV, VariableDie, Location);
1812 } else if (RegOp.getReg())
1813 addVariableAddress(DV, VariableDie, MachineLocation(RegOp.getReg()));
1814 } else if (DVInsn->getOperand(0).isImm())
1815 addConstantValue(VariableDie, DVInsn->getOperand(0), DV.getType());
1816 else if (DVInsn->getOperand(0).isFPImm())
1817 addConstantFPValue(VariableDie, DVInsn->getOperand(0));
1818 else if (DVInsn->getOperand(0).isCImm())
1819 addConstantValue(VariableDie, DVInsn->getOperand(0).getCImm(),
1820 isUnsignedDIType(DD, DV.getType()));
1822 DV.setDIE(VariableDie);
1825 // .. else use frame index.
1826 int FI = DV.getFrameIndex();
1828 unsigned FrameReg = 0;
1829 const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
1830 int Offset = TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
1831 MachineLocation Location(FrameReg, Offset);
1832 addVariableAddress(DV, VariableDie, Location);
1836 DV.setDIE(VariableDie);
1840 /// constructMemberDIE - Construct member DIE from DIDerivedType.
1841 void DwarfUnit::constructMemberDIE(DIE &Buffer, DIDerivedType DT) {
1842 DIE *MemberDie = createAndAddDIE(DT.getTag(), Buffer);
1843 StringRef Name = DT.getName();
1845 addString(MemberDie, dwarf::DW_AT_name, Name);
1847 addType(MemberDie, resolve(DT.getTypeDerivedFrom()));
1849 addSourceLine(MemberDie, DT);
1851 if (DT.getTag() == dwarf::DW_TAG_inheritance && DT.isVirtual()) {
1853 // For C++, virtual base classes are not at fixed offset. Use following
1854 // expression to extract appropriate offset from vtable.
1855 // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1857 DIELoc *VBaseLocationDie = new (DIEValueAllocator) DIELoc();
1858 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1859 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1860 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1861 addUInt(VBaseLocationDie, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1862 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1863 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1864 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1866 addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
1868 uint64_t Size = DT.getSizeInBits();
1869 uint64_t FieldSize = getBaseTypeSize(DD, DT);
1870 uint64_t OffsetInBytes;
1872 if (Size != FieldSize) {
1874 addUInt(MemberDie, dwarf::DW_AT_byte_size, None,
1875 getBaseTypeSize(DD, DT) >> 3);
1876 addUInt(MemberDie, dwarf::DW_AT_bit_size, None, DT.getSizeInBits());
1878 uint64_t Offset = DT.getOffsetInBits();
1879 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1880 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1881 uint64_t FieldOffset = (HiMark - FieldSize);
1882 Offset -= FieldOffset;
1884 // Maybe we need to work from the other end.
1885 if (Asm->getDataLayout().isLittleEndian())
1886 Offset = FieldSize - (Offset + Size);
1887 addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset);
1889 // Here DW_AT_data_member_location points to the anonymous
1890 // field that includes this bit field.
1891 OffsetInBytes = FieldOffset >> 3;
1893 // This is not a bitfield.
1894 OffsetInBytes = DT.getOffsetInBits() >> 3;
1896 if (DD->getDwarfVersion() <= 2) {
1897 DIELoc *MemLocationDie = new (DIEValueAllocator) DIELoc();
1898 addUInt(MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1899 addUInt(MemLocationDie, dwarf::DW_FORM_udata, OffsetInBytes);
1900 addBlock(MemberDie, dwarf::DW_AT_data_member_location, MemLocationDie);
1902 addUInt(MemberDie, dwarf::DW_AT_data_member_location, None,
1906 if (DT.isProtected())
1907 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1908 dwarf::DW_ACCESS_protected);
1909 else if (DT.isPrivate())
1910 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1911 dwarf::DW_ACCESS_private);
1912 // Otherwise C++ member and base classes are considered public.
1914 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1915 dwarf::DW_ACCESS_public);
1917 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1918 dwarf::DW_VIRTUALITY_virtual);
1920 // Objective-C properties.
1921 if (MDNode *PNode = DT.getObjCProperty())
1922 if (DIEEntry *PropertyDie = getDIEEntry(PNode))
1923 MemberDie->addValue(dwarf::DW_AT_APPLE_property, dwarf::DW_FORM_ref4,
1926 if (DT.isArtificial())
1927 addFlag(MemberDie, dwarf::DW_AT_artificial);
1930 /// getOrCreateStaticMemberDIE - Create new DIE for C++ static member.
1931 DIE *DwarfUnit::getOrCreateStaticMemberDIE(DIDerivedType DT) {
1935 // Construct the context before querying for the existence of the DIE in case
1936 // such construction creates the DIE.
1937 DIE *ContextDIE = getOrCreateContextDIE(resolve(DT.getContext()));
1938 assert(dwarf::isType(ContextDIE->getTag()) &&
1939 "Static member should belong to a type.");
1941 DIE *StaticMemberDIE = getDIE(DT);
1942 if (StaticMemberDIE)
1943 return StaticMemberDIE;
1945 StaticMemberDIE = createAndAddDIE(DT.getTag(), *ContextDIE, DT);
1947 DIType Ty = resolve(DT.getTypeDerivedFrom());
1949 addString(StaticMemberDIE, dwarf::DW_AT_name, DT.getName());
1950 addType(StaticMemberDIE, Ty);
1951 addSourceLine(StaticMemberDIE, DT);
1952 addFlag(StaticMemberDIE, dwarf::DW_AT_external);
1953 addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
1955 // FIXME: We could omit private if the parent is a class_type, and
1956 // public if the parent is something else.
1957 if (DT.isProtected())
1958 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1959 dwarf::DW_ACCESS_protected);
1960 else if (DT.isPrivate())
1961 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1962 dwarf::DW_ACCESS_private);
1964 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1965 dwarf::DW_ACCESS_public);
1967 if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT.getConstant()))
1968 addConstantValue(StaticMemberDIE, CI, isUnsignedDIType(DD, Ty));
1969 if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT.getConstant()))
1970 addConstantFPValue(StaticMemberDIE, CFP);
1972 return StaticMemberDIE;
1975 void DwarfUnit::emitHeader(const MCSection *ASection,
1976 const MCSymbol *ASectionSym) const {
1977 Asm->OutStreamer.AddComment("DWARF version number");
1978 Asm->EmitInt16(DD->getDwarfVersion());
1979 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
1980 // We share one abbreviations table across all units so it's always at the
1981 // start of the section. Use a relocatable offset where needed to ensure
1982 // linking doesn't invalidate that offset.
1983 Asm->EmitSectionOffset(ASectionSym, ASectionSym);
1984 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1985 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
1988 void DwarfCompileUnit::initStmtList(MCSymbol *DwarfLineSectionSym) {
1989 // Define start line table label for each Compile Unit.
1990 MCSymbol *LineTableStartSym =
1991 Asm->GetTempSymbol("line_table_start", getUniqueID());
1992 Asm->OutStreamer.getContext().setMCLineTableSymbol(LineTableStartSym,
1995 // Use a single line table if we are generating assembly.
1996 bool UseTheFirstCU =
1997 Asm->OutStreamer.hasRawTextSupport() || (getUniqueID() == 0);
1999 stmtListIndex = UnitDie->getValues().size();
2001 // DW_AT_stmt_list is a offset of line number information for this
2002 // compile unit in debug_line section. For split dwarf this is
2003 // left in the skeleton CU and so not included.
2004 // The line table entries are not always emitted in assembly, so it
2005 // is not okay to use line_table_start here.
2006 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2007 addSectionLabel(UnitDie.get(), dwarf::DW_AT_stmt_list,
2008 UseTheFirstCU ? DwarfLineSectionSym : LineTableStartSym);
2009 else if (UseTheFirstCU)
2010 addSectionOffset(UnitDie.get(), dwarf::DW_AT_stmt_list, 0);
2012 addSectionDelta(UnitDie.get(), dwarf::DW_AT_stmt_list, LineTableStartSym,
2013 DwarfLineSectionSym);
2016 void DwarfCompileUnit::applyStmtList(DIE &D) {
2017 D.addValue(dwarf::DW_AT_stmt_list,
2018 UnitDie->getAbbrev().getData()[stmtListIndex].getForm(),
2019 UnitDie->getValues()[stmtListIndex]);
2022 void DwarfTypeUnit::emitHeader(const MCSection *ASection,
2023 const MCSymbol *ASectionSym) const {
2024 DwarfUnit::emitHeader(ASection, ASectionSym);
2025 Asm->OutStreamer.AddComment("Type Signature");
2026 Asm->OutStreamer.EmitIntValue(TypeSignature, sizeof(TypeSignature));
2027 Asm->OutStreamer.AddComment("Type DIE Offset");
2028 // In a skeleton type unit there is no type DIE so emit a zero offset.
2029 Asm->OutStreamer.EmitIntValue(Ty ? Ty->getOffset() : 0,
2030 sizeof(Ty->getOffset()));
2033 void DwarfTypeUnit::initSection(const MCSection *Section) {
2034 assert(!this->Section);
2035 this->Section = Section;
2036 // Since each type unit is contained in its own COMDAT section, the begin
2037 // label and the section label are the same. Using the begin label emission in
2038 // DwarfDebug to emit the section label as well is slightly subtle/sneaky, but
2039 // the only other alternative of lazily constructing start-of-section labels
2040 // and storing a mapping in DwarfDebug (or AsmPrinter).
2041 this->SectionSym = this->LabelBegin =
2042 Asm->GetTempSymbol(Section->getLabelBeginName(), getUniqueID());
2044 Asm->GetTempSymbol(Section->getLabelEndName(), getUniqueID());
2045 this->LabelRange = Asm->GetTempSymbol("gnu_ranges", getUniqueID());