1 //===-- llvm/CodeGen/DwarfUnit.cpp - Dwarf Type and Compile Units ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains support for constructing a dwarf compile unit.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "dwarfdebug"
16 #include "DwarfUnit.h"
17 #include "DwarfAccelTable.h"
18 #include "DwarfDebug.h"
19 #include "llvm/ADT/APFloat.h"
20 #include "llvm/DIBuilder.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/GlobalVariable.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/IR/Mangler.h"
26 #include "llvm/MC/MCAsmInfo.h"
27 #include "llvm/MC/MCContext.h"
28 #include "llvm/MC/MCSection.h"
29 #include "llvm/MC/MCStreamer.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Target/TargetFrameLowering.h"
32 #include "llvm/Target/TargetLoweringObjectFile.h"
33 #include "llvm/Target/TargetMachine.h"
34 #include "llvm/Target/TargetRegisterInfo.h"
39 GenerateDwarfTypeUnits("generate-type-units", cl::Hidden,
40 cl::desc("Generate DWARF4 type units."),
43 /// Unit - Unit constructor.
44 DwarfUnit::DwarfUnit(unsigned UID, DIE *D, DICompileUnit Node, AsmPrinter *A,
45 DwarfDebug *DW, DwarfFile *DWU)
46 : UniqueID(UID), CUNode(Node), UnitDie(D), DebugInfoOffset(0), Asm(A),
47 DD(DW), DU(DWU), IndexTyDie(0), Section(0), Skeleton(0) {
48 DIEIntegerOne = new (DIEValueAllocator) DIEInteger(1);
51 DwarfCompileUnit::DwarfCompileUnit(unsigned UID, DIE *D, DICompileUnit Node,
52 AsmPrinter *A, DwarfDebug *DW,
54 : DwarfUnit(UID, D, Node, A, DW, DWU) {
58 DwarfTypeUnit::DwarfTypeUnit(unsigned UID, DIE *D, DwarfCompileUnit &CU,
59 AsmPrinter *A, DwarfDebug *DW, DwarfFile *DWU)
60 : DwarfUnit(UID, D, CU.getCUNode(), A, DW, DWU), CU(CU) {
64 /// ~Unit - Destructor for compile unit.
65 DwarfUnit::~DwarfUnit() {
66 for (unsigned j = 0, M = DIEBlocks.size(); j < M; ++j)
67 DIEBlocks[j]->~DIEBlock();
70 /// createDIEEntry - Creates a new DIEEntry to be a proxy for a debug
71 /// information entry.
72 DIEEntry *DwarfUnit::createDIEEntry(DIE *Entry) {
73 DIEEntry *Value = new (DIEValueAllocator) DIEEntry(Entry);
77 /// getDefaultLowerBound - Return the default lower bound for an array. If the
78 /// DWARF version doesn't handle the language, return -1.
79 int64_t DwarfUnit::getDefaultLowerBound() const {
80 switch (getLanguage()) {
84 case dwarf::DW_LANG_C89:
85 case dwarf::DW_LANG_C99:
86 case dwarf::DW_LANG_C:
87 case dwarf::DW_LANG_C_plus_plus:
88 case dwarf::DW_LANG_ObjC:
89 case dwarf::DW_LANG_ObjC_plus_plus:
92 case dwarf::DW_LANG_Fortran77:
93 case dwarf::DW_LANG_Fortran90:
94 case dwarf::DW_LANG_Fortran95:
97 // The languages below have valid values only if the DWARF version >= 4.
98 case dwarf::DW_LANG_Java:
99 case dwarf::DW_LANG_Python:
100 case dwarf::DW_LANG_UPC:
101 case dwarf::DW_LANG_D:
102 if (dwarf::DWARF_VERSION >= 4)
106 case dwarf::DW_LANG_Ada83:
107 case dwarf::DW_LANG_Ada95:
108 case dwarf::DW_LANG_Cobol74:
109 case dwarf::DW_LANG_Cobol85:
110 case dwarf::DW_LANG_Modula2:
111 case dwarf::DW_LANG_Pascal83:
112 case dwarf::DW_LANG_PLI:
113 if (dwarf::DWARF_VERSION >= 4)
121 /// Check whether the DIE for this MDNode can be shared across CUs.
122 static bool isShareableAcrossCUs(DIDescriptor D) {
123 // When the MDNode can be part of the type system, the DIE can be shared
125 // Combining type units and cross-CU DIE sharing is lower value (since
126 // cross-CU DIE sharing is used in LTO and removes type redundancy at that
127 // level already) but may be implementable for some value in projects
128 // building multiple independent libraries with LTO and then linking those
130 return (D.isType() ||
131 (D.isSubprogram() && !DISubprogram(D).isDefinition())) &&
132 !GenerateDwarfTypeUnits;
135 /// getDIE - Returns the debug information entry map slot for the
136 /// specified debug variable. We delegate the request to DwarfDebug
137 /// when the DIE for this MDNode can be shared across CUs. The mappings
138 /// will be kept in DwarfDebug for shareable DIEs.
139 DIE *DwarfUnit::getDIE(DIDescriptor D) const {
140 if (isShareableAcrossCUs(D))
141 return DD->getDIE(D);
142 return MDNodeToDieMap.lookup(D);
145 /// insertDIE - Insert DIE into the map. We delegate the request to DwarfDebug
146 /// when the DIE for this MDNode can be shared across CUs. The mappings
147 /// will be kept in DwarfDebug for shareable DIEs.
148 void DwarfUnit::insertDIE(DIDescriptor Desc, DIE *D) {
149 if (isShareableAcrossCUs(Desc)) {
150 DD->insertDIE(Desc, D);
153 MDNodeToDieMap.insert(std::make_pair(Desc, D));
156 /// addFlag - Add a flag that is true.
157 void DwarfUnit::addFlag(DIE *Die, dwarf::Attribute Attribute) {
158 if (DD->getDwarfVersion() >= 4)
159 Die->addValue(Attribute, dwarf::DW_FORM_flag_present, DIEIntegerOne);
161 Die->addValue(Attribute, dwarf::DW_FORM_flag, DIEIntegerOne);
164 /// addUInt - Add an unsigned integer attribute data and value.
166 void DwarfUnit::addUInt(DIE *Die, dwarf::Attribute Attribute,
167 Optional<dwarf::Form> Form, uint64_t Integer) {
169 Form = DIEInteger::BestForm(false, Integer);
170 DIEValue *Value = Integer == 1 ? DIEIntegerOne : new (DIEValueAllocator)
172 Die->addValue(Attribute, *Form, Value);
175 void DwarfUnit::addUInt(DIEBlock *Block, dwarf::Form Form, uint64_t Integer) {
176 addUInt(Block, (dwarf::Attribute)0, Form, Integer);
179 /// addSInt - Add an signed integer attribute data and value.
181 void DwarfUnit::addSInt(DIE *Die, dwarf::Attribute Attribute,
182 Optional<dwarf::Form> Form, int64_t Integer) {
184 Form = DIEInteger::BestForm(true, Integer);
185 DIEValue *Value = new (DIEValueAllocator) DIEInteger(Integer);
186 Die->addValue(Attribute, *Form, Value);
189 void DwarfUnit::addSInt(DIEBlock *Die, Optional<dwarf::Form> Form,
191 addSInt(Die, (dwarf::Attribute)0, Form, Integer);
194 /// addString - Add a string attribute data and value. We always emit a
195 /// reference to the string pool instead of immediate strings so that DIEs have
196 /// more predictable sizes. In the case of split dwarf we emit an index
197 /// into another table which gets us the static offset into the string
199 void DwarfUnit::addString(DIE *Die, dwarf::Attribute Attribute,
202 if (!DD->useSplitDwarf())
203 return addLocalString(Die, Attribute, String);
205 unsigned idx = DU->getStringPoolIndex(String);
206 DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
207 DIEValue *Str = new (DIEValueAllocator) DIEString(Value, String);
208 Die->addValue(Attribute, dwarf::DW_FORM_GNU_str_index, Str);
211 /// addLocalString - Add a string attribute data and value. This is guaranteed
212 /// to be in the local string pool instead of indirected.
213 void DwarfUnit::addLocalString(DIE *Die, dwarf::Attribute Attribute,
215 MCSymbol *Symb = DU->getStringPoolEntry(String);
217 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
218 Value = new (DIEValueAllocator) DIELabel(Symb);
220 MCSymbol *StringPool = DU->getStringPoolSym();
221 Value = new (DIEValueAllocator) DIEDelta(Symb, StringPool);
223 DIEValue *Str = new (DIEValueAllocator) DIEString(Value, String);
224 Die->addValue(Attribute, dwarf::DW_FORM_strp, Str);
227 /// addExpr - Add a Dwarf expression attribute data and value.
229 void DwarfUnit::addExpr(DIEBlock *Die, dwarf::Form Form, const MCExpr *Expr) {
230 DIEValue *Value = new (DIEValueAllocator) DIEExpr(Expr);
231 Die->addValue((dwarf::Attribute)0, Form, Value);
234 /// addLabel - Add a Dwarf label attribute data and value.
236 void DwarfUnit::addLabel(DIE *Die, dwarf::Attribute Attribute, dwarf::Form Form,
237 const MCSymbol *Label) {
238 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
239 Die->addValue(Attribute, Form, Value);
242 void DwarfUnit::addLabel(DIEBlock *Die, dwarf::Form Form,
243 const MCSymbol *Label) {
244 addLabel(Die, (dwarf::Attribute)0, Form, Label);
247 /// addSectionLabel - Add a Dwarf section label attribute data and value.
249 void DwarfUnit::addSectionLabel(DIE *Die, dwarf::Attribute Attribute,
250 const MCSymbol *Label) {
251 if (DD->getDwarfVersion() >= 4)
252 addLabel(Die, Attribute, dwarf::DW_FORM_sec_offset, Label);
254 addLabel(Die, Attribute, dwarf::DW_FORM_data4, Label);
257 /// addSectionOffset - Add an offset into a section attribute data and value.
259 void DwarfUnit::addSectionOffset(DIE *Die, dwarf::Attribute Attribute,
261 if (DD->getDwarfVersion() >= 4)
262 addUInt(Die, Attribute, dwarf::DW_FORM_sec_offset, Integer);
264 addUInt(Die, Attribute, dwarf::DW_FORM_data4, Integer);
267 /// addLabelAddress - Add a dwarf label attribute data and value using
268 /// DW_FORM_addr or DW_FORM_GNU_addr_index.
270 void DwarfCompileUnit::addLabelAddress(DIE *Die, dwarf::Attribute Attribute,
273 DD->addArangeLabel(SymbolCU(this, Label));
275 if (!DD->useSplitDwarf()) {
277 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
278 Die->addValue(Attribute, dwarf::DW_FORM_addr, Value);
280 DIEValue *Value = new (DIEValueAllocator) DIEInteger(0);
281 Die->addValue(Attribute, dwarf::DW_FORM_addr, Value);
284 unsigned idx = DU->getAddrPoolIndex(Label);
285 DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
286 Die->addValue(Attribute, dwarf::DW_FORM_GNU_addr_index, Value);
290 /// addOpAddress - Add a dwarf op address data and value using the
291 /// form given and an op of either DW_FORM_addr or DW_FORM_GNU_addr_index.
293 void DwarfUnit::addOpAddress(DIEBlock *Die, const MCSymbol *Sym) {
294 if (!DD->useSplitDwarf()) {
295 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
296 addLabel(Die, dwarf::DW_FORM_udata, Sym);
298 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index);
299 addUInt(Die, dwarf::DW_FORM_GNU_addr_index, DU->getAddrPoolIndex(Sym));
303 /// addSectionDelta - Add a section label delta attribute data and value.
305 void DwarfUnit::addSectionDelta(DIE *Die, dwarf::Attribute Attribute,
306 const MCSymbol *Hi, const MCSymbol *Lo) {
307 DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
308 if (DD->getDwarfVersion() >= 4)
309 Die->addValue(Attribute, dwarf::DW_FORM_sec_offset, Value);
311 Die->addValue(Attribute, dwarf::DW_FORM_data4, Value);
314 /// addDIEEntry - Add a DIE attribute data and value.
316 void DwarfUnit::addDIEEntry(DIE *Die, dwarf::Attribute Attribute, DIE *Entry) {
317 addDIEEntry(Die, Attribute, createDIEEntry(Entry));
320 void DwarfUnit::addDIETypeSignature(DIE *Die, const DwarfTypeUnit &Type) {
321 Die->addValue(dwarf::DW_AT_signature, dwarf::DW_FORM_ref_sig8,
322 new (DIEValueAllocator) DIETypeSignature(Type));
325 void DwarfUnit::addDIEEntry(DIE *Die, dwarf::Attribute Attribute,
327 const DIE *DieCU = Die->getUnitOrNull();
328 const DIE *EntryCU = Entry->getEntry()->getUnitOrNull();
330 // We assume that Die belongs to this CU, if it is not linked to any CU yet.
331 DieCU = getUnitDie();
333 EntryCU = getUnitDie();
334 Die->addValue(Attribute, EntryCU == DieCU ? dwarf::DW_FORM_ref4
335 : dwarf::DW_FORM_ref_addr,
339 /// Create a DIE with the given Tag, add the DIE to its parent, and
340 /// call insertDIE if MD is not null.
341 DIE *DwarfUnit::createAndAddDIE(unsigned Tag, DIE &Parent, DIDescriptor N) {
342 DIE *Die = new DIE(Tag);
343 Parent.addChild(Die);
349 /// addBlock - Add block data.
351 void DwarfUnit::addBlock(DIE *Die, dwarf::Attribute Attribute,
353 Block->ComputeSize(Asm);
354 DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
355 Die->addValue(Attribute, Block->BestForm(), Block);
358 /// addSourceLine - Add location information to specified debug information
360 void DwarfUnit::addSourceLine(DIE *Die, unsigned Line, StringRef File,
361 StringRef Directory) {
366 DD->getOrCreateSourceID(File, Directory, getCU().getUniqueID());
367 assert(FileID && "Invalid file id");
368 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
369 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
372 /// addSourceLine - Add location information to specified debug information
374 void DwarfUnit::addSourceLine(DIE *Die, DIVariable V) {
375 assert(V.isVariable());
377 addSourceLine(Die, V.getLineNumber(), V.getContext().getFilename(), V.getContext().getDirectory());
380 /// addSourceLine - Add location information to specified debug information
382 void DwarfUnit::addSourceLine(DIE *Die, DIGlobalVariable G) {
383 assert(G.isGlobalVariable());
385 addSourceLine(Die, G.getLineNumber(), G.getFilename(), G.getDirectory());
388 /// addSourceLine - Add location information to specified debug information
390 void DwarfUnit::addSourceLine(DIE *Die, DISubprogram SP) {
391 assert(SP.isSubprogram());
393 addSourceLine(Die, SP.getLineNumber(), SP.getFilename(), SP.getDirectory());
396 /// addSourceLine - Add location information to specified debug information
398 void DwarfUnit::addSourceLine(DIE *Die, DIType Ty) {
401 addSourceLine(Die, Ty.getLineNumber(), Ty.getFilename(), Ty.getDirectory());
404 /// addSourceLine - Add location information to specified debug information
406 void DwarfUnit::addSourceLine(DIE *Die, DIObjCProperty Ty) {
407 assert(Ty.isObjCProperty());
409 DIFile File = Ty.getFile();
410 addSourceLine(Die, Ty.getLineNumber(), File.getFilename(),
411 File.getDirectory());
414 /// addSourceLine - Add location information to specified debug information
416 void DwarfUnit::addSourceLine(DIE *Die, DINameSpace NS) {
419 addSourceLine(Die, NS.getLineNumber(), NS.getFilename(), NS.getDirectory());
422 /// addVariableAddress - Add DW_AT_location attribute for a
423 /// DbgVariable based on provided MachineLocation.
424 void DwarfUnit::addVariableAddress(const DbgVariable &DV, DIE *Die,
425 MachineLocation Location) {
426 if (DV.variableHasComplexAddress())
427 addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
428 else if (DV.isBlockByrefVariable())
429 addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location);
431 addAddress(Die, dwarf::DW_AT_location, Location,
432 DV.getVariable().isIndirect());
435 /// addRegisterOp - Add register operand.
436 void DwarfUnit::addRegisterOp(DIEBlock *TheDie, unsigned Reg) {
437 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
438 int DWReg = RI->getDwarfRegNum(Reg, false);
439 bool isSubRegister = DWReg < 0;
443 // Go up the super-register chain until we hit a valid dwarf register number.
444 for (MCSuperRegIterator SR(Reg, RI); SR.isValid() && DWReg < 0; ++SR) {
445 DWReg = RI->getDwarfRegNum(*SR, false);
447 Idx = RI->getSubRegIndex(*SR, Reg);
451 DEBUG(llvm::dbgs() << "Invalid Dwarf register number.\n");
452 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_nop);
458 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + DWReg);
460 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
461 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
466 unsigned Size = RI->getSubRegIdxSize(Idx);
467 unsigned Offset = RI->getSubRegIdxOffset(Idx);
469 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_bit_piece);
470 addUInt(TheDie, dwarf::DW_FORM_data1, Size);
471 addUInt(TheDie, dwarf::DW_FORM_data1, Offset);
473 unsigned ByteSize = Size / 8; // Assuming 8 bits per byte.
474 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_piece);
475 addUInt(TheDie, dwarf::DW_FORM_data1, ByteSize);
480 /// addRegisterOffset - Add register offset.
481 void DwarfUnit::addRegisterOffset(DIEBlock *TheDie, unsigned Reg,
483 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
484 unsigned DWReg = RI->getDwarfRegNum(Reg, false);
485 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
486 if (Reg == TRI->getFrameRegister(*Asm->MF))
487 // If variable offset is based in frame register then use fbreg.
488 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_fbreg);
490 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + DWReg);
492 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
493 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
495 addSInt(TheDie, dwarf::DW_FORM_sdata, Offset);
498 /// addAddress - Add an address attribute to a die based on the location
500 void DwarfUnit::addAddress(DIE *Die, dwarf::Attribute Attribute,
501 const MachineLocation &Location, bool Indirect) {
502 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
504 if (Location.isReg() && !Indirect)
505 addRegisterOp(Block, Location.getReg());
507 addRegisterOffset(Block, Location.getReg(), Location.getOffset());
508 if (Indirect && !Location.isReg()) {
509 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
513 // Now attach the location information to the DIE.
514 addBlock(Die, Attribute, Block);
517 /// addComplexAddress - Start with the address based on the location provided,
518 /// and generate the DWARF information necessary to find the actual variable
519 /// given the extra address information encoded in the DbgVariable, starting
520 /// from the starting location. Add the DWARF information to the die.
522 void DwarfUnit::addComplexAddress(const DbgVariable &DV, DIE *Die,
523 dwarf::Attribute Attribute,
524 const MachineLocation &Location) {
525 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
526 unsigned N = DV.getNumAddrElements();
528 if (Location.isReg()) {
529 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
530 // If first address element is OpPlus then emit
531 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
532 addRegisterOffset(Block, Location.getReg(), DV.getAddrElement(1));
535 addRegisterOp(Block, Location.getReg());
537 addRegisterOffset(Block, Location.getReg(), Location.getOffset());
540 uint64_t Element = DV.getAddrElement(i);
541 if (Element == DIBuilder::OpPlus) {
542 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
543 addUInt(Block, dwarf::DW_FORM_udata, DV.getAddrElement(++i));
544 } else if (Element == DIBuilder::OpDeref) {
545 if (!Location.isReg())
546 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
548 llvm_unreachable("unknown DIBuilder Opcode");
551 // Now attach the location information to the DIE.
552 addBlock(Die, Attribute, Block);
555 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
556 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
557 gives the variable VarName either the struct, or a pointer to the struct, as
558 its type. This is necessary for various behind-the-scenes things the
559 compiler needs to do with by-reference variables in Blocks.
561 However, as far as the original *programmer* is concerned, the variable
562 should still have type 'SomeType', as originally declared.
564 The function getBlockByrefType dives into the __Block_byref_x_VarName
565 struct to find the original type of the variable, which is then assigned to
566 the variable's Debug Information Entry as its real type. So far, so good.
567 However now the debugger will expect the variable VarName to have the type
568 SomeType. So we need the location attribute for the variable to be an
569 expression that explains to the debugger how to navigate through the
570 pointers and struct to find the actual variable of type SomeType.
572 The following function does just that. We start by getting
573 the "normal" location for the variable. This will be the location
574 of either the struct __Block_byref_x_VarName or the pointer to the
575 struct __Block_byref_x_VarName.
577 The struct will look something like:
579 struct __Block_byref_x_VarName {
581 struct __Block_byref_x_VarName *forwarding;
582 ... <various other fields>
584 ... <maybe more fields>
587 If we are given the struct directly (as our starting point) we
588 need to tell the debugger to:
590 1). Add the offset of the forwarding field.
592 2). Follow that pointer to get the real __Block_byref_x_VarName
593 struct to use (the real one may have been copied onto the heap).
595 3). Add the offset for the field VarName, to find the actual variable.
597 If we started with a pointer to the struct, then we need to
598 dereference that pointer first, before the other steps.
599 Translating this into DWARF ops, we will need to append the following
600 to the current location description for the variable:
602 DW_OP_deref -- optional, if we start with a pointer
603 DW_OP_plus_uconst <forward_fld_offset>
605 DW_OP_plus_uconst <varName_fld_offset>
607 That is what this function does. */
609 /// addBlockByrefAddress - Start with the address based on the location
610 /// provided, and generate the DWARF information necessary to find the
611 /// actual Block variable (navigating the Block struct) based on the
612 /// starting location. Add the DWARF information to the die. For
613 /// more information, read large comment just above here.
615 void DwarfUnit::addBlockByrefAddress(const DbgVariable &DV, DIE *Die,
616 dwarf::Attribute Attribute,
617 const MachineLocation &Location) {
618 DIType Ty = DV.getType();
620 uint16_t Tag = Ty.getTag();
621 bool isPointer = false;
623 StringRef varName = DV.getName();
625 if (Tag == dwarf::DW_TAG_pointer_type) {
626 DIDerivedType DTy(Ty);
627 TmpTy = resolve(DTy.getTypeDerivedFrom());
631 DICompositeType blockStruct(TmpTy);
633 // Find the __forwarding field and the variable field in the __Block_byref
635 DIArray Fields = blockStruct.getTypeArray();
636 DIDerivedType varField;
637 DIDerivedType forwardingField;
639 for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
640 DIDerivedType DT(Fields.getElement(i));
641 StringRef fieldName = DT.getName();
642 if (fieldName == "__forwarding")
643 forwardingField = DT;
644 else if (fieldName == varName)
648 // Get the offsets for the forwarding field and the variable field.
649 unsigned forwardingFieldOffset = forwardingField.getOffsetInBits() >> 3;
650 unsigned varFieldOffset = varField.getOffsetInBits() >> 2;
652 // Decode the original location, and use that as the start of the byref
653 // variable's location.
654 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
656 if (Location.isReg())
657 addRegisterOp(Block, Location.getReg());
659 addRegisterOffset(Block, Location.getReg(), Location.getOffset());
661 // If we started with a pointer to the __Block_byref... struct, then
662 // the first thing we need to do is dereference the pointer (DW_OP_deref).
664 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
666 // Next add the offset for the '__forwarding' field:
667 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
668 // adding the offset if it's 0.
669 if (forwardingFieldOffset > 0) {
670 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
671 addUInt(Block, dwarf::DW_FORM_udata, forwardingFieldOffset);
674 // Now dereference the __forwarding field to get to the real __Block_byref
675 // struct: DW_OP_deref.
676 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
678 // Now that we've got the real __Block_byref... struct, add the offset
679 // for the variable's field to get to the location of the actual variable:
680 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
681 if (varFieldOffset > 0) {
682 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
683 addUInt(Block, dwarf::DW_FORM_udata, varFieldOffset);
686 // Now attach the location information to the DIE.
687 addBlock(Die, Attribute, Block);
690 /// isTypeSigned - Return true if the type is signed.
691 static bool isTypeSigned(DwarfDebug *DD, DIType Ty, int *SizeInBits) {
692 if (Ty.isDerivedType())
693 return isTypeSigned(DD, DD->resolve(DIDerivedType(Ty).getTypeDerivedFrom()),
695 if (Ty.isBasicType())
696 if (DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed ||
697 DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed_char) {
698 *SizeInBits = Ty.getSizeInBits();
704 /// Return true if type encoding is unsigned.
705 static bool isUnsignedDIType(DwarfDebug *DD, DIType Ty) {
706 DIDerivedType DTy(Ty);
707 if (DTy.isDerivedType())
708 return isUnsignedDIType(DD, DD->resolve(DTy.getTypeDerivedFrom()));
711 if (BTy.isBasicType()) {
712 unsigned Encoding = BTy.getEncoding();
713 if (Encoding == dwarf::DW_ATE_unsigned ||
714 Encoding == dwarf::DW_ATE_unsigned_char ||
715 Encoding == dwarf::DW_ATE_boolean)
721 /// If this type is derived from a base type then return base type size.
722 static uint64_t getBaseTypeSize(DwarfDebug *DD, DIDerivedType Ty) {
723 unsigned Tag = Ty.getTag();
725 if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef &&
726 Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type &&
727 Tag != dwarf::DW_TAG_restrict_type)
728 return Ty.getSizeInBits();
730 DIType BaseType = DD->resolve(Ty.getTypeDerivedFrom());
732 // If this type is not derived from any type then take conservative approach.
733 if (!BaseType.isValid())
734 return Ty.getSizeInBits();
736 // If this is a derived type, go ahead and get the base type, unless it's a
737 // reference then it's just the size of the field. Pointer types have no need
738 // of this since they're a different type of qualification on the type.
739 if (BaseType.getTag() == dwarf::DW_TAG_reference_type ||
740 BaseType.getTag() == dwarf::DW_TAG_rvalue_reference_type)
741 return Ty.getSizeInBits();
743 if (BaseType.isDerivedType())
744 return getBaseTypeSize(DD, DIDerivedType(BaseType));
746 return BaseType.getSizeInBits();
749 /// addConstantValue - Add constant value entry in variable DIE.
750 void DwarfUnit::addConstantValue(DIE *Die, const MachineOperand &MO,
752 // FIXME: This is a bit conservative/simple - it emits negative values at
753 // their maximum bit width which is a bit unfortunate (& doesn't prefer
754 // udata/sdata over dataN as suggested by the DWARF spec)
755 assert(MO.isImm() && "Invalid machine operand!");
757 bool SignedConstant = isTypeSigned(DD, Ty, &SizeInBits);
760 // If we're a signed constant definitely use sdata.
761 if (SignedConstant) {
762 addSInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, MO.getImm());
766 // Else use data for now unless it's larger than we can deal with.
767 switch (SizeInBits) {
769 Form = dwarf::DW_FORM_data1;
772 Form = dwarf::DW_FORM_data2;
775 Form = dwarf::DW_FORM_data4;
778 Form = dwarf::DW_FORM_data8;
781 Form = dwarf::DW_FORM_udata;
782 addUInt(Die, dwarf::DW_AT_const_value, Form, MO.getImm());
785 addUInt(Die, dwarf::DW_AT_const_value, Form, MO.getImm());
788 /// addConstantFPValue - Add constant value entry in variable DIE.
789 void DwarfUnit::addConstantFPValue(DIE *Die, const MachineOperand &MO) {
790 assert(MO.isFPImm() && "Invalid machine operand!");
791 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
792 APFloat FPImm = MO.getFPImm()->getValueAPF();
794 // Get the raw data form of the floating point.
795 const APInt FltVal = FPImm.bitcastToAPInt();
796 const char *FltPtr = (const char *)FltVal.getRawData();
798 int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
799 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
800 int Incr = (LittleEndian ? 1 : -1);
801 int Start = (LittleEndian ? 0 : NumBytes - 1);
802 int Stop = (LittleEndian ? NumBytes : -1);
804 // Output the constant to DWARF one byte at a time.
805 for (; Start != Stop; Start += Incr)
806 addUInt(Block, dwarf::DW_FORM_data1, (unsigned char)0xFF & FltPtr[Start]);
808 addBlock(Die, dwarf::DW_AT_const_value, Block);
811 /// addConstantFPValue - Add constant value entry in variable DIE.
812 void DwarfUnit::addConstantFPValue(DIE *Die, const ConstantFP *CFP) {
813 // Pass this down to addConstantValue as an unsigned bag of bits.
814 addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true);
817 /// addConstantValue - Add constant value entry in variable DIE.
818 void DwarfUnit::addConstantValue(DIE *Die, const ConstantInt *CI,
820 addConstantValue(Die, CI->getValue(), Unsigned);
823 // addConstantValue - Add constant value entry in variable DIE.
824 void DwarfUnit::addConstantValue(DIE *Die, const APInt &Val, bool Unsigned) {
825 unsigned CIBitWidth = Val.getBitWidth();
826 if (CIBitWidth <= 64) {
827 // If we're a signed constant definitely use sdata.
829 addSInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
834 // Else use data for now unless it's larger than we can deal with.
836 switch (CIBitWidth) {
838 Form = dwarf::DW_FORM_data1;
841 Form = dwarf::DW_FORM_data2;
844 Form = dwarf::DW_FORM_data4;
847 Form = dwarf::DW_FORM_data8;
850 addUInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_udata,
854 addUInt(Die, dwarf::DW_AT_const_value, Form, Val.getZExtValue());
858 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
860 // Get the raw data form of the large APInt.
861 const uint64_t *Ptr64 = Val.getRawData();
863 int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
864 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
866 // Output the constant to DWARF one byte at a time.
867 for (int i = 0; i < NumBytes; i++) {
870 c = Ptr64[i / 8] >> (8 * (i & 7));
872 c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
873 addUInt(Block, dwarf::DW_FORM_data1, c);
876 addBlock(Die, dwarf::DW_AT_const_value, Block);
879 /// addTemplateParams - Add template parameters into buffer.
880 void DwarfUnit::addTemplateParams(DIE &Buffer, DIArray TParams) {
881 // Add template parameters.
882 for (unsigned i = 0, e = TParams.getNumElements(); i != e; ++i) {
883 DIDescriptor Element = TParams.getElement(i);
884 if (Element.isTemplateTypeParameter())
885 constructTemplateTypeParameterDIE(Buffer,
886 DITemplateTypeParameter(Element));
887 else if (Element.isTemplateValueParameter())
888 constructTemplateValueParameterDIE(Buffer,
889 DITemplateValueParameter(Element));
893 /// getOrCreateContextDIE - Get context owner's DIE.
894 DIE *DwarfUnit::getOrCreateContextDIE(DIScope Context) {
895 if (!Context || Context.isFile())
897 if (Context.isType())
898 return getOrCreateTypeDIE(DIType(Context));
899 if (Context.isNameSpace())
900 return getOrCreateNameSpace(DINameSpace(Context));
901 if (Context.isSubprogram())
902 return getOrCreateSubprogramDIE(DISubprogram(Context));
903 return getDIE(Context);
906 DIE *DwarfUnit::createTypeDIE(DICompositeType Ty) {
907 DIScope Context = resolve(Ty.getContext());
908 DIE *ContextDIE = getOrCreateContextDIE(Context);
910 DIE *TyDIE = getDIE(Ty);
915 TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
917 constructTypeDIE(*TyDIE, Ty);
919 updateAcceleratorTables(Context, Ty, TyDIE);
923 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
925 DIE *DwarfUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
932 // Construct the context before querying for the existence of the DIE in case
933 // such construction creates the DIE.
934 DIScope Context = resolve(Ty.getContext());
935 DIE *ContextDIE = getOrCreateContextDIE(Context);
938 DIE *TyDIE = getDIE(Ty);
943 TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
945 if (Ty.isBasicType())
946 constructTypeDIE(*TyDIE, DIBasicType(Ty));
947 else if (Ty.isCompositeType()) {
948 DICompositeType CTy(Ty);
949 if (GenerateDwarfTypeUnits && !Ty.isForwardDecl())
950 if (MDString *TypeId = CTy.getIdentifier()) {
951 DD->addDwarfTypeUnitType(getCU(), TypeId->getString(), TyDIE, CTy);
952 // Skip updating the accellerator tables since this is not the full type
955 constructTypeDIE(*TyDIE, CTy);
957 assert(Ty.isDerivedType() && "Unknown kind of DIType");
958 constructTypeDIE(*TyDIE, DIDerivedType(Ty));
961 updateAcceleratorTables(Context, Ty, TyDIE);
966 void DwarfUnit::updateAcceleratorTables(DIScope Context, DIType Ty,
968 if (!Ty.getName().empty() && !Ty.isForwardDecl()) {
969 bool IsImplementation = 0;
970 if (Ty.isCompositeType()) {
971 DICompositeType CT(Ty);
972 // A runtime language of 0 actually means C/C++ and that any
973 // non-negative value is some version of Objective-C/C++.
974 IsImplementation = (CT.getRunTimeLang() == 0) || CT.isObjcClassComplete();
976 unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0;
977 addAccelType(Ty.getName(), std::make_pair(TyDIE, Flags));
979 if (!Context || Context.isCompileUnit() || Context.isFile() ||
980 Context.isNameSpace())
981 GlobalTypes[getParentContextString(Context) + Ty.getName().str()] = TyDIE;
985 /// addType - Add a new type attribute to the specified entity.
986 void DwarfUnit::addType(DIE *Entity, DIType Ty, dwarf::Attribute Attribute) {
987 assert(Ty && "Trying to add a type that doesn't exist?");
989 // Check for pre-existence.
990 DIEEntry *Entry = getDIEEntry(Ty);
991 // If it exists then use the existing value.
993 addDIEEntry(Entity, Attribute, Entry);
998 DIE *Buffer = getOrCreateTypeDIE(Ty);
1001 Entry = createDIEEntry(Buffer);
1002 insertDIEEntry(Ty, Entry);
1003 addDIEEntry(Entity, Attribute, Entry);
1006 // Accelerator table mutators - add each name along with its companion
1007 // DIE to the proper table while ensuring that the name that we're going
1008 // to reference is in the string table. We do this since the names we
1009 // add may not only be identical to the names in the DIE.
1010 void DwarfUnit::addAccelName(StringRef Name, const DIE *Die) {
1011 if (!DD->useDwarfAccelTables()) return;
1012 DU->getStringPoolEntry(Name);
1013 std::vector<const DIE *> &DIEs = AccelNames[Name];
1014 DIEs.push_back(Die);
1017 void DwarfUnit::addAccelObjC(StringRef Name, const DIE *Die) {
1018 if (!DD->useDwarfAccelTables()) return;
1019 DU->getStringPoolEntry(Name);
1020 std::vector<const DIE *> &DIEs = AccelObjC[Name];
1021 DIEs.push_back(Die);
1024 void DwarfUnit::addAccelNamespace(StringRef Name, const DIE *Die) {
1025 if (!DD->useDwarfAccelTables()) return;
1026 DU->getStringPoolEntry(Name);
1027 std::vector<const DIE *> &DIEs = AccelNamespace[Name];
1028 DIEs.push_back(Die);
1031 void DwarfUnit::addAccelType(StringRef Name,
1032 std::pair<const DIE *, unsigned> Die) {
1033 if (!DD->useDwarfAccelTables()) return;
1034 DU->getStringPoolEntry(Name);
1035 std::vector<std::pair<const DIE *, unsigned> > &DIEs = AccelTypes[Name];
1036 DIEs.push_back(Die);
1039 /// addGlobalName - Add a new global name to the compile unit.
1040 void DwarfUnit::addGlobalName(StringRef Name, DIE *Die, DIScope Context) {
1041 std::string FullName = getParentContextString(Context) + Name.str();
1042 GlobalNames[FullName] = Die;
1045 /// getParentContextString - Walks the metadata parent chain in a language
1046 /// specific manner (using the compile unit language) and returns
1047 /// it as a string. This is done at the metadata level because DIEs may
1048 /// not currently have been added to the parent context and walking the
1049 /// DIEs looking for names is more expensive than walking the metadata.
1050 std::string DwarfUnit::getParentContextString(DIScope Context) const {
1054 // FIXME: Decide whether to implement this for non-C++ languages.
1055 if (getLanguage() != dwarf::DW_LANG_C_plus_plus)
1059 SmallVector<DIScope, 1> Parents;
1060 while (!Context.isCompileUnit()) {
1061 Parents.push_back(Context);
1062 if (Context.getContext())
1063 Context = resolve(Context.getContext());
1065 // Structure, etc types will have a NULL context if they're at the top
1070 // Reverse iterate over our list to go from the outermost construct to the
1072 for (SmallVectorImpl<DIScope>::reverse_iterator I = Parents.rbegin(),
1076 StringRef Name = Ctx.getName();
1077 if (!Name.empty()) {
1085 /// constructTypeDIE - Construct basic type die from DIBasicType.
1086 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
1087 // Get core information.
1088 StringRef Name = BTy.getName();
1089 // Add name if not anonymous or intermediate type.
1091 addString(&Buffer, dwarf::DW_AT_name, Name);
1093 // An unspecified type only has a name attribute.
1094 if (BTy.getTag() == dwarf::DW_TAG_unspecified_type)
1097 addUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1100 uint64_t Size = BTy.getSizeInBits() >> 3;
1101 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1104 /// constructTypeDIE - Construct derived type die from DIDerivedType.
1105 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
1106 // Get core information.
1107 StringRef Name = DTy.getName();
1108 uint64_t Size = DTy.getSizeInBits() >> 3;
1109 uint16_t Tag = Buffer.getTag();
1111 // Map to main type, void will not have a type.
1112 DIType FromTy = resolve(DTy.getTypeDerivedFrom());
1114 addType(&Buffer, FromTy);
1116 // Add name if not anonymous or intermediate type.
1118 addString(&Buffer, dwarf::DW_AT_name, Name);
1120 // Add size if non-zero (derived types might be zero-sized.)
1121 if (Size && Tag != dwarf::DW_TAG_pointer_type)
1122 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1124 if (Tag == dwarf::DW_TAG_ptr_to_member_type)
1125 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type,
1126 getOrCreateTypeDIE(resolve(DTy.getClassType())));
1127 // Add source line info if available and TyDesc is not a forward declaration.
1128 if (!DTy.isForwardDecl())
1129 addSourceLine(&Buffer, DTy);
1132 /// constructTypeDIE - Construct type DIE from DICompositeType.
1133 void DwarfUnit::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
1134 // Add name if not anonymous or intermediate type.
1135 StringRef Name = CTy.getName();
1137 uint64_t Size = CTy.getSizeInBits() >> 3;
1138 uint16_t Tag = Buffer.getTag();
1141 case dwarf::DW_TAG_array_type:
1142 constructArrayTypeDIE(Buffer, CTy);
1144 case dwarf::DW_TAG_enumeration_type:
1145 constructEnumTypeDIE(Buffer, CTy);
1147 case dwarf::DW_TAG_subroutine_type: {
1148 // Add return type. A void return won't have a type.
1149 DIArray Elements = CTy.getTypeArray();
1150 DIType RTy(Elements.getElement(0));
1152 addType(&Buffer, RTy);
1154 bool isPrototyped = true;
1156 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
1157 DIDescriptor Ty = Elements.getElement(i);
1158 if (Ty.isUnspecifiedParameter()) {
1159 createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
1160 isPrototyped = false;
1162 DIE *Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
1163 addType(Arg, DIType(Ty));
1164 if (DIType(Ty).isArtificial())
1165 addFlag(Arg, dwarf::DW_AT_artificial);
1168 // Add prototype flag if we're dealing with a C language and the
1169 // function has been prototyped.
1170 uint16_t Language = getLanguage();
1172 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1173 Language == dwarf::DW_LANG_ObjC))
1174 addFlag(&Buffer, dwarf::DW_AT_prototyped);
1176 if (CTy.isLValueReference())
1177 addFlag(&Buffer, dwarf::DW_AT_reference);
1179 if (CTy.isRValueReference())
1180 addFlag(&Buffer, dwarf::DW_AT_rvalue_reference);
1182 case dwarf::DW_TAG_structure_type:
1183 case dwarf::DW_TAG_union_type:
1184 case dwarf::DW_TAG_class_type: {
1185 // Add elements to structure type.
1186 DIArray Elements = CTy.getTypeArray();
1187 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1188 DIDescriptor Element = Elements.getElement(i);
1189 DIE *ElemDie = NULL;
1190 if (Element.isSubprogram())
1191 ElemDie = getOrCreateSubprogramDIE(DISubprogram(Element));
1192 else if (Element.isDerivedType()) {
1193 DIDerivedType DDTy(Element);
1194 if (DDTy.getTag() == dwarf::DW_TAG_friend) {
1195 ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
1196 addType(ElemDie, resolve(DDTy.getTypeDerivedFrom()),
1197 dwarf::DW_AT_friend);
1198 } else if (DDTy.isStaticMember()) {
1199 getOrCreateStaticMemberDIE(DDTy);
1201 constructMemberDIE(Buffer, DDTy);
1203 } else if (Element.isObjCProperty()) {
1204 DIObjCProperty Property(Element);
1205 ElemDie = createAndAddDIE(Property.getTag(), Buffer);
1206 StringRef PropertyName = Property.getObjCPropertyName();
1207 addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
1208 if (Property.getType())
1209 addType(ElemDie, Property.getType());
1210 addSourceLine(ElemDie, Property);
1211 StringRef GetterName = Property.getObjCPropertyGetterName();
1212 if (!GetterName.empty())
1213 addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
1214 StringRef SetterName = Property.getObjCPropertySetterName();
1215 if (!SetterName.empty())
1216 addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
1217 unsigned PropertyAttributes = 0;
1218 if (Property.isReadOnlyObjCProperty())
1219 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readonly;
1220 if (Property.isReadWriteObjCProperty())
1221 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readwrite;
1222 if (Property.isAssignObjCProperty())
1223 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_assign;
1224 if (Property.isRetainObjCProperty())
1225 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_retain;
1226 if (Property.isCopyObjCProperty())
1227 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_copy;
1228 if (Property.isNonAtomicObjCProperty())
1229 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_nonatomic;
1230 if (PropertyAttributes)
1231 addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None,
1232 PropertyAttributes);
1234 DIEEntry *Entry = getDIEEntry(Element);
1236 Entry = createDIEEntry(ElemDie);
1237 insertDIEEntry(Element, Entry);
1243 if (CTy.isAppleBlockExtension())
1244 addFlag(&Buffer, dwarf::DW_AT_APPLE_block);
1246 DICompositeType ContainingType(resolve(CTy.getContainingType()));
1248 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type,
1249 getOrCreateTypeDIE(ContainingType));
1251 if (CTy.isObjcClassComplete())
1252 addFlag(&Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
1254 // Add template parameters to a class, structure or union types.
1255 // FIXME: The support isn't in the metadata for this yet.
1256 if (Tag == dwarf::DW_TAG_class_type ||
1257 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
1258 addTemplateParams(Buffer, CTy.getTemplateParams());
1266 // Add name if not anonymous or intermediate type.
1268 addString(&Buffer, dwarf::DW_AT_name, Name);
1270 if (Tag == dwarf::DW_TAG_enumeration_type ||
1271 Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
1272 Tag == dwarf::DW_TAG_union_type) {
1273 // Add size if non-zero (derived types might be zero-sized.)
1274 // TODO: Do we care about size for enum forward declarations?
1276 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1277 else if (!CTy.isForwardDecl())
1278 // Add zero size if it is not a forward declaration.
1279 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, 0);
1281 // If we're a forward decl, say so.
1282 if (CTy.isForwardDecl())
1283 addFlag(&Buffer, dwarf::DW_AT_declaration);
1285 // Add source line info if available.
1286 if (!CTy.isForwardDecl())
1287 addSourceLine(&Buffer, CTy);
1289 // No harm in adding the runtime language to the declaration.
1290 unsigned RLang = CTy.getRunTimeLang();
1292 addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
1297 /// constructTemplateTypeParameterDIE - Construct new DIE for the given
1298 /// DITemplateTypeParameter.
1299 void DwarfUnit::constructTemplateTypeParameterDIE(DIE &Buffer,
1300 DITemplateTypeParameter TP) {
1302 createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
1303 // Add the type if it exists, it could be void and therefore no type.
1305 addType(ParamDIE, resolve(TP.getType()));
1306 if (!TP.getName().empty())
1307 addString(ParamDIE, dwarf::DW_AT_name, TP.getName());
1310 /// constructTemplateValueParameterDIE - Construct new DIE for the given
1311 /// DITemplateValueParameter.
1313 DwarfUnit::constructTemplateValueParameterDIE(DIE &Buffer,
1314 DITemplateValueParameter VP) {
1315 DIE *ParamDIE = createAndAddDIE(VP.getTag(), Buffer);
1317 // Add the type if there is one, template template and template parameter
1318 // packs will not have a type.
1319 if (VP.getTag() == dwarf::DW_TAG_template_value_parameter)
1320 addType(ParamDIE, resolve(VP.getType()));
1321 if (!VP.getName().empty())
1322 addString(ParamDIE, dwarf::DW_AT_name, VP.getName());
1323 if (Value *Val = VP.getValue()) {
1324 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val))
1325 addConstantValue(ParamDIE, CI,
1326 isUnsignedDIType(DD, resolve(VP.getType())));
1327 else if (GlobalValue *GV = dyn_cast<GlobalValue>(Val)) {
1328 // For declaration non-type template parameters (such as global values and
1330 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1331 addOpAddress(Block, Asm->getSymbol(GV));
1332 // Emit DW_OP_stack_value to use the address as the immediate value of the
1333 // parameter, rather than a pointer to it.
1334 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
1335 addBlock(ParamDIE, dwarf::DW_AT_location, Block);
1336 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1337 assert(isa<MDString>(Val));
1338 addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
1339 cast<MDString>(Val)->getString());
1340 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1341 assert(isa<MDNode>(Val));
1342 DIArray A(cast<MDNode>(Val));
1343 addTemplateParams(*ParamDIE, A);
1348 /// getOrCreateNameSpace - Create a DIE for DINameSpace.
1349 DIE *DwarfUnit::getOrCreateNameSpace(DINameSpace NS) {
1350 // Construct the context before querying for the existence of the DIE in case
1351 // such construction creates the DIE.
1352 DIE *ContextDIE = getOrCreateContextDIE(NS.getContext());
1354 DIE *NDie = getDIE(NS);
1357 NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS);
1359 if (!NS.getName().empty()) {
1360 addString(NDie, dwarf::DW_AT_name, NS.getName());
1361 addAccelNamespace(NS.getName(), NDie);
1362 addGlobalName(NS.getName(), NDie, NS.getContext());
1364 addAccelNamespace("(anonymous namespace)", NDie);
1365 addSourceLine(NDie, NS);
1369 /// getOrCreateSubprogramDIE - Create new DIE using SP.
1370 DIE *DwarfUnit::getOrCreateSubprogramDIE(DISubprogram SP) {
1371 // Construct the context before querying for the existence of the DIE in case
1372 // such construction creates the DIE (as is the case for member function
1374 DIE *ContextDIE = getOrCreateContextDIE(resolve(SP.getContext()));
1376 DIE *SPDie = getDIE(SP);
1380 DISubprogram SPDecl = SP.getFunctionDeclaration();
1381 if (SPDecl.isSubprogram())
1382 // Add subprogram definitions to the CU die directly.
1383 ContextDIE = UnitDie.get();
1385 // DW_TAG_inlined_subroutine may refer to this DIE.
1386 SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
1388 DIE *DeclDie = NULL;
1389 if (SPDecl.isSubprogram())
1390 DeclDie = getOrCreateSubprogramDIE(SPDecl);
1392 // Add function template parameters.
1393 addTemplateParams(*SPDie, SP.getTemplateParams());
1395 // If this DIE is going to refer declaration info using AT_specification
1396 // then there is no need to add other attributes.
1398 // Refer function declaration directly.
1399 addDIEEntry(SPDie, dwarf::DW_AT_specification, DeclDie);
1404 // Add the linkage name if we have one.
1405 StringRef LinkageName = SP.getLinkageName();
1406 if (!LinkageName.empty())
1407 addString(SPDie, dwarf::DW_AT_MIPS_linkage_name,
1408 GlobalValue::getRealLinkageName(LinkageName));
1410 // Constructors and operators for anonymous aggregates do not have names.
1411 if (!SP.getName().empty())
1412 addString(SPDie, dwarf::DW_AT_name, SP.getName());
1414 addSourceLine(SPDie, SP);
1416 // Add the prototype if we have a prototype and we have a C like
1418 uint16_t Language = getLanguage();
1419 if (SP.isPrototyped() &&
1420 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1421 Language == dwarf::DW_LANG_ObjC))
1422 addFlag(SPDie, dwarf::DW_AT_prototyped);
1424 DICompositeType SPTy = SP.getType();
1425 assert(SPTy.getTag() == dwarf::DW_TAG_subroutine_type &&
1426 "the type of a subprogram should be a subroutine");
1428 DIArray Args = SPTy.getTypeArray();
1429 // Add a return type. If this is a type like a C/C++ void type we don't add a
1431 if (Args.getElement(0))
1432 addType(SPDie, DIType(Args.getElement(0)));
1434 unsigned VK = SP.getVirtuality();
1436 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1437 DIEBlock *Block = getDIEBlock();
1438 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1439 addUInt(Block, dwarf::DW_FORM_udata, SP.getVirtualIndex());
1440 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
1441 ContainingTypeMap.insert(
1442 std::make_pair(SPDie, resolve(SP.getContainingType())));
1445 if (!SP.isDefinition()) {
1446 addFlag(SPDie, dwarf::DW_AT_declaration);
1448 // Add arguments. Do not add arguments for subprogram definition. They will
1449 // be handled while processing variables.
1450 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1451 DIE *Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, *SPDie);
1452 DIType ATy(Args.getElement(i));
1454 if (ATy.isArtificial())
1455 addFlag(Arg, dwarf::DW_AT_artificial);
1459 if (SP.isArtificial())
1460 addFlag(SPDie, dwarf::DW_AT_artificial);
1462 if (!SP.isLocalToUnit())
1463 addFlag(SPDie, dwarf::DW_AT_external);
1465 if (SP.isOptimized())
1466 addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1468 if (unsigned isa = Asm->getISAEncoding()) {
1469 addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1472 if (SP.isLValueReference())
1473 addFlag(SPDie, dwarf::DW_AT_reference);
1475 if (SP.isRValueReference())
1476 addFlag(SPDie, dwarf::DW_AT_rvalue_reference);
1478 if (SP.isProtected())
1479 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1480 dwarf::DW_ACCESS_protected);
1481 else if (SP.isPrivate())
1482 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1483 dwarf::DW_ACCESS_private);
1485 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1486 dwarf::DW_ACCESS_public);
1488 if (SP.isExplicit())
1489 addFlag(SPDie, dwarf::DW_AT_explicit);
1494 // Return const expression if value is a GEP to access merged global
1496 // i8* getelementptr ({ i8, i8, i8, i8 }* @_MergedGlobals, i32 0, i32 0)
1497 static const ConstantExpr *getMergedGlobalExpr(const Value *V) {
1498 const ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(V);
1499 if (!CE || CE->getNumOperands() != 3 ||
1500 CE->getOpcode() != Instruction::GetElementPtr)
1503 // First operand points to a global struct.
1504 Value *Ptr = CE->getOperand(0);
1505 if (!isa<GlobalValue>(Ptr) ||
1506 !isa<StructType>(cast<PointerType>(Ptr->getType())->getElementType()))
1509 // Second operand is zero.
1510 const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(CE->getOperand(1));
1511 if (!CI || !CI->isZero())
1514 // Third operand is offset.
1515 if (!isa<ConstantInt>(CE->getOperand(2)))
1521 /// createGlobalVariableDIE - create global variable DIE.
1522 void DwarfCompileUnit::createGlobalVariableDIE(DIGlobalVariable GV) {
1523 // Check for pre-existence.
1527 assert(GV.isGlobalVariable());
1529 DIScope GVContext = GV.getContext();
1530 DIType GTy = GV.getType();
1532 // If this is a static data member definition, some attributes belong
1533 // to the declaration DIE.
1534 DIE *VariableDIE = NULL;
1535 bool IsStaticMember = false;
1536 DIDerivedType SDMDecl = GV.getStaticDataMemberDeclaration();
1537 if (SDMDecl.Verify()) {
1538 assert(SDMDecl.isStaticMember() && "Expected static member decl");
1539 // We need the declaration DIE that is in the static member's class.
1540 VariableDIE = getOrCreateStaticMemberDIE(SDMDecl);
1541 IsStaticMember = true;
1544 // If this is not a static data member definition, create the variable
1545 // DIE and add the initial set of attributes to it.
1547 // Construct the context before querying for the existence of the DIE in
1548 // case such construction creates the DIE.
1549 DIE *ContextDIE = getOrCreateContextDIE(GVContext);
1552 VariableDIE = createAndAddDIE(GV.getTag(), *ContextDIE, GV);
1554 // Add name and type.
1555 addString(VariableDIE, dwarf::DW_AT_name, GV.getDisplayName());
1556 addType(VariableDIE, GTy);
1558 // Add scoping info.
1559 if (!GV.isLocalToUnit())
1560 addFlag(VariableDIE, dwarf::DW_AT_external);
1562 // Add line number info.
1563 addSourceLine(VariableDIE, GV);
1567 bool addToAccelTable = false;
1568 DIE *VariableSpecDIE = NULL;
1569 bool isGlobalVariable = GV.getGlobal() != NULL;
1570 if (isGlobalVariable) {
1571 addToAccelTable = true;
1572 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1573 const MCSymbol *Sym = Asm->getSymbol(GV.getGlobal());
1574 if (GV.getGlobal()->isThreadLocal()) {
1575 // FIXME: Make this work with -gsplit-dwarf.
1576 unsigned PointerSize = Asm->getDataLayout().getPointerSize();
1577 assert((PointerSize == 4 || PointerSize == 8) &&
1578 "Add support for other sizes if necessary");
1579 const MCExpr *Expr =
1580 Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym);
1581 // Based on GCC's support for TLS:
1582 if (!DD->useSplitDwarf()) {
1583 // 1) Start with a constNu of the appropriate pointer size
1584 addUInt(Block, dwarf::DW_FORM_data1,
1585 PointerSize == 4 ? dwarf::DW_OP_const4u : dwarf::DW_OP_const8u);
1586 // 2) containing the (relocated) offset of the TLS variable
1587 // within the module's TLS block.
1588 addExpr(Block, dwarf::DW_FORM_udata, Expr);
1590 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
1591 addUInt(Block, dwarf::DW_FORM_udata, DU->getAddrPoolIndex(Expr));
1593 // 3) followed by a custom OP to make the debugger do a TLS lookup.
1594 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_push_tls_address);
1596 DD->addArangeLabel(SymbolCU(this, Sym));
1597 addOpAddress(Block, Sym);
1599 // Do not create specification DIE if context is either compile unit
1601 if (GVContext && GV.isDefinition() && !GVContext.isCompileUnit() &&
1602 !GVContext.isFile() && !DD->isSubprogramContext(GVContext)) {
1603 // Create specification DIE.
1604 VariableSpecDIE = createAndAddDIE(dwarf::DW_TAG_variable, *UnitDie);
1605 addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification, VariableDIE);
1606 addBlock(VariableSpecDIE, dwarf::DW_AT_location, Block);
1607 // A static member's declaration is already flagged as such.
1608 if (!SDMDecl.Verify())
1609 addFlag(VariableDIE, dwarf::DW_AT_declaration);
1611 addBlock(VariableDIE, dwarf::DW_AT_location, Block);
1613 // Add the linkage name.
1614 StringRef LinkageName = GV.getLinkageName();
1615 if (!LinkageName.empty())
1616 // From DWARF4: DIEs to which DW_AT_linkage_name may apply include:
1617 // TAG_common_block, TAG_constant, TAG_entry_point, TAG_subprogram and
1619 addString(IsStaticMember && VariableSpecDIE ? VariableSpecDIE
1621 dwarf::DW_AT_MIPS_linkage_name,
1622 GlobalValue::getRealLinkageName(LinkageName));
1623 } else if (const ConstantInt *CI =
1624 dyn_cast_or_null<ConstantInt>(GV.getConstant())) {
1625 // AT_const_value was added when the static member was created. To avoid
1626 // emitting AT_const_value multiple times, we only add AT_const_value when
1627 // it is not a static member.
1628 if (!IsStaticMember)
1629 addConstantValue(VariableDIE, CI, isUnsignedDIType(DD, GTy));
1630 } else if (const ConstantExpr *CE = getMergedGlobalExpr(GV->getOperand(11))) {
1631 addToAccelTable = true;
1632 // GV is a merged global.
1633 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1634 Value *Ptr = CE->getOperand(0);
1635 MCSymbol *Sym = Asm->getSymbol(cast<GlobalValue>(Ptr));
1636 DD->addArangeLabel(SymbolCU(this, Sym));
1637 addOpAddress(Block, Sym);
1638 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1639 SmallVector<Value *, 3> Idx(CE->op_begin() + 1, CE->op_end());
1640 addUInt(Block, dwarf::DW_FORM_udata,
1641 Asm->getDataLayout().getIndexedOffset(Ptr->getType(), Idx));
1642 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1643 addBlock(VariableDIE, dwarf::DW_AT_location, Block);
1646 if (addToAccelTable) {
1647 DIE *AddrDIE = VariableSpecDIE ? VariableSpecDIE : VariableDIE;
1648 addAccelName(GV.getName(), AddrDIE);
1650 // If the linkage name is different than the name, go ahead and output
1651 // that as well into the name table.
1652 if (GV.getLinkageName() != "" && GV.getName() != GV.getLinkageName())
1653 addAccelName(GV.getLinkageName(), AddrDIE);
1656 if (!GV.isLocalToUnit())
1657 addGlobalName(GV.getName(), VariableSpecDIE ? VariableSpecDIE : VariableDIE,
1661 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
1662 void DwarfUnit::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy) {
1663 DIE *DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
1664 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, IndexTy);
1666 // The LowerBound value defines the lower bounds which is typically zero for
1667 // C/C++. The Count value is the number of elements. Values are 64 bit. If
1668 // Count == -1 then the array is unbounded and we do not emit
1669 // DW_AT_lower_bound and DW_AT_upper_bound attributes. If LowerBound == 0 and
1670 // Count == 0, then the array has zero elements in which case we do not emit
1672 int64_t LowerBound = SR.getLo();
1673 int64_t DefaultLowerBound = getDefaultLowerBound();
1674 int64_t Count = SR.getCount();
1676 if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
1677 addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound);
1679 if (Count != -1 && Count != 0)
1680 // FIXME: An unbounded array should reference the expression that defines
1682 addUInt(DW_Subrange, dwarf::DW_AT_upper_bound, None,
1683 LowerBound + Count - 1);
1686 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
1687 void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, DICompositeType CTy) {
1689 addFlag(&Buffer, dwarf::DW_AT_GNU_vector);
1691 // Emit the element type.
1692 addType(&Buffer, resolve(CTy.getTypeDerivedFrom()));
1694 // Get an anonymous type for index type.
1695 // FIXME: This type should be passed down from the front end
1696 // as different languages may have different sizes for indexes.
1697 DIE *IdxTy = getIndexTyDie();
1699 // Construct an anonymous type for index type.
1700 IdxTy = createAndAddDIE(dwarf::DW_TAG_base_type, *UnitDie);
1701 addString(IdxTy, dwarf::DW_AT_name, "int");
1702 addUInt(IdxTy, dwarf::DW_AT_byte_size, None, sizeof(int32_t));
1703 addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1704 dwarf::DW_ATE_signed);
1705 setIndexTyDie(IdxTy);
1708 // Add subranges to array type.
1709 DIArray Elements = CTy.getTypeArray();
1710 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1711 DIDescriptor Element = Elements.getElement(i);
1712 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1713 constructSubrangeDIE(Buffer, DISubrange(Element), IdxTy);
1717 /// constructEnumTypeDIE - Construct an enum type DIE from DICompositeType.
1718 void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, DICompositeType CTy) {
1719 DIArray Elements = CTy.getTypeArray();
1721 // Add enumerators to enumeration type.
1722 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1723 DIEnumerator Enum(Elements.getElement(i));
1724 if (Enum.isEnumerator()) {
1725 DIE *Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
1726 StringRef Name = Enum.getName();
1727 addString(Enumerator, dwarf::DW_AT_name, Name);
1728 int64_t Value = Enum.getEnumValue();
1729 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
1733 DIType DTy = resolve(CTy.getTypeDerivedFrom());
1735 addType(&Buffer, DTy);
1736 addFlag(&Buffer, dwarf::DW_AT_enum_class);
1740 /// constructContainingTypeDIEs - Construct DIEs for types that contain
1742 void DwarfUnit::constructContainingTypeDIEs() {
1743 for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(),
1744 CE = ContainingTypeMap.end();
1746 DIE *SPDie = CI->first;
1747 DIDescriptor D(CI->second);
1750 DIE *NDie = getDIE(D);
1753 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, NDie);
1757 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
1758 DIE *DwarfUnit::constructVariableDIE(DbgVariable &DV, bool isScopeAbstract) {
1759 StringRef Name = DV.getName();
1761 // Define variable debug information entry.
1762 DIE *VariableDie = new DIE(DV.getTag());
1763 DbgVariable *AbsVar = DV.getAbstractVariable();
1764 DIE *AbsDIE = AbsVar ? AbsVar->getDIE() : NULL;
1766 addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin, AbsDIE);
1769 addString(VariableDie, dwarf::DW_AT_name, Name);
1770 addSourceLine(VariableDie, DV.getVariable());
1771 addType(VariableDie, DV.getType());
1774 if (DV.isArtificial())
1775 addFlag(VariableDie, dwarf::DW_AT_artificial);
1777 if (isScopeAbstract) {
1778 DV.setDIE(VariableDie);
1782 // Add variable address.
1784 unsigned Offset = DV.getDotDebugLocOffset();
1785 if (Offset != ~0U) {
1786 addSectionLabel(VariableDie, dwarf::DW_AT_location,
1787 Asm->GetTempSymbol("debug_loc", Offset));
1788 DV.setDIE(VariableDie);
1792 // Check if variable is described by a DBG_VALUE instruction.
1793 if (const MachineInstr *DVInsn = DV.getMInsn()) {
1794 assert(DVInsn->getNumOperands() == 3);
1795 if (DVInsn->getOperand(0).isReg()) {
1796 const MachineOperand RegOp = DVInsn->getOperand(0);
1797 // If the second operand is an immediate, this is an indirect value.
1798 if (DVInsn->getOperand(1).isImm()) {
1799 MachineLocation Location(RegOp.getReg(),
1800 DVInsn->getOperand(1).getImm());
1801 addVariableAddress(DV, VariableDie, Location);
1802 } else if (RegOp.getReg())
1803 addVariableAddress(DV, VariableDie, MachineLocation(RegOp.getReg()));
1804 } else if (DVInsn->getOperand(0).isImm())
1805 addConstantValue(VariableDie, DVInsn->getOperand(0), DV.getType());
1806 else if (DVInsn->getOperand(0).isFPImm())
1807 addConstantFPValue(VariableDie, DVInsn->getOperand(0));
1808 else if (DVInsn->getOperand(0).isCImm())
1809 addConstantValue(VariableDie, DVInsn->getOperand(0).getCImm(),
1810 isUnsignedDIType(DD, DV.getType()));
1812 DV.setDIE(VariableDie);
1815 // .. else use frame index.
1816 int FI = DV.getFrameIndex();
1818 unsigned FrameReg = 0;
1819 const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
1820 int Offset = TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
1821 MachineLocation Location(FrameReg, Offset);
1822 addVariableAddress(DV, VariableDie, Location);
1826 DV.setDIE(VariableDie);
1830 /// constructMemberDIE - Construct member DIE from DIDerivedType.
1831 void DwarfUnit::constructMemberDIE(DIE &Buffer, DIDerivedType DT) {
1832 DIE *MemberDie = createAndAddDIE(DT.getTag(), Buffer);
1833 StringRef Name = DT.getName();
1835 addString(MemberDie, dwarf::DW_AT_name, Name);
1837 addType(MemberDie, resolve(DT.getTypeDerivedFrom()));
1839 addSourceLine(MemberDie, DT);
1841 if (DT.getTag() == dwarf::DW_TAG_inheritance && DT.isVirtual()) {
1843 // For C++, virtual base classes are not at fixed offset. Use following
1844 // expression to extract appropriate offset from vtable.
1845 // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1847 DIEBlock *VBaseLocationDie = new (DIEValueAllocator) DIEBlock();
1848 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1849 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1850 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1851 addUInt(VBaseLocationDie, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1852 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1853 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1854 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1856 addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
1858 uint64_t Size = DT.getSizeInBits();
1859 uint64_t FieldSize = getBaseTypeSize(DD, DT);
1860 uint64_t OffsetInBytes;
1862 if (Size != FieldSize) {
1864 addUInt(MemberDie, dwarf::DW_AT_byte_size, None,
1865 getBaseTypeSize(DD, DT) >> 3);
1866 addUInt(MemberDie, dwarf::DW_AT_bit_size, None, DT.getSizeInBits());
1868 uint64_t Offset = DT.getOffsetInBits();
1869 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1870 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1871 uint64_t FieldOffset = (HiMark - FieldSize);
1872 Offset -= FieldOffset;
1874 // Maybe we need to work from the other end.
1875 if (Asm->getDataLayout().isLittleEndian())
1876 Offset = FieldSize - (Offset + Size);
1877 addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset);
1879 // Here DW_AT_data_member_location points to the anonymous
1880 // field that includes this bit field.
1881 OffsetInBytes = FieldOffset >> 3;
1883 // This is not a bitfield.
1884 OffsetInBytes = DT.getOffsetInBits() >> 3;
1886 if (DD->getDwarfVersion() <= 2) {
1887 DIEBlock *MemLocationDie = new (DIEValueAllocator) DIEBlock();
1888 addUInt(MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1889 addUInt(MemLocationDie, dwarf::DW_FORM_udata, OffsetInBytes);
1890 addBlock(MemberDie, dwarf::DW_AT_data_member_location, MemLocationDie);
1892 addUInt(MemberDie, dwarf::DW_AT_data_member_location, None,
1896 if (DT.isProtected())
1897 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1898 dwarf::DW_ACCESS_protected);
1899 else if (DT.isPrivate())
1900 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1901 dwarf::DW_ACCESS_private);
1902 // Otherwise C++ member and base classes are considered public.
1904 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1905 dwarf::DW_ACCESS_public);
1907 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1908 dwarf::DW_VIRTUALITY_virtual);
1910 // Objective-C properties.
1911 if (MDNode *PNode = DT.getObjCProperty())
1912 if (DIEEntry *PropertyDie = getDIEEntry(PNode))
1913 MemberDie->addValue(dwarf::DW_AT_APPLE_property, dwarf::DW_FORM_ref4,
1916 if (DT.isArtificial())
1917 addFlag(MemberDie, dwarf::DW_AT_artificial);
1920 /// getOrCreateStaticMemberDIE - Create new DIE for C++ static member.
1921 DIE *DwarfUnit::getOrCreateStaticMemberDIE(DIDerivedType DT) {
1925 // Construct the context before querying for the existence of the DIE in case
1926 // such construction creates the DIE.
1927 DIE *ContextDIE = getOrCreateContextDIE(resolve(DT.getContext()));
1928 assert(dwarf::isType(ContextDIE->getTag()) &&
1929 "Static member should belong to a type.");
1931 DIE *StaticMemberDIE = getDIE(DT);
1932 if (StaticMemberDIE)
1933 return StaticMemberDIE;
1935 StaticMemberDIE = createAndAddDIE(DT.getTag(), *ContextDIE, DT);
1937 DIType Ty = resolve(DT.getTypeDerivedFrom());
1939 addString(StaticMemberDIE, dwarf::DW_AT_name, DT.getName());
1940 addType(StaticMemberDIE, Ty);
1941 addSourceLine(StaticMemberDIE, DT);
1942 addFlag(StaticMemberDIE, dwarf::DW_AT_external);
1943 addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
1945 // FIXME: We could omit private if the parent is a class_type, and
1946 // public if the parent is something else.
1947 if (DT.isProtected())
1948 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1949 dwarf::DW_ACCESS_protected);
1950 else if (DT.isPrivate())
1951 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1952 dwarf::DW_ACCESS_private);
1954 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1955 dwarf::DW_ACCESS_public);
1957 if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT.getConstant()))
1958 addConstantValue(StaticMemberDIE, CI, isUnsignedDIType(DD, Ty));
1959 if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT.getConstant()))
1960 addConstantFPValue(StaticMemberDIE, CFP);
1962 return StaticMemberDIE;
1965 void DwarfUnit::emitHeader(const MCSection *ASection,
1966 const MCSymbol *ASectionSym) const {
1967 Asm->OutStreamer.AddComment("DWARF version number");
1968 Asm->EmitInt16(DD->getDwarfVersion());
1969 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
1970 // We share one abbreviations table across all units so it's always at the
1971 // start of the section. Use a relocatable offset where needed to ensure
1972 // linking doesn't invalidate that offset.
1973 Asm->EmitSectionOffset(ASectionSym, ASectionSym);
1974 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1975 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
1978 DwarfCompileUnit::~DwarfCompileUnit() {}
1979 DwarfTypeUnit::~DwarfTypeUnit() {}
1981 void DwarfTypeUnit::emitHeader(const MCSection *ASection,
1982 const MCSymbol *ASectionSym) const {
1983 DwarfUnit::emitHeader(ASection, ASectionSym);
1984 Asm->OutStreamer.AddComment("Type Signature");
1985 Asm->OutStreamer.EmitIntValue(TypeSignature, sizeof(TypeSignature));
1986 Asm->OutStreamer.AddComment("Type DIE Offset");
1987 // In a skeleton type unit there is no type DIE so emit a zero offset.
1988 Asm->OutStreamer.EmitIntValue(Ty ? Ty->getOffset() : 0,
1989 sizeof(Ty->getOffset()));
1992 void DwarfTypeUnit::initSection(const MCSection *Section) {
1993 assert(!this->Section);
1994 this->Section = Section;
1995 // Since each type unit is contained in its own COMDAT section, the begin
1996 // label and the section label are the same. Using the begin label emission in
1997 // DwarfDebug to emit the section label as well is slightly subtle/sneaky, but
1998 // the only other alternative of lazily constructing start-of-section labels
1999 // and storing a mapping in DwarfDebug (or AsmPrinter).
2000 this->SectionSym = this->LabelBegin =
2001 Asm->GetTempSymbol(Section->getLabelBeginName(), getUniqueID());
2003 Asm->GetTempSymbol(Section->getLabelEndName(), getUniqueID());
2004 this->LabelRange = Asm->GetTempSymbol("gnu_ranges", getUniqueID());