1 //===-- llvm/CodeGen/DwarfCompileUnit.cpp - Dwarf Compile Unit ------------===//
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 "DwarfCompileUnit.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/MC/MCSection.h"
26 #include "llvm/MC/MCStreamer.h"
27 #include "llvm/Target/Mangler.h"
28 #include "llvm/Target/TargetFrameLowering.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/Target/TargetLoweringObjectFile.h"
31 #include "llvm/Target/TargetRegisterInfo.h"
35 /// CompileUnit - Compile unit constructor.
36 CompileUnit::CompileUnit(unsigned UID, DIE *D, const MDNode *N, AsmPrinter *A,
37 DwarfDebug *DW, DwarfUnits *DWU)
38 : UniqueID(UID), Node(N), CUDie(D), Asm(A), DD(DW), DU(DWU), IndexTyDie(0),
40 DIEIntegerOne = new (DIEValueAllocator) DIEInteger(1);
44 /// ~CompileUnit - Destructor for compile unit.
45 CompileUnit::~CompileUnit() {
46 for (unsigned j = 0, M = DIEBlocks.size(); j < M; ++j)
47 DIEBlocks[j]->~DIEBlock();
50 /// createDIEEntry - Creates a new DIEEntry to be a proxy for a debug
51 /// information entry.
52 DIEEntry *CompileUnit::createDIEEntry(DIE *Entry) {
53 DIEEntry *Value = new (DIEValueAllocator) DIEEntry(Entry);
57 /// getDefaultLowerBound - Return the default lower bound for an array. If the
58 /// DWARF version doesn't handle the language, return -1.
59 int64_t CompileUnit::getDefaultLowerBound() const {
60 switch (DICompileUnit(Node).getLanguage()) {
64 case dwarf::DW_LANG_C89:
65 case dwarf::DW_LANG_C99:
66 case dwarf::DW_LANG_C:
67 case dwarf::DW_LANG_C_plus_plus:
68 case dwarf::DW_LANG_ObjC:
69 case dwarf::DW_LANG_ObjC_plus_plus:
72 case dwarf::DW_LANG_Fortran77:
73 case dwarf::DW_LANG_Fortran90:
74 case dwarf::DW_LANG_Fortran95:
77 // The languages below have valid values only if the DWARF version >= 4.
78 case dwarf::DW_LANG_Java:
79 case dwarf::DW_LANG_Python:
80 case dwarf::DW_LANG_UPC:
81 case dwarf::DW_LANG_D:
82 if (dwarf::DWARF_VERSION >= 4)
86 case dwarf::DW_LANG_Ada83:
87 case dwarf::DW_LANG_Ada95:
88 case dwarf::DW_LANG_Cobol74:
89 case dwarf::DW_LANG_Cobol85:
90 case dwarf::DW_LANG_Modula2:
91 case dwarf::DW_LANG_Pascal83:
92 case dwarf::DW_LANG_PLI:
93 if (dwarf::DWARF_VERSION >= 4)
101 /// Check whether the DIE for this MDNode can be shared across CUs.
102 static bool isShareableAcrossCUs(const MDNode *N) {
103 // When the MDNode can be part of the type system, the DIE can be
104 // shared across CUs.
105 return DIDescriptor(N).isType() ||
106 (DIDescriptor(N).isSubprogram() && !DISubprogram(N).isDefinition());
109 /// getDIE - Returns the debug information entry map slot for the
110 /// specified debug variable. We delegate the request to DwarfDebug
111 /// when the DIE for this MDNode can be shared across CUs. The mappings
112 /// will be kept in DwarfDebug for shareable DIEs.
113 DIE *CompileUnit::getDIE(const MDNode *N) const {
114 if (isShareableAcrossCUs(N))
115 return DD->getDIE(N);
116 return MDNodeToDieMap.lookup(N);
119 /// insertDIE - Insert DIE into the map. We delegate the request to DwarfDebug
120 /// when the DIE for this MDNode can be shared across CUs. The mappings
121 /// will be kept in DwarfDebug for shareable DIEs.
122 void CompileUnit::insertDIE(const MDNode *N, DIE *D) {
123 if (isShareableAcrossCUs(N)) {
127 MDNodeToDieMap.insert(std::make_pair(N, D));
130 /// addFlag - Add a flag that is true.
131 void CompileUnit::addFlag(DIE *Die, dwarf::Attribute Attribute) {
132 if (DD->getDwarfVersion() >= 4)
133 Die->addValue(Attribute, dwarf::DW_FORM_flag_present, DIEIntegerOne);
135 Die->addValue(Attribute, dwarf::DW_FORM_flag, DIEIntegerOne);
138 /// addUInt - Add an unsigned integer attribute data and value.
140 void CompileUnit::addUInt(DIE *Die, dwarf::Attribute Attribute,
141 Optional<dwarf::Form> Form, uint64_t Integer) {
143 Form = DIEInteger::BestForm(false, Integer);
144 DIEValue *Value = Integer == 1 ? DIEIntegerOne : new (DIEValueAllocator)
146 Die->addValue(Attribute, *Form, Value);
149 void CompileUnit::addUInt(DIEBlock *Block, dwarf::Form Form, uint64_t Integer) {
150 addUInt(Block, (dwarf::Attribute)0, Form, Integer);
153 /// addSInt - Add an signed integer attribute data and value.
155 void CompileUnit::addSInt(DIE *Die, dwarf::Attribute Attribute,
156 Optional<dwarf::Form> Form, int64_t Integer) {
158 Form = DIEInteger::BestForm(true, Integer);
159 DIEValue *Value = new (DIEValueAllocator) DIEInteger(Integer);
160 Die->addValue(Attribute, *Form, Value);
163 void CompileUnit::addSInt(DIEBlock *Die, Optional<dwarf::Form> Form,
165 addSInt(Die, (dwarf::Attribute)0, Form, Integer);
168 /// addString - Add a string attribute data and value. We always emit a
169 /// reference to the string pool instead of immediate strings so that DIEs have
170 /// more predictable sizes. In the case of split dwarf we emit an index
171 /// into another table which gets us the static offset into the string
173 void CompileUnit::addString(DIE *Die, dwarf::Attribute Attribute, StringRef String) {
176 if (!DD->useSplitDwarf()) {
177 MCSymbol *Symb = DU->getStringPoolEntry(String);
178 if (Asm->needsRelocationsForDwarfStringPool())
179 Value = new (DIEValueAllocator) DIELabel(Symb);
181 MCSymbol *StringPool = DU->getStringPoolSym();
182 Value = new (DIEValueAllocator) DIEDelta(Symb, StringPool);
184 Form = dwarf::DW_FORM_strp;
186 unsigned idx = DU->getStringPoolIndex(String);
187 Value = new (DIEValueAllocator) DIEInteger(idx);
188 Form = dwarf::DW_FORM_GNU_str_index;
190 DIEValue *Str = new (DIEValueAllocator) DIEString(Value, String);
191 Die->addValue(Attribute, Form, Str);
194 /// addLocalString - Add a string attribute data and value. This is guaranteed
195 /// to be in the local string pool instead of indirected.
196 void CompileUnit::addLocalString(DIE *Die, dwarf::Attribute Attribute,
198 MCSymbol *Symb = DU->getStringPoolEntry(String);
200 if (Asm->needsRelocationsForDwarfStringPool())
201 Value = new (DIEValueAllocator) DIELabel(Symb);
203 MCSymbol *StringPool = DU->getStringPoolSym();
204 Value = new (DIEValueAllocator) DIEDelta(Symb, StringPool);
206 Die->addValue(Attribute, dwarf::DW_FORM_strp, Value);
209 /// addExpr - Add a Dwarf expression attribute data and value.
211 void CompileUnit::addExpr(DIEBlock *Die, dwarf::Form Form, const MCExpr *Expr) {
212 DIEValue *Value = new (DIEValueAllocator) DIEExpr(Expr);
213 Die->addValue((dwarf::Attribute)0, Form, Value);
216 /// addLabel - Add a Dwarf label attribute data and value.
218 void CompileUnit::addLabel(DIE *Die, dwarf::Attribute Attribute, dwarf::Form Form,
219 const MCSymbol *Label) {
220 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
221 Die->addValue(Attribute, Form, Value);
224 void CompileUnit::addLabel(DIEBlock *Die, dwarf::Form Form,
225 const MCSymbol *Label) {
226 addLabel(Die, (dwarf::Attribute)0, Form, Label);
229 /// addLabelAddress - Add a dwarf label attribute data and value using
230 /// DW_FORM_addr or DW_FORM_GNU_addr_index.
232 void CompileUnit::addLabelAddress(DIE *Die, dwarf::Attribute Attribute,
235 DD->addArangeLabel(SymbolCU(this, Label));
237 if (!DD->useSplitDwarf()) {
239 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
240 Die->addValue(Attribute, dwarf::DW_FORM_addr, Value);
242 DIEValue *Value = new (DIEValueAllocator) DIEInteger(0);
243 Die->addValue(Attribute, dwarf::DW_FORM_addr, Value);
246 unsigned idx = DU->getAddrPoolIndex(Label);
247 DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
248 Die->addValue(Attribute, dwarf::DW_FORM_GNU_addr_index, Value);
252 /// addOpAddress - Add a dwarf op address data and value using the
253 /// form given and an op of either DW_FORM_addr or DW_FORM_GNU_addr_index.
255 void CompileUnit::addOpAddress(DIEBlock *Die, const MCSymbol *Sym) {
256 DD->addArangeLabel(SymbolCU(this, Sym));
257 if (!DD->useSplitDwarf()) {
258 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
259 addLabel(Die, dwarf::DW_FORM_udata, Sym);
261 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index);
262 addUInt(Die, dwarf::DW_FORM_GNU_addr_index, DU->getAddrPoolIndex(Sym));
266 /// addDelta - Add a label delta attribute data and value.
268 void CompileUnit::addDelta(DIE *Die, dwarf::Attribute Attribute, dwarf::Form Form,
269 const MCSymbol *Hi, const MCSymbol *Lo) {
270 DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
271 Die->addValue(Attribute, Form, Value);
274 /// addDIEEntry - Add a DIE attribute data and value.
276 void CompileUnit::addDIEEntry(DIE *Die, dwarf::Attribute Attribute, DIE *Entry) {
277 addDIEEntry(Die, Attribute, createDIEEntry(Entry));
280 void CompileUnit::addDIEEntry(DIE *Die, dwarf::Attribute Attribute,
282 const DIE *DieCU = Die->getCompileUnitOrNull();
283 const DIE *EntryCU = Entry->getEntry()->getCompileUnitOrNull();
285 // We assume that Die belongs to this CU, if it is not linked to any CU yet.
288 EntryCU = getCUDie();
289 Die->addValue(Attribute, EntryCU == DieCU ? dwarf::DW_FORM_ref4
290 : dwarf::DW_FORM_ref_addr,
294 /// Create a DIE with the given Tag, add the DIE to its parent, and
295 /// call insertDIE if MD is not null.
296 DIE *CompileUnit::createAndAddDIE(unsigned Tag, DIE &Parent, const MDNode *MD) {
297 DIE *Die = new DIE(Tag);
298 Parent.addChild(Die);
304 /// addBlock - Add block data.
306 void CompileUnit::addBlock(DIE *Die, dwarf::Attribute Attribute,
308 Block->ComputeSize(Asm);
309 DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
310 Die->addValue(Attribute, Block->BestForm(), Block);
313 /// addSourceLine - Add location information to specified debug information
315 void CompileUnit::addSourceLine(DIE *Die, DIVariable V) {
320 unsigned Line = V.getLineNumber();
324 DD->getOrCreateSourceID(V.getContext().getFilename(),
325 V.getContext().getDirectory(), getUniqueID());
326 assert(FileID && "Invalid file id");
327 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
328 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
331 /// addSourceLine - Add location information to specified debug information
333 void CompileUnit::addSourceLine(DIE *Die, DIGlobalVariable G) {
334 // Verify global variable.
335 if (!G.isGlobalVariable())
338 unsigned Line = G.getLineNumber();
342 DD->getOrCreateSourceID(G.getFilename(), G.getDirectory(), getUniqueID());
343 assert(FileID && "Invalid file id");
344 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
345 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
348 /// addSourceLine - Add location information to specified debug information
350 void CompileUnit::addSourceLine(DIE *Die, DISubprogram SP) {
351 // Verify subprogram.
352 if (!SP.isSubprogram())
355 // If the line number is 0, don't add it.
356 unsigned Line = SP.getLineNumber();
360 unsigned FileID = DD->getOrCreateSourceID(SP.getFilename(), SP.getDirectory(),
362 assert(FileID && "Invalid file id");
363 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
364 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
367 /// addSourceLine - Add location information to specified debug information
369 void CompileUnit::addSourceLine(DIE *Die, DIType Ty) {
374 unsigned Line = Ty.getLineNumber();
377 unsigned FileID = DD->getOrCreateSourceID(Ty.getFilename(), Ty.getDirectory(),
379 assert(FileID && "Invalid file id");
380 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
381 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
384 /// addSourceLine - Add location information to specified debug information
386 void CompileUnit::addSourceLine(DIE *Die, DIObjCProperty Ty) {
388 if (!Ty.isObjCProperty())
391 unsigned Line = Ty.getLineNumber();
394 DIFile File = Ty.getFile();
395 unsigned FileID = DD->getOrCreateSourceID(File.getFilename(),
396 File.getDirectory(), getUniqueID());
397 assert(FileID && "Invalid file id");
398 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
399 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
402 /// addSourceLine - Add location information to specified debug information
404 void CompileUnit::addSourceLine(DIE *Die, DINameSpace NS) {
409 unsigned Line = NS.getLineNumber();
412 StringRef FN = NS.getFilename();
415 DD->getOrCreateSourceID(FN, NS.getDirectory(), getUniqueID());
416 assert(FileID && "Invalid file id");
417 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
418 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
421 /// addVariableAddress - Add DW_AT_location attribute for a
422 /// DbgVariable based on provided MachineLocation.
423 void CompileUnit::addVariableAddress(const DbgVariable &DV, DIE *Die,
424 MachineLocation Location) {
425 if (DV.variableHasComplexAddress())
426 addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
427 else if (DV.isBlockByrefVariable())
428 addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location);
430 addAddress(Die, dwarf::DW_AT_location, Location,
431 DV.getVariable().isIndirect());
434 /// addRegisterOp - Add register operand.
435 void CompileUnit::addRegisterOp(DIEBlock *TheDie, unsigned Reg) {
436 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
437 unsigned DWReg = RI->getDwarfRegNum(Reg, false);
439 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + DWReg);
441 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
442 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
446 /// addRegisterOffset - Add register offset.
447 void CompileUnit::addRegisterOffset(DIEBlock *TheDie, unsigned Reg,
449 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
450 unsigned DWReg = RI->getDwarfRegNum(Reg, false);
451 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
452 if (Reg == TRI->getFrameRegister(*Asm->MF))
453 // If variable offset is based in frame register then use fbreg.
454 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_fbreg);
456 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + DWReg);
458 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
459 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
461 addSInt(TheDie, dwarf::DW_FORM_sdata, Offset);
464 /// addAddress - Add an address attribute to a die based on the location
466 void CompileUnit::addAddress(DIE *Die, dwarf::Attribute Attribute,
467 const MachineLocation &Location, bool Indirect) {
468 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
470 if (Location.isReg() && !Indirect)
471 addRegisterOp(Block, Location.getReg());
473 addRegisterOffset(Block, Location.getReg(), Location.getOffset());
474 if (Indirect && !Location.isReg()) {
475 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
479 // Now attach the location information to the DIE.
480 addBlock(Die, Attribute, Block);
483 /// addComplexAddress - Start with the address based on the location provided,
484 /// and generate the DWARF information necessary to find the actual variable
485 /// given the extra address information encoded in the DIVariable, starting from
486 /// the starting location. Add the DWARF information to the die.
488 void CompileUnit::addComplexAddress(const DbgVariable &DV, DIE *Die,
489 dwarf::Attribute Attribute,
490 const MachineLocation &Location) {
491 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
492 unsigned N = DV.getNumAddrElements();
494 if (Location.isReg()) {
495 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
496 // If first address element is OpPlus then emit
497 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
498 addRegisterOffset(Block, Location.getReg(), DV.getAddrElement(1));
501 addRegisterOp(Block, Location.getReg());
503 addRegisterOffset(Block, Location.getReg(), Location.getOffset());
506 uint64_t Element = DV.getAddrElement(i);
507 if (Element == DIBuilder::OpPlus) {
508 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
509 addUInt(Block, dwarf::DW_FORM_udata, DV.getAddrElement(++i));
510 } else if (Element == DIBuilder::OpDeref) {
511 if (!Location.isReg())
512 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
514 llvm_unreachable("unknown DIBuilder Opcode");
517 // Now attach the location information to the DIE.
518 addBlock(Die, Attribute, Block);
521 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
522 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
523 gives the variable VarName either the struct, or a pointer to the struct, as
524 its type. This is necessary for various behind-the-scenes things the
525 compiler needs to do with by-reference variables in Blocks.
527 However, as far as the original *programmer* is concerned, the variable
528 should still have type 'SomeType', as originally declared.
530 The function getBlockByrefType dives into the __Block_byref_x_VarName
531 struct to find the original type of the variable, which is then assigned to
532 the variable's Debug Information Entry as its real type. So far, so good.
533 However now the debugger will expect the variable VarName to have the type
534 SomeType. So we need the location attribute for the variable to be an
535 expression that explains to the debugger how to navigate through the
536 pointers and struct to find the actual variable of type SomeType.
538 The following function does just that. We start by getting
539 the "normal" location for the variable. This will be the location
540 of either the struct __Block_byref_x_VarName or the pointer to the
541 struct __Block_byref_x_VarName.
543 The struct will look something like:
545 struct __Block_byref_x_VarName {
547 struct __Block_byref_x_VarName *forwarding;
548 ... <various other fields>
550 ... <maybe more fields>
553 If we are given the struct directly (as our starting point) we
554 need to tell the debugger to:
556 1). Add the offset of the forwarding field.
558 2). Follow that pointer to get the real __Block_byref_x_VarName
559 struct to use (the real one may have been copied onto the heap).
561 3). Add the offset for the field VarName, to find the actual variable.
563 If we started with a pointer to the struct, then we need to
564 dereference that pointer first, before the other steps.
565 Translating this into DWARF ops, we will need to append the following
566 to the current location description for the variable:
568 DW_OP_deref -- optional, if we start with a pointer
569 DW_OP_plus_uconst <forward_fld_offset>
571 DW_OP_plus_uconst <varName_fld_offset>
573 That is what this function does. */
575 /// addBlockByrefAddress - Start with the address based on the location
576 /// provided, and generate the DWARF information necessary to find the
577 /// actual Block variable (navigating the Block struct) based on the
578 /// starting location. Add the DWARF information to the die. For
579 /// more information, read large comment just above here.
581 void CompileUnit::addBlockByrefAddress(const DbgVariable &DV, DIE *Die,
582 dwarf::Attribute Attribute,
583 const MachineLocation &Location) {
584 DIType Ty = DV.getType();
586 uint16_t Tag = Ty.getTag();
587 bool isPointer = false;
589 StringRef varName = DV.getName();
591 if (Tag == dwarf::DW_TAG_pointer_type) {
592 DIDerivedType DTy = DIDerivedType(Ty);
593 TmpTy = resolve(DTy.getTypeDerivedFrom());
597 DICompositeType blockStruct = DICompositeType(TmpTy);
599 // Find the __forwarding field and the variable field in the __Block_byref
601 DIArray Fields = blockStruct.getTypeArray();
602 DIDescriptor varField = DIDescriptor();
603 DIDescriptor forwardingField = DIDescriptor();
605 for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
606 DIDescriptor Element = Fields.getElement(i);
607 DIDerivedType DT = DIDerivedType(Element);
608 StringRef fieldName = DT.getName();
609 if (fieldName == "__forwarding")
610 forwardingField = Element;
611 else if (fieldName == varName)
615 // Get the offsets for the forwarding field and the variable field.
616 unsigned forwardingFieldOffset =
617 DIDerivedType(forwardingField).getOffsetInBits() >> 3;
618 unsigned varFieldOffset = DIDerivedType(varField).getOffsetInBits() >> 3;
620 // Decode the original location, and use that as the start of the byref
621 // variable's location.
622 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
624 if (Location.isReg())
625 addRegisterOp(Block, Location.getReg());
627 addRegisterOffset(Block, Location.getReg(), Location.getOffset());
629 // If we started with a pointer to the __Block_byref... struct, then
630 // the first thing we need to do is dereference the pointer (DW_OP_deref).
632 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
634 // Next add the offset for the '__forwarding' field:
635 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
636 // adding the offset if it's 0.
637 if (forwardingFieldOffset > 0) {
638 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
639 addUInt(Block, dwarf::DW_FORM_udata, forwardingFieldOffset);
642 // Now dereference the __forwarding field to get to the real __Block_byref
643 // struct: DW_OP_deref.
644 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
646 // Now that we've got the real __Block_byref... struct, add the offset
647 // for the variable's field to get to the location of the actual variable:
648 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
649 if (varFieldOffset > 0) {
650 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
651 addUInt(Block, dwarf::DW_FORM_udata, varFieldOffset);
654 // Now attach the location information to the DIE.
655 addBlock(Die, Attribute, Block);
658 /// isTypeSigned - Return true if the type is signed.
659 static bool isTypeSigned(DwarfDebug *DD, DIType Ty, int *SizeInBits) {
660 if (Ty.isDerivedType())
661 return isTypeSigned(DD, DD->resolve(DIDerivedType(Ty).getTypeDerivedFrom()),
663 if (Ty.isBasicType())
664 if (DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed ||
665 DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed_char) {
666 *SizeInBits = Ty.getSizeInBits();
672 /// Return true if type encoding is unsigned.
673 static bool isUnsignedDIType(DwarfDebug *DD, DIType Ty) {
674 DIDerivedType DTy(Ty);
675 if (DTy.isDerivedType())
676 return isUnsignedDIType(DD, DD->resolve(DTy.getTypeDerivedFrom()));
679 if (BTy.isBasicType()) {
680 unsigned Encoding = BTy.getEncoding();
681 if (Encoding == dwarf::DW_ATE_unsigned ||
682 Encoding == dwarf::DW_ATE_unsigned_char ||
683 Encoding == dwarf::DW_ATE_boolean)
689 /// If this type is derived from a base type then return base type size.
690 static uint64_t getBaseTypeSize(DwarfDebug *DD, DIDerivedType Ty) {
691 unsigned Tag = Ty.getTag();
693 if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef &&
694 Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type &&
695 Tag != dwarf::DW_TAG_restrict_type)
696 return Ty.getSizeInBits();
698 DIType BaseType = DD->resolve(Ty.getTypeDerivedFrom());
700 // If this type is not derived from any type then take conservative approach.
701 if (!BaseType.isValid())
702 return Ty.getSizeInBits();
704 // If this is a derived type, go ahead and get the base type, unless it's a
705 // reference then it's just the size of the field. Pointer types have no need
706 // of this since they're a different type of qualification on the type.
707 if (BaseType.getTag() == dwarf::DW_TAG_reference_type ||
708 BaseType.getTag() == dwarf::DW_TAG_rvalue_reference_type)
709 return Ty.getSizeInBits();
711 if (BaseType.isDerivedType())
712 return getBaseTypeSize(DD, DIDerivedType(BaseType));
714 return BaseType.getSizeInBits();
717 /// addConstantValue - Add constant value entry in variable DIE.
718 void CompileUnit::addConstantValue(DIE *Die, const MachineOperand &MO,
720 // FIXME: This is a bit conservative/simple - it emits negative values at
721 // their maximum bit width which is a bit unfortunate (& doesn't prefer
722 // udata/sdata over dataN as suggested by the DWARF spec)
723 assert(MO.isImm() && "Invalid machine operand!");
725 bool SignedConstant = isTypeSigned(DD, Ty, &SizeInBits);
728 // If we're a signed constant definitely use sdata.
729 if (SignedConstant) {
730 addSInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, MO.getImm());
734 // Else use data for now unless it's larger than we can deal with.
735 switch (SizeInBits) {
737 Form = dwarf::DW_FORM_data1;
740 Form = dwarf::DW_FORM_data2;
743 Form = dwarf::DW_FORM_data4;
746 Form = dwarf::DW_FORM_data8;
749 Form = dwarf::DW_FORM_udata;
750 addUInt(Die, dwarf::DW_AT_const_value, Form, MO.getImm());
753 addUInt(Die, dwarf::DW_AT_const_value, Form, MO.getImm());
756 /// addConstantFPValue - Add constant value entry in variable DIE.
757 void CompileUnit::addConstantFPValue(DIE *Die, const MachineOperand &MO) {
758 assert(MO.isFPImm() && "Invalid machine operand!");
759 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
760 APFloat FPImm = MO.getFPImm()->getValueAPF();
762 // Get the raw data form of the floating point.
763 const APInt FltVal = FPImm.bitcastToAPInt();
764 const char *FltPtr = (const char *)FltVal.getRawData();
766 int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
767 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
768 int Incr = (LittleEndian ? 1 : -1);
769 int Start = (LittleEndian ? 0 : NumBytes - 1);
770 int Stop = (LittleEndian ? NumBytes : -1);
772 // Output the constant to DWARF one byte at a time.
773 for (; Start != Stop; Start += Incr)
774 addUInt(Block, dwarf::DW_FORM_data1,
775 (unsigned char)0xFF & FltPtr[Start]);
777 addBlock(Die, dwarf::DW_AT_const_value, Block);
780 /// addConstantFPValue - Add constant value entry in variable DIE.
781 void CompileUnit::addConstantFPValue(DIE *Die, const ConstantFP *CFP) {
782 // Pass this down to addConstantValue as an unsigned bag of bits.
783 addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true);
786 /// addConstantValue - Add constant value entry in variable DIE.
787 void CompileUnit::addConstantValue(DIE *Die, const ConstantInt *CI,
789 addConstantValue(Die, CI->getValue(), Unsigned);
792 // addConstantValue - Add constant value entry in variable DIE.
793 void CompileUnit::addConstantValue(DIE *Die, const APInt &Val, bool Unsigned) {
794 unsigned CIBitWidth = Val.getBitWidth();
795 if (CIBitWidth <= 64) {
796 // If we're a signed constant definitely use sdata.
798 addSInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
803 // Else use data for now unless it's larger than we can deal with.
805 switch (CIBitWidth) {
807 Form = dwarf::DW_FORM_data1;
810 Form = dwarf::DW_FORM_data2;
813 Form = dwarf::DW_FORM_data4;
816 Form = dwarf::DW_FORM_data8;
819 addUInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_udata,
823 addUInt(Die, dwarf::DW_AT_const_value, Form, Val.getZExtValue());
827 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
829 // Get the raw data form of the large APInt.
830 const uint64_t *Ptr64 = Val.getRawData();
832 int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
833 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
835 // Output the constant to DWARF one byte at a time.
836 for (int i = 0; i < NumBytes; i++) {
839 c = Ptr64[i / 8] >> (8 * (i & 7));
841 c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
842 addUInt(Block, dwarf::DW_FORM_data1, c);
845 addBlock(Die, dwarf::DW_AT_const_value, Block);
848 /// addTemplateParams - Add template parameters into buffer.
849 void CompileUnit::addTemplateParams(DIE &Buffer, DIArray TParams) {
850 // Add template parameters.
851 for (unsigned i = 0, e = TParams.getNumElements(); i != e; ++i) {
852 DIDescriptor Element = TParams.getElement(i);
853 if (Element.isTemplateTypeParameter())
854 constructTemplateTypeParameterDIE(Buffer,
855 DITemplateTypeParameter(Element));
856 else if (Element.isTemplateValueParameter())
857 constructTemplateValueParameterDIE(Buffer,
858 DITemplateValueParameter(Element));
862 /// getOrCreateContextDIE - Get context owner's DIE.
863 DIE *CompileUnit::getOrCreateContextDIE(DIScope Context) {
864 if (Context.isType())
865 return getOrCreateTypeDIE(DIType(Context));
866 else if (Context.isNameSpace())
867 return getOrCreateNameSpace(DINameSpace(Context));
868 else if (Context.isSubprogram())
869 return getOrCreateSubprogramDIE(DISubprogram(Context));
871 return getDIE(Context);
874 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
876 DIE *CompileUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
881 // Construct the context before querying for the existence of the DIE in case
882 // such construction creates the DIE.
883 DIE *ContextDIE = getOrCreateContextDIE(resolve(Ty.getContext()));
885 ContextDIE = CUDie.get();
887 DIE *TyDIE = getDIE(Ty);
892 TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
894 if (Ty.isBasicType())
895 constructTypeDIE(*TyDIE, DIBasicType(Ty));
896 else if (Ty.isCompositeType())
897 constructTypeDIE(*TyDIE, DICompositeType(Ty));
899 assert(Ty.isDerivedType() && "Unknown kind of DIType");
900 constructTypeDIE(*TyDIE, DIDerivedType(Ty));
902 // If this is a named finished type then include it in the list of types
903 // for the accelerator tables.
904 if (!Ty.getName().empty() && !Ty.isForwardDecl()) {
905 bool IsImplementation = 0;
906 if (Ty.isCompositeType()) {
907 DICompositeType CT(Ty);
908 // A runtime language of 0 actually means C/C++ and that any
909 // non-negative value is some version of Objective-C/C++.
910 IsImplementation = (CT.getRunTimeLang() == 0) || CT.isObjcClassComplete();
912 unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0;
913 addAccelType(Ty.getName(), std::make_pair(TyDIE, Flags));
919 /// addType - Add a new type attribute to the specified entity.
920 void CompileUnit::addType(DIE *Entity, DIType Ty, dwarf::Attribute Attribute) {
921 assert(Ty && "Trying to add a type that doesn't exist?");
923 // Check for pre-existence.
924 DIEEntry *Entry = getDIEEntry(Ty);
925 // If it exists then use the existing value.
927 addDIEEntry(Entity, Attribute, Entry);
932 DIE *Buffer = getOrCreateTypeDIE(Ty);
935 Entry = createDIEEntry(Buffer);
936 insertDIEEntry(Ty, Entry);
937 addDIEEntry(Entity, Attribute, Entry);
939 // If this is a complete composite type then include it in the
940 // list of global types.
944 // Accelerator table mutators - add each name along with its companion
945 // DIE to the proper table while ensuring that the name that we're going
946 // to reference is in the string table. We do this since the names we
947 // add may not only be identical to the names in the DIE.
948 void CompileUnit::addAccelName(StringRef Name, DIE *Die) {
949 DU->getStringPoolEntry(Name);
950 std::vector<DIE *> &DIEs = AccelNames[Name];
954 void CompileUnit::addAccelObjC(StringRef Name, DIE *Die) {
955 DU->getStringPoolEntry(Name);
956 std::vector<DIE *> &DIEs = AccelObjC[Name];
960 void CompileUnit::addAccelNamespace(StringRef Name, DIE *Die) {
961 DU->getStringPoolEntry(Name);
962 std::vector<DIE *> &DIEs = AccelNamespace[Name];
966 void CompileUnit::addAccelType(StringRef Name, std::pair<DIE *, unsigned> Die) {
967 DU->getStringPoolEntry(Name);
968 std::vector<std::pair<DIE *, unsigned> > &DIEs = AccelTypes[Name];
972 /// addGlobalName - Add a new global name to the compile unit.
973 void CompileUnit::addGlobalName(StringRef Name, DIE *Die, DIScope Context) {
974 std::string FullName = getParentContextString(Context) + Name.str();
975 GlobalNames[FullName] = Die;
978 /// addGlobalType - Add a new global type to the compile unit.
980 void CompileUnit::addGlobalType(DIType Ty) {
981 DIScope Context = resolve(Ty.getContext());
982 if (!Ty.getName().empty() && !Ty.isForwardDecl() &&
983 (!Context || Context.isCompileUnit() || Context.isFile() ||
984 Context.isNameSpace()))
985 if (DIEEntry *Entry = getDIEEntry(Ty)) {
986 std::string FullName =
987 getParentContextString(Context) + Ty.getName().str();
988 GlobalTypes[FullName] = Entry->getEntry();
992 /// getParentContextString - Walks the metadata parent chain in a language
993 /// specific manner (using the compile unit language) and returns
994 /// it as a string. This is done at the metadata level because DIEs may
995 /// not currently have been added to the parent context and walking the
996 /// DIEs looking for names is more expensive than walking the metadata.
997 std::string CompileUnit::getParentContextString(DIScope Context) const {
1001 // FIXME: Decide whether to implement this for non-C++ languages.
1002 if (getLanguage() != dwarf::DW_LANG_C_plus_plus)
1006 SmallVector<DIScope, 1> Parents;
1007 while (!Context.isCompileUnit()) {
1008 Parents.push_back(Context);
1009 if (Context.getContext())
1010 Context = resolve(Context.getContext());
1012 // Structure, etc types will have a NULL context if they're at the top
1017 // Reverse iterate over our list to go from the outermost construct to the
1019 for (SmallVectorImpl<DIScope>::reverse_iterator I = Parents.rbegin(),
1023 StringRef Name = Ctx.getName();
1024 if (!Name.empty()) {
1032 /// addPubTypes - Add subprogram argument types for pubtypes section.
1033 void CompileUnit::addPubTypes(DISubprogram SP) {
1034 DICompositeType SPTy = SP.getType();
1035 uint16_t SPTag = SPTy.getTag();
1036 if (SPTag != dwarf::DW_TAG_subroutine_type)
1039 DIArray Args = SPTy.getTypeArray();
1040 for (unsigned i = 0, e = Args.getNumElements(); i != e; ++i) {
1041 DIType ATy(Args.getElement(i));
1048 /// constructTypeDIE - Construct basic type die from DIBasicType.
1049 void CompileUnit::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
1050 // Get core information.
1051 StringRef Name = BTy.getName();
1052 // Add name if not anonymous or intermediate type.
1054 addString(&Buffer, dwarf::DW_AT_name, Name);
1056 // An unspecified type only has a name attribute.
1057 if (BTy.getTag() == dwarf::DW_TAG_unspecified_type)
1060 addUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1063 uint64_t Size = BTy.getSizeInBits() >> 3;
1064 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1067 /// constructTypeDIE - Construct derived type die from DIDerivedType.
1068 void CompileUnit::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
1069 // Get core information.
1070 StringRef Name = DTy.getName();
1071 uint64_t Size = DTy.getSizeInBits() >> 3;
1072 uint16_t Tag = Buffer.getTag();
1074 // Map to main type, void will not have a type.
1075 DIType FromTy = resolve(DTy.getTypeDerivedFrom());
1077 addType(&Buffer, FromTy);
1079 // Add name if not anonymous or intermediate type.
1081 addString(&Buffer, dwarf::DW_AT_name, Name);
1083 // Add size if non-zero (derived types might be zero-sized.)
1084 if (Size && Tag != dwarf::DW_TAG_pointer_type)
1085 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1087 if (Tag == dwarf::DW_TAG_ptr_to_member_type)
1088 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type,
1089 getOrCreateTypeDIE(resolve(DTy.getClassType())));
1090 // Add source line info if available and TyDesc is not a forward declaration.
1091 if (!DTy.isForwardDecl())
1092 addSourceLine(&Buffer, DTy);
1095 /// Return true if the type is appropriately scoped to be contained inside
1096 /// its own type unit.
1097 static bool isTypeUnitScoped(DIType Ty, const DwarfDebug *DD) {
1098 DIScope Parent = DD->resolve(Ty.getContext());
1100 // Don't generate a hash for anything scoped inside a function.
1101 if (Parent.isSubprogram())
1103 Parent = DD->resolve(Parent.getContext());
1108 /// Return true if the type should be split out into a type unit.
1109 static bool shouldCreateTypeUnit(DICompositeType CTy, const DwarfDebug *DD) {
1110 uint16_t Tag = CTy.getTag();
1113 case dwarf::DW_TAG_structure_type:
1114 case dwarf::DW_TAG_union_type:
1115 case dwarf::DW_TAG_enumeration_type:
1116 case dwarf::DW_TAG_class_type:
1117 // If this is a class, structure, union, or enumeration type
1118 // that is a definition (not a declaration), and not scoped
1119 // inside a function then separate this out as a type unit.
1120 return !CTy.isForwardDecl() && isTypeUnitScoped(CTy, DD);
1126 /// constructTypeDIE - Construct type DIE from DICompositeType.
1127 void CompileUnit::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
1128 // Get core information.
1129 StringRef Name = CTy.getName();
1131 uint64_t Size = CTy.getSizeInBits() >> 3;
1132 uint16_t Tag = Buffer.getTag();
1135 case dwarf::DW_TAG_array_type:
1136 constructArrayTypeDIE(Buffer, &CTy);
1138 case dwarf::DW_TAG_enumeration_type: {
1139 DIArray Elements = CTy.getTypeArray();
1141 // Add enumerators to enumeration type.
1142 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1143 DIDescriptor Enum(Elements.getElement(i));
1144 if (Enum.isEnumerator())
1145 constructEnumTypeDIE(Buffer, DIEnumerator(Enum));
1147 DIType DTy = resolve(CTy.getTypeDerivedFrom());
1149 addType(&Buffer, DTy);
1150 addFlag(&Buffer, dwarf::DW_AT_enum_class);
1153 case dwarf::DW_TAG_subroutine_type: {
1154 // Add return type. A void return won't have a type.
1155 DIArray Elements = CTy.getTypeArray();
1156 DIDescriptor RTy = Elements.getElement(0);
1158 addType(&Buffer, DIType(RTy));
1160 bool isPrototyped = true;
1162 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
1163 DIDescriptor Ty = Elements.getElement(i);
1164 if (Ty.isUnspecifiedParameter()) {
1165 createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
1166 isPrototyped = false;
1168 DIE *Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
1169 addType(Arg, DIType(Ty));
1170 if (DIType(Ty).isArtificial())
1171 addFlag(Arg, dwarf::DW_AT_artificial);
1174 // Add prototype flag if we're dealing with a C language and the
1175 // function has been prototyped.
1176 uint16_t Language = DICompileUnit(Node).getLanguage();
1178 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1179 Language == dwarf::DW_LANG_ObjC))
1180 addFlag(&Buffer, dwarf::DW_AT_prototyped);
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 DISubprogram SP(Element);
1192 ElemDie = getOrCreateSubprogramDIE(DISubprogram(Element));
1193 if (SP.isProtected())
1194 addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1195 dwarf::DW_ACCESS_protected);
1196 else if (SP.isPrivate())
1197 addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1198 dwarf::DW_ACCESS_private);
1200 addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1201 dwarf::DW_ACCESS_public);
1202 if (SP.isExplicit())
1203 addFlag(ElemDie, dwarf::DW_AT_explicit);
1204 } else if (Element.isDerivedType()) {
1205 DIDerivedType DDTy(Element);
1206 if (DDTy.getTag() == dwarf::DW_TAG_friend) {
1207 ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
1208 addType(ElemDie, resolve(DDTy.getTypeDerivedFrom()),
1209 dwarf::DW_AT_friend);
1210 } else if (DDTy.isStaticMember()) {
1211 getOrCreateStaticMemberDIE(DDTy);
1213 constructMemberDIE(Buffer, DDTy);
1215 } else if (Element.isObjCProperty()) {
1216 DIObjCProperty Property(Element);
1217 ElemDie = createAndAddDIE(Property.getTag(), Buffer);
1218 StringRef PropertyName = Property.getObjCPropertyName();
1219 addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
1220 addType(ElemDie, Property.getType());
1221 addSourceLine(ElemDie, Property);
1222 StringRef GetterName = Property.getObjCPropertyGetterName();
1223 if (!GetterName.empty())
1224 addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
1225 StringRef SetterName = Property.getObjCPropertySetterName();
1226 if (!SetterName.empty())
1227 addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
1228 unsigned PropertyAttributes = 0;
1229 if (Property.isReadOnlyObjCProperty())
1230 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readonly;
1231 if (Property.isReadWriteObjCProperty())
1232 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readwrite;
1233 if (Property.isAssignObjCProperty())
1234 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_assign;
1235 if (Property.isRetainObjCProperty())
1236 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_retain;
1237 if (Property.isCopyObjCProperty())
1238 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_copy;
1239 if (Property.isNonAtomicObjCProperty())
1240 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_nonatomic;
1241 if (PropertyAttributes)
1242 addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None,
1243 PropertyAttributes);
1245 DIEEntry *Entry = getDIEEntry(Element);
1247 Entry = createDIEEntry(ElemDie);
1248 insertDIEEntry(Element, Entry);
1254 if (CTy.isAppleBlockExtension())
1255 addFlag(&Buffer, dwarf::DW_AT_APPLE_block);
1257 DICompositeType ContainingType(resolve(CTy.getContainingType()));
1258 if (DIDescriptor(ContainingType).isCompositeType())
1259 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type,
1260 getOrCreateTypeDIE(DIType(ContainingType)));
1262 if (CTy.isObjcClassComplete())
1263 addFlag(&Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
1265 // Add template parameters to a class, structure or union types.
1266 // FIXME: The support isn't in the metadata for this yet.
1267 if (Tag == dwarf::DW_TAG_class_type ||
1268 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
1269 addTemplateParams(Buffer, CTy.getTemplateParams());
1277 // Add name if not anonymous or intermediate type.
1279 addString(&Buffer, dwarf::DW_AT_name, Name);
1281 if (Tag == dwarf::DW_TAG_enumeration_type ||
1282 Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
1283 Tag == dwarf::DW_TAG_union_type) {
1284 // Add size if non-zero (derived types might be zero-sized.)
1285 // TODO: Do we care about size for enum forward declarations?
1287 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1288 else if (!CTy.isForwardDecl())
1289 // Add zero size if it is not a forward declaration.
1290 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, 0);
1292 // If we're a forward decl, say so.
1293 if (CTy.isForwardDecl())
1294 addFlag(&Buffer, dwarf::DW_AT_declaration);
1296 // Add source line info if available.
1297 if (!CTy.isForwardDecl())
1298 addSourceLine(&Buffer, CTy);
1300 // No harm in adding the runtime language to the declaration.
1301 unsigned RLang = CTy.getRunTimeLang();
1303 addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
1306 // If this is a type applicable to a type unit it then add it to the
1307 // list of types we'll compute a hash for later.
1308 if (shouldCreateTypeUnit(CTy, DD))
1309 DD->addTypeUnitType(&Buffer);
1312 /// constructTemplateTypeParameterDIE - Construct new DIE for the given
1313 /// DITemplateTypeParameter.
1315 CompileUnit::constructTemplateTypeParameterDIE(DIE &Buffer,
1316 DITemplateTypeParameter TP) {
1318 createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
1319 // Add the type if it exists, it could be void and therefore no type.
1321 addType(ParamDIE, resolve(TP.getType()));
1322 if (!TP.getName().empty())
1323 addString(ParamDIE, dwarf::DW_AT_name, TP.getName());
1326 /// constructTemplateValueParameterDIE - Construct new DIE for the given
1327 /// DITemplateValueParameter.
1329 CompileUnit::constructTemplateValueParameterDIE(DIE &Buffer,
1330 DITemplateValueParameter VP) {
1331 DIE *ParamDIE = createAndAddDIE(VP.getTag(), Buffer);
1333 // Add the type if there is one, template template and template parameter
1334 // packs will not have a type.
1335 if (VP.getTag() == dwarf::DW_TAG_template_value_parameter)
1336 addType(ParamDIE, resolve(VP.getType()));
1337 if (!VP.getName().empty())
1338 addString(ParamDIE, dwarf::DW_AT_name, VP.getName());
1339 if (Value *Val = VP.getValue()) {
1340 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val))
1341 addConstantValue(ParamDIE, CI,
1342 isUnsignedDIType(DD, resolve(VP.getType())));
1343 else if (GlobalValue *GV = dyn_cast<GlobalValue>(Val)) {
1344 // For declaration non-type template parameters (such as global values and
1346 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1347 addOpAddress(Block, Asm->getSymbol(GV));
1348 // Emit DW_OP_stack_value to use the address as the immediate value of the
1349 // parameter, rather than a pointer to it.
1350 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
1351 addBlock(ParamDIE, dwarf::DW_AT_location, Block);
1352 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1353 assert(isa<MDString>(Val));
1354 addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
1355 cast<MDString>(Val)->getString());
1356 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1357 assert(isa<MDNode>(Val));
1358 DIArray A(cast<MDNode>(Val));
1359 addTemplateParams(*ParamDIE, A);
1364 /// getOrCreateNameSpace - Create a DIE for DINameSpace.
1365 DIE *CompileUnit::getOrCreateNameSpace(DINameSpace NS) {
1366 // Construct the context before querying for the existence of the DIE in case
1367 // such construction creates the DIE.
1368 DIE *ContextDIE = getOrCreateContextDIE(NS.getContext());
1370 // If the context is null, DIE should belong to the CU we call construct
1372 ContextDIE = CUDie.get();
1374 DIE *NDie = getDIE(NS);
1377 NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS);
1379 if (!NS.getName().empty()) {
1380 addString(NDie, dwarf::DW_AT_name, NS.getName());
1381 addAccelNamespace(NS.getName(), NDie);
1382 addGlobalName(NS.getName(), NDie, NS.getContext());
1384 addAccelNamespace("(anonymous namespace)", NDie);
1385 addSourceLine(NDie, NS);
1389 /// getOrCreateSubprogramDIE - Create new DIE using SP.
1390 DIE *CompileUnit::getOrCreateSubprogramDIE(DISubprogram SP) {
1391 // Construct the context before querying for the existence of the DIE in case
1392 // such construction creates the DIE (as is the case for member function
1394 DIE *ContextDIE = getOrCreateContextDIE(resolve(SP.getContext()));
1396 ContextDIE = CUDie.get();
1398 DIE *SPDie = getDIE(SP);
1402 DISubprogram SPDecl = SP.getFunctionDeclaration();
1403 if (SPDecl.isSubprogram())
1404 // Add subprogram definitions to the CU die directly.
1405 ContextDIE = CUDie.get();
1407 // DW_TAG_inlined_subroutine may refer to this DIE.
1408 SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
1410 DIE *DeclDie = NULL;
1411 if (SPDecl.isSubprogram())
1412 DeclDie = getOrCreateSubprogramDIE(SPDecl);
1414 // Add function template parameters.
1415 addTemplateParams(*SPDie, SP.getTemplateParams());
1417 // If this DIE is going to refer declaration info using AT_specification
1418 // then there is no need to add other attributes.
1420 // Refer function declaration directly.
1421 addDIEEntry(SPDie, dwarf::DW_AT_specification, DeclDie);
1426 // Add the linkage name if we have one.
1427 StringRef LinkageName = SP.getLinkageName();
1428 if (!LinkageName.empty())
1429 addString(SPDie, dwarf::DW_AT_MIPS_linkage_name,
1430 GlobalValue::getRealLinkageName(LinkageName));
1432 // Constructors and operators for anonymous aggregates do not have names.
1433 if (!SP.getName().empty())
1434 addString(SPDie, dwarf::DW_AT_name, SP.getName());
1436 addSourceLine(SPDie, SP);
1438 // Add the prototype if we have a prototype and we have a C like
1440 uint16_t Language = DICompileUnit(Node).getLanguage();
1441 if (SP.isPrototyped() &&
1442 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1443 Language == dwarf::DW_LANG_ObjC))
1444 addFlag(SPDie, dwarf::DW_AT_prototyped);
1446 DICompositeType SPTy = SP.getType();
1447 assert(SPTy.getTag() == dwarf::DW_TAG_subroutine_type &&
1448 "the type of a subprogram should be a subroutine");
1450 DIArray Args = SPTy.getTypeArray();
1451 // Add a return type. If this is a type like a C/C++ void type we don't add a
1453 if (Args.getElement(0))
1454 addType(SPDie, DIType(Args.getElement(0)));
1456 unsigned VK = SP.getVirtuality();
1458 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1459 DIEBlock *Block = getDIEBlock();
1460 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1461 addUInt(Block, dwarf::DW_FORM_udata, SP.getVirtualIndex());
1462 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
1463 ContainingTypeMap.insert(std::make_pair(SPDie,
1464 resolve(SP.getContainingType())));
1467 if (!SP.isDefinition()) {
1468 addFlag(SPDie, dwarf::DW_AT_declaration);
1470 // Add arguments. Do not add arguments for subprogram definition. They will
1471 // be handled while processing variables.
1472 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1473 DIE *Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, *SPDie);
1474 DIType ATy = DIType(Args.getElement(i));
1476 if (ATy.isArtificial())
1477 addFlag(Arg, dwarf::DW_AT_artificial);
1481 if (SP.isArtificial())
1482 addFlag(SPDie, dwarf::DW_AT_artificial);
1484 if (!SP.isLocalToUnit())
1485 addFlag(SPDie, dwarf::DW_AT_external);
1487 if (SP.isOptimized())
1488 addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1490 if (unsigned isa = Asm->getISAEncoding()) {
1491 addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1497 // Return const expression if value is a GEP to access merged global
1499 // i8* getelementptr ({ i8, i8, i8, i8 }* @_MergedGlobals, i32 0, i32 0)
1500 static const ConstantExpr *getMergedGlobalExpr(const Value *V) {
1501 const ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(V);
1502 if (!CE || CE->getNumOperands() != 3 ||
1503 CE->getOpcode() != Instruction::GetElementPtr)
1506 // First operand points to a global struct.
1507 Value *Ptr = CE->getOperand(0);
1508 if (!isa<GlobalValue>(Ptr) ||
1509 !isa<StructType>(cast<PointerType>(Ptr->getType())->getElementType()))
1512 // Second operand is zero.
1513 const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(CE->getOperand(1));
1514 if (!CI || !CI->isZero())
1517 // Third operand is offset.
1518 if (!isa<ConstantInt>(CE->getOperand(2)))
1524 /// createGlobalVariableDIE - create global variable DIE.
1525 void CompileUnit::createGlobalVariableDIE(const MDNode *N) {
1526 // Check for pre-existence.
1530 DIGlobalVariable GV(N);
1531 if (!GV.isGlobalVariable())
1534 DIScope GVContext = GV.getContext();
1535 DIType GTy = GV.getType();
1537 // If this is a static data member definition, some attributes belong
1538 // to the declaration DIE.
1539 DIE *VariableDIE = NULL;
1540 bool IsStaticMember = false;
1541 DIDerivedType SDMDecl = GV.getStaticDataMemberDeclaration();
1542 if (SDMDecl.Verify()) {
1543 assert(SDMDecl.isStaticMember() && "Expected static member decl");
1544 // We need the declaration DIE that is in the static member's class.
1545 VariableDIE = getOrCreateStaticMemberDIE(SDMDecl);
1546 IsStaticMember = true;
1549 // If this is not a static data member definition, create the variable
1550 // DIE and add the initial set of attributes to it.
1552 // Construct the context before querying for the existence of the DIE in
1553 // case such construction creates the DIE.
1554 DIE *ContextDIE = getOrCreateContextDIE(GVContext);
1556 ContextDIE = CUDie.get();
1559 VariableDIE = createAndAddDIE(GV.getTag(), *ContextDIE, N);
1561 // Add name and type.
1562 addString(VariableDIE, dwarf::DW_AT_name, GV.getDisplayName());
1563 addType(VariableDIE, GTy);
1565 // Add scoping info.
1566 if (!GV.isLocalToUnit())
1567 addFlag(VariableDIE, dwarf::DW_AT_external);
1569 // Add line number info.
1570 addSourceLine(VariableDIE, GV);
1574 bool addToAccelTable = false;
1575 DIE *VariableSpecDIE = NULL;
1576 bool isGlobalVariable = GV.getGlobal() != NULL;
1577 if (isGlobalVariable) {
1578 addToAccelTable = true;
1579 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1580 const MCSymbol *Sym = Asm->getSymbol(GV.getGlobal());
1581 if (GV.getGlobal()->isThreadLocal()) {
1582 // FIXME: Make this work with -gsplit-dwarf.
1583 unsigned PointerSize = Asm->getDataLayout().getPointerSize();
1584 assert((PointerSize == 4 || PointerSize == 8) &&
1585 "Add support for other sizes if necessary");
1586 const MCExpr *Expr =
1587 Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym);
1588 // Based on GCC's support for TLS:
1589 if (!DD->useSplitDwarf()) {
1590 // 1) Start with a constNu of the appropriate pointer size
1591 addUInt(Block, dwarf::DW_FORM_data1,
1592 PointerSize == 4 ? dwarf::DW_OP_const4u : dwarf::DW_OP_const8u);
1593 // 2) containing the (relocated) offset of the TLS variable
1594 // within the module's TLS block.
1595 addExpr(Block, dwarf::DW_FORM_udata, Expr);
1597 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
1598 addUInt(Block, dwarf::DW_FORM_udata, DU->getAddrPoolIndex(Expr));
1600 // 3) followed by a custom OP to make the debugger do a TLS lookup.
1601 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_push_tls_address);
1603 addOpAddress(Block, Sym);
1604 // Do not create specification DIE if context is either compile unit
1606 if (GVContext && GV.isDefinition() && !GVContext.isCompileUnit() &&
1607 !GVContext.isFile() && !DD->isSubprogramContext(GVContext)) {
1608 // Create specification DIE.
1609 VariableSpecDIE = createAndAddDIE(dwarf::DW_TAG_variable, *CUDie.get());
1610 addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification, VariableDIE);
1611 addBlock(VariableSpecDIE, dwarf::DW_AT_location, Block);
1612 // A static member's declaration is already flagged as such.
1613 if (!SDMDecl.Verify())
1614 addFlag(VariableDIE, dwarf::DW_AT_declaration);
1616 addBlock(VariableDIE, dwarf::DW_AT_location, Block);
1618 // Add the linkage name.
1619 StringRef LinkageName = GV.getLinkageName();
1620 if (!LinkageName.empty())
1621 // From DWARF4: DIEs to which DW_AT_linkage_name may apply include:
1622 // TAG_common_block, TAG_constant, TAG_entry_point, TAG_subprogram and
1624 addString(IsStaticMember && VariableSpecDIE ? VariableSpecDIE
1626 dwarf::DW_AT_MIPS_linkage_name,
1627 GlobalValue::getRealLinkageName(LinkageName));
1628 } else if (const ConstantInt *CI =
1629 dyn_cast_or_null<ConstantInt>(GV.getConstant())) {
1630 // AT_const_value was added when the static member was created. To avoid
1631 // emitting AT_const_value multiple times, we only add AT_const_value when
1632 // it is not a static member.
1633 if (!IsStaticMember)
1634 addConstantValue(VariableDIE, CI, isUnsignedDIType(DD, GTy));
1635 } else if (const ConstantExpr *CE = getMergedGlobalExpr(N->getOperand(11))) {
1636 addToAccelTable = true;
1637 // GV is a merged global.
1638 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1639 Value *Ptr = CE->getOperand(0);
1640 addOpAddress(Block, Asm->getSymbol(cast<GlobalValue>(Ptr)));
1641 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1642 SmallVector<Value *, 3> Idx(CE->op_begin() + 1, CE->op_end());
1643 addUInt(Block, dwarf::DW_FORM_udata,
1644 Asm->getDataLayout().getIndexedOffset(Ptr->getType(), Idx));
1645 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1646 addBlock(VariableDIE, dwarf::DW_AT_location, Block);
1649 if (addToAccelTable) {
1650 DIE *AddrDIE = VariableSpecDIE ? VariableSpecDIE : VariableDIE;
1651 addAccelName(GV.getName(), AddrDIE);
1653 // If the linkage name is different than the name, go ahead and output
1654 // that as well into the name table.
1655 if (GV.getLinkageName() != "" && GV.getName() != GV.getLinkageName())
1656 addAccelName(GV.getLinkageName(), AddrDIE);
1659 if (!GV.isLocalToUnit())
1660 addGlobalName(GV.getName(), VariableSpecDIE ? VariableSpecDIE : VariableDIE,
1664 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
1665 void CompileUnit::constructSubrangeDIE(DIE &Buffer, DISubrange SR,
1667 DIE *DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
1668 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, IndexTy);
1670 // The LowerBound value defines the lower bounds which is typically zero for
1671 // C/C++. The Count value is the number of elements. Values are 64 bit. If
1672 // Count == -1 then the array is unbounded and we do not emit
1673 // DW_AT_lower_bound and DW_AT_upper_bound attributes. If LowerBound == 0 and
1674 // Count == 0, then the array has zero elements in which case we do not emit
1676 int64_t LowerBound = SR.getLo();
1677 int64_t DefaultLowerBound = getDefaultLowerBound();
1678 int64_t Count = SR.getCount();
1680 if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
1681 addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound);
1683 if (Count != -1 && Count != 0)
1684 // FIXME: An unbounded array should reference the expression that defines
1686 addUInt(DW_Subrange, dwarf::DW_AT_upper_bound, None, LowerBound + Count - 1);
1689 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
1690 void CompileUnit::constructArrayTypeDIE(DIE &Buffer, DICompositeType *CTy) {
1691 if (CTy->isVector())
1692 addFlag(&Buffer, dwarf::DW_AT_GNU_vector);
1694 // Emit the element type.
1695 addType(&Buffer, resolve(CTy->getTypeDerivedFrom()));
1697 // Get an anonymous type for index type.
1698 // FIXME: This type should be passed down from the front end
1699 // as different languages may have different sizes for indexes.
1700 DIE *IdxTy = getIndexTyDie();
1702 // Construct an anonymous type for index type.
1703 IdxTy = createAndAddDIE(dwarf::DW_TAG_base_type, *CUDie.get());
1704 addString(IdxTy, dwarf::DW_AT_name, "int");
1705 addUInt(IdxTy, dwarf::DW_AT_byte_size, None, sizeof(int32_t));
1706 addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1707 dwarf::DW_ATE_signed);
1708 setIndexTyDie(IdxTy);
1711 // Add subranges to array type.
1712 DIArray Elements = CTy->getTypeArray();
1713 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1714 DIDescriptor Element = Elements.getElement(i);
1715 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1716 constructSubrangeDIE(Buffer, DISubrange(Element), IdxTy);
1720 /// constructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
1721 void CompileUnit::constructEnumTypeDIE(DIE &Buffer, DIEnumerator ETy) {
1722 DIE *Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
1723 StringRef Name = ETy.getName();
1724 addString(Enumerator, dwarf::DW_AT_name, Name);
1725 int64_t Value = ETy.getEnumValue();
1726 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, Value);
1729 /// constructContainingTypeDIEs - Construct DIEs for types that contain
1731 void CompileUnit::constructContainingTypeDIEs() {
1732 for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(),
1733 CE = ContainingTypeMap.end();
1735 DIE *SPDie = CI->first;
1736 const MDNode *N = CI->second;
1739 DIE *NDie = getDIE(N);
1742 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, NDie);
1746 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
1747 DIE *CompileUnit::constructVariableDIE(DbgVariable *DV, bool isScopeAbstract) {
1748 StringRef Name = DV->getName();
1750 // Define variable debug information entry.
1751 DIE *VariableDie = new DIE(DV->getTag());
1752 DbgVariable *AbsVar = DV->getAbstractVariable();
1753 DIE *AbsDIE = AbsVar ? AbsVar->getDIE() : NULL;
1755 addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin, AbsDIE);
1758 addString(VariableDie, dwarf::DW_AT_name, Name);
1759 addSourceLine(VariableDie, DV->getVariable());
1760 addType(VariableDie, DV->getType());
1763 if (DV->isArtificial())
1764 addFlag(VariableDie, dwarf::DW_AT_artificial);
1766 if (isScopeAbstract) {
1767 DV->setDIE(VariableDie);
1771 // Add variable address.
1773 unsigned Offset = DV->getDotDebugLocOffset();
1774 if (Offset != ~0U) {
1775 addLabel(VariableDie, dwarf::DW_AT_location, dwarf::DW_FORM_data4,
1776 Asm->GetTempSymbol("debug_loc", Offset));
1777 DV->setDIE(VariableDie);
1781 // Check if variable is described by a DBG_VALUE instruction.
1782 if (const MachineInstr *DVInsn = DV->getMInsn()) {
1783 assert(DVInsn->getNumOperands() == 3);
1784 if (DVInsn->getOperand(0).isReg()) {
1785 const MachineOperand RegOp = DVInsn->getOperand(0);
1786 // If the second operand is an immediate, this is an indirect value.
1787 if (DVInsn->getOperand(1).isImm()) {
1788 MachineLocation Location(RegOp.getReg(),
1789 DVInsn->getOperand(1).getImm());
1790 addVariableAddress(*DV, VariableDie, Location);
1791 } else if (RegOp.getReg())
1792 addVariableAddress(*DV, VariableDie, MachineLocation(RegOp.getReg()));
1793 } else if (DVInsn->getOperand(0).isImm())
1794 addConstantValue(VariableDie, DVInsn->getOperand(0), DV->getType());
1795 else if (DVInsn->getOperand(0).isFPImm())
1796 addConstantFPValue(VariableDie, DVInsn->getOperand(0));
1797 else if (DVInsn->getOperand(0).isCImm())
1798 addConstantValue(VariableDie, DVInsn->getOperand(0).getCImm(),
1799 isUnsignedDIType(DD, DV->getType()));
1801 DV->setDIE(VariableDie);
1804 // .. else use frame index.
1805 int FI = DV->getFrameIndex();
1807 unsigned FrameReg = 0;
1808 const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
1809 int Offset = TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
1810 MachineLocation Location(FrameReg, Offset);
1811 addVariableAddress(*DV, VariableDie, Location);
1815 DV->setDIE(VariableDie);
1819 /// constructMemberDIE - Construct member DIE from DIDerivedType.
1820 void CompileUnit::constructMemberDIE(DIE &Buffer, DIDerivedType DT) {
1821 DIE *MemberDie = createAndAddDIE(DT.getTag(), Buffer);
1822 StringRef Name = DT.getName();
1824 addString(MemberDie, dwarf::DW_AT_name, Name);
1826 addType(MemberDie, resolve(DT.getTypeDerivedFrom()));
1828 addSourceLine(MemberDie, DT);
1830 DIEBlock *MemLocationDie = new (DIEValueAllocator) DIEBlock();
1831 addUInt(MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1834 if (DT.getTag() == dwarf::DW_TAG_inheritance && DT.isVirtual()) {
1836 // For C++, virtual base classes are not at fixed offset. Use following
1837 // expression to extract appropriate offset from vtable.
1838 // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1840 DIEBlock *VBaseLocationDie = new (DIEValueAllocator) DIEBlock();
1841 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1842 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1843 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1844 addUInt(VBaseLocationDie, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1845 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1846 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1847 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1849 addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
1851 uint64_t Size = DT.getSizeInBits();
1852 uint64_t FieldSize = getBaseTypeSize(DD, DT);
1853 uint64_t OffsetInBytes;
1855 if (Size != FieldSize) {
1857 addUInt(MemberDie, dwarf::DW_AT_byte_size, None,
1858 getBaseTypeSize(DD, DT) >> 3);
1859 addUInt(MemberDie, dwarf::DW_AT_bit_size, None, DT.getSizeInBits());
1861 uint64_t Offset = DT.getOffsetInBits();
1862 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1863 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1864 uint64_t FieldOffset = (HiMark - FieldSize);
1865 Offset -= FieldOffset;
1867 // Maybe we need to work from the other end.
1868 if (Asm->getDataLayout().isLittleEndian())
1869 Offset = FieldSize - (Offset + Size);
1870 addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset);
1872 // Here WD_AT_data_member_location points to the anonymous
1873 // field that includes this bit field.
1874 OffsetInBytes = FieldOffset >> 3;
1876 // This is not a bitfield.
1877 OffsetInBytes = DT.getOffsetInBits() >> 3;
1878 addUInt(MemberDie, dwarf::DW_AT_data_member_location, None,
1882 if (DT.isProtected())
1883 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1884 dwarf::DW_ACCESS_protected);
1885 else if (DT.isPrivate())
1886 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1887 dwarf::DW_ACCESS_private);
1888 // Otherwise C++ member and base classes are considered public.
1890 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1891 dwarf::DW_ACCESS_public);
1893 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1894 dwarf::DW_VIRTUALITY_virtual);
1896 // Objective-C properties.
1897 if (MDNode *PNode = DT.getObjCProperty())
1898 if (DIEEntry *PropertyDie = getDIEEntry(PNode))
1899 MemberDie->addValue(dwarf::DW_AT_APPLE_property, dwarf::DW_FORM_ref4,
1902 if (DT.isArtificial())
1903 addFlag(MemberDie, dwarf::DW_AT_artificial);
1906 /// getOrCreateStaticMemberDIE - Create new DIE for C++ static member.
1907 DIE *CompileUnit::getOrCreateStaticMemberDIE(const DIDerivedType DT) {
1911 // Construct the context before querying for the existence of the DIE in case
1912 // such construction creates the DIE.
1913 DIE *ContextDIE = getOrCreateContextDIE(resolve(DT.getContext()));
1914 assert(ContextDIE && "Static member should belong to a non-CU context.");
1916 DIE *StaticMemberDIE = getDIE(DT);
1917 if (StaticMemberDIE)
1918 return StaticMemberDIE;
1920 StaticMemberDIE = createAndAddDIE(DT.getTag(), *ContextDIE, DT);
1922 DIType Ty = resolve(DT.getTypeDerivedFrom());
1924 addString(StaticMemberDIE, dwarf::DW_AT_name, DT.getName());
1925 addType(StaticMemberDIE, Ty);
1926 addSourceLine(StaticMemberDIE, DT);
1927 addFlag(StaticMemberDIE, dwarf::DW_AT_external);
1928 addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
1930 // FIXME: We could omit private if the parent is a class_type, and
1931 // public if the parent is something else.
1932 if (DT.isProtected())
1933 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1934 dwarf::DW_ACCESS_protected);
1935 else if (DT.isPrivate())
1936 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1937 dwarf::DW_ACCESS_private);
1939 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1940 dwarf::DW_ACCESS_public);
1942 if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT.getConstant()))
1943 addConstantValue(StaticMemberDIE, CI, isUnsignedDIType(DD, Ty));
1944 if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT.getConstant()))
1945 addConstantFPValue(StaticMemberDIE, CFP);
1947 return StaticMemberDIE;
1950 void CompileUnit::emitHeader(const MCSection *ASection,
1951 const MCSymbol *ASectionSym) {
1952 Asm->OutStreamer.AddComment("DWARF version number");
1953 Asm->EmitInt16(DD->getDwarfVersion());
1954 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
1955 Asm->EmitSectionOffset(Asm->GetTempSymbol(ASection->getLabelBeginName()),
1957 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1958 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());