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, DICompileUnit Node,
37 AsmPrinter *A, DwarfDebug *DW, DwarfUnits *DWU)
38 : UniqueID(UID), Node(Node), CUDie(D), Asm(A), DD(DW), DU(DWU),
39 IndexTyDie(0), DebugInfoOffset(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 (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(DIDescriptor D) {
103 // When the MDNode can be part of the type system, the DIE can be
104 // shared across CUs.
106 (D.isSubprogram() && !DISubprogram(D).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(DIDescriptor D) const {
114 if (isShareableAcrossCUs(D))
115 return DD->getDIE(D);
116 return MDNodeToDieMap.lookup(D);
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(DIDescriptor Desc, DIE *D) {
123 if (isShareableAcrossCUs(Desc)) {
124 DD->insertDIE(Desc, D);
127 MDNodeToDieMap.insert(std::make_pair(Desc, 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,
177 if (!DD->useSplitDwarf()) {
178 MCSymbol *Symb = DU->getStringPoolEntry(String);
179 if (Asm->needsRelocationsForDwarfStringPool())
180 Value = new (DIEValueAllocator) DIELabel(Symb);
182 MCSymbol *StringPool = DU->getStringPoolSym();
183 Value = new (DIEValueAllocator) DIEDelta(Symb, StringPool);
185 Form = dwarf::DW_FORM_strp;
187 unsigned idx = DU->getStringPoolIndex(String);
188 Value = new (DIEValueAllocator) DIEInteger(idx);
189 Form = dwarf::DW_FORM_GNU_str_index;
191 DIEValue *Str = new (DIEValueAllocator) DIEString(Value, String);
192 Die->addValue(Attribute, Form, Str);
195 /// addLocalString - Add a string attribute data and value. This is guaranteed
196 /// to be in the local string pool instead of indirected.
197 void CompileUnit::addLocalString(DIE *Die, dwarf::Attribute Attribute,
199 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 Die->addValue(Attribute, dwarf::DW_FORM_strp, Value);
210 /// addExpr - Add a Dwarf expression attribute data and value.
212 void CompileUnit::addExpr(DIEBlock *Die, dwarf::Form Form, const MCExpr *Expr) {
213 DIEValue *Value = new (DIEValueAllocator) DIEExpr(Expr);
214 Die->addValue((dwarf::Attribute)0, Form, Value);
217 /// addLabel - Add a Dwarf label attribute data and value.
219 void CompileUnit::addLabel(DIE *Die, dwarf::Attribute Attribute,
220 dwarf::Form Form, const MCSymbol *Label) {
221 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
222 Die->addValue(Attribute, Form, Value);
225 void CompileUnit::addLabel(DIEBlock *Die, dwarf::Form Form,
226 const MCSymbol *Label) {
227 addLabel(Die, (dwarf::Attribute)0, Form, Label);
230 /// addSectionLabel - Add a Dwarf section label attribute data and value.
232 void CompileUnit::addSectionLabel(DIE *Die, dwarf::Attribute Attribute,
233 const MCSymbol *Label) {
234 if (DD->getDwarfVersion() >= 4)
235 addLabel(Die, Attribute, dwarf::DW_FORM_sec_offset, Label);
237 addLabel(Die, Attribute, dwarf::DW_FORM_data4, Label);
240 /// addSectionOffset - Add an offset into a section attribute data and value.
242 void CompileUnit::addSectionOffset(DIE *Die, dwarf::Attribute Attribute,
244 if (DD->getDwarfVersion() >= 4)
245 addUInt(Die, Attribute, dwarf::DW_FORM_sec_offset, Integer);
247 addUInt(Die, Attribute, dwarf::DW_FORM_data4, Integer);
250 /// addLabelAddress - Add a dwarf label attribute data and value using
251 /// DW_FORM_addr or DW_FORM_GNU_addr_index.
253 void CompileUnit::addLabelAddress(DIE *Die, dwarf::Attribute Attribute,
256 DD->addArangeLabel(SymbolCU(this, Label));
258 if (!DD->useSplitDwarf()) {
260 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
261 Die->addValue(Attribute, dwarf::DW_FORM_addr, Value);
263 DIEValue *Value = new (DIEValueAllocator) DIEInteger(0);
264 Die->addValue(Attribute, dwarf::DW_FORM_addr, Value);
267 unsigned idx = DU->getAddrPoolIndex(Label);
268 DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
269 Die->addValue(Attribute, dwarf::DW_FORM_GNU_addr_index, Value);
273 /// addOpAddress - Add a dwarf op address data and value using the
274 /// form given and an op of either DW_FORM_addr or DW_FORM_GNU_addr_index.
276 void CompileUnit::addOpAddress(DIEBlock *Die, const MCSymbol *Sym) {
277 DD->addArangeLabel(SymbolCU(this, Sym));
278 if (!DD->useSplitDwarf()) {
279 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
280 addLabel(Die, dwarf::DW_FORM_udata, Sym);
282 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index);
283 addUInt(Die, dwarf::DW_FORM_GNU_addr_index, DU->getAddrPoolIndex(Sym));
287 /// addSectionDelta - Add a section label delta attribute data and value.
289 void CompileUnit::addSectionDelta(DIE *Die, dwarf::Attribute Attribute,
290 const MCSymbol *Hi, const MCSymbol *Lo) {
291 DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
292 if (DD->getDwarfVersion() >= 4)
293 Die->addValue(Attribute, dwarf::DW_FORM_sec_offset, Value);
295 Die->addValue(Attribute, dwarf::DW_FORM_data4, Value);
298 /// addDIEEntry - Add a DIE attribute data and value.
300 void CompileUnit::addDIEEntry(DIE *Die, dwarf::Attribute Attribute,
302 addDIEEntry(Die, Attribute, createDIEEntry(Entry));
305 void CompileUnit::addDIEEntry(DIE *Die, dwarf::Attribute Attribute,
307 const DIE *DieCU = Die->getCompileUnitOrNull();
308 const DIE *EntryCU = Entry->getEntry()->getCompileUnitOrNull();
310 // We assume that Die belongs to this CU, if it is not linked to any CU yet.
313 EntryCU = getCUDie();
314 Die->addValue(Attribute, EntryCU == DieCU ? dwarf::DW_FORM_ref4
315 : dwarf::DW_FORM_ref_addr,
319 /// Create a DIE with the given Tag, add the DIE to its parent, and
320 /// call insertDIE if MD is not null.
321 DIE *CompileUnit::createAndAddDIE(unsigned Tag, DIE &Parent, DIDescriptor N) {
322 DIE *Die = new DIE(Tag);
323 Parent.addChild(Die);
329 /// addBlock - Add block data.
331 void CompileUnit::addBlock(DIE *Die, dwarf::Attribute Attribute,
333 Block->ComputeSize(Asm);
334 DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
335 Die->addValue(Attribute, Block->BestForm(), Block);
338 /// addSourceLine - Add location information to specified debug information
340 void CompileUnit::addSourceLine(DIE *Die, DIVariable V) {
345 unsigned Line = V.getLineNumber();
349 DD->getOrCreateSourceID(V.getContext().getFilename(),
350 V.getContext().getDirectory(), getUniqueID());
351 assert(FileID && "Invalid file id");
352 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
353 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
356 /// addSourceLine - Add location information to specified debug information
358 void CompileUnit::addSourceLine(DIE *Die, DIGlobalVariable G) {
359 // Verify global variable.
360 if (!G.isGlobalVariable())
363 unsigned Line = G.getLineNumber();
367 DD->getOrCreateSourceID(G.getFilename(), G.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 CompileUnit::addSourceLine(DIE *Die, DISubprogram SP) {
376 // Verify subprogram.
377 if (!SP.isSubprogram())
380 // If the line number is 0, don't add it.
381 unsigned Line = SP.getLineNumber();
385 unsigned FileID = DD->getOrCreateSourceID(SP.getFilename(), SP.getDirectory(),
387 assert(FileID && "Invalid file id");
388 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
389 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
392 /// addSourceLine - Add location information to specified debug information
394 void CompileUnit::addSourceLine(DIE *Die, DIType Ty) {
399 unsigned Line = Ty.getLineNumber();
402 unsigned FileID = DD->getOrCreateSourceID(Ty.getFilename(), Ty.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 CompileUnit::addSourceLine(DIE *Die, DIObjCProperty Ty) {
413 if (!Ty.isObjCProperty())
416 unsigned Line = Ty.getLineNumber();
419 DIFile File = Ty.getFile();
420 unsigned FileID = DD->getOrCreateSourceID(File.getFilename(),
421 File.getDirectory(), getUniqueID());
422 assert(FileID && "Invalid file id");
423 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
424 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
427 /// addSourceLine - Add location information to specified debug information
429 void CompileUnit::addSourceLine(DIE *Die, DINameSpace NS) {
434 unsigned Line = NS.getLineNumber();
437 StringRef FN = NS.getFilename();
440 DD->getOrCreateSourceID(FN, NS.getDirectory(), getUniqueID());
441 assert(FileID && "Invalid file id");
442 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
443 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
446 /// addVariableAddress - Add DW_AT_location attribute for a
447 /// DbgVariable based on provided MachineLocation.
448 void CompileUnit::addVariableAddress(const DbgVariable &DV, DIE *Die,
449 MachineLocation Location) {
450 if (DV.variableHasComplexAddress())
451 addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
452 else if (DV.isBlockByrefVariable())
453 addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location);
455 addAddress(Die, dwarf::DW_AT_location, Location,
456 DV.getVariable().isIndirect());
459 /// addRegisterOp - Add register operand.
460 void CompileUnit::addRegisterOp(DIEBlock *TheDie, unsigned Reg) {
461 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
462 unsigned DWReg = RI->getDwarfRegNum(Reg, false);
464 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + DWReg);
466 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
467 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
471 /// addRegisterOffset - Add register offset.
472 void CompileUnit::addRegisterOffset(DIEBlock *TheDie, unsigned Reg,
474 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
475 unsigned DWReg = RI->getDwarfRegNum(Reg, false);
476 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
477 if (Reg == TRI->getFrameRegister(*Asm->MF))
478 // If variable offset is based in frame register then use fbreg.
479 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_fbreg);
481 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + DWReg);
483 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
484 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
486 addSInt(TheDie, dwarf::DW_FORM_sdata, Offset);
489 /// addAddress - Add an address attribute to a die based on the location
491 void CompileUnit::addAddress(DIE *Die, dwarf::Attribute Attribute,
492 const MachineLocation &Location, bool Indirect) {
493 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
495 if (Location.isReg() && !Indirect)
496 addRegisterOp(Block, Location.getReg());
498 addRegisterOffset(Block, Location.getReg(), Location.getOffset());
499 if (Indirect && !Location.isReg()) {
500 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
504 // Now attach the location information to the DIE.
505 addBlock(Die, Attribute, Block);
508 /// addComplexAddress - Start with the address based on the location provided,
509 /// and generate the DWARF information necessary to find the actual variable
510 /// given the extra address information encoded in the DIVariable, starting from
511 /// the starting location. Add the DWARF information to the die.
513 void CompileUnit::addComplexAddress(const DbgVariable &DV, DIE *Die,
514 dwarf::Attribute Attribute,
515 const MachineLocation &Location) {
516 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
517 unsigned N = DV.getNumAddrElements();
519 if (Location.isReg()) {
520 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
521 // If first address element is OpPlus then emit
522 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
523 addRegisterOffset(Block, Location.getReg(), DV.getAddrElement(1));
526 addRegisterOp(Block, Location.getReg());
528 addRegisterOffset(Block, Location.getReg(), Location.getOffset());
531 uint64_t Element = DV.getAddrElement(i);
532 if (Element == DIBuilder::OpPlus) {
533 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
534 addUInt(Block, dwarf::DW_FORM_udata, DV.getAddrElement(++i));
535 } else if (Element == DIBuilder::OpDeref) {
536 if (!Location.isReg())
537 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
539 llvm_unreachable("unknown DIBuilder Opcode");
542 // Now attach the location information to the DIE.
543 addBlock(Die, Attribute, Block);
546 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
547 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
548 gives the variable VarName either the struct, or a pointer to the struct, as
549 its type. This is necessary for various behind-the-scenes things the
550 compiler needs to do with by-reference variables in Blocks.
552 However, as far as the original *programmer* is concerned, the variable
553 should still have type 'SomeType', as originally declared.
555 The function getBlockByrefType dives into the __Block_byref_x_VarName
556 struct to find the original type of the variable, which is then assigned to
557 the variable's Debug Information Entry as its real type. So far, so good.
558 However now the debugger will expect the variable VarName to have the type
559 SomeType. So we need the location attribute for the variable to be an
560 expression that explains to the debugger how to navigate through the
561 pointers and struct to find the actual variable of type SomeType.
563 The following function does just that. We start by getting
564 the "normal" location for the variable. This will be the location
565 of either the struct __Block_byref_x_VarName or the pointer to the
566 struct __Block_byref_x_VarName.
568 The struct will look something like:
570 struct __Block_byref_x_VarName {
572 struct __Block_byref_x_VarName *forwarding;
573 ... <various other fields>
575 ... <maybe more fields>
578 If we are given the struct directly (as our starting point) we
579 need to tell the debugger to:
581 1). Add the offset of the forwarding field.
583 2). Follow that pointer to get the real __Block_byref_x_VarName
584 struct to use (the real one may have been copied onto the heap).
586 3). Add the offset for the field VarName, to find the actual variable.
588 If we started with a pointer to the struct, then we need to
589 dereference that pointer first, before the other steps.
590 Translating this into DWARF ops, we will need to append the following
591 to the current location description for the variable:
593 DW_OP_deref -- optional, if we start with a pointer
594 DW_OP_plus_uconst <forward_fld_offset>
596 DW_OP_plus_uconst <varName_fld_offset>
598 That is what this function does. */
600 /// addBlockByrefAddress - Start with the address based on the location
601 /// provided, and generate the DWARF information necessary to find the
602 /// actual Block variable (navigating the Block struct) based on the
603 /// starting location. Add the DWARF information to the die. For
604 /// more information, read large comment just above here.
606 void CompileUnit::addBlockByrefAddress(const DbgVariable &DV, DIE *Die,
607 dwarf::Attribute Attribute,
608 const MachineLocation &Location) {
609 DIType Ty = DV.getType();
611 uint16_t Tag = Ty.getTag();
612 bool isPointer = false;
614 StringRef varName = DV.getName();
616 if (Tag == dwarf::DW_TAG_pointer_type) {
617 DIDerivedType DTy(Ty);
618 TmpTy = resolve(DTy.getTypeDerivedFrom());
622 DICompositeType blockStruct(TmpTy);
624 // Find the __forwarding field and the variable field in the __Block_byref
626 DIArray Fields = blockStruct.getTypeArray();
627 DIDerivedType varField;
628 DIDerivedType forwardingField;
630 for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
631 DIDerivedType DT(Fields.getElement(i));
632 StringRef fieldName = DT.getName();
633 if (fieldName == "__forwarding")
634 forwardingField = DT;
635 else if (fieldName == varName)
639 // Get the offsets for the forwarding field and the variable field.
640 unsigned forwardingFieldOffset = forwardingField.getOffsetInBits() >> 3;
641 unsigned varFieldOffset = varField.getOffsetInBits() >> 2;
643 // Decode the original location, and use that as the start of the byref
644 // variable's location.
645 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
647 if (Location.isReg())
648 addRegisterOp(Block, Location.getReg());
650 addRegisterOffset(Block, Location.getReg(), Location.getOffset());
652 // If we started with a pointer to the __Block_byref... struct, then
653 // the first thing we need to do is dereference the pointer (DW_OP_deref).
655 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
657 // Next add the offset for the '__forwarding' field:
658 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
659 // adding the offset if it's 0.
660 if (forwardingFieldOffset > 0) {
661 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
662 addUInt(Block, dwarf::DW_FORM_udata, forwardingFieldOffset);
665 // Now dereference the __forwarding field to get to the real __Block_byref
666 // struct: DW_OP_deref.
667 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
669 // Now that we've got the real __Block_byref... struct, add the offset
670 // for the variable's field to get to the location of the actual variable:
671 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
672 if (varFieldOffset > 0) {
673 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
674 addUInt(Block, dwarf::DW_FORM_udata, varFieldOffset);
677 // Now attach the location information to the DIE.
678 addBlock(Die, Attribute, Block);
681 /// isTypeSigned - Return true if the type is signed.
682 static bool isTypeSigned(DwarfDebug *DD, DIType Ty, int *SizeInBits) {
683 if (Ty.isDerivedType())
684 return isTypeSigned(DD, DD->resolve(DIDerivedType(Ty).getTypeDerivedFrom()),
686 if (Ty.isBasicType())
687 if (DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed ||
688 DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed_char) {
689 *SizeInBits = Ty.getSizeInBits();
695 /// Return true if type encoding is unsigned.
696 static bool isUnsignedDIType(DwarfDebug *DD, DIType Ty) {
697 DIDerivedType DTy(Ty);
698 if (DTy.isDerivedType())
699 return isUnsignedDIType(DD, DD->resolve(DTy.getTypeDerivedFrom()));
702 if (BTy.isBasicType()) {
703 unsigned Encoding = BTy.getEncoding();
704 if (Encoding == dwarf::DW_ATE_unsigned ||
705 Encoding == dwarf::DW_ATE_unsigned_char ||
706 Encoding == dwarf::DW_ATE_boolean)
712 /// If this type is derived from a base type then return base type size.
713 static uint64_t getBaseTypeSize(DwarfDebug *DD, DIDerivedType Ty) {
714 unsigned Tag = Ty.getTag();
716 if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef &&
717 Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type &&
718 Tag != dwarf::DW_TAG_restrict_type)
719 return Ty.getSizeInBits();
721 DIType BaseType = DD->resolve(Ty.getTypeDerivedFrom());
723 // If this type is not derived from any type then take conservative approach.
724 if (!BaseType.isValid())
725 return Ty.getSizeInBits();
727 // If this is a derived type, go ahead and get the base type, unless it's a
728 // reference then it's just the size of the field. Pointer types have no need
729 // of this since they're a different type of qualification on the type.
730 if (BaseType.getTag() == dwarf::DW_TAG_reference_type ||
731 BaseType.getTag() == dwarf::DW_TAG_rvalue_reference_type)
732 return Ty.getSizeInBits();
734 if (BaseType.isDerivedType())
735 return getBaseTypeSize(DD, DIDerivedType(BaseType));
737 return BaseType.getSizeInBits();
740 /// addConstantValue - Add constant value entry in variable DIE.
741 void CompileUnit::addConstantValue(DIE *Die, const MachineOperand &MO,
743 // FIXME: This is a bit conservative/simple - it emits negative values at
744 // their maximum bit width which is a bit unfortunate (& doesn't prefer
745 // udata/sdata over dataN as suggested by the DWARF spec)
746 assert(MO.isImm() && "Invalid machine operand!");
748 bool SignedConstant = isTypeSigned(DD, Ty, &SizeInBits);
751 // If we're a signed constant definitely use sdata.
752 if (SignedConstant) {
753 addSInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, MO.getImm());
757 // Else use data for now unless it's larger than we can deal with.
758 switch (SizeInBits) {
760 Form = dwarf::DW_FORM_data1;
763 Form = dwarf::DW_FORM_data2;
766 Form = dwarf::DW_FORM_data4;
769 Form = dwarf::DW_FORM_data8;
772 Form = dwarf::DW_FORM_udata;
773 addUInt(Die, dwarf::DW_AT_const_value, Form, MO.getImm());
776 addUInt(Die, dwarf::DW_AT_const_value, Form, MO.getImm());
779 /// addConstantFPValue - Add constant value entry in variable DIE.
780 void CompileUnit::addConstantFPValue(DIE *Die, const MachineOperand &MO) {
781 assert(MO.isFPImm() && "Invalid machine operand!");
782 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
783 APFloat FPImm = MO.getFPImm()->getValueAPF();
785 // Get the raw data form of the floating point.
786 const APInt FltVal = FPImm.bitcastToAPInt();
787 const char *FltPtr = (const char *)FltVal.getRawData();
789 int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
790 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
791 int Incr = (LittleEndian ? 1 : -1);
792 int Start = (LittleEndian ? 0 : NumBytes - 1);
793 int Stop = (LittleEndian ? NumBytes : -1);
795 // Output the constant to DWARF one byte at a time.
796 for (; Start != Stop; Start += Incr)
797 addUInt(Block, dwarf::DW_FORM_data1, (unsigned char)0xFF & FltPtr[Start]);
799 addBlock(Die, dwarf::DW_AT_const_value, Block);
802 /// addConstantFPValue - Add constant value entry in variable DIE.
803 void CompileUnit::addConstantFPValue(DIE *Die, const ConstantFP *CFP) {
804 // Pass this down to addConstantValue as an unsigned bag of bits.
805 addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true);
808 /// addConstantValue - Add constant value entry in variable DIE.
809 void CompileUnit::addConstantValue(DIE *Die, const ConstantInt *CI,
811 addConstantValue(Die, CI->getValue(), Unsigned);
814 // addConstantValue - Add constant value entry in variable DIE.
815 void CompileUnit::addConstantValue(DIE *Die, const APInt &Val, bool Unsigned) {
816 unsigned CIBitWidth = Val.getBitWidth();
817 if (CIBitWidth <= 64) {
818 // If we're a signed constant definitely use sdata.
820 addSInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
825 // Else use data for now unless it's larger than we can deal with.
827 switch (CIBitWidth) {
829 Form = dwarf::DW_FORM_data1;
832 Form = dwarf::DW_FORM_data2;
835 Form = dwarf::DW_FORM_data4;
838 Form = dwarf::DW_FORM_data8;
841 addUInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_udata,
845 addUInt(Die, dwarf::DW_AT_const_value, Form, Val.getZExtValue());
849 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
851 // Get the raw data form of the large APInt.
852 const uint64_t *Ptr64 = Val.getRawData();
854 int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
855 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
857 // Output the constant to DWARF one byte at a time.
858 for (int i = 0; i < NumBytes; i++) {
861 c = Ptr64[i / 8] >> (8 * (i & 7));
863 c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
864 addUInt(Block, dwarf::DW_FORM_data1, c);
867 addBlock(Die, dwarf::DW_AT_const_value, Block);
870 /// addTemplateParams - Add template parameters into buffer.
871 void CompileUnit::addTemplateParams(DIE &Buffer, DIArray TParams) {
872 // Add template parameters.
873 for (unsigned i = 0, e = TParams.getNumElements(); i != e; ++i) {
874 DIDescriptor Element = TParams.getElement(i);
875 if (Element.isTemplateTypeParameter())
876 constructTemplateTypeParameterDIE(Buffer,
877 DITemplateTypeParameter(Element));
878 else if (Element.isTemplateValueParameter())
879 constructTemplateValueParameterDIE(Buffer,
880 DITemplateValueParameter(Element));
884 /// getOrCreateContextDIE - Get context owner's DIE.
885 DIE *CompileUnit::getOrCreateContextDIE(DIScope Context) {
886 if (!Context || Context.isFile())
888 if (Context.isType())
889 return getOrCreateTypeDIE(DIType(Context));
890 if (Context.isNameSpace())
891 return getOrCreateNameSpace(DINameSpace(Context));
892 if (Context.isSubprogram())
893 return getOrCreateSubprogramDIE(DISubprogram(Context));
894 return getDIE(Context);
897 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
899 DIE *CompileUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
906 // Construct the context before querying for the existence of the DIE in case
907 // such construction creates the DIE.
908 DIE *ContextDIE = getOrCreateContextDIE(resolve(Ty.getContext()));
911 DIE *TyDIE = getDIE(Ty);
916 TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
918 if (Ty.isBasicType())
919 constructTypeDIE(*TyDIE, DIBasicType(Ty));
920 else if (Ty.isCompositeType())
921 constructTypeDIE(*TyDIE, DICompositeType(Ty));
923 assert(Ty.isDerivedType() && "Unknown kind of DIType");
924 constructTypeDIE(*TyDIE, DIDerivedType(Ty));
926 // If this is a named finished type then include it in the list of types
927 // for the accelerator tables.
928 if (!Ty.getName().empty() && !Ty.isForwardDecl()) {
929 bool IsImplementation = 0;
930 if (Ty.isCompositeType()) {
931 DICompositeType CT(Ty);
932 // A runtime language of 0 actually means C/C++ and that any
933 // non-negative value is some version of Objective-C/C++.
934 IsImplementation = (CT.getRunTimeLang() == 0) || CT.isObjcClassComplete();
936 unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0;
937 addAccelType(Ty.getName(), std::make_pair(TyDIE, Flags));
943 /// addType - Add a new type attribute to the specified entity.
944 void CompileUnit::addType(DIE *Entity, DIType Ty, dwarf::Attribute Attribute) {
945 assert(Ty && "Trying to add a type that doesn't exist?");
947 // Check for pre-existence.
948 DIEEntry *Entry = getDIEEntry(Ty);
949 // If it exists then use the existing value.
951 addDIEEntry(Entity, Attribute, Entry);
956 DIE *Buffer = getOrCreateTypeDIE(Ty);
959 Entry = createDIEEntry(Buffer);
960 insertDIEEntry(Ty, Entry);
961 addDIEEntry(Entity, Attribute, Entry);
963 // If this is a complete composite type then include it in the
964 // list of global types.
968 // Accelerator table mutators - add each name along with its companion
969 // DIE to the proper table while ensuring that the name that we're going
970 // to reference is in the string table. We do this since the names we
971 // add may not only be identical to the names in the DIE.
972 void CompileUnit::addAccelName(StringRef Name, DIE *Die) {
973 DU->getStringPoolEntry(Name);
974 std::vector<DIE *> &DIEs = AccelNames[Name];
978 void CompileUnit::addAccelObjC(StringRef Name, DIE *Die) {
979 DU->getStringPoolEntry(Name);
980 std::vector<DIE *> &DIEs = AccelObjC[Name];
984 void CompileUnit::addAccelNamespace(StringRef Name, DIE *Die) {
985 DU->getStringPoolEntry(Name);
986 std::vector<DIE *> &DIEs = AccelNamespace[Name];
990 void CompileUnit::addAccelType(StringRef Name, std::pair<DIE *, unsigned> Die) {
991 DU->getStringPoolEntry(Name);
992 std::vector<std::pair<DIE *, unsigned> > &DIEs = AccelTypes[Name];
996 /// addGlobalName - Add a new global name to the compile unit.
997 void CompileUnit::addGlobalName(StringRef Name, DIE *Die, DIScope Context) {
998 std::string FullName = getParentContextString(Context) + Name.str();
999 GlobalNames[FullName] = Die;
1002 /// addGlobalType - Add a new global type to the compile unit.
1004 void CompileUnit::addGlobalType(DIType Ty) {
1005 DIScope Context = resolve(Ty.getContext());
1006 if (!Ty.getName().empty() && !Ty.isForwardDecl() &&
1007 (!Context || Context.isCompileUnit() || Context.isFile() ||
1008 Context.isNameSpace()))
1009 if (DIEEntry *Entry = getDIEEntry(Ty)) {
1010 std::string FullName =
1011 getParentContextString(Context) + Ty.getName().str();
1012 GlobalTypes[FullName] = Entry->getEntry();
1016 /// getParentContextString - Walks the metadata parent chain in a language
1017 /// specific manner (using the compile unit language) and returns
1018 /// it as a string. This is done at the metadata level because DIEs may
1019 /// not currently have been added to the parent context and walking the
1020 /// DIEs looking for names is more expensive than walking the metadata.
1021 std::string CompileUnit::getParentContextString(DIScope Context) const {
1025 // FIXME: Decide whether to implement this for non-C++ languages.
1026 if (getLanguage() != dwarf::DW_LANG_C_plus_plus)
1030 SmallVector<DIScope, 1> Parents;
1031 while (!Context.isCompileUnit()) {
1032 Parents.push_back(Context);
1033 if (Context.getContext())
1034 Context = resolve(Context.getContext());
1036 // Structure, etc types will have a NULL context if they're at the top
1041 // Reverse iterate over our list to go from the outermost construct to the
1043 for (SmallVectorImpl<DIScope>::reverse_iterator I = Parents.rbegin(),
1047 StringRef Name = Ctx.getName();
1048 if (!Name.empty()) {
1056 /// addPubTypes - Add subprogram argument types for pubtypes section.
1057 void CompileUnit::addPubTypes(DISubprogram SP) {
1058 DICompositeType SPTy = SP.getType();
1059 uint16_t SPTag = SPTy.getTag();
1060 if (SPTag != dwarf::DW_TAG_subroutine_type)
1063 DIArray Args = SPTy.getTypeArray();
1064 for (unsigned i = 0, e = Args.getNumElements(); i != e; ++i) {
1065 DIType ATy(Args.getElement(i));
1072 /// constructTypeDIE - Construct basic type die from DIBasicType.
1073 void CompileUnit::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
1074 // Get core information.
1075 StringRef Name = BTy.getName();
1076 // Add name if not anonymous or intermediate type.
1078 addString(&Buffer, dwarf::DW_AT_name, Name);
1080 // An unspecified type only has a name attribute.
1081 if (BTy.getTag() == dwarf::DW_TAG_unspecified_type)
1084 addUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1087 uint64_t Size = BTy.getSizeInBits() >> 3;
1088 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1091 /// constructTypeDIE - Construct derived type die from DIDerivedType.
1092 void CompileUnit::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
1093 // Get core information.
1094 StringRef Name = DTy.getName();
1095 uint64_t Size = DTy.getSizeInBits() >> 3;
1096 uint16_t Tag = Buffer.getTag();
1098 // Map to main type, void will not have a type.
1099 DIType FromTy = resolve(DTy.getTypeDerivedFrom());
1101 addType(&Buffer, FromTy);
1103 // Add name if not anonymous or intermediate type.
1105 addString(&Buffer, dwarf::DW_AT_name, Name);
1107 // Add size if non-zero (derived types might be zero-sized.)
1108 if (Size && Tag != dwarf::DW_TAG_pointer_type)
1109 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1111 if (Tag == dwarf::DW_TAG_ptr_to_member_type)
1112 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type,
1113 getOrCreateTypeDIE(resolve(DTy.getClassType())));
1114 // Add source line info if available and TyDesc is not a forward declaration.
1115 if (!DTy.isForwardDecl())
1116 addSourceLine(&Buffer, DTy);
1119 /// constructSubprogramArguments - Construct function argument DIEs.
1120 void CompileUnit::constructSubprogramArguments(DIE &Buffer, DIArray Args) {
1121 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1122 DIDescriptor Ty = Args.getElement(i);
1123 if (Ty.isUnspecifiedParameter()) {
1124 assert(i == N-1 && "ellipsis must be the last argument");
1125 createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
1127 DIE *Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
1128 addType(Arg, DIType(Ty));
1129 if (DIType(Ty).isArtificial())
1130 addFlag(Arg, dwarf::DW_AT_artificial);
1135 /// Return true if the type is appropriately scoped to be contained inside
1136 /// its own type unit.
1137 static bool isTypeUnitScoped(DIType Ty, const DwarfDebug *DD) {
1138 DIScope Parent = DD->resolve(Ty.getContext());
1140 // Don't generate a hash for anything scoped inside a function.
1141 if (Parent.isSubprogram())
1143 Parent = DD->resolve(Parent.getContext());
1148 /// Return true if the type should be split out into a type unit.
1149 static bool shouldCreateTypeUnit(DICompositeType CTy, const DwarfDebug *DD) {
1150 uint16_t Tag = CTy.getTag();
1153 case dwarf::DW_TAG_structure_type:
1154 case dwarf::DW_TAG_union_type:
1155 case dwarf::DW_TAG_enumeration_type:
1156 case dwarf::DW_TAG_class_type:
1157 // If this is a class, structure, union, or enumeration type
1158 // that is a definition (not a declaration), and not scoped
1159 // inside a function then separate this out as a type unit.
1160 return !CTy.isForwardDecl() && isTypeUnitScoped(CTy, DD);
1166 /// constructTypeDIE - Construct type DIE from DICompositeType.
1167 void CompileUnit::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
1168 // Get core information.
1169 StringRef Name = CTy.getName();
1171 uint64_t Size = CTy.getSizeInBits() >> 3;
1172 uint16_t Tag = Buffer.getTag();
1175 case dwarf::DW_TAG_array_type:
1176 constructArrayTypeDIE(Buffer, CTy);
1178 case dwarf::DW_TAG_enumeration_type:
1179 constructEnumTypeDIE(Buffer, CTy);
1181 case dwarf::DW_TAG_subroutine_type: {
1182 // Add return type. A void return won't have a type.
1183 DIArray Elements = CTy.getTypeArray();
1184 DIType RTy(Elements.getElement(0));
1186 addType(&Buffer, RTy);
1188 bool isPrototyped = true;
1189 if (Elements.getNumElements() == 2 &&
1190 Elements.getElement(1).isUnspecifiedParameter())
1191 isPrototyped = false;
1193 constructSubprogramArguments(Buffer, Elements);
1195 // Add prototype flag if we're dealing with a C language and the
1196 // function has been prototyped.
1197 uint16_t Language = getLanguage();
1199 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1200 Language == dwarf::DW_LANG_ObjC))
1201 addFlag(&Buffer, dwarf::DW_AT_prototyped);
1203 case dwarf::DW_TAG_structure_type:
1204 case dwarf::DW_TAG_union_type:
1205 case dwarf::DW_TAG_class_type: {
1206 // Add elements to structure type.
1207 DIArray Elements = CTy.getTypeArray();
1208 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1209 DIDescriptor Element = Elements.getElement(i);
1210 DIE *ElemDie = NULL;
1211 if (Element.isSubprogram()) {
1212 DISubprogram SP(Element);
1213 ElemDie = getOrCreateSubprogramDIE(SP);
1214 if (SP.isProtected())
1215 addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1216 dwarf::DW_ACCESS_protected);
1217 else if (SP.isPrivate())
1218 addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1219 dwarf::DW_ACCESS_private);
1221 addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1222 dwarf::DW_ACCESS_public);
1223 if (SP.isExplicit())
1224 addFlag(ElemDie, dwarf::DW_AT_explicit);
1225 } else if (Element.isDerivedType()) {
1226 DIDerivedType DDTy(Element);
1227 if (DDTy.getTag() == dwarf::DW_TAG_friend) {
1228 ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
1229 addType(ElemDie, resolve(DDTy.getTypeDerivedFrom()),
1230 dwarf::DW_AT_friend);
1231 } else if (DDTy.isStaticMember()) {
1232 getOrCreateStaticMemberDIE(DDTy);
1234 constructMemberDIE(Buffer, DDTy);
1236 } else if (Element.isObjCProperty()) {
1237 DIObjCProperty Property(Element);
1238 ElemDie = createAndAddDIE(Property.getTag(), Buffer);
1239 StringRef PropertyName = Property.getObjCPropertyName();
1240 addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
1241 addType(ElemDie, Property.getType());
1242 addSourceLine(ElemDie, Property);
1243 StringRef GetterName = Property.getObjCPropertyGetterName();
1244 if (!GetterName.empty())
1245 addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
1246 StringRef SetterName = Property.getObjCPropertySetterName();
1247 if (!SetterName.empty())
1248 addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
1249 unsigned PropertyAttributes = 0;
1250 if (Property.isReadOnlyObjCProperty())
1251 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readonly;
1252 if (Property.isReadWriteObjCProperty())
1253 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readwrite;
1254 if (Property.isAssignObjCProperty())
1255 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_assign;
1256 if (Property.isRetainObjCProperty())
1257 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_retain;
1258 if (Property.isCopyObjCProperty())
1259 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_copy;
1260 if (Property.isNonAtomicObjCProperty())
1261 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_nonatomic;
1262 if (PropertyAttributes)
1263 addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None,
1264 PropertyAttributes);
1266 DIEEntry *Entry = getDIEEntry(Element);
1268 Entry = createDIEEntry(ElemDie);
1269 insertDIEEntry(Element, Entry);
1275 if (CTy.isAppleBlockExtension())
1276 addFlag(&Buffer, dwarf::DW_AT_APPLE_block);
1278 DICompositeType ContainingType(resolve(CTy.getContainingType()));
1280 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type,
1281 getOrCreateTypeDIE(ContainingType));
1283 if (CTy.isObjcClassComplete())
1284 addFlag(&Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
1286 // Add template parameters to a class, structure or union types.
1287 // FIXME: The support isn't in the metadata for this yet.
1288 if (Tag == dwarf::DW_TAG_class_type ||
1289 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
1290 addTemplateParams(Buffer, CTy.getTemplateParams());
1298 // Add name if not anonymous or intermediate type.
1300 addString(&Buffer, dwarf::DW_AT_name, Name);
1302 if (Tag == dwarf::DW_TAG_enumeration_type ||
1303 Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
1304 Tag == dwarf::DW_TAG_union_type) {
1305 // Add size if non-zero (derived types might be zero-sized.)
1306 // TODO: Do we care about size for enum forward declarations?
1308 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1309 else if (!CTy.isForwardDecl())
1310 // Add zero size if it is not a forward declaration.
1311 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, 0);
1313 // If we're a forward decl, say so.
1314 if (CTy.isForwardDecl())
1315 addFlag(&Buffer, dwarf::DW_AT_declaration);
1317 // Add source line info if available.
1318 if (!CTy.isForwardDecl())
1319 addSourceLine(&Buffer, CTy);
1321 // No harm in adding the runtime language to the declaration.
1322 unsigned RLang = CTy.getRunTimeLang();
1324 addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
1327 // If this is a type applicable to a type unit it then add it to the
1328 // list of types we'll compute a hash for later.
1329 if (shouldCreateTypeUnit(CTy, DD))
1330 DD->addTypeUnitType(&Buffer);
1333 /// constructTemplateTypeParameterDIE - Construct new DIE for the given
1334 /// DITemplateTypeParameter.
1336 CompileUnit::constructTemplateTypeParameterDIE(DIE &Buffer,
1337 DITemplateTypeParameter TP) {
1339 createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
1340 // Add the type if it exists, it could be void and therefore no type.
1342 addType(ParamDIE, resolve(TP.getType()));
1343 if (!TP.getName().empty())
1344 addString(ParamDIE, dwarf::DW_AT_name, TP.getName());
1347 /// constructTemplateValueParameterDIE - Construct new DIE for the given
1348 /// DITemplateValueParameter.
1350 CompileUnit::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 *CompileUnit::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 *CompileUnit::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 = CUDie.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 constructSubprogramArguments(*SPDie, Args);
1490 if (SP.isArtificial())
1491 addFlag(SPDie, dwarf::DW_AT_artificial);
1493 if (!SP.isLocalToUnit())
1494 addFlag(SPDie, dwarf::DW_AT_external);
1496 if (SP.isOptimized())
1497 addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1499 if (unsigned isa = Asm->getISAEncoding()) {
1500 addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1506 // Return const expression if value is a GEP to access merged global
1508 // i8* getelementptr ({ i8, i8, i8, i8 }* @_MergedGlobals, i32 0, i32 0)
1509 static const ConstantExpr *getMergedGlobalExpr(const Value *V) {
1510 const ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(V);
1511 if (!CE || CE->getNumOperands() != 3 ||
1512 CE->getOpcode() != Instruction::GetElementPtr)
1515 // First operand points to a global struct.
1516 Value *Ptr = CE->getOperand(0);
1517 if (!isa<GlobalValue>(Ptr) ||
1518 !isa<StructType>(cast<PointerType>(Ptr->getType())->getElementType()))
1521 // Second operand is zero.
1522 const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(CE->getOperand(1));
1523 if (!CI || !CI->isZero())
1526 // Third operand is offset.
1527 if (!isa<ConstantInt>(CE->getOperand(2)))
1533 /// createGlobalVariableDIE - create global variable DIE.
1534 void CompileUnit::createGlobalVariableDIE(DIGlobalVariable GV) {
1536 // Check for pre-existence.
1540 if (!GV.isGlobalVariable())
1543 DIScope GVContext = GV.getContext();
1544 DIType GTy = GV.getType();
1546 // If this is a static data member definition, some attributes belong
1547 // to the declaration DIE.
1548 DIE *VariableDIE = NULL;
1549 bool IsStaticMember = false;
1550 DIDerivedType SDMDecl = GV.getStaticDataMemberDeclaration();
1551 if (SDMDecl.Verify()) {
1552 assert(SDMDecl.isStaticMember() && "Expected static member decl");
1553 // We need the declaration DIE that is in the static member's class.
1554 VariableDIE = getOrCreateStaticMemberDIE(SDMDecl);
1555 IsStaticMember = true;
1558 // If this is not a static data member definition, create the variable
1559 // DIE and add the initial set of attributes to it.
1561 // Construct the context before querying for the existence of the DIE in
1562 // case such construction creates the DIE.
1563 DIE *ContextDIE = getOrCreateContextDIE(GVContext);
1566 VariableDIE = createAndAddDIE(GV.getTag(), *ContextDIE, GV);
1568 // Add name and type.
1569 addString(VariableDIE, dwarf::DW_AT_name, GV.getDisplayName());
1570 addType(VariableDIE, GTy);
1572 // Add scoping info.
1573 if (!GV.isLocalToUnit())
1574 addFlag(VariableDIE, dwarf::DW_AT_external);
1576 // Add line number info.
1577 addSourceLine(VariableDIE, GV);
1581 bool addToAccelTable = false;
1582 DIE *VariableSpecDIE = NULL;
1583 bool isGlobalVariable = GV.getGlobal() != NULL;
1584 if (isGlobalVariable) {
1585 addToAccelTable = true;
1586 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1587 const MCSymbol *Sym = Asm->getSymbol(GV.getGlobal());
1588 if (GV.getGlobal()->isThreadLocal()) {
1589 // FIXME: Make this work with -gsplit-dwarf.
1590 unsigned PointerSize = Asm->getDataLayout().getPointerSize();
1591 assert((PointerSize == 4 || PointerSize == 8) &&
1592 "Add support for other sizes if necessary");
1593 const MCExpr *Expr =
1594 Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym);
1595 // Based on GCC's support for TLS:
1596 if (!DD->useSplitDwarf()) {
1597 // 1) Start with a constNu of the appropriate pointer size
1598 addUInt(Block, dwarf::DW_FORM_data1,
1599 PointerSize == 4 ? dwarf::DW_OP_const4u : dwarf::DW_OP_const8u);
1600 // 2) containing the (relocated) offset of the TLS variable
1601 // within the module's TLS block.
1602 addExpr(Block, dwarf::DW_FORM_udata, Expr);
1604 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
1605 addUInt(Block, dwarf::DW_FORM_udata, DU->getAddrPoolIndex(Expr));
1607 // 3) followed by a custom OP to make the debugger do a TLS lookup.
1608 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_push_tls_address);
1610 addOpAddress(Block, Sym);
1611 // Do not create specification DIE if context is either compile unit
1613 if (GVContext && GV.isDefinition() && !GVContext.isCompileUnit() &&
1614 !GVContext.isFile() && !DD->isSubprogramContext(GVContext)) {
1615 // Create specification DIE.
1616 VariableSpecDIE = createAndAddDIE(dwarf::DW_TAG_variable, *CUDie);
1617 addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification, VariableDIE);
1618 addBlock(VariableSpecDIE, dwarf::DW_AT_location, Block);
1619 // A static member's declaration is already flagged as such.
1620 if (!SDMDecl.Verify())
1621 addFlag(VariableDIE, dwarf::DW_AT_declaration);
1623 addBlock(VariableDIE, dwarf::DW_AT_location, Block);
1625 // Add the linkage name.
1626 StringRef LinkageName = GV.getLinkageName();
1627 if (!LinkageName.empty())
1628 // From DWARF4: DIEs to which DW_AT_linkage_name may apply include:
1629 // TAG_common_block, TAG_constant, TAG_entry_point, TAG_subprogram and
1631 addString(IsStaticMember && VariableSpecDIE ? VariableSpecDIE
1633 dwarf::DW_AT_MIPS_linkage_name,
1634 GlobalValue::getRealLinkageName(LinkageName));
1635 } else if (const ConstantInt *CI =
1636 dyn_cast_or_null<ConstantInt>(GV.getConstant())) {
1637 // AT_const_value was added when the static member was created. To avoid
1638 // emitting AT_const_value multiple times, we only add AT_const_value when
1639 // it is not a static member.
1640 if (!IsStaticMember)
1641 addConstantValue(VariableDIE, CI, isUnsignedDIType(DD, GTy));
1642 } else if (const ConstantExpr *CE = getMergedGlobalExpr(GV->getOperand(11))) {
1643 addToAccelTable = true;
1644 // GV is a merged global.
1645 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1646 Value *Ptr = CE->getOperand(0);
1647 addOpAddress(Block, Asm->getSymbol(cast<GlobalValue>(Ptr)));
1648 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1649 SmallVector<Value *, 3> Idx(CE->op_begin() + 1, CE->op_end());
1650 addUInt(Block, dwarf::DW_FORM_udata,
1651 Asm->getDataLayout().getIndexedOffset(Ptr->getType(), Idx));
1652 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1653 addBlock(VariableDIE, dwarf::DW_AT_location, Block);
1656 if (addToAccelTable) {
1657 DIE *AddrDIE = VariableSpecDIE ? VariableSpecDIE : VariableDIE;
1658 addAccelName(GV.getName(), AddrDIE);
1660 // If the linkage name is different than the name, go ahead and output
1661 // that as well into the name table.
1662 if (GV.getLinkageName() != "" && GV.getName() != GV.getLinkageName())
1663 addAccelName(GV.getLinkageName(), AddrDIE);
1666 if (!GV.isLocalToUnit())
1667 addGlobalName(GV.getName(), VariableSpecDIE ? VariableSpecDIE : VariableDIE,
1671 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
1672 void CompileUnit::constructSubrangeDIE(DIE &Buffer, DISubrange SR,
1674 DIE *DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
1675 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, IndexTy);
1677 // The LowerBound value defines the lower bounds which is typically zero for
1678 // C/C++. The Count value is the number of elements. Values are 64 bit. If
1679 // Count == -1 then the array is unbounded and we do not emit
1680 // DW_AT_lower_bound and DW_AT_upper_bound attributes. If LowerBound == 0 and
1681 // Count == 0, then the array has zero elements in which case we do not emit
1683 int64_t LowerBound = SR.getLo();
1684 int64_t DefaultLowerBound = getDefaultLowerBound();
1685 int64_t Count = SR.getCount();
1687 if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
1688 addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound);
1690 if (Count != -1 && Count != 0)
1691 // FIXME: An unbounded array should reference the expression that defines
1693 addUInt(DW_Subrange, dwarf::DW_AT_upper_bound, None,
1694 LowerBound + Count - 1);
1697 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
1698 void CompileUnit::constructArrayTypeDIE(DIE &Buffer, DICompositeType CTy) {
1700 addFlag(&Buffer, dwarf::DW_AT_GNU_vector);
1702 // Emit the element type.
1703 addType(&Buffer, resolve(CTy.getTypeDerivedFrom()));
1705 // Get an anonymous type for index type.
1706 // FIXME: This type should be passed down from the front end
1707 // as different languages may have different sizes for indexes.
1708 DIE *IdxTy = getIndexTyDie();
1710 // Construct an anonymous type for index type.
1711 IdxTy = createAndAddDIE(dwarf::DW_TAG_base_type, *CUDie.get());
1712 addString(IdxTy, dwarf::DW_AT_name, "int");
1713 addUInt(IdxTy, dwarf::DW_AT_byte_size, None, sizeof(int32_t));
1714 addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1715 dwarf::DW_ATE_signed);
1716 setIndexTyDie(IdxTy);
1719 // Add subranges to array type.
1720 DIArray Elements = CTy.getTypeArray();
1721 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1722 DIDescriptor Element = Elements.getElement(i);
1723 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1724 constructSubrangeDIE(Buffer, DISubrange(Element), IdxTy);
1728 /// constructEnumTypeDIE - Construct an enum type DIE from DICompositeType.
1729 void CompileUnit::constructEnumTypeDIE(DIE &Buffer, DICompositeType CTy) {
1730 DIArray Elements = CTy.getTypeArray();
1732 // Add enumerators to enumeration type.
1733 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1734 DIEnumerator Enum(Elements.getElement(i));
1735 if (Enum.isEnumerator()) {
1736 DIE *Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
1737 StringRef Name = Enum.getName();
1738 addString(Enumerator, dwarf::DW_AT_name, Name);
1739 int64_t Value = Enum.getEnumValue();
1740 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, Value);
1743 DIType DTy = resolve(CTy.getTypeDerivedFrom());
1745 addType(&Buffer, DTy);
1746 addFlag(&Buffer, dwarf::DW_AT_enum_class);
1750 /// constructContainingTypeDIEs - Construct DIEs for types that contain
1752 void CompileUnit::constructContainingTypeDIEs() {
1753 for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(),
1754 CE = ContainingTypeMap.end();
1756 DIE *SPDie = CI->first;
1757 DIDescriptor D(CI->second);
1760 DIE *NDie = getDIE(D);
1763 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, NDie);
1767 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
1768 DIE *CompileUnit::constructVariableDIE(DbgVariable &DV, bool isScopeAbstract) {
1769 StringRef Name = DV.getName();
1771 // Define variable debug information entry.
1772 DIE *VariableDie = new DIE(DV.getTag());
1773 DbgVariable *AbsVar = DV.getAbstractVariable();
1774 DIE *AbsDIE = AbsVar ? AbsVar->getDIE() : NULL;
1776 addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin, AbsDIE);
1779 addString(VariableDie, dwarf::DW_AT_name, Name);
1780 addSourceLine(VariableDie, DV.getVariable());
1781 addType(VariableDie, DV.getType());
1784 if (DV.isArtificial())
1785 addFlag(VariableDie, dwarf::DW_AT_artificial);
1787 if (isScopeAbstract) {
1788 DV.setDIE(VariableDie);
1792 // Add variable address.
1794 unsigned Offset = DV.getDotDebugLocOffset();
1795 if (Offset != ~0U) {
1796 addSectionLabel(VariableDie, dwarf::DW_AT_location,
1797 Asm->GetTempSymbol("debug_loc", Offset));
1798 DV.setDIE(VariableDie);
1802 // Check if variable is described by a DBG_VALUE instruction.
1803 if (const MachineInstr *DVInsn = DV.getMInsn()) {
1804 assert(DVInsn->getNumOperands() == 3);
1805 if (DVInsn->getOperand(0).isReg()) {
1806 const MachineOperand RegOp = DVInsn->getOperand(0);
1807 // If the second operand is an immediate, this is an indirect value.
1808 if (DVInsn->getOperand(1).isImm()) {
1809 MachineLocation Location(RegOp.getReg(),
1810 DVInsn->getOperand(1).getImm());
1811 addVariableAddress(DV, VariableDie, Location);
1812 } else if (RegOp.getReg())
1813 addVariableAddress(DV, VariableDie, MachineLocation(RegOp.getReg()));
1814 } else if (DVInsn->getOperand(0).isImm())
1815 addConstantValue(VariableDie, DVInsn->getOperand(0), DV.getType());
1816 else if (DVInsn->getOperand(0).isFPImm())
1817 addConstantFPValue(VariableDie, DVInsn->getOperand(0));
1818 else if (DVInsn->getOperand(0).isCImm())
1819 addConstantValue(VariableDie, DVInsn->getOperand(0).getCImm(),
1820 isUnsignedDIType(DD, DV.getType()));
1822 DV.setDIE(VariableDie);
1825 // .. else use frame index.
1826 int FI = DV.getFrameIndex();
1828 unsigned FrameReg = 0;
1829 const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
1830 int Offset = TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
1831 MachineLocation Location(FrameReg, Offset);
1832 addVariableAddress(DV, VariableDie, Location);
1836 DV.setDIE(VariableDie);
1840 /// constructMemberDIE - Construct member DIE from DIDerivedType.
1841 void CompileUnit::constructMemberDIE(DIE &Buffer, DIDerivedType DT) {
1842 DIE *MemberDie = createAndAddDIE(DT.getTag(), Buffer);
1843 StringRef Name = DT.getName();
1845 addString(MemberDie, dwarf::DW_AT_name, Name);
1847 addType(MemberDie, resolve(DT.getTypeDerivedFrom()));
1849 addSourceLine(MemberDie, DT);
1851 if (DT.getTag() == dwarf::DW_TAG_inheritance && DT.isVirtual()) {
1853 // For C++, virtual base classes are not at fixed offset. Use following
1854 // expression to extract appropriate offset from vtable.
1855 // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1857 DIEBlock *VBaseLocationDie = new (DIEValueAllocator) DIEBlock();
1858 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1859 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1860 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1861 addUInt(VBaseLocationDie, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1862 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1863 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1864 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1866 addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
1868 uint64_t Size = DT.getSizeInBits();
1869 uint64_t FieldSize = getBaseTypeSize(DD, DT);
1870 uint64_t OffsetInBytes;
1872 if (Size != FieldSize) {
1874 addUInt(MemberDie, dwarf::DW_AT_byte_size, None,
1875 getBaseTypeSize(DD, DT) >> 3);
1876 addUInt(MemberDie, dwarf::DW_AT_bit_size, None, DT.getSizeInBits());
1878 uint64_t Offset = DT.getOffsetInBits();
1879 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1880 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1881 uint64_t FieldOffset = (HiMark - FieldSize);
1882 Offset -= FieldOffset;
1884 // Maybe we need to work from the other end.
1885 if (Asm->getDataLayout().isLittleEndian())
1886 Offset = FieldSize - (Offset + Size);
1887 addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset);
1889 // Here WD_AT_data_member_location points to the anonymous
1890 // field that includes this bit field.
1891 OffsetInBytes = FieldOffset >> 3;
1893 // This is not a bitfield.
1894 OffsetInBytes = DT.getOffsetInBits() >> 3;
1896 if (DD->getDwarfVersion() <= 2) {
1897 DIEBlock *MemLocationDie = new (DIEValueAllocator) DIEBlock();
1898 addUInt(MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1899 addUInt(MemLocationDie, dwarf::DW_FORM_udata, OffsetInBytes);
1900 addBlock(MemberDie, dwarf::DW_AT_data_member_location, MemLocationDie);
1902 addUInt(MemberDie, dwarf::DW_AT_data_member_location, None,
1906 if (DT.isProtected())
1907 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1908 dwarf::DW_ACCESS_protected);
1909 else if (DT.isPrivate())
1910 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1911 dwarf::DW_ACCESS_private);
1912 // Otherwise C++ member and base classes are considered public.
1914 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1915 dwarf::DW_ACCESS_public);
1917 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1918 dwarf::DW_VIRTUALITY_virtual);
1920 // Objective-C properties.
1921 if (MDNode *PNode = DT.getObjCProperty())
1922 if (DIEEntry *PropertyDie = getDIEEntry(PNode))
1923 MemberDie->addValue(dwarf::DW_AT_APPLE_property, dwarf::DW_FORM_ref4,
1926 if (DT.isArtificial())
1927 addFlag(MemberDie, dwarf::DW_AT_artificial);
1930 /// getOrCreateStaticMemberDIE - Create new DIE for C++ static member.
1931 DIE *CompileUnit::getOrCreateStaticMemberDIE(DIDerivedType DT) {
1935 // Construct the context before querying for the existence of the DIE in case
1936 // such construction creates the DIE.
1937 DIE *ContextDIE = getOrCreateContextDIE(resolve(DT.getContext()));
1938 assert(dwarf::isType(ContextDIE->getTag()) &&
1939 "Static member should belong to a type.");
1941 DIE *StaticMemberDIE = getDIE(DT);
1942 if (StaticMemberDIE)
1943 return StaticMemberDIE;
1945 StaticMemberDIE = createAndAddDIE(DT.getTag(), *ContextDIE, DT);
1947 DIType Ty = resolve(DT.getTypeDerivedFrom());
1949 addString(StaticMemberDIE, dwarf::DW_AT_name, DT.getName());
1950 addType(StaticMemberDIE, Ty);
1951 addSourceLine(StaticMemberDIE, DT);
1952 addFlag(StaticMemberDIE, dwarf::DW_AT_external);
1953 addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
1955 // FIXME: We could omit private if the parent is a class_type, and
1956 // public if the parent is something else.
1957 if (DT.isProtected())
1958 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1959 dwarf::DW_ACCESS_protected);
1960 else if (DT.isPrivate())
1961 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1962 dwarf::DW_ACCESS_private);
1964 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1965 dwarf::DW_ACCESS_public);
1967 if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT.getConstant()))
1968 addConstantValue(StaticMemberDIE, CI, isUnsignedDIType(DD, Ty));
1969 if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT.getConstant()))
1970 addConstantFPValue(StaticMemberDIE, CFP);
1972 return StaticMemberDIE;
1975 void CompileUnit::emitHeader(const MCSection *ASection,
1976 const MCSymbol *ASectionSym) {
1977 Asm->OutStreamer.AddComment("DWARF version number");
1978 Asm->EmitInt16(DD->getDwarfVersion());
1979 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
1980 Asm->EmitSectionOffset(Asm->GetTempSymbol(ASection->getLabelBeginName()),
1982 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1983 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());