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/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"
32 #include "llvm/Support/CommandLine.h"
36 static cl::opt<bool> GenerateTypeUnits("generate-type-units", cl::Hidden,
37 cl::desc("Generate DWARF4 type units."),
40 /// Unit - Unit constructor.
41 Unit::Unit(unsigned UID, DIE *D, DICompileUnit Node, AsmPrinter *A,
42 DwarfDebug *DW, DwarfUnits *DWU)
43 : UniqueID(UID), Node(Node), UnitDie(D), DebugInfoOffset(0), Asm(A), DD(DW),
44 DU(DWU), IndexTyDie(0) {
45 DIEIntegerOne = new (DIEValueAllocator) DIEInteger(1);
48 CompileUnit::CompileUnit(unsigned UID, DIE *D, DICompileUnit Node,
49 AsmPrinter *A, DwarfDebug *DW, DwarfUnits *DWU)
50 : Unit(UID, D, Node, A, DW, DWU) {
54 TypeUnit::TypeUnit(unsigned UID, DIE *D, uint16_t Language, AsmPrinter *A,
55 DwarfDebug *DW, DwarfUnits *DWU)
56 : Unit(UID, D, DICompileUnit(), A, DW, DWU), Language(Language) {}
58 /// ~Unit - Destructor for compile unit.
60 for (unsigned j = 0, M = DIEBlocks.size(); j < M; ++j)
61 DIEBlocks[j]->~DIEBlock();
62 for (SmallVectorImpl<RangeSpanList *>::iterator RI = getRangeLists().begin(),
63 RE = getRangeLists().end();
68 /// createDIEEntry - Creates a new DIEEntry to be a proxy for a debug
69 /// information entry.
70 DIEEntry *Unit::createDIEEntry(DIE *Entry) {
71 DIEEntry *Value = new (DIEValueAllocator) DIEEntry(Entry);
75 /// getDefaultLowerBound - Return the default lower bound for an array. If the
76 /// DWARF version doesn't handle the language, return -1.
77 int64_t Unit::getDefaultLowerBound() const {
78 switch (getLanguage()) {
82 case dwarf::DW_LANG_C89:
83 case dwarf::DW_LANG_C99:
84 case dwarf::DW_LANG_C:
85 case dwarf::DW_LANG_C_plus_plus:
86 case dwarf::DW_LANG_ObjC:
87 case dwarf::DW_LANG_ObjC_plus_plus:
90 case dwarf::DW_LANG_Fortran77:
91 case dwarf::DW_LANG_Fortran90:
92 case dwarf::DW_LANG_Fortran95:
95 // The languages below have valid values only if the DWARF version >= 4.
96 case dwarf::DW_LANG_Java:
97 case dwarf::DW_LANG_Python:
98 case dwarf::DW_LANG_UPC:
99 case dwarf::DW_LANG_D:
100 if (dwarf::DWARF_VERSION >= 4)
104 case dwarf::DW_LANG_Ada83:
105 case dwarf::DW_LANG_Ada95:
106 case dwarf::DW_LANG_Cobol74:
107 case dwarf::DW_LANG_Cobol85:
108 case dwarf::DW_LANG_Modula2:
109 case dwarf::DW_LANG_Pascal83:
110 case dwarf::DW_LANG_PLI:
111 if (dwarf::DWARF_VERSION >= 4)
119 /// Check whether the DIE for this MDNode can be shared across CUs.
120 static bool isShareableAcrossCUs(DIDescriptor D) {
121 // When the MDNode can be part of the type system, the DIE can be shared
123 // Combining type units and cross-CU DIE sharing is lower value (since
124 // cross-CU DIE sharing is used in LTO and removes type redundancy at that
125 // level already) but may be implementable for some value in projects
126 // building multiple independent libraries with LTO and then linking those
128 return (D.isType() ||
129 (D.isSubprogram() && !DISubprogram(D).isDefinition())) &&
133 /// getDIE - Returns the debug information entry map slot for the
134 /// specified debug variable. We delegate the request to DwarfDebug
135 /// when the DIE for this MDNode can be shared across CUs. The mappings
136 /// will be kept in DwarfDebug for shareable DIEs.
137 DIE *Unit::getDIE(DIDescriptor D) const {
138 if (isShareableAcrossCUs(D))
139 return DD->getDIE(D);
140 return MDNodeToDieMap.lookup(D);
143 /// insertDIE - Insert DIE into the map. We delegate the request to DwarfDebug
144 /// when the DIE for this MDNode can be shared across CUs. The mappings
145 /// will be kept in DwarfDebug for shareable DIEs.
146 void Unit::insertDIE(DIDescriptor Desc, DIE *D) {
147 if (isShareableAcrossCUs(Desc)) {
148 DD->insertDIE(Desc, D);
151 MDNodeToDieMap.insert(std::make_pair(Desc, D));
154 /// addFlag - Add a flag that is true.
155 void Unit::addFlag(DIE *Die, dwarf::Attribute Attribute) {
156 if (DD->getDwarfVersion() >= 4)
157 Die->addValue(Attribute, dwarf::DW_FORM_flag_present, DIEIntegerOne);
159 Die->addValue(Attribute, dwarf::DW_FORM_flag, DIEIntegerOne);
162 /// addUInt - Add an unsigned integer attribute data and value.
164 void Unit::addUInt(DIE *Die, dwarf::Attribute Attribute,
165 Optional<dwarf::Form> Form, uint64_t Integer) {
167 Form = DIEInteger::BestForm(false, Integer);
168 DIEValue *Value = Integer == 1 ? DIEIntegerOne : new (DIEValueAllocator)
170 Die->addValue(Attribute, *Form, Value);
173 void Unit::addUInt(DIEBlock *Block, dwarf::Form Form, uint64_t Integer) {
174 addUInt(Block, (dwarf::Attribute)0, Form, Integer);
177 /// addSInt - Add an signed integer attribute data and value.
179 void Unit::addSInt(DIE *Die, dwarf::Attribute Attribute,
180 Optional<dwarf::Form> Form, int64_t Integer) {
182 Form = DIEInteger::BestForm(true, Integer);
183 DIEValue *Value = new (DIEValueAllocator) DIEInteger(Integer);
184 Die->addValue(Attribute, *Form, Value);
187 void Unit::addSInt(DIEBlock *Die, Optional<dwarf::Form> Form, int64_t Integer) {
188 addSInt(Die, (dwarf::Attribute)0, Form, Integer);
191 /// addString - Add a string attribute data and value. We always emit a
192 /// reference to the string pool instead of immediate strings so that DIEs have
193 /// more predictable sizes. In the case of split dwarf we emit an index
194 /// into another table which gets us the static offset into the string
196 void Unit::addString(DIE *Die, dwarf::Attribute Attribute, StringRef String) {
199 if (!DD->useSplitDwarf()) {
200 MCSymbol *Symb = DU->getStringPoolEntry(String);
201 if (Asm->needsRelocationsForDwarfStringPool())
202 Value = new (DIEValueAllocator) DIELabel(Symb);
204 MCSymbol *StringPool = DU->getStringPoolSym();
205 Value = new (DIEValueAllocator) DIEDelta(Symb, StringPool);
207 Form = dwarf::DW_FORM_strp;
209 unsigned idx = DU->getStringPoolIndex(String);
210 Value = new (DIEValueAllocator) DIEInteger(idx);
211 Form = dwarf::DW_FORM_GNU_str_index;
213 DIEValue *Str = new (DIEValueAllocator) DIEString(Value, String);
214 Die->addValue(Attribute, Form, Str);
217 /// addLocalString - Add a string attribute data and value. This is guaranteed
218 /// to be in the local string pool instead of indirected.
219 void Unit::addLocalString(DIE *Die, dwarf::Attribute Attribute,
221 MCSymbol *Symb = DU->getStringPoolEntry(String);
223 if (Asm->needsRelocationsForDwarfStringPool())
224 Value = new (DIEValueAllocator) DIELabel(Symb);
226 MCSymbol *StringPool = DU->getStringPoolSym();
227 Value = new (DIEValueAllocator) DIEDelta(Symb, StringPool);
229 Die->addValue(Attribute, dwarf::DW_FORM_strp, Value);
232 /// addExpr - Add a Dwarf expression attribute data and value.
234 void Unit::addExpr(DIEBlock *Die, dwarf::Form Form, const MCExpr *Expr) {
235 DIEValue *Value = new (DIEValueAllocator) DIEExpr(Expr);
236 Die->addValue((dwarf::Attribute)0, Form, Value);
239 /// addLabel - Add a Dwarf label attribute data and value.
241 void Unit::addLabel(DIE *Die, dwarf::Attribute Attribute, dwarf::Form Form,
242 const MCSymbol *Label) {
243 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
244 Die->addValue(Attribute, Form, Value);
247 void Unit::addLabel(DIEBlock *Die, dwarf::Form Form, const MCSymbol *Label) {
248 addLabel(Die, (dwarf::Attribute)0, Form, Label);
251 /// addSectionLabel - Add a Dwarf section label attribute data and value.
253 void Unit::addSectionLabel(DIE *Die, dwarf::Attribute Attribute,
254 const MCSymbol *Label) {
255 if (DD->getDwarfVersion() >= 4)
256 addLabel(Die, Attribute, dwarf::DW_FORM_sec_offset, Label);
258 addLabel(Die, Attribute, dwarf::DW_FORM_data4, Label);
261 /// addSectionOffset - Add an offset into a section attribute data and value.
263 void Unit::addSectionOffset(DIE *Die, dwarf::Attribute Attribute,
265 if (DD->getDwarfVersion() >= 4)
266 addUInt(Die, Attribute, dwarf::DW_FORM_sec_offset, Integer);
268 addUInt(Die, Attribute, dwarf::DW_FORM_data4, Integer);
271 /// addLabelAddress - Add a dwarf label attribute data and value using
272 /// DW_FORM_addr or DW_FORM_GNU_addr_index.
274 void CompileUnit::addLabelAddress(DIE *Die, dwarf::Attribute Attribute,
277 DD->addArangeLabel(SymbolCU(this, Label));
279 if (!DD->useSplitDwarf()) {
281 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
282 Die->addValue(Attribute, dwarf::DW_FORM_addr, Value);
284 DIEValue *Value = new (DIEValueAllocator) DIEInteger(0);
285 Die->addValue(Attribute, dwarf::DW_FORM_addr, Value);
288 unsigned idx = DU->getAddrPoolIndex(Label);
289 DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
290 Die->addValue(Attribute, dwarf::DW_FORM_GNU_addr_index, Value);
294 /// addOpAddress - Add a dwarf op address data and value using the
295 /// form given and an op of either DW_FORM_addr or DW_FORM_GNU_addr_index.
297 void Unit::addOpAddress(DIEBlock *Die, const MCSymbol *Sym) {
298 if (!DD->useSplitDwarf()) {
299 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
300 addLabel(Die, dwarf::DW_FORM_udata, Sym);
302 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index);
303 addUInt(Die, dwarf::DW_FORM_GNU_addr_index, DU->getAddrPoolIndex(Sym));
307 /// addSectionDelta - Add a section label delta attribute data and value.
309 void Unit::addSectionDelta(DIE *Die, dwarf::Attribute Attribute,
310 const MCSymbol *Hi, const MCSymbol *Lo) {
311 DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
312 if (DD->getDwarfVersion() >= 4)
313 Die->addValue(Attribute, dwarf::DW_FORM_sec_offset, Value);
315 Die->addValue(Attribute, dwarf::DW_FORM_data4, Value);
318 /// addDIEEntry - Add a DIE attribute data and value.
320 void Unit::addDIEEntry(DIE *Die, dwarf::Attribute Attribute, DIE *Entry) {
321 addDIEEntry(Die, Attribute, createDIEEntry(Entry));
324 void Unit::addDIEEntry(DIE *Die, dwarf::Attribute Attribute, DIEEntry *Entry) {
325 const DIE *DieCU = Die->getUnitOrNull();
326 const DIE *EntryCU = Entry->getEntry()->getUnitOrNull();
328 // We assume that Die belongs to this CU, if it is not linked to any CU yet.
329 DieCU = getUnitDie();
331 EntryCU = getUnitDie();
332 Die->addValue(Attribute, EntryCU == DieCU ? dwarf::DW_FORM_ref4
333 : dwarf::DW_FORM_ref_addr,
337 /// Create a DIE with the given Tag, add the DIE to its parent, and
338 /// call insertDIE if MD is not null.
339 DIE *Unit::createAndAddDIE(unsigned Tag, DIE &Parent, DIDescriptor N) {
340 DIE *Die = new DIE(Tag);
341 Parent.addChild(Die);
347 /// addBlock - Add block data.
349 void Unit::addBlock(DIE *Die, dwarf::Attribute Attribute, DIEBlock *Block) {
350 Block->ComputeSize(Asm);
351 DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
352 Die->addValue(Attribute, Block->BestForm(), Block);
355 /// addSourceLine - Add location information to specified debug information
357 void Unit::addSourceLine(DIE *Die, DIVariable V) {
362 unsigned Line = V.getLineNumber();
366 DD->getOrCreateSourceID(V.getContext().getFilename(),
367 V.getContext().getDirectory(), getUniqueID());
368 assert(FileID && "Invalid file id");
369 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
370 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
373 /// addSourceLine - Add location information to specified debug information
375 void Unit::addSourceLine(DIE *Die, DIGlobalVariable G) {
376 // Verify global variable.
377 if (!G.isGlobalVariable())
380 unsigned Line = G.getLineNumber();
384 DD->getOrCreateSourceID(G.getFilename(), G.getDirectory(), getUniqueID());
385 assert(FileID && "Invalid file id");
386 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
387 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
390 /// addSourceLine - Add location information to specified debug information
392 void Unit::addSourceLine(DIE *Die, DISubprogram SP) {
393 // Verify subprogram.
394 if (!SP.isSubprogram())
397 // If the line number is 0, don't add it.
398 unsigned Line = SP.getLineNumber();
402 unsigned FileID = DD->getOrCreateSourceID(SP.getFilename(), SP.getDirectory(),
404 assert(FileID && "Invalid file id");
405 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
406 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
409 /// addSourceLine - Add location information to specified debug information
411 void Unit::addSourceLine(DIE *Die, DIType Ty) {
416 unsigned Line = Ty.getLineNumber();
419 unsigned FileID = DD->getOrCreateSourceID(Ty.getFilename(), Ty.getDirectory(),
421 assert(FileID && "Invalid file id");
422 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
423 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
426 /// addSourceLine - Add location information to specified debug information
428 void Unit::addSourceLine(DIE *Die, DIObjCProperty Ty) {
430 if (!Ty.isObjCProperty())
433 unsigned Line = Ty.getLineNumber();
436 DIFile File = Ty.getFile();
437 unsigned FileID = DD->getOrCreateSourceID(File.getFilename(),
438 File.getDirectory(), getUniqueID());
439 assert(FileID && "Invalid file id");
440 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
441 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
444 /// addSourceLine - Add location information to specified debug information
446 void Unit::addSourceLine(DIE *Die, DINameSpace NS) {
451 unsigned Line = NS.getLineNumber();
454 StringRef FN = NS.getFilename();
457 DD->getOrCreateSourceID(FN, NS.getDirectory(), getUniqueID());
458 assert(FileID && "Invalid file id");
459 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
460 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
463 /// addVariableAddress - Add DW_AT_location attribute for a
464 /// DbgVariable based on provided MachineLocation.
465 void Unit::addVariableAddress(const DbgVariable &DV, DIE *Die,
466 MachineLocation Location) {
467 if (DV.variableHasComplexAddress())
468 addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
469 else if (DV.isBlockByrefVariable())
470 addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location);
472 addAddress(Die, dwarf::DW_AT_location, Location,
473 DV.getVariable().isIndirect());
476 /// addRegisterOp - Add register operand.
477 void Unit::addRegisterOp(DIEBlock *TheDie, unsigned Reg) {
478 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
479 unsigned DWReg = RI->getDwarfRegNum(Reg, false);
481 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + DWReg);
483 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
484 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
488 /// addRegisterOffset - Add register offset.
489 void Unit::addRegisterOffset(DIEBlock *TheDie, unsigned Reg, int64_t Offset) {
490 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
491 unsigned DWReg = RI->getDwarfRegNum(Reg, false);
492 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
493 if (Reg == TRI->getFrameRegister(*Asm->MF))
494 // If variable offset is based in frame register then use fbreg.
495 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_fbreg);
497 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + DWReg);
499 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
500 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
502 addSInt(TheDie, dwarf::DW_FORM_sdata, Offset);
505 /// addAddress - Add an address attribute to a die based on the location
507 void Unit::addAddress(DIE *Die, dwarf::Attribute Attribute,
508 const MachineLocation &Location, bool Indirect) {
509 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
511 if (Location.isReg() && !Indirect)
512 addRegisterOp(Block, Location.getReg());
514 addRegisterOffset(Block, Location.getReg(), Location.getOffset());
515 if (Indirect && !Location.isReg()) {
516 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
520 // Now attach the location information to the DIE.
521 addBlock(Die, Attribute, Block);
524 /// addComplexAddress - Start with the address based on the location provided,
525 /// and generate the DWARF information necessary to find the actual variable
526 /// given the extra address information encoded in the DIVariable, starting from
527 /// the starting location. Add the DWARF information to the die.
529 void Unit::addComplexAddress(const DbgVariable &DV, DIE *Die,
530 dwarf::Attribute Attribute,
531 const MachineLocation &Location) {
532 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
533 unsigned N = DV.getNumAddrElements();
535 if (Location.isReg()) {
536 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
537 // If first address element is OpPlus then emit
538 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
539 addRegisterOffset(Block, Location.getReg(), DV.getAddrElement(1));
542 addRegisterOp(Block, Location.getReg());
544 addRegisterOffset(Block, Location.getReg(), Location.getOffset());
547 uint64_t Element = DV.getAddrElement(i);
548 if (Element == DIBuilder::OpPlus) {
549 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
550 addUInt(Block, dwarf::DW_FORM_udata, DV.getAddrElement(++i));
551 } else if (Element == DIBuilder::OpDeref) {
552 if (!Location.isReg())
553 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
555 llvm_unreachable("unknown DIBuilder Opcode");
558 // Now attach the location information to the DIE.
559 addBlock(Die, Attribute, Block);
562 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
563 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
564 gives the variable VarName either the struct, or a pointer to the struct, as
565 its type. This is necessary for various behind-the-scenes things the
566 compiler needs to do with by-reference variables in Blocks.
568 However, as far as the original *programmer* is concerned, the variable
569 should still have type 'SomeType', as originally declared.
571 The function getBlockByrefType dives into the __Block_byref_x_VarName
572 struct to find the original type of the variable, which is then assigned to
573 the variable's Debug Information Entry as its real type. So far, so good.
574 However now the debugger will expect the variable VarName to have the type
575 SomeType. So we need the location attribute for the variable to be an
576 expression that explains to the debugger how to navigate through the
577 pointers and struct to find the actual variable of type SomeType.
579 The following function does just that. We start by getting
580 the "normal" location for the variable. This will be the location
581 of either the struct __Block_byref_x_VarName or the pointer to the
582 struct __Block_byref_x_VarName.
584 The struct will look something like:
586 struct __Block_byref_x_VarName {
588 struct __Block_byref_x_VarName *forwarding;
589 ... <various other fields>
591 ... <maybe more fields>
594 If we are given the struct directly (as our starting point) we
595 need to tell the debugger to:
597 1). Add the offset of the forwarding field.
599 2). Follow that pointer to get the real __Block_byref_x_VarName
600 struct to use (the real one may have been copied onto the heap).
602 3). Add the offset for the field VarName, to find the actual variable.
604 If we started with a pointer to the struct, then we need to
605 dereference that pointer first, before the other steps.
606 Translating this into DWARF ops, we will need to append the following
607 to the current location description for the variable:
609 DW_OP_deref -- optional, if we start with a pointer
610 DW_OP_plus_uconst <forward_fld_offset>
612 DW_OP_plus_uconst <varName_fld_offset>
614 That is what this function does. */
616 /// addBlockByrefAddress - Start with the address based on the location
617 /// provided, and generate the DWARF information necessary to find the
618 /// actual Block variable (navigating the Block struct) based on the
619 /// starting location. Add the DWARF information to the die. For
620 /// more information, read large comment just above here.
622 void Unit::addBlockByrefAddress(const DbgVariable &DV, DIE *Die,
623 dwarf::Attribute Attribute,
624 const MachineLocation &Location) {
625 DIType Ty = DV.getType();
627 uint16_t Tag = Ty.getTag();
628 bool isPointer = false;
630 StringRef varName = DV.getName();
632 if (Tag == dwarf::DW_TAG_pointer_type) {
633 DIDerivedType DTy(Ty);
634 TmpTy = resolve(DTy.getTypeDerivedFrom());
638 DICompositeType blockStruct(TmpTy);
640 // Find the __forwarding field and the variable field in the __Block_byref
642 DIArray Fields = blockStruct.getTypeArray();
643 DIDerivedType varField;
644 DIDerivedType forwardingField;
646 for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
647 DIDerivedType DT(Fields.getElement(i));
648 StringRef fieldName = DT.getName();
649 if (fieldName == "__forwarding")
650 forwardingField = DT;
651 else if (fieldName == varName)
655 // Get the offsets for the forwarding field and the variable field.
656 unsigned forwardingFieldOffset = forwardingField.getOffsetInBits() >> 3;
657 unsigned varFieldOffset = varField.getOffsetInBits() >> 2;
659 // Decode the original location, and use that as the start of the byref
660 // variable's location.
661 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
663 if (Location.isReg())
664 addRegisterOp(Block, Location.getReg());
666 addRegisterOffset(Block, Location.getReg(), Location.getOffset());
668 // If we started with a pointer to the __Block_byref... struct, then
669 // the first thing we need to do is dereference the pointer (DW_OP_deref).
671 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
673 // Next add the offset for the '__forwarding' field:
674 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
675 // adding the offset if it's 0.
676 if (forwardingFieldOffset > 0) {
677 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
678 addUInt(Block, dwarf::DW_FORM_udata, forwardingFieldOffset);
681 // Now dereference the __forwarding field to get to the real __Block_byref
682 // struct: DW_OP_deref.
683 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
685 // Now that we've got the real __Block_byref... struct, add the offset
686 // for the variable's field to get to the location of the actual variable:
687 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
688 if (varFieldOffset > 0) {
689 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
690 addUInt(Block, dwarf::DW_FORM_udata, varFieldOffset);
693 // Now attach the location information to the DIE.
694 addBlock(Die, Attribute, Block);
697 /// isTypeSigned - Return true if the type is signed.
698 static bool isTypeSigned(DwarfDebug *DD, DIType Ty, int *SizeInBits) {
699 if (Ty.isDerivedType())
700 return isTypeSigned(DD, DD->resolve(DIDerivedType(Ty).getTypeDerivedFrom()),
702 if (Ty.isBasicType())
703 if (DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed ||
704 DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed_char) {
705 *SizeInBits = Ty.getSizeInBits();
711 /// Return true if type encoding is unsigned.
712 static bool isUnsignedDIType(DwarfDebug *DD, DIType Ty) {
713 DIDerivedType DTy(Ty);
714 if (DTy.isDerivedType())
715 return isUnsignedDIType(DD, DD->resolve(DTy.getTypeDerivedFrom()));
718 if (BTy.isBasicType()) {
719 unsigned Encoding = BTy.getEncoding();
720 if (Encoding == dwarf::DW_ATE_unsigned ||
721 Encoding == dwarf::DW_ATE_unsigned_char ||
722 Encoding == dwarf::DW_ATE_boolean)
728 /// If this type is derived from a base type then return base type size.
729 static uint64_t getBaseTypeSize(DwarfDebug *DD, DIDerivedType Ty) {
730 unsigned Tag = Ty.getTag();
732 if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef &&
733 Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type &&
734 Tag != dwarf::DW_TAG_restrict_type)
735 return Ty.getSizeInBits();
737 DIType BaseType = DD->resolve(Ty.getTypeDerivedFrom());
739 // If this type is not derived from any type then take conservative approach.
740 if (!BaseType.isValid())
741 return Ty.getSizeInBits();
743 // If this is a derived type, go ahead and get the base type, unless it's a
744 // reference then it's just the size of the field. Pointer types have no need
745 // of this since they're a different type of qualification on the type.
746 if (BaseType.getTag() == dwarf::DW_TAG_reference_type ||
747 BaseType.getTag() == dwarf::DW_TAG_rvalue_reference_type)
748 return Ty.getSizeInBits();
750 if (BaseType.isDerivedType())
751 return getBaseTypeSize(DD, DIDerivedType(BaseType));
753 return BaseType.getSizeInBits();
756 /// addConstantValue - Add constant value entry in variable DIE.
757 void Unit::addConstantValue(DIE *Die, const MachineOperand &MO, DIType Ty) {
758 // FIXME: This is a bit conservative/simple - it emits negative values at
759 // their maximum bit width which is a bit unfortunate (& doesn't prefer
760 // udata/sdata over dataN as suggested by the DWARF spec)
761 assert(MO.isImm() && "Invalid machine operand!");
763 bool SignedConstant = isTypeSigned(DD, Ty, &SizeInBits);
766 // If we're a signed constant definitely use sdata.
767 if (SignedConstant) {
768 addSInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, MO.getImm());
772 // Else use data for now unless it's larger than we can deal with.
773 switch (SizeInBits) {
775 Form = dwarf::DW_FORM_data1;
778 Form = dwarf::DW_FORM_data2;
781 Form = dwarf::DW_FORM_data4;
784 Form = dwarf::DW_FORM_data8;
787 Form = dwarf::DW_FORM_udata;
788 addUInt(Die, dwarf::DW_AT_const_value, Form, MO.getImm());
791 addUInt(Die, dwarf::DW_AT_const_value, Form, MO.getImm());
794 /// addConstantFPValue - Add constant value entry in variable DIE.
795 void Unit::addConstantFPValue(DIE *Die, const MachineOperand &MO) {
796 assert(MO.isFPImm() && "Invalid machine operand!");
797 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
798 APFloat FPImm = MO.getFPImm()->getValueAPF();
800 // Get the raw data form of the floating point.
801 const APInt FltVal = FPImm.bitcastToAPInt();
802 const char *FltPtr = (const char *)FltVal.getRawData();
804 int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
805 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
806 int Incr = (LittleEndian ? 1 : -1);
807 int Start = (LittleEndian ? 0 : NumBytes - 1);
808 int Stop = (LittleEndian ? NumBytes : -1);
810 // Output the constant to DWARF one byte at a time.
811 for (; Start != Stop; Start += Incr)
812 addUInt(Block, dwarf::DW_FORM_data1, (unsigned char)0xFF & FltPtr[Start]);
814 addBlock(Die, dwarf::DW_AT_const_value, Block);
817 /// addConstantFPValue - Add constant value entry in variable DIE.
818 void Unit::addConstantFPValue(DIE *Die, const ConstantFP *CFP) {
819 // Pass this down to addConstantValue as an unsigned bag of bits.
820 addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true);
823 /// addConstantValue - Add constant value entry in variable DIE.
824 void Unit::addConstantValue(DIE *Die, const ConstantInt *CI, bool Unsigned) {
825 addConstantValue(Die, CI->getValue(), Unsigned);
828 // addConstantValue - Add constant value entry in variable DIE.
829 void Unit::addConstantValue(DIE *Die, const APInt &Val, bool Unsigned) {
830 unsigned CIBitWidth = Val.getBitWidth();
831 if (CIBitWidth <= 64) {
832 // If we're a signed constant definitely use sdata.
834 addSInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
839 // Else use data for now unless it's larger than we can deal with.
841 switch (CIBitWidth) {
843 Form = dwarf::DW_FORM_data1;
846 Form = dwarf::DW_FORM_data2;
849 Form = dwarf::DW_FORM_data4;
852 Form = dwarf::DW_FORM_data8;
855 addUInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_udata,
859 addUInt(Die, dwarf::DW_AT_const_value, Form, Val.getZExtValue());
863 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
865 // Get the raw data form of the large APInt.
866 const uint64_t *Ptr64 = Val.getRawData();
868 int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
869 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
871 // Output the constant to DWARF one byte at a time.
872 for (int i = 0; i < NumBytes; i++) {
875 c = Ptr64[i / 8] >> (8 * (i & 7));
877 c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
878 addUInt(Block, dwarf::DW_FORM_data1, c);
881 addBlock(Die, dwarf::DW_AT_const_value, Block);
884 /// addTemplateParams - Add template parameters into buffer.
885 void Unit::addTemplateParams(DIE &Buffer, DIArray TParams) {
886 // Add template parameters.
887 for (unsigned i = 0, e = TParams.getNumElements(); i != e; ++i) {
888 DIDescriptor Element = TParams.getElement(i);
889 if (Element.isTemplateTypeParameter())
890 constructTemplateTypeParameterDIE(Buffer,
891 DITemplateTypeParameter(Element));
892 else if (Element.isTemplateValueParameter())
893 constructTemplateValueParameterDIE(Buffer,
894 DITemplateValueParameter(Element));
898 /// getOrCreateContextDIE - Get context owner's DIE.
899 DIE *Unit::getOrCreateContextDIE(DIScope Context) {
900 if (!Context || Context.isFile())
902 if (Context.isType())
903 return getOrCreateTypeDIE(DIType(Context));
904 if (Context.isNameSpace())
905 return getOrCreateNameSpace(DINameSpace(Context));
906 if (Context.isSubprogram())
907 return getOrCreateSubprogramDIE(DISubprogram(Context));
908 return getDIE(Context);
911 DIE *Unit::createTypeDIE(DICompositeType Ty) {
912 DIScope Context = resolve(Ty.getContext());
913 DIE *ContextDIE = getOrCreateContextDIE(Context);
915 DIE *TyDIE = getDIE(Ty);
920 TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
922 constructTypeDIE(*TyDIE, Ty);
924 updateAcceleratorTables(Context, Ty, TyDIE);
928 /// Return true if the type is appropriately scoped to be contained inside
929 /// its own type unit.
930 static bool isTypeUnitScoped(DIType Ty, const DwarfDebug *DD) {
931 DIScope Parent = DD->resolve(Ty.getContext());
933 // Don't generate a hash for anything scoped inside a function.
934 if (Parent.isSubprogram())
936 Parent = DD->resolve(Parent.getContext());
941 /// Return true if the type should be split out into a type unit.
942 static bool shouldCreateTypeUnit(DICompositeType CTy, const DwarfDebug *DD) {
943 if (!GenerateTypeUnits)
946 uint16_t Tag = CTy.getTag();
949 case dwarf::DW_TAG_structure_type:
950 case dwarf::DW_TAG_union_type:
951 case dwarf::DW_TAG_enumeration_type:
952 case dwarf::DW_TAG_class_type:
953 // If this is a class, structure, union, or enumeration type
954 // that is a definition (not a declaration), and not scoped
955 // inside a function then separate this out as a type unit.
956 return !CTy.isForwardDecl() && isTypeUnitScoped(CTy, DD);
962 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
964 DIE *Unit::getOrCreateTypeDIE(const MDNode *TyNode) {
971 // Construct the context before querying for the existence of the DIE in case
972 // such construction creates the DIE.
973 DIScope Context = resolve(Ty.getContext());
974 DIE *ContextDIE = getOrCreateContextDIE(Context);
977 DIE *TyDIE = getDIE(Ty);
982 TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
984 if (Ty.isBasicType())
985 constructTypeDIE(*TyDIE, DIBasicType(Ty));
986 else if (Ty.isCompositeType()) {
987 DICompositeType CTy(Ty);
988 if (shouldCreateTypeUnit(CTy, DD)) {
989 DD->addTypeUnitType(getLanguage(), TyDIE, CTy);
990 // Skip updating the accellerator tables since this is not the full type
993 constructTypeDIE(*TyDIE, CTy);
995 assert(Ty.isDerivedType() && "Unknown kind of DIType");
996 constructTypeDIE(*TyDIE, DIDerivedType(Ty));
999 updateAcceleratorTables(Context, Ty, TyDIE);
1004 void Unit::updateAcceleratorTables(DIScope Context, DIType Ty,
1006 if (!Ty.getName().empty() && !Ty.isForwardDecl()) {
1007 bool IsImplementation = 0;
1008 if (Ty.isCompositeType()) {
1009 DICompositeType CT(Ty);
1010 // A runtime language of 0 actually means C/C++ and that any
1011 // non-negative value is some version of Objective-C/C++.
1012 IsImplementation = (CT.getRunTimeLang() == 0) || CT.isObjcClassComplete();
1014 unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0;
1015 addAccelType(Ty.getName(), std::make_pair(TyDIE, Flags));
1017 if (!Context || Context.isCompileUnit() || Context.isFile() ||
1018 Context.isNameSpace())
1019 GlobalTypes[getParentContextString(Context) + Ty.getName().str()] = TyDIE;
1023 /// addType - Add a new type attribute to the specified entity.
1024 void Unit::addType(DIE *Entity, DIType Ty, dwarf::Attribute Attribute) {
1025 assert(Ty && "Trying to add a type that doesn't exist?");
1027 // Check for pre-existence.
1028 DIEEntry *Entry = getDIEEntry(Ty);
1029 // If it exists then use the existing value.
1031 addDIEEntry(Entity, Attribute, Entry);
1036 DIE *Buffer = getOrCreateTypeDIE(Ty);
1039 Entry = createDIEEntry(Buffer);
1040 insertDIEEntry(Ty, Entry);
1041 addDIEEntry(Entity, Attribute, Entry);
1044 // Accelerator table mutators - add each name along with its companion
1045 // DIE to the proper table while ensuring that the name that we're going
1046 // to reference is in the string table. We do this since the names we
1047 // add may not only be identical to the names in the DIE.
1048 void Unit::addAccelName(StringRef Name, const DIE *Die) {
1049 DU->getStringPoolEntry(Name);
1050 std::vector<const DIE *> &DIEs = AccelNames[Name];
1051 DIEs.push_back(Die);
1054 void Unit::addAccelObjC(StringRef Name, const DIE *Die) {
1055 DU->getStringPoolEntry(Name);
1056 std::vector<const DIE *> &DIEs = AccelObjC[Name];
1057 DIEs.push_back(Die);
1060 void Unit::addAccelNamespace(StringRef Name, const DIE *Die) {
1061 DU->getStringPoolEntry(Name);
1062 std::vector<const DIE *> &DIEs = AccelNamespace[Name];
1063 DIEs.push_back(Die);
1066 void Unit::addAccelType(StringRef Name, std::pair<const DIE *, unsigned> Die) {
1067 DU->getStringPoolEntry(Name);
1068 std::vector<std::pair<const DIE *, unsigned> > &DIEs = AccelTypes[Name];
1069 DIEs.push_back(Die);
1072 /// addGlobalName - Add a new global name to the compile unit.
1073 void Unit::addGlobalName(StringRef Name, DIE *Die, DIScope Context) {
1074 std::string FullName = getParentContextString(Context) + Name.str();
1075 GlobalNames[FullName] = Die;
1078 /// getParentContextString - Walks the metadata parent chain in a language
1079 /// specific manner (using the compile unit language) and returns
1080 /// it as a string. This is done at the metadata level because DIEs may
1081 /// not currently have been added to the parent context and walking the
1082 /// DIEs looking for names is more expensive than walking the metadata.
1083 std::string Unit::getParentContextString(DIScope Context) const {
1087 // FIXME: Decide whether to implement this for non-C++ languages.
1088 if (getLanguage() != dwarf::DW_LANG_C_plus_plus)
1092 SmallVector<DIScope, 1> Parents;
1093 while (!Context.isCompileUnit()) {
1094 Parents.push_back(Context);
1095 if (Context.getContext())
1096 Context = resolve(Context.getContext());
1098 // Structure, etc types will have a NULL context if they're at the top
1103 // Reverse iterate over our list to go from the outermost construct to the
1105 for (SmallVectorImpl<DIScope>::reverse_iterator I = Parents.rbegin(),
1109 StringRef Name = Ctx.getName();
1110 if (!Name.empty()) {
1118 /// constructTypeDIE - Construct basic type die from DIBasicType.
1119 void Unit::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
1120 // Get core information.
1121 StringRef Name = BTy.getName();
1122 // Add name if not anonymous or intermediate type.
1124 addString(&Buffer, dwarf::DW_AT_name, Name);
1126 // An unspecified type only has a name attribute.
1127 if (BTy.getTag() == dwarf::DW_TAG_unspecified_type)
1130 addUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1133 uint64_t Size = BTy.getSizeInBits() >> 3;
1134 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1137 /// constructTypeDIE - Construct derived type die from DIDerivedType.
1138 void Unit::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
1139 // Get core information.
1140 StringRef Name = DTy.getName();
1141 uint64_t Size = DTy.getSizeInBits() >> 3;
1142 uint16_t Tag = Buffer.getTag();
1144 // Map to main type, void will not have a type.
1145 DIType FromTy = resolve(DTy.getTypeDerivedFrom());
1147 addType(&Buffer, FromTy);
1149 // Add name if not anonymous or intermediate type.
1151 addString(&Buffer, dwarf::DW_AT_name, Name);
1153 // Add size if non-zero (derived types might be zero-sized.)
1154 if (Size && Tag != dwarf::DW_TAG_pointer_type)
1155 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1157 if (Tag == dwarf::DW_TAG_ptr_to_member_type)
1158 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type,
1159 getOrCreateTypeDIE(resolve(DTy.getClassType())));
1160 // Add source line info if available and TyDesc is not a forward declaration.
1161 if (!DTy.isForwardDecl())
1162 addSourceLine(&Buffer, DTy);
1165 /// constructTypeDIE - Construct type DIE from DICompositeType.
1166 void Unit::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
1167 // Add name if not anonymous or intermediate type.
1168 StringRef Name = CTy.getName();
1170 uint64_t Size = CTy.getSizeInBits() >> 3;
1171 uint16_t Tag = Buffer.getTag();
1174 case dwarf::DW_TAG_array_type:
1175 constructArrayTypeDIE(Buffer, CTy);
1177 case dwarf::DW_TAG_enumeration_type:
1178 constructEnumTypeDIE(Buffer, CTy);
1180 case dwarf::DW_TAG_subroutine_type: {
1181 // Add return type. A void return won't have a type.
1182 DIArray Elements = CTy.getTypeArray();
1183 DIType RTy(Elements.getElement(0));
1185 addType(&Buffer, RTy);
1187 bool isPrototyped = true;
1189 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
1190 DIDescriptor Ty = Elements.getElement(i);
1191 if (Ty.isUnspecifiedParameter()) {
1192 createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
1193 isPrototyped = false;
1195 DIE *Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
1196 addType(Arg, DIType(Ty));
1197 if (DIType(Ty).isArtificial())
1198 addFlag(Arg, dwarf::DW_AT_artificial);
1201 // Add prototype flag if we're dealing with a C language and the
1202 // function has been prototyped.
1203 uint16_t Language = getLanguage();
1205 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1206 Language == dwarf::DW_LANG_ObjC))
1207 addFlag(&Buffer, dwarf::DW_AT_prototyped);
1209 case dwarf::DW_TAG_structure_type:
1210 case dwarf::DW_TAG_union_type:
1211 case dwarf::DW_TAG_class_type: {
1212 // Add elements to structure type.
1213 DIArray Elements = CTy.getTypeArray();
1214 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1215 DIDescriptor Element = Elements.getElement(i);
1216 DIE *ElemDie = NULL;
1217 if (Element.isSubprogram()) {
1218 DISubprogram SP(Element);
1219 ElemDie = getOrCreateSubprogramDIE(SP);
1220 if (SP.isProtected())
1221 addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1222 dwarf::DW_ACCESS_protected);
1223 else if (SP.isPrivate())
1224 addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1225 dwarf::DW_ACCESS_private);
1227 addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1228 dwarf::DW_ACCESS_public);
1229 if (SP.isExplicit())
1230 addFlag(ElemDie, dwarf::DW_AT_explicit);
1231 } else if (Element.isDerivedType()) {
1232 DIDerivedType DDTy(Element);
1233 if (DDTy.getTag() == dwarf::DW_TAG_friend) {
1234 ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
1235 addType(ElemDie, resolve(DDTy.getTypeDerivedFrom()),
1236 dwarf::DW_AT_friend);
1237 } else if (DDTy.isStaticMember()) {
1238 getOrCreateStaticMemberDIE(DDTy);
1240 constructMemberDIE(Buffer, DDTy);
1242 } else if (Element.isObjCProperty()) {
1243 DIObjCProperty Property(Element);
1244 ElemDie = createAndAddDIE(Property.getTag(), Buffer);
1245 StringRef PropertyName = Property.getObjCPropertyName();
1246 addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
1247 addType(ElemDie, Property.getType());
1248 addSourceLine(ElemDie, Property);
1249 StringRef GetterName = Property.getObjCPropertyGetterName();
1250 if (!GetterName.empty())
1251 addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
1252 StringRef SetterName = Property.getObjCPropertySetterName();
1253 if (!SetterName.empty())
1254 addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
1255 unsigned PropertyAttributes = 0;
1256 if (Property.isReadOnlyObjCProperty())
1257 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readonly;
1258 if (Property.isReadWriteObjCProperty())
1259 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readwrite;
1260 if (Property.isAssignObjCProperty())
1261 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_assign;
1262 if (Property.isRetainObjCProperty())
1263 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_retain;
1264 if (Property.isCopyObjCProperty())
1265 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_copy;
1266 if (Property.isNonAtomicObjCProperty())
1267 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_nonatomic;
1268 if (PropertyAttributes)
1269 addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None,
1270 PropertyAttributes);
1272 DIEEntry *Entry = getDIEEntry(Element);
1274 Entry = createDIEEntry(ElemDie);
1275 insertDIEEntry(Element, Entry);
1281 if (CTy.isAppleBlockExtension())
1282 addFlag(&Buffer, dwarf::DW_AT_APPLE_block);
1284 DICompositeType ContainingType(resolve(CTy.getContainingType()));
1286 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type,
1287 getOrCreateTypeDIE(ContainingType));
1289 if (CTy.isObjcClassComplete())
1290 addFlag(&Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
1292 // Add template parameters to a class, structure or union types.
1293 // FIXME: The support isn't in the metadata for this yet.
1294 if (Tag == dwarf::DW_TAG_class_type ||
1295 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
1296 addTemplateParams(Buffer, CTy.getTemplateParams());
1304 // Add name if not anonymous or intermediate type.
1306 addString(&Buffer, dwarf::DW_AT_name, Name);
1308 if (Tag == dwarf::DW_TAG_enumeration_type ||
1309 Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
1310 Tag == dwarf::DW_TAG_union_type) {
1311 // Add size if non-zero (derived types might be zero-sized.)
1312 // TODO: Do we care about size for enum forward declarations?
1314 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1315 else if (!CTy.isForwardDecl())
1316 // Add zero size if it is not a forward declaration.
1317 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, 0);
1319 // If we're a forward decl, say so.
1320 if (CTy.isForwardDecl())
1321 addFlag(&Buffer, dwarf::DW_AT_declaration);
1323 // Add source line info if available.
1324 if (!CTy.isForwardDecl())
1325 addSourceLine(&Buffer, CTy);
1327 // No harm in adding the runtime language to the declaration.
1328 unsigned RLang = CTy.getRunTimeLang();
1330 addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
1335 /// constructTemplateTypeParameterDIE - Construct new DIE for the given
1336 /// DITemplateTypeParameter.
1337 void Unit::constructTemplateTypeParameterDIE(DIE &Buffer,
1338 DITemplateTypeParameter TP) {
1340 createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
1341 // Add the type if it exists, it could be void and therefore no type.
1343 addType(ParamDIE, resolve(TP.getType()));
1344 if (!TP.getName().empty())
1345 addString(ParamDIE, dwarf::DW_AT_name, TP.getName());
1348 /// constructTemplateValueParameterDIE - Construct new DIE for the given
1349 /// DITemplateValueParameter.
1350 void Unit::constructTemplateValueParameterDIE(DIE &Buffer,
1351 DITemplateValueParameter VP) {
1352 DIE *ParamDIE = createAndAddDIE(VP.getTag(), Buffer);
1354 // Add the type if there is one, template template and template parameter
1355 // packs will not have a type.
1356 if (VP.getTag() == dwarf::DW_TAG_template_value_parameter)
1357 addType(ParamDIE, resolve(VP.getType()));
1358 if (!VP.getName().empty())
1359 addString(ParamDIE, dwarf::DW_AT_name, VP.getName());
1360 if (Value *Val = VP.getValue()) {
1361 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val))
1362 addConstantValue(ParamDIE, CI,
1363 isUnsignedDIType(DD, resolve(VP.getType())));
1364 else if (GlobalValue *GV = dyn_cast<GlobalValue>(Val)) {
1365 // For declaration non-type template parameters (such as global values and
1367 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1368 addOpAddress(Block, Asm->getSymbol(GV));
1369 // Emit DW_OP_stack_value to use the address as the immediate value of the
1370 // parameter, rather than a pointer to it.
1371 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
1372 addBlock(ParamDIE, dwarf::DW_AT_location, Block);
1373 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1374 assert(isa<MDString>(Val));
1375 addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
1376 cast<MDString>(Val)->getString());
1377 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1378 assert(isa<MDNode>(Val));
1379 DIArray A(cast<MDNode>(Val));
1380 addTemplateParams(*ParamDIE, A);
1385 /// getOrCreateNameSpace - Create a DIE for DINameSpace.
1386 DIE *Unit::getOrCreateNameSpace(DINameSpace NS) {
1387 // Construct the context before querying for the existence of the DIE in case
1388 // such construction creates the DIE.
1389 DIE *ContextDIE = getOrCreateContextDIE(NS.getContext());
1391 DIE *NDie = getDIE(NS);
1394 NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS);
1396 if (!NS.getName().empty()) {
1397 addString(NDie, dwarf::DW_AT_name, NS.getName());
1398 addAccelNamespace(NS.getName(), NDie);
1399 addGlobalName(NS.getName(), NDie, NS.getContext());
1401 addAccelNamespace("(anonymous namespace)", NDie);
1402 addSourceLine(NDie, NS);
1406 /// getOrCreateSubprogramDIE - Create new DIE using SP.
1407 DIE *Unit::getOrCreateSubprogramDIE(DISubprogram SP) {
1408 // Construct the context before querying for the existence of the DIE in case
1409 // such construction creates the DIE (as is the case for member function
1411 DIE *ContextDIE = getOrCreateContextDIE(resolve(SP.getContext()));
1413 DIE *SPDie = getDIE(SP);
1417 DISubprogram SPDecl = SP.getFunctionDeclaration();
1418 if (SPDecl.isSubprogram())
1419 // Add subprogram definitions to the CU die directly.
1420 ContextDIE = UnitDie.get();
1422 // DW_TAG_inlined_subroutine may refer to this DIE.
1423 SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
1425 DIE *DeclDie = NULL;
1426 if (SPDecl.isSubprogram())
1427 DeclDie = getOrCreateSubprogramDIE(SPDecl);
1429 // Add function template parameters.
1430 addTemplateParams(*SPDie, SP.getTemplateParams());
1432 // If this DIE is going to refer declaration info using AT_specification
1433 // then there is no need to add other attributes.
1435 // Refer function declaration directly.
1436 addDIEEntry(SPDie, dwarf::DW_AT_specification, DeclDie);
1441 // Add the linkage name if we have one.
1442 StringRef LinkageName = SP.getLinkageName();
1443 if (!LinkageName.empty())
1444 addString(SPDie, dwarf::DW_AT_MIPS_linkage_name,
1445 GlobalValue::getRealLinkageName(LinkageName));
1447 // Constructors and operators for anonymous aggregates do not have names.
1448 if (!SP.getName().empty())
1449 addString(SPDie, dwarf::DW_AT_name, SP.getName());
1451 addSourceLine(SPDie, SP);
1453 // Add the prototype if we have a prototype and we have a C like
1455 uint16_t Language = getLanguage();
1456 if (SP.isPrototyped() &&
1457 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1458 Language == dwarf::DW_LANG_ObjC))
1459 addFlag(SPDie, dwarf::DW_AT_prototyped);
1461 DICompositeType SPTy = SP.getType();
1462 assert(SPTy.getTag() == dwarf::DW_TAG_subroutine_type &&
1463 "the type of a subprogram should be a subroutine");
1465 DIArray Args = SPTy.getTypeArray();
1466 // Add a return type. If this is a type like a C/C++ void type we don't add a
1468 if (Args.getElement(0))
1469 addType(SPDie, DIType(Args.getElement(0)));
1471 unsigned VK = SP.getVirtuality();
1473 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1474 DIEBlock *Block = getDIEBlock();
1475 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1476 addUInt(Block, dwarf::DW_FORM_udata, SP.getVirtualIndex());
1477 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
1478 ContainingTypeMap.insert(
1479 std::make_pair(SPDie, resolve(SP.getContainingType())));
1482 if (!SP.isDefinition()) {
1483 addFlag(SPDie, dwarf::DW_AT_declaration);
1485 // Add arguments. Do not add arguments for subprogram definition. They will
1486 // be handled while processing variables.
1487 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1488 DIE *Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, *SPDie);
1489 DIType ATy(Args.getElement(i));
1491 if (ATy.isArtificial())
1492 addFlag(Arg, dwarf::DW_AT_artificial);
1496 if (SP.isArtificial())
1497 addFlag(SPDie, dwarf::DW_AT_artificial);
1499 if (!SP.isLocalToUnit())
1500 addFlag(SPDie, dwarf::DW_AT_external);
1502 if (SP.isOptimized())
1503 addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1505 if (unsigned isa = Asm->getISAEncoding()) {
1506 addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1512 // Return const expression if value is a GEP to access merged global
1514 // i8* getelementptr ({ i8, i8, i8, i8 }* @_MergedGlobals, i32 0, i32 0)
1515 static const ConstantExpr *getMergedGlobalExpr(const Value *V) {
1516 const ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(V);
1517 if (!CE || CE->getNumOperands() != 3 ||
1518 CE->getOpcode() != Instruction::GetElementPtr)
1521 // First operand points to a global struct.
1522 Value *Ptr = CE->getOperand(0);
1523 if (!isa<GlobalValue>(Ptr) ||
1524 !isa<StructType>(cast<PointerType>(Ptr->getType())->getElementType()))
1527 // Second operand is zero.
1528 const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(CE->getOperand(1));
1529 if (!CI || !CI->isZero())
1532 // Third operand is offset.
1533 if (!isa<ConstantInt>(CE->getOperand(2)))
1539 /// createGlobalVariableDIE - create global variable DIE.
1540 void CompileUnit::createGlobalVariableDIE(DIGlobalVariable GV) {
1541 // Check for pre-existence.
1545 if (!GV.isGlobalVariable())
1548 DIScope GVContext = GV.getContext();
1549 DIType GTy = GV.getType();
1551 // If this is a static data member definition, some attributes belong
1552 // to the declaration DIE.
1553 DIE *VariableDIE = NULL;
1554 bool IsStaticMember = false;
1555 DIDerivedType SDMDecl = GV.getStaticDataMemberDeclaration();
1556 if (SDMDecl.Verify()) {
1557 assert(SDMDecl.isStaticMember() && "Expected static member decl");
1558 // We need the declaration DIE that is in the static member's class.
1559 VariableDIE = getOrCreateStaticMemberDIE(SDMDecl);
1560 IsStaticMember = true;
1563 // If this is not a static data member definition, create the variable
1564 // DIE and add the initial set of attributes to it.
1566 // Construct the context before querying for the existence of the DIE in
1567 // case such construction creates the DIE.
1568 DIE *ContextDIE = getOrCreateContextDIE(GVContext);
1571 VariableDIE = createAndAddDIE(GV.getTag(), *ContextDIE, GV);
1573 // Add name and type.
1574 addString(VariableDIE, dwarf::DW_AT_name, GV.getDisplayName());
1575 addType(VariableDIE, GTy);
1577 // Add scoping info.
1578 if (!GV.isLocalToUnit())
1579 addFlag(VariableDIE, dwarf::DW_AT_external);
1581 // Add line number info.
1582 addSourceLine(VariableDIE, GV);
1586 bool addToAccelTable = false;
1587 DIE *VariableSpecDIE = NULL;
1588 bool isGlobalVariable = GV.getGlobal() != NULL;
1589 if (isGlobalVariable) {
1590 addToAccelTable = true;
1591 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1592 const MCSymbol *Sym = Asm->getSymbol(GV.getGlobal());
1593 if (GV.getGlobal()->isThreadLocal()) {
1594 // FIXME: Make this work with -gsplit-dwarf.
1595 unsigned PointerSize = Asm->getDataLayout().getPointerSize();
1596 assert((PointerSize == 4 || PointerSize == 8) &&
1597 "Add support for other sizes if necessary");
1598 const MCExpr *Expr =
1599 Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym);
1600 // Based on GCC's support for TLS:
1601 if (!DD->useSplitDwarf()) {
1602 // 1) Start with a constNu of the appropriate pointer size
1603 addUInt(Block, dwarf::DW_FORM_data1,
1604 PointerSize == 4 ? dwarf::DW_OP_const4u : dwarf::DW_OP_const8u);
1605 // 2) containing the (relocated) offset of the TLS variable
1606 // within the module's TLS block.
1607 addExpr(Block, dwarf::DW_FORM_udata, Expr);
1609 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
1610 addUInt(Block, dwarf::DW_FORM_udata, DU->getAddrPoolIndex(Expr));
1612 // 3) followed by a custom OP to make the debugger do a TLS lookup.
1613 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_push_tls_address);
1615 DD->addArangeLabel(SymbolCU(this, Sym));
1616 addOpAddress(Block, Sym);
1618 // Do not create specification DIE if context is either compile unit
1620 if (GVContext && GV.isDefinition() && !GVContext.isCompileUnit() &&
1621 !GVContext.isFile() && !DD->isSubprogramContext(GVContext)) {
1622 // Create specification DIE.
1623 VariableSpecDIE = createAndAddDIE(dwarf::DW_TAG_variable, *UnitDie);
1624 addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification, VariableDIE);
1625 addBlock(VariableSpecDIE, dwarf::DW_AT_location, Block);
1626 // A static member's declaration is already flagged as such.
1627 if (!SDMDecl.Verify())
1628 addFlag(VariableDIE, dwarf::DW_AT_declaration);
1630 addBlock(VariableDIE, dwarf::DW_AT_location, Block);
1632 // Add the linkage name.
1633 StringRef LinkageName = GV.getLinkageName();
1634 if (!LinkageName.empty())
1635 // From DWARF4: DIEs to which DW_AT_linkage_name may apply include:
1636 // TAG_common_block, TAG_constant, TAG_entry_point, TAG_subprogram and
1638 addString(IsStaticMember && VariableSpecDIE ? VariableSpecDIE
1640 dwarf::DW_AT_MIPS_linkage_name,
1641 GlobalValue::getRealLinkageName(LinkageName));
1642 } else if (const ConstantInt *CI =
1643 dyn_cast_or_null<ConstantInt>(GV.getConstant())) {
1644 // AT_const_value was added when the static member was created. To avoid
1645 // emitting AT_const_value multiple times, we only add AT_const_value when
1646 // it is not a static member.
1647 if (!IsStaticMember)
1648 addConstantValue(VariableDIE, CI, isUnsignedDIType(DD, GTy));
1649 } else if (const ConstantExpr *CE = getMergedGlobalExpr(GV->getOperand(11))) {
1650 addToAccelTable = true;
1651 // GV is a merged global.
1652 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1653 Value *Ptr = CE->getOperand(0);
1654 MCSymbol *Sym = Asm->getSymbol(cast<GlobalValue>(Ptr));
1655 DD->addArangeLabel(SymbolCU(this, Sym));
1656 addOpAddress(Block, Sym);
1657 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1658 SmallVector<Value *, 3> Idx(CE->op_begin() + 1, CE->op_end());
1659 addUInt(Block, dwarf::DW_FORM_udata,
1660 Asm->getDataLayout().getIndexedOffset(Ptr->getType(), Idx));
1661 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1662 addBlock(VariableDIE, dwarf::DW_AT_location, Block);
1665 if (addToAccelTable) {
1666 DIE *AddrDIE = VariableSpecDIE ? VariableSpecDIE : VariableDIE;
1667 addAccelName(GV.getName(), AddrDIE);
1669 // If the linkage name is different than the name, go ahead and output
1670 // that as well into the name table.
1671 if (GV.getLinkageName() != "" && GV.getName() != GV.getLinkageName())
1672 addAccelName(GV.getLinkageName(), AddrDIE);
1675 if (!GV.isLocalToUnit())
1676 addGlobalName(GV.getName(), VariableSpecDIE ? VariableSpecDIE : VariableDIE,
1680 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
1681 void Unit::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy) {
1682 DIE *DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
1683 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, IndexTy);
1685 // The LowerBound value defines the lower bounds which is typically zero for
1686 // C/C++. The Count value is the number of elements. Values are 64 bit. If
1687 // Count == -1 then the array is unbounded and we do not emit
1688 // DW_AT_lower_bound and DW_AT_upper_bound attributes. If LowerBound == 0 and
1689 // Count == 0, then the array has zero elements in which case we do not emit
1691 int64_t LowerBound = SR.getLo();
1692 int64_t DefaultLowerBound = getDefaultLowerBound();
1693 int64_t Count = SR.getCount();
1695 if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
1696 addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound);
1698 if (Count != -1 && Count != 0)
1699 // FIXME: An unbounded array should reference the expression that defines
1701 addUInt(DW_Subrange, dwarf::DW_AT_upper_bound, None,
1702 LowerBound + Count - 1);
1705 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
1706 void Unit::constructArrayTypeDIE(DIE &Buffer, DICompositeType CTy) {
1708 addFlag(&Buffer, dwarf::DW_AT_GNU_vector);
1710 // Emit the element type.
1711 addType(&Buffer, resolve(CTy.getTypeDerivedFrom()));
1713 // Get an anonymous type for index type.
1714 // FIXME: This type should be passed down from the front end
1715 // as different languages may have different sizes for indexes.
1716 DIE *IdxTy = getIndexTyDie();
1718 // Construct an anonymous type for index type.
1719 IdxTy = createAndAddDIE(dwarf::DW_TAG_base_type, *UnitDie);
1720 addString(IdxTy, dwarf::DW_AT_name, "int");
1721 addUInt(IdxTy, dwarf::DW_AT_byte_size, None, sizeof(int32_t));
1722 addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1723 dwarf::DW_ATE_signed);
1724 setIndexTyDie(IdxTy);
1727 // Add subranges to array type.
1728 DIArray Elements = CTy.getTypeArray();
1729 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1730 DIDescriptor Element = Elements.getElement(i);
1731 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1732 constructSubrangeDIE(Buffer, DISubrange(Element), IdxTy);
1736 /// constructEnumTypeDIE - Construct an enum type DIE from DICompositeType.
1737 void Unit::constructEnumTypeDIE(DIE &Buffer, DICompositeType CTy) {
1738 DIArray Elements = CTy.getTypeArray();
1740 // Add enumerators to enumeration type.
1741 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1742 DIEnumerator Enum(Elements.getElement(i));
1743 if (Enum.isEnumerator()) {
1744 DIE *Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
1745 StringRef Name = Enum.getName();
1746 addString(Enumerator, dwarf::DW_AT_name, Name);
1747 int64_t Value = Enum.getEnumValue();
1748 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
1752 DIType DTy = resolve(CTy.getTypeDerivedFrom());
1754 addType(&Buffer, DTy);
1755 addFlag(&Buffer, dwarf::DW_AT_enum_class);
1759 /// constructContainingTypeDIEs - Construct DIEs for types that contain
1761 void Unit::constructContainingTypeDIEs() {
1762 for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(),
1763 CE = ContainingTypeMap.end();
1765 DIE *SPDie = CI->first;
1766 DIDescriptor D(CI->second);
1769 DIE *NDie = getDIE(D);
1772 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, NDie);
1776 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
1777 DIE *Unit::constructVariableDIE(DbgVariable &DV, bool isScopeAbstract) {
1778 StringRef Name = DV.getName();
1780 // Define variable debug information entry.
1781 DIE *VariableDie = new DIE(DV.getTag());
1782 DbgVariable *AbsVar = DV.getAbstractVariable();
1783 DIE *AbsDIE = AbsVar ? AbsVar->getDIE() : NULL;
1785 addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin, AbsDIE);
1788 addString(VariableDie, dwarf::DW_AT_name, Name);
1789 addSourceLine(VariableDie, DV.getVariable());
1790 addType(VariableDie, DV.getType());
1793 if (DV.isArtificial())
1794 addFlag(VariableDie, dwarf::DW_AT_artificial);
1796 if (isScopeAbstract) {
1797 DV.setDIE(VariableDie);
1801 // Add variable address.
1803 unsigned Offset = DV.getDotDebugLocOffset();
1804 if (Offset != ~0U) {
1805 addSectionLabel(VariableDie, dwarf::DW_AT_location,
1806 Asm->GetTempSymbol("debug_loc", Offset));
1807 DV.setDIE(VariableDie);
1811 // Check if variable is described by a DBG_VALUE instruction.
1812 if (const MachineInstr *DVInsn = DV.getMInsn()) {
1813 assert(DVInsn->getNumOperands() == 3);
1814 if (DVInsn->getOperand(0).isReg()) {
1815 const MachineOperand RegOp = DVInsn->getOperand(0);
1816 // If the second operand is an immediate, this is an indirect value.
1817 if (DVInsn->getOperand(1).isImm()) {
1818 MachineLocation Location(RegOp.getReg(),
1819 DVInsn->getOperand(1).getImm());
1820 addVariableAddress(DV, VariableDie, Location);
1821 } else if (RegOp.getReg())
1822 addVariableAddress(DV, VariableDie, MachineLocation(RegOp.getReg()));
1823 } else if (DVInsn->getOperand(0).isImm())
1824 addConstantValue(VariableDie, DVInsn->getOperand(0), DV.getType());
1825 else if (DVInsn->getOperand(0).isFPImm())
1826 addConstantFPValue(VariableDie, DVInsn->getOperand(0));
1827 else if (DVInsn->getOperand(0).isCImm())
1828 addConstantValue(VariableDie, DVInsn->getOperand(0).getCImm(),
1829 isUnsignedDIType(DD, DV.getType()));
1831 DV.setDIE(VariableDie);
1834 // .. else use frame index.
1835 int FI = DV.getFrameIndex();
1837 unsigned FrameReg = 0;
1838 const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
1839 int Offset = TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
1840 MachineLocation Location(FrameReg, Offset);
1841 addVariableAddress(DV, VariableDie, Location);
1845 DV.setDIE(VariableDie);
1849 /// constructMemberDIE - Construct member DIE from DIDerivedType.
1850 void Unit::constructMemberDIE(DIE &Buffer, DIDerivedType DT) {
1851 DIE *MemberDie = createAndAddDIE(DT.getTag(), Buffer);
1852 StringRef Name = DT.getName();
1854 addString(MemberDie, dwarf::DW_AT_name, Name);
1856 addType(MemberDie, resolve(DT.getTypeDerivedFrom()));
1858 addSourceLine(MemberDie, DT);
1860 DIEBlock *MemLocationDie = new (DIEValueAllocator) DIEBlock();
1861 addUInt(MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1863 if (DT.getTag() == dwarf::DW_TAG_inheritance && DT.isVirtual()) {
1865 // For C++, virtual base classes are not at fixed offset. Use following
1866 // expression to extract appropriate offset from vtable.
1867 // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1869 DIEBlock *VBaseLocationDie = new (DIEValueAllocator) DIEBlock();
1870 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1871 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1872 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1873 addUInt(VBaseLocationDie, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1874 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1875 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1876 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1878 addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
1880 uint64_t Size = DT.getSizeInBits();
1881 uint64_t FieldSize = getBaseTypeSize(DD, DT);
1882 uint64_t OffsetInBytes;
1884 if (Size != FieldSize) {
1886 addUInt(MemberDie, dwarf::DW_AT_byte_size, None,
1887 getBaseTypeSize(DD, DT) >> 3);
1888 addUInt(MemberDie, dwarf::DW_AT_bit_size, None, DT.getSizeInBits());
1890 uint64_t Offset = DT.getOffsetInBits();
1891 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1892 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1893 uint64_t FieldOffset = (HiMark - FieldSize);
1894 Offset -= FieldOffset;
1896 // Maybe we need to work from the other end.
1897 if (Asm->getDataLayout().isLittleEndian())
1898 Offset = FieldSize - (Offset + Size);
1899 addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset);
1901 // Here WD_AT_data_member_location points to the anonymous
1902 // field that includes this bit field.
1903 OffsetInBytes = FieldOffset >> 3;
1905 // This is not a bitfield.
1906 OffsetInBytes = DT.getOffsetInBits() >> 3;
1907 addUInt(MemberDie, dwarf::DW_AT_data_member_location, None, OffsetInBytes);
1910 if (DT.isProtected())
1911 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1912 dwarf::DW_ACCESS_protected);
1913 else if (DT.isPrivate())
1914 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1915 dwarf::DW_ACCESS_private);
1916 // Otherwise C++ member and base classes are considered public.
1918 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1919 dwarf::DW_ACCESS_public);
1921 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1922 dwarf::DW_VIRTUALITY_virtual);
1924 // Objective-C properties.
1925 if (MDNode *PNode = DT.getObjCProperty())
1926 if (DIEEntry *PropertyDie = getDIEEntry(PNode))
1927 MemberDie->addValue(dwarf::DW_AT_APPLE_property, dwarf::DW_FORM_ref4,
1930 if (DT.isArtificial())
1931 addFlag(MemberDie, dwarf::DW_AT_artificial);
1934 /// getOrCreateStaticMemberDIE - Create new DIE for C++ static member.
1935 DIE *Unit::getOrCreateStaticMemberDIE(DIDerivedType DT) {
1939 // Construct the context before querying for the existence of the DIE in case
1940 // such construction creates the DIE.
1941 DIE *ContextDIE = getOrCreateContextDIE(resolve(DT.getContext()));
1942 assert(dwarf::isType(ContextDIE->getTag()) &&
1943 "Static member should belong to a type.");
1945 DIE *StaticMemberDIE = getDIE(DT);
1946 if (StaticMemberDIE)
1947 return StaticMemberDIE;
1949 StaticMemberDIE = createAndAddDIE(DT.getTag(), *ContextDIE, DT);
1951 DIType Ty = resolve(DT.getTypeDerivedFrom());
1953 addString(StaticMemberDIE, dwarf::DW_AT_name, DT.getName());
1954 addType(StaticMemberDIE, Ty);
1955 addSourceLine(StaticMemberDIE, DT);
1956 addFlag(StaticMemberDIE, dwarf::DW_AT_external);
1957 addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
1959 // FIXME: We could omit private if the parent is a class_type, and
1960 // public if the parent is something else.
1961 if (DT.isProtected())
1962 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1963 dwarf::DW_ACCESS_protected);
1964 else if (DT.isPrivate())
1965 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1966 dwarf::DW_ACCESS_private);
1968 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1969 dwarf::DW_ACCESS_public);
1971 if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT.getConstant()))
1972 addConstantValue(StaticMemberDIE, CI, isUnsignedDIType(DD, Ty));
1973 if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT.getConstant()))
1974 addConstantFPValue(StaticMemberDIE, CFP);
1976 return StaticMemberDIE;
1979 void Unit::emitHeader(const MCSection *ASection, const MCSymbol *ASectionSym) {
1980 Asm->OutStreamer.AddComment("DWARF version number");
1981 Asm->EmitInt16(DD->getDwarfVersion());
1982 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
1983 // We share one abbreviations table across all compilation units so it's
1984 // always at the start of the section. Use a relocatable offset where needed
1985 // to ensure linking doesn't invalidate that offset.
1986 Asm->EmitSectionOffset(ASectionSym, ASectionSym);
1987 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1988 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());