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 #include "DwarfUnit.h"
15 #include "DwarfAccelTable.h"
16 #include "DwarfDebug.h"
17 #include "llvm/ADT/APFloat.h"
18 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/DIBuilder.h"
20 #include "llvm/IR/DataLayout.h"
21 #include "llvm/IR/GlobalVariable.h"
22 #include "llvm/IR/Instructions.h"
23 #include "llvm/IR/Mangler.h"
24 #include "llvm/MC/MCAsmInfo.h"
25 #include "llvm/MC/MCContext.h"
26 #include "llvm/MC/MCSection.h"
27 #include "llvm/MC/MCStreamer.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Target/TargetFrameLowering.h"
30 #include "llvm/Target/TargetLoweringObjectFile.h"
31 #include "llvm/Target/TargetMachine.h"
32 #include "llvm/Target/TargetRegisterInfo.h"
36 #define DEBUG_TYPE "dwarfdebug"
39 GenerateDwarfTypeUnits("generate-type-units", cl::Hidden,
40 cl::desc("Generate DWARF4 type units."),
43 /// Unit - Unit constructor.
44 DwarfUnit::DwarfUnit(unsigned UID, DIE *D, DICompileUnit Node, AsmPrinter *A,
45 DwarfDebug *DW, DwarfFile *DWU)
46 : UniqueID(UID), CUNode(Node), UnitDie(D), DebugInfoOffset(0), Asm(A),
47 DD(DW), DU(DWU), IndexTyDie(0), Section(0), Skeleton(0) {
48 DIEIntegerOne = new (DIEValueAllocator) DIEInteger(1);
51 DwarfCompileUnit::DwarfCompileUnit(unsigned UID, DIE *D, DICompileUnit Node,
52 AsmPrinter *A, DwarfDebug *DW,
54 : DwarfUnit(UID, D, Node, A, DW, DWU) {
58 DwarfTypeUnit::DwarfTypeUnit(unsigned UID, DIE *D, DwarfCompileUnit &CU,
59 AsmPrinter *A, DwarfDebug *DW, DwarfFile *DWU,
60 MCDwarfDwoLineTable *SplitLineTable)
61 : DwarfUnit(UID, D, CU.getCUNode(), A, DW, DWU), CU(CU),
62 SplitLineTable(SplitLineTable) {
64 addSectionOffset(UnitDie.get(), dwarf::DW_AT_stmt_list, 0);
67 /// ~Unit - Destructor for compile unit.
68 DwarfUnit::~DwarfUnit() {
69 for (unsigned j = 0, M = DIEBlocks.size(); j < M; ++j)
70 DIEBlocks[j]->~DIEBlock();
71 for (unsigned j = 0, M = DIELocs.size(); j < M; ++j)
72 DIELocs[j]->~DIELoc();
75 /// createDIEEntry - Creates a new DIEEntry to be a proxy for a debug
76 /// information entry.
77 DIEEntry *DwarfUnit::createDIEEntry(DIE *Entry) {
78 DIEEntry *Value = new (DIEValueAllocator) DIEEntry(Entry);
82 /// getDefaultLowerBound - Return the default lower bound for an array. If the
83 /// DWARF version doesn't handle the language, return -1.
84 int64_t DwarfUnit::getDefaultLowerBound() const {
85 switch (getLanguage()) {
89 case dwarf::DW_LANG_C89:
90 case dwarf::DW_LANG_C99:
91 case dwarf::DW_LANG_C:
92 case dwarf::DW_LANG_C_plus_plus:
93 case dwarf::DW_LANG_ObjC:
94 case dwarf::DW_LANG_ObjC_plus_plus:
97 case dwarf::DW_LANG_Fortran77:
98 case dwarf::DW_LANG_Fortran90:
99 case dwarf::DW_LANG_Fortran95:
102 // The languages below have valid values only if the DWARF version >= 4.
103 case dwarf::DW_LANG_Java:
104 case dwarf::DW_LANG_Python:
105 case dwarf::DW_LANG_UPC:
106 case dwarf::DW_LANG_D:
107 if (dwarf::DWARF_VERSION >= 4)
111 case dwarf::DW_LANG_Ada83:
112 case dwarf::DW_LANG_Ada95:
113 case dwarf::DW_LANG_Cobol74:
114 case dwarf::DW_LANG_Cobol85:
115 case dwarf::DW_LANG_Modula2:
116 case dwarf::DW_LANG_Pascal83:
117 case dwarf::DW_LANG_PLI:
118 if (dwarf::DWARF_VERSION >= 4)
126 /// Check whether the DIE for this MDNode can be shared across CUs.
127 static bool isShareableAcrossCUs(DIDescriptor D) {
128 // When the MDNode can be part of the type system, the DIE can be shared
130 // Combining type units and cross-CU DIE sharing is lower value (since
131 // cross-CU DIE sharing is used in LTO and removes type redundancy at that
132 // level already) but may be implementable for some value in projects
133 // building multiple independent libraries with LTO and then linking those
135 return (D.isType() ||
136 (D.isSubprogram() && !DISubprogram(D).isDefinition())) &&
137 !GenerateDwarfTypeUnits;
140 /// getDIE - Returns the debug information entry map slot for the
141 /// specified debug variable. We delegate the request to DwarfDebug
142 /// when the DIE for this MDNode can be shared across CUs. The mappings
143 /// will be kept in DwarfDebug for shareable DIEs.
144 DIE *DwarfUnit::getDIE(DIDescriptor D) const {
145 if (isShareableAcrossCUs(D))
146 return DD->getDIE(D);
147 return MDNodeToDieMap.lookup(D);
150 /// insertDIE - Insert DIE into the map. We delegate the request to DwarfDebug
151 /// when the DIE for this MDNode can be shared across CUs. The mappings
152 /// will be kept in DwarfDebug for shareable DIEs.
153 void DwarfUnit::insertDIE(DIDescriptor Desc, DIE *D) {
154 if (isShareableAcrossCUs(Desc)) {
155 DD->insertDIE(Desc, D);
158 MDNodeToDieMap.insert(std::make_pair(Desc, D));
161 /// addFlag - Add a flag that is true.
162 void DwarfUnit::addFlag(DIE *Die, dwarf::Attribute Attribute) {
163 if (DD->getDwarfVersion() >= 4)
164 Die->addValue(Attribute, dwarf::DW_FORM_flag_present, DIEIntegerOne);
166 Die->addValue(Attribute, dwarf::DW_FORM_flag, DIEIntegerOne);
169 /// addUInt - Add an unsigned integer attribute data and value.
171 void DwarfUnit::addUInt(DIE *Die, dwarf::Attribute Attribute,
172 Optional<dwarf::Form> Form, uint64_t Integer) {
174 Form = DIEInteger::BestForm(false, Integer);
175 DIEValue *Value = Integer == 1 ? DIEIntegerOne : new (DIEValueAllocator)
177 Die->addValue(Attribute, *Form, Value);
180 void DwarfUnit::addUInt(DIE *Block, dwarf::Form Form, uint64_t Integer) {
181 addUInt(Block, (dwarf::Attribute)0, Form, Integer);
184 /// addSInt - Add an signed integer attribute data and value.
186 void DwarfUnit::addSInt(DIE *Die, dwarf::Attribute Attribute,
187 Optional<dwarf::Form> Form, int64_t Integer) {
189 Form = DIEInteger::BestForm(true, Integer);
190 DIEValue *Value = new (DIEValueAllocator) DIEInteger(Integer);
191 Die->addValue(Attribute, *Form, Value);
194 void DwarfUnit::addSInt(DIELoc *Die, Optional<dwarf::Form> Form,
196 addSInt(Die, (dwarf::Attribute)0, Form, Integer);
199 /// addString - Add a string attribute data and value. We always emit a
200 /// reference to the string pool instead of immediate strings so that DIEs have
201 /// more predictable sizes. In the case of split dwarf we emit an index
202 /// into another table which gets us the static offset into the string
204 void DwarfUnit::addString(DIE *Die, dwarf::Attribute Attribute,
207 if (!DD->useSplitDwarf())
208 return addLocalString(Die, Attribute, String);
210 unsigned idx = DU->getStringPoolIndex(String);
211 DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
212 DIEValue *Str = new (DIEValueAllocator) DIEString(Value, String);
213 Die->addValue(Attribute, dwarf::DW_FORM_GNU_str_index, Str);
216 /// addLocalString - Add a string attribute data and value. This is guaranteed
217 /// to be in the local string pool instead of indirected.
218 void DwarfUnit::addLocalString(DIE *Die, dwarf::Attribute Attribute,
220 MCSymbol *Symb = DU->getStringPoolEntry(String);
222 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
223 Value = new (DIEValueAllocator) DIELabel(Symb);
225 MCSymbol *StringPool = DU->getStringPoolSym();
226 Value = new (DIEValueAllocator) DIEDelta(Symb, StringPool);
228 DIEValue *Str = new (DIEValueAllocator) DIEString(Value, String);
229 Die->addValue(Attribute, dwarf::DW_FORM_strp, Str);
232 /// addExpr - Add a Dwarf expression attribute data and value.
234 void DwarfUnit::addExpr(DIELoc *Die, dwarf::Form Form, const MCExpr *Expr) {
235 DIEValue *Value = new (DIEValueAllocator) DIEExpr(Expr);
236 Die->addValue((dwarf::Attribute)0, Form, Value);
239 /// addLocationList - Add a Dwarf loclistptr attribute data and value.
241 void DwarfUnit::addLocationList(DIE *Die, dwarf::Attribute Attribute,
243 DIEValue *Value = new (DIEValueAllocator) DIELocList(Index);
244 dwarf::Form Form = DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
245 : dwarf::DW_FORM_data4;
246 Die->addValue(Attribute, Form, Value);
249 /// addLabel - Add a Dwarf label attribute data and value.
251 void DwarfUnit::addLabel(DIE *Die, dwarf::Attribute Attribute, dwarf::Form Form,
252 const MCSymbol *Label) {
253 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
254 Die->addValue(Attribute, Form, Value);
257 void DwarfUnit::addLabel(DIELoc *Die, dwarf::Form Form, const MCSymbol *Label) {
258 addLabel(Die, (dwarf::Attribute)0, Form, Label);
261 /// addSectionLabel - Add a Dwarf section label attribute data and value.
263 void DwarfUnit::addSectionLabel(DIE *Die, dwarf::Attribute Attribute,
264 const MCSymbol *Label) {
265 if (DD->getDwarfVersion() >= 4)
266 addLabel(Die, Attribute, dwarf::DW_FORM_sec_offset, Label);
268 addLabel(Die, Attribute, dwarf::DW_FORM_data4, Label);
271 /// addSectionOffset - Add an offset into a section attribute data and value.
273 void DwarfUnit::addSectionOffset(DIE *Die, dwarf::Attribute Attribute,
275 if (DD->getDwarfVersion() >= 4)
276 addUInt(Die, Attribute, dwarf::DW_FORM_sec_offset, Integer);
278 addUInt(Die, Attribute, dwarf::DW_FORM_data4, Integer);
281 /// addLabelAddress - Add a dwarf label attribute data and value using
282 /// DW_FORM_addr or DW_FORM_GNU_addr_index.
284 void DwarfCompileUnit::addLabelAddress(DIE *Die, dwarf::Attribute Attribute,
285 const MCSymbol *Label) {
287 if (!DD->useSplitDwarf())
288 return addLocalLabelAddress(Die, Attribute, Label);
291 DD->addArangeLabel(SymbolCU(this, Label));
293 unsigned idx = DU->getAddrPoolIndex(Label);
294 DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
295 Die->addValue(Attribute, dwarf::DW_FORM_GNU_addr_index, Value);
298 void DwarfCompileUnit::addLocalLabelAddress(DIE *Die,
299 dwarf::Attribute Attribute,
300 const MCSymbol *Label) {
302 DD->addArangeLabel(SymbolCU(this, Label));
305 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
306 Die->addValue(Attribute, dwarf::DW_FORM_addr, Value);
308 DIEValue *Value = new (DIEValueAllocator) DIEInteger(0);
309 Die->addValue(Attribute, dwarf::DW_FORM_addr, Value);
313 unsigned DwarfCompileUnit::getOrCreateSourceID(StringRef FileName, StringRef DirName) {
314 // If we print assembly, we can't separate .file entries according to
315 // compile units. Thus all files will belong to the default compile unit.
317 // FIXME: add a better feature test than hasRawTextSupport. Even better,
318 // extend .file to support this.
319 return Asm->OutStreamer.EmitDwarfFileDirective(
320 0, DirName, FileName,
321 Asm->OutStreamer.hasRawTextSupport() ? 0 : getUniqueID());
324 unsigned DwarfTypeUnit::getOrCreateSourceID(StringRef FileName, StringRef DirName) {
325 return SplitLineTable ? SplitLineTable->getFile(DirName, FileName)
326 : getCU().getOrCreateSourceID(FileName, DirName);
329 /// addOpAddress - Add a dwarf op address data and value using the
330 /// form given and an op of either DW_FORM_addr or DW_FORM_GNU_addr_index.
332 void DwarfUnit::addOpAddress(DIELoc *Die, const MCSymbol *Sym) {
333 if (!DD->useSplitDwarf()) {
334 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
335 addLabel(Die, dwarf::DW_FORM_udata, Sym);
337 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index);
338 addUInt(Die, dwarf::DW_FORM_GNU_addr_index, DU->getAddrPoolIndex(Sym));
342 /// addSectionDelta - Add a section label delta attribute data and value.
344 void DwarfUnit::addSectionDelta(DIE *Die, dwarf::Attribute Attribute,
345 const MCSymbol *Hi, const MCSymbol *Lo) {
346 DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
347 if (DD->getDwarfVersion() >= 4)
348 Die->addValue(Attribute, dwarf::DW_FORM_sec_offset, Value);
350 Die->addValue(Attribute, dwarf::DW_FORM_data4, Value);
353 void DwarfUnit::addLabelDelta(DIE *Die, dwarf::Attribute Attribute,
354 const MCSymbol *Hi, const MCSymbol *Lo) {
355 DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
356 Die->addValue(Attribute, dwarf::DW_FORM_data4, Value);
359 /// addDIEEntry - Add a DIE attribute data and value.
361 void DwarfUnit::addDIEEntry(DIE *Die, dwarf::Attribute Attribute, DIE *Entry) {
362 addDIEEntry(Die, Attribute, createDIEEntry(Entry));
365 void DwarfUnit::addDIETypeSignature(DIE *Die, const DwarfTypeUnit &Type) {
366 Die->addValue(dwarf::DW_AT_signature, dwarf::DW_FORM_ref_sig8,
367 new (DIEValueAllocator) DIETypeSignature(Type));
370 void DwarfUnit::addDIEEntry(DIE *Die, dwarf::Attribute Attribute,
372 const DIE *DieCU = Die->getUnitOrNull();
373 const DIE *EntryCU = Entry->getEntry()->getUnitOrNull();
375 // We assume that Die belongs to this CU, if it is not linked to any CU yet.
376 DieCU = getUnitDie();
378 EntryCU = getUnitDie();
379 Die->addValue(Attribute, EntryCU == DieCU ? dwarf::DW_FORM_ref4
380 : dwarf::DW_FORM_ref_addr,
384 /// Create a DIE with the given Tag, add the DIE to its parent, and
385 /// call insertDIE if MD is not null.
386 DIE *DwarfUnit::createAndAddDIE(unsigned Tag, DIE &Parent, DIDescriptor N) {
387 assert(Tag != dwarf::DW_TAG_auto_variable &&
388 Tag != dwarf::DW_TAG_arg_variable);
389 DIE *Die = new DIE((dwarf::Tag)Tag);
390 Parent.addChild(Die);
396 /// addBlock - Add block data.
398 void DwarfUnit::addBlock(DIE *Die, dwarf::Attribute Attribute, DIELoc *Loc) {
399 Loc->ComputeSize(Asm);
400 DIELocs.push_back(Loc); // Memoize so we can call the destructor later on.
401 Die->addValue(Attribute, Loc->BestForm(DD->getDwarfVersion()), Loc);
404 void DwarfUnit::addBlock(DIE *Die, dwarf::Attribute Attribute,
406 Block->ComputeSize(Asm);
407 DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
408 Die->addValue(Attribute, Block->BestForm(), Block);
411 /// addSourceLine - Add location information to specified debug information
413 void DwarfUnit::addSourceLine(DIE *Die, unsigned Line, StringRef File,
414 StringRef Directory) {
418 unsigned FileID = getOrCreateSourceID(File, Directory);
419 assert(FileID && "Invalid file id");
420 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
421 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
424 /// addSourceLine - Add location information to specified debug information
426 void DwarfUnit::addSourceLine(DIE *Die, DIVariable V) {
427 assert(V.isVariable());
429 addSourceLine(Die, V.getLineNumber(), V.getContext().getFilename(),
430 V.getContext().getDirectory());
433 /// addSourceLine - Add location information to specified debug information
435 void DwarfUnit::addSourceLine(DIE *Die, DIGlobalVariable G) {
436 assert(G.isGlobalVariable());
438 addSourceLine(Die, G.getLineNumber(), G.getFilename(), G.getDirectory());
441 /// addSourceLine - Add location information to specified debug information
443 void DwarfUnit::addSourceLine(DIE *Die, DISubprogram SP) {
444 assert(SP.isSubprogram());
446 addSourceLine(Die, SP.getLineNumber(), SP.getFilename(), SP.getDirectory());
449 /// addSourceLine - Add location information to specified debug information
451 void DwarfUnit::addSourceLine(DIE *Die, DIType Ty) {
454 addSourceLine(Die, Ty.getLineNumber(), Ty.getFilename(), Ty.getDirectory());
457 /// addSourceLine - Add location information to specified debug information
459 void DwarfUnit::addSourceLine(DIE *Die, DIObjCProperty Ty) {
460 assert(Ty.isObjCProperty());
462 DIFile File = Ty.getFile();
463 addSourceLine(Die, Ty.getLineNumber(), File.getFilename(),
464 File.getDirectory());
467 /// addSourceLine - Add location information to specified debug information
469 void DwarfUnit::addSourceLine(DIE *Die, DINameSpace NS) {
472 addSourceLine(Die, NS.getLineNumber(), NS.getFilename(), NS.getDirectory());
475 /// addVariableAddress - Add DW_AT_location attribute for a
476 /// DbgVariable based on provided MachineLocation.
477 void DwarfUnit::addVariableAddress(const DbgVariable &DV, DIE *Die,
478 MachineLocation Location) {
479 if (DV.variableHasComplexAddress())
480 addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
481 else if (DV.isBlockByrefVariable())
482 addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location);
484 addAddress(Die, dwarf::DW_AT_location, Location,
485 DV.getVariable().isIndirect());
488 /// addRegisterOp - Add register operand.
489 void DwarfUnit::addRegisterOp(DIELoc *TheDie, unsigned Reg) {
490 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
491 int DWReg = RI->getDwarfRegNum(Reg, false);
492 bool isSubRegister = DWReg < 0;
496 // Go up the super-register chain until we hit a valid dwarf register number.
497 for (MCSuperRegIterator SR(Reg, RI); SR.isValid() && DWReg < 0; ++SR) {
498 DWReg = RI->getDwarfRegNum(*SR, false);
500 Idx = RI->getSubRegIndex(*SR, Reg);
504 DEBUG(dbgs() << "Invalid Dwarf register number.\n");
505 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_nop);
511 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + DWReg);
513 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
514 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
519 unsigned Size = RI->getSubRegIdxSize(Idx);
520 unsigned Offset = RI->getSubRegIdxOffset(Idx);
522 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_bit_piece);
523 addUInt(TheDie, dwarf::DW_FORM_data1, Size);
524 addUInt(TheDie, dwarf::DW_FORM_data1, Offset);
526 unsigned ByteSize = Size / 8; // Assuming 8 bits per byte.
527 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_piece);
528 addUInt(TheDie, dwarf::DW_FORM_data1, ByteSize);
533 /// addRegisterOffset - Add register offset.
534 void DwarfUnit::addRegisterOffset(DIELoc *TheDie, unsigned Reg,
536 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
537 unsigned DWReg = RI->getDwarfRegNum(Reg, false);
538 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
539 if (Reg == TRI->getFrameRegister(*Asm->MF))
540 // If variable offset is based in frame register then use fbreg.
541 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_fbreg);
543 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + DWReg);
545 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
546 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
548 addSInt(TheDie, dwarf::DW_FORM_sdata, Offset);
551 /// addAddress - Add an address attribute to a die based on the location
553 void DwarfUnit::addAddress(DIE *Die, dwarf::Attribute Attribute,
554 const MachineLocation &Location, bool Indirect) {
555 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
557 if (Location.isReg() && !Indirect)
558 addRegisterOp(Loc, Location.getReg());
560 addRegisterOffset(Loc, Location.getReg(), Location.getOffset());
561 if (Indirect && !Location.isReg()) {
562 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
566 // Now attach the location information to the DIE.
567 addBlock(Die, Attribute, Loc);
570 /// addComplexAddress - Start with the address based on the location provided,
571 /// and generate the DWARF information necessary to find the actual variable
572 /// given the extra address information encoded in the DbgVariable, starting
573 /// from the starting location. Add the DWARF information to the die.
575 void DwarfUnit::addComplexAddress(const DbgVariable &DV, DIE *Die,
576 dwarf::Attribute Attribute,
577 const MachineLocation &Location) {
578 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
579 unsigned N = DV.getNumAddrElements();
581 if (Location.isReg()) {
582 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
583 // If first address element is OpPlus then emit
584 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
585 addRegisterOffset(Loc, Location.getReg(), DV.getAddrElement(1));
588 addRegisterOp(Loc, Location.getReg());
590 addRegisterOffset(Loc, Location.getReg(), Location.getOffset());
593 uint64_t Element = DV.getAddrElement(i);
594 if (Element == DIBuilder::OpPlus) {
595 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
596 addUInt(Loc, dwarf::DW_FORM_udata, DV.getAddrElement(++i));
597 } else if (Element == DIBuilder::OpDeref) {
598 if (!Location.isReg())
599 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
601 llvm_unreachable("unknown DIBuilder Opcode");
604 // Now attach the location information to the DIE.
605 addBlock(Die, Attribute, Loc);
608 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
609 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
610 gives the variable VarName either the struct, or a pointer to the struct, as
611 its type. This is necessary for various behind-the-scenes things the
612 compiler needs to do with by-reference variables in Blocks.
614 However, as far as the original *programmer* is concerned, the variable
615 should still have type 'SomeType', as originally declared.
617 The function getBlockByrefType dives into the __Block_byref_x_VarName
618 struct to find the original type of the variable, which is then assigned to
619 the variable's Debug Information Entry as its real type. So far, so good.
620 However now the debugger will expect the variable VarName to have the type
621 SomeType. So we need the location attribute for the variable to be an
622 expression that explains to the debugger how to navigate through the
623 pointers and struct to find the actual variable of type SomeType.
625 The following function does just that. We start by getting
626 the "normal" location for the variable. This will be the location
627 of either the struct __Block_byref_x_VarName or the pointer to the
628 struct __Block_byref_x_VarName.
630 The struct will look something like:
632 struct __Block_byref_x_VarName {
634 struct __Block_byref_x_VarName *forwarding;
635 ... <various other fields>
637 ... <maybe more fields>
640 If we are given the struct directly (as our starting point) we
641 need to tell the debugger to:
643 1). Add the offset of the forwarding field.
645 2). Follow that pointer to get the real __Block_byref_x_VarName
646 struct to use (the real one may have been copied onto the heap).
648 3). Add the offset for the field VarName, to find the actual variable.
650 If we started with a pointer to the struct, then we need to
651 dereference that pointer first, before the other steps.
652 Translating this into DWARF ops, we will need to append the following
653 to the current location description for the variable:
655 DW_OP_deref -- optional, if we start with a pointer
656 DW_OP_plus_uconst <forward_fld_offset>
658 DW_OP_plus_uconst <varName_fld_offset>
660 That is what this function does. */
662 /// addBlockByrefAddress - Start with the address based on the location
663 /// provided, and generate the DWARF information necessary to find the
664 /// actual Block variable (navigating the Block struct) based on the
665 /// starting location. Add the DWARF information to the die. For
666 /// more information, read large comment just above here.
668 void DwarfUnit::addBlockByrefAddress(const DbgVariable &DV, DIE *Die,
669 dwarf::Attribute Attribute,
670 const MachineLocation &Location) {
671 DIType Ty = DV.getType();
673 uint16_t Tag = Ty.getTag();
674 bool isPointer = false;
676 StringRef varName = DV.getName();
678 if (Tag == dwarf::DW_TAG_pointer_type) {
679 DIDerivedType DTy(Ty);
680 TmpTy = resolve(DTy.getTypeDerivedFrom());
684 DICompositeType blockStruct(TmpTy);
686 // Find the __forwarding field and the variable field in the __Block_byref
688 DIArray Fields = blockStruct.getTypeArray();
689 DIDerivedType varField;
690 DIDerivedType forwardingField;
692 for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
693 DIDerivedType DT(Fields.getElement(i));
694 StringRef fieldName = DT.getName();
695 if (fieldName == "__forwarding")
696 forwardingField = DT;
697 else if (fieldName == varName)
701 // Get the offsets for the forwarding field and the variable field.
702 unsigned forwardingFieldOffset = forwardingField.getOffsetInBits() >> 3;
703 unsigned varFieldOffset = varField.getOffsetInBits() >> 2;
705 // Decode the original location, and use that as the start of the byref
706 // variable's location.
707 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
709 if (Location.isReg())
710 addRegisterOp(Loc, Location.getReg());
712 addRegisterOffset(Loc, Location.getReg(), Location.getOffset());
714 // If we started with a pointer to the __Block_byref... struct, then
715 // the first thing we need to do is dereference the pointer (DW_OP_deref).
717 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
719 // Next add the offset for the '__forwarding' field:
720 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
721 // adding the offset if it's 0.
722 if (forwardingFieldOffset > 0) {
723 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
724 addUInt(Loc, dwarf::DW_FORM_udata, forwardingFieldOffset);
727 // Now dereference the __forwarding field to get to the real __Block_byref
728 // struct: DW_OP_deref.
729 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
731 // Now that we've got the real __Block_byref... struct, add the offset
732 // for the variable's field to get to the location of the actual variable:
733 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
734 if (varFieldOffset > 0) {
735 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
736 addUInt(Loc, dwarf::DW_FORM_udata, varFieldOffset);
739 // Now attach the location information to the DIE.
740 addBlock(Die, Attribute, Loc);
743 /// isTypeSigned - Return true if the type is signed.
744 static bool isTypeSigned(DwarfDebug *DD, DIType Ty, int *SizeInBits) {
745 if (Ty.isDerivedType())
746 return isTypeSigned(DD, DD->resolve(DIDerivedType(Ty).getTypeDerivedFrom()),
748 if (Ty.isBasicType())
749 if (DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed ||
750 DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed_char) {
751 *SizeInBits = Ty.getSizeInBits();
757 /// Return true if type encoding is unsigned.
758 static bool isUnsignedDIType(DwarfDebug *DD, DIType Ty) {
759 DIDerivedType DTy(Ty);
760 if (DTy.isDerivedType())
761 return isUnsignedDIType(DD, DD->resolve(DTy.getTypeDerivedFrom()));
764 if (BTy.isBasicType()) {
765 unsigned Encoding = BTy.getEncoding();
766 if (Encoding == dwarf::DW_ATE_unsigned ||
767 Encoding == dwarf::DW_ATE_unsigned_char ||
768 Encoding == dwarf::DW_ATE_boolean)
774 /// If this type is derived from a base type then return base type size.
775 static uint64_t getBaseTypeSize(DwarfDebug *DD, DIDerivedType Ty) {
776 unsigned Tag = Ty.getTag();
778 if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef &&
779 Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type &&
780 Tag != dwarf::DW_TAG_restrict_type)
781 return Ty.getSizeInBits();
783 DIType BaseType = DD->resolve(Ty.getTypeDerivedFrom());
785 // If this type is not derived from any type or the type is a declaration then
786 // take conservative approach.
787 if (!BaseType.isValid() || BaseType.isForwardDecl())
788 return Ty.getSizeInBits();
790 // If this is a derived type, go ahead and get the base type, unless it's a
791 // reference then it's just the size of the field. Pointer types have no need
792 // of this since they're a different type of qualification on the type.
793 if (BaseType.getTag() == dwarf::DW_TAG_reference_type ||
794 BaseType.getTag() == dwarf::DW_TAG_rvalue_reference_type)
795 return Ty.getSizeInBits();
797 if (BaseType.isDerivedType())
798 return getBaseTypeSize(DD, DIDerivedType(BaseType));
800 return BaseType.getSizeInBits();
803 /// addConstantValue - Add constant value entry in variable DIE.
804 void DwarfUnit::addConstantValue(DIE *Die, const MachineOperand &MO,
806 // FIXME: This is a bit conservative/simple - it emits negative values at
807 // their maximum bit width which is a bit unfortunate (& doesn't prefer
808 // udata/sdata over dataN as suggested by the DWARF spec)
809 assert(MO.isImm() && "Invalid machine operand!");
811 bool SignedConstant = isTypeSigned(DD, Ty, &SizeInBits);
814 // If we're a signed constant definitely use sdata.
815 if (SignedConstant) {
816 addSInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, MO.getImm());
820 // Else use data for now unless it's larger than we can deal with.
821 switch (SizeInBits) {
823 Form = dwarf::DW_FORM_data1;
826 Form = dwarf::DW_FORM_data2;
829 Form = dwarf::DW_FORM_data4;
832 Form = dwarf::DW_FORM_data8;
835 Form = dwarf::DW_FORM_udata;
836 addUInt(Die, dwarf::DW_AT_const_value, Form, MO.getImm());
839 addUInt(Die, dwarf::DW_AT_const_value, Form, MO.getImm());
842 /// addConstantFPValue - Add constant value entry in variable DIE.
843 void DwarfUnit::addConstantFPValue(DIE *Die, const MachineOperand &MO) {
844 assert(MO.isFPImm() && "Invalid machine operand!");
845 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
846 APFloat FPImm = MO.getFPImm()->getValueAPF();
848 // Get the raw data form of the floating point.
849 const APInt FltVal = FPImm.bitcastToAPInt();
850 const char *FltPtr = (const char *)FltVal.getRawData();
852 int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
853 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
854 int Incr = (LittleEndian ? 1 : -1);
855 int Start = (LittleEndian ? 0 : NumBytes - 1);
856 int Stop = (LittleEndian ? NumBytes : -1);
858 // Output the constant to DWARF one byte at a time.
859 for (; Start != Stop; Start += Incr)
860 addUInt(Block, dwarf::DW_FORM_data1, (unsigned char)0xFF & FltPtr[Start]);
862 addBlock(Die, dwarf::DW_AT_const_value, Block);
865 /// addConstantFPValue - Add constant value entry in variable DIE.
866 void DwarfUnit::addConstantFPValue(DIE *Die, const ConstantFP *CFP) {
867 // Pass this down to addConstantValue as an unsigned bag of bits.
868 addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true);
871 /// addConstantValue - Add constant value entry in variable DIE.
872 void DwarfUnit::addConstantValue(DIE *Die, const ConstantInt *CI,
874 addConstantValue(Die, CI->getValue(), Unsigned);
877 // addConstantValue - Add constant value entry in variable DIE.
878 void DwarfUnit::addConstantValue(DIE *Die, const APInt &Val, bool Unsigned) {
879 unsigned CIBitWidth = Val.getBitWidth();
880 if (CIBitWidth <= 64) {
881 // If we're a signed constant definitely use sdata.
883 addSInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
888 // Else use data for now unless it's larger than we can deal with.
890 switch (CIBitWidth) {
892 Form = dwarf::DW_FORM_data1;
895 Form = dwarf::DW_FORM_data2;
898 Form = dwarf::DW_FORM_data4;
901 Form = dwarf::DW_FORM_data8;
904 addUInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_udata,
908 addUInt(Die, dwarf::DW_AT_const_value, Form, Val.getZExtValue());
912 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
914 // Get the raw data form of the large APInt.
915 const uint64_t *Ptr64 = Val.getRawData();
917 int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
918 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
920 // Output the constant to DWARF one byte at a time.
921 for (int i = 0; i < NumBytes; i++) {
924 c = Ptr64[i / 8] >> (8 * (i & 7));
926 c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
927 addUInt(Block, dwarf::DW_FORM_data1, c);
930 addBlock(Die, dwarf::DW_AT_const_value, Block);
933 /// addTemplateParams - Add template parameters into buffer.
934 void DwarfUnit::addTemplateParams(DIE &Buffer, DIArray TParams) {
935 // Add template parameters.
936 for (unsigned i = 0, e = TParams.getNumElements(); i != e; ++i) {
937 DIDescriptor Element = TParams.getElement(i);
938 if (Element.isTemplateTypeParameter())
939 constructTemplateTypeParameterDIE(Buffer,
940 DITemplateTypeParameter(Element));
941 else if (Element.isTemplateValueParameter())
942 constructTemplateValueParameterDIE(Buffer,
943 DITemplateValueParameter(Element));
947 /// getOrCreateContextDIE - Get context owner's DIE.
948 DIE *DwarfUnit::getOrCreateContextDIE(DIScope Context) {
949 if (!Context || Context.isFile())
951 if (Context.isType())
952 return getOrCreateTypeDIE(DIType(Context));
953 if (Context.isNameSpace())
954 return getOrCreateNameSpace(DINameSpace(Context));
955 if (Context.isSubprogram())
956 return getOrCreateSubprogramDIE(DISubprogram(Context));
957 return getDIE(Context);
960 DIE *DwarfUnit::createTypeDIE(DICompositeType Ty) {
961 DIScope Context = resolve(Ty.getContext());
962 DIE *ContextDIE = getOrCreateContextDIE(Context);
964 DIE *TyDIE = getDIE(Ty);
969 TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
971 constructTypeDIE(*TyDIE, Ty);
973 updateAcceleratorTables(Context, Ty, TyDIE);
977 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
979 DIE *DwarfUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
985 assert(Ty == resolve(Ty.getRef()) &&
986 "type was not uniqued, possible ODR violation.");
988 // DW_TAG_restrict_type is not supported in DWARF2
989 if (Ty.getTag() == dwarf::DW_TAG_restrict_type && DD->getDwarfVersion() <= 2)
990 return getOrCreateTypeDIE(resolve(DIDerivedType(Ty).getTypeDerivedFrom()));
992 // Construct the context before querying for the existence of the DIE in case
993 // such construction creates the DIE.
994 DIScope Context = resolve(Ty.getContext());
995 DIE *ContextDIE = getOrCreateContextDIE(Context);
998 DIE *TyDIE = getDIE(Ty);
1003 TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
1005 updateAcceleratorTables(Context, Ty, TyDIE);
1007 if (Ty.isBasicType())
1008 constructTypeDIE(*TyDIE, DIBasicType(Ty));
1009 else if (Ty.isCompositeType()) {
1010 DICompositeType CTy(Ty);
1011 if (GenerateDwarfTypeUnits && !Ty.isForwardDecl())
1012 if (MDString *TypeId = CTy.getIdentifier()) {
1013 DD->addDwarfTypeUnitType(getCU(), TypeId->getString(), TyDIE, CTy);
1014 // Skip updating the accelerator tables since this is not the full type.
1017 constructTypeDIE(*TyDIE, CTy);
1019 assert(Ty.isDerivedType() && "Unknown kind of DIType");
1020 constructTypeDIE(*TyDIE, DIDerivedType(Ty));
1026 void DwarfUnit::updateAcceleratorTables(DIScope Context, DIType Ty,
1028 if (!Ty.getName().empty() && !Ty.isForwardDecl()) {
1029 bool IsImplementation = 0;
1030 if (Ty.isCompositeType()) {
1031 DICompositeType CT(Ty);
1032 // A runtime language of 0 actually means C/C++ and that any
1033 // non-negative value is some version of Objective-C/C++.
1034 IsImplementation = (CT.getRunTimeLang() == 0) || CT.isObjcClassComplete();
1036 unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0;
1037 addAccelType(Ty.getName(), std::make_pair(TyDIE, Flags));
1039 if ((!Context || Context.isCompileUnit() || Context.isFile() ||
1040 Context.isNameSpace()) &&
1041 getCUNode().getEmissionKind() != DIBuilder::LineTablesOnly)
1042 GlobalTypes[getParentContextString(Context) + Ty.getName().str()] = TyDIE;
1046 /// addType - Add a new type attribute to the specified entity.
1047 void DwarfUnit::addType(DIE *Entity, DIType Ty, dwarf::Attribute Attribute) {
1048 assert(Ty && "Trying to add a type that doesn't exist?");
1050 // Check for pre-existence.
1051 DIEEntry *Entry = getDIEEntry(Ty);
1052 // If it exists then use the existing value.
1054 addDIEEntry(Entity, Attribute, Entry);
1059 DIE *Buffer = getOrCreateTypeDIE(Ty);
1062 Entry = createDIEEntry(Buffer);
1063 insertDIEEntry(Ty, Entry);
1064 addDIEEntry(Entity, Attribute, Entry);
1067 // Accelerator table mutators - add each name along with its companion
1068 // DIE to the proper table while ensuring that the name that we're going
1069 // to reference is in the string table. We do this since the names we
1070 // add may not only be identical to the names in the DIE.
1071 void DwarfUnit::addAccelName(StringRef Name, const DIE *Die) {
1072 if (!DD->useDwarfAccelTables())
1074 DU->getStringPoolEntry(Name);
1075 std::vector<const DIE *> &DIEs = AccelNames[Name];
1076 DIEs.push_back(Die);
1079 void DwarfUnit::addAccelObjC(StringRef Name, const DIE *Die) {
1080 if (!DD->useDwarfAccelTables())
1082 DU->getStringPoolEntry(Name);
1083 std::vector<const DIE *> &DIEs = AccelObjC[Name];
1084 DIEs.push_back(Die);
1087 void DwarfUnit::addAccelNamespace(StringRef Name, const DIE *Die) {
1088 if (!DD->useDwarfAccelTables())
1090 DU->getStringPoolEntry(Name);
1091 std::vector<const DIE *> &DIEs = AccelNamespace[Name];
1092 DIEs.push_back(Die);
1095 void DwarfUnit::addAccelType(StringRef Name,
1096 std::pair<const DIE *, unsigned> Die) {
1097 if (!DD->useDwarfAccelTables())
1099 DU->getStringPoolEntry(Name);
1100 std::vector<std::pair<const DIE *, unsigned> > &DIEs = AccelTypes[Name];
1101 DIEs.push_back(Die);
1104 /// addGlobalName - Add a new global name to the compile unit.
1105 void DwarfUnit::addGlobalName(StringRef Name, DIE *Die, DIScope Context) {
1106 if (getCUNode().getEmissionKind() == DIBuilder::LineTablesOnly)
1108 std::string FullName = getParentContextString(Context) + Name.str();
1109 GlobalNames[FullName] = Die;
1112 /// getParentContextString - Walks the metadata parent chain in a language
1113 /// specific manner (using the compile unit language) and returns
1114 /// it as a string. This is done at the metadata level because DIEs may
1115 /// not currently have been added to the parent context and walking the
1116 /// DIEs looking for names is more expensive than walking the metadata.
1117 std::string DwarfUnit::getParentContextString(DIScope Context) const {
1121 // FIXME: Decide whether to implement this for non-C++ languages.
1122 if (getLanguage() != dwarf::DW_LANG_C_plus_plus)
1126 SmallVector<DIScope, 1> Parents;
1127 while (!Context.isCompileUnit()) {
1128 Parents.push_back(Context);
1129 if (Context.getContext())
1130 Context = resolve(Context.getContext());
1132 // Structure, etc types will have a NULL context if they're at the top
1137 // Reverse iterate over our list to go from the outermost construct to the
1139 for (SmallVectorImpl<DIScope>::reverse_iterator I = Parents.rbegin(),
1143 StringRef Name = Ctx.getName();
1144 if (!Name.empty()) {
1152 /// constructTypeDIE - Construct basic type die from DIBasicType.
1153 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
1154 // Get core information.
1155 StringRef Name = BTy.getName();
1156 // Add name if not anonymous or intermediate type.
1158 addString(&Buffer, dwarf::DW_AT_name, Name);
1160 // An unspecified type only has a name attribute.
1161 if (BTy.getTag() == dwarf::DW_TAG_unspecified_type)
1164 addUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1167 uint64_t Size = BTy.getSizeInBits() >> 3;
1168 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1171 /// constructTypeDIE - Construct derived type die from DIDerivedType.
1172 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
1173 // Get core information.
1174 StringRef Name = DTy.getName();
1175 uint64_t Size = DTy.getSizeInBits() >> 3;
1176 uint16_t Tag = Buffer.getTag();
1178 // Map to main type, void will not have a type.
1179 DIType FromTy = resolve(DTy.getTypeDerivedFrom());
1181 addType(&Buffer, FromTy);
1183 // Add name if not anonymous or intermediate type.
1185 addString(&Buffer, dwarf::DW_AT_name, Name);
1187 // Add size if non-zero (derived types might be zero-sized.)
1188 if (Size && Tag != dwarf::DW_TAG_pointer_type)
1189 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1191 if (Tag == dwarf::DW_TAG_ptr_to_member_type)
1192 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type,
1193 getOrCreateTypeDIE(resolve(DTy.getClassType())));
1194 // Add source line info if available and TyDesc is not a forward declaration.
1195 if (!DTy.isForwardDecl())
1196 addSourceLine(&Buffer, DTy);
1199 /// constructSubprogramArguments - Construct function argument DIEs.
1200 void DwarfUnit::constructSubprogramArguments(DIE &Buffer, DIArray Args) {
1201 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1202 DIDescriptor Ty = Args.getElement(i);
1203 if (Ty.isUnspecifiedParameter()) {
1204 assert(i == N-1 && "Unspecified parameter must be the last argument");
1205 createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
1207 DIE *Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
1208 addType(Arg, DIType(Ty));
1209 if (DIType(Ty).isArtificial())
1210 addFlag(Arg, dwarf::DW_AT_artificial);
1215 /// constructTypeDIE - Construct type DIE from DICompositeType.
1216 void DwarfUnit::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
1217 // Add name if not anonymous or intermediate type.
1218 StringRef Name = CTy.getName();
1220 uint64_t Size = CTy.getSizeInBits() >> 3;
1221 uint16_t Tag = Buffer.getTag();
1224 case dwarf::DW_TAG_array_type:
1225 constructArrayTypeDIE(Buffer, CTy);
1227 case dwarf::DW_TAG_enumeration_type:
1228 constructEnumTypeDIE(Buffer, CTy);
1230 case dwarf::DW_TAG_subroutine_type: {
1231 // Add return type. A void return won't have a type.
1232 DIArray Elements = CTy.getTypeArray();
1233 DIType RTy(Elements.getElement(0));
1235 addType(&Buffer, RTy);
1237 bool isPrototyped = true;
1238 if (Elements.getNumElements() == 2 &&
1239 Elements.getElement(1).isUnspecifiedParameter())
1240 isPrototyped = false;
1242 constructSubprogramArguments(Buffer, Elements);
1244 // Add prototype flag if we're dealing with a C language and the
1245 // function has been prototyped.
1246 uint16_t Language = getLanguage();
1248 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1249 Language == dwarf::DW_LANG_ObjC))
1250 addFlag(&Buffer, dwarf::DW_AT_prototyped);
1252 if (CTy.isLValueReference())
1253 addFlag(&Buffer, dwarf::DW_AT_reference);
1255 if (CTy.isRValueReference())
1256 addFlag(&Buffer, dwarf::DW_AT_rvalue_reference);
1258 case dwarf::DW_TAG_structure_type:
1259 case dwarf::DW_TAG_union_type:
1260 case dwarf::DW_TAG_class_type: {
1261 // Add elements to structure type.
1262 DIArray Elements = CTy.getTypeArray();
1263 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1264 DIDescriptor Element = Elements.getElement(i);
1265 DIE *ElemDie = NULL;
1266 if (Element.isSubprogram())
1267 ElemDie = getOrCreateSubprogramDIE(DISubprogram(Element));
1268 else if (Element.isDerivedType()) {
1269 DIDerivedType DDTy(Element);
1270 if (DDTy.getTag() == dwarf::DW_TAG_friend) {
1271 ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
1272 addType(ElemDie, resolve(DDTy.getTypeDerivedFrom()),
1273 dwarf::DW_AT_friend);
1274 } else if (DDTy.isStaticMember()) {
1275 getOrCreateStaticMemberDIE(DDTy);
1277 constructMemberDIE(Buffer, DDTy);
1279 } else if (Element.isObjCProperty()) {
1280 DIObjCProperty Property(Element);
1281 ElemDie = createAndAddDIE(Property.getTag(), Buffer);
1282 StringRef PropertyName = Property.getObjCPropertyName();
1283 addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
1284 if (Property.getType())
1285 addType(ElemDie, Property.getType());
1286 addSourceLine(ElemDie, Property);
1287 StringRef GetterName = Property.getObjCPropertyGetterName();
1288 if (!GetterName.empty())
1289 addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
1290 StringRef SetterName = Property.getObjCPropertySetterName();
1291 if (!SetterName.empty())
1292 addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
1293 unsigned PropertyAttributes = 0;
1294 if (Property.isReadOnlyObjCProperty())
1295 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readonly;
1296 if (Property.isReadWriteObjCProperty())
1297 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readwrite;
1298 if (Property.isAssignObjCProperty())
1299 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_assign;
1300 if (Property.isRetainObjCProperty())
1301 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_retain;
1302 if (Property.isCopyObjCProperty())
1303 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_copy;
1304 if (Property.isNonAtomicObjCProperty())
1305 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_nonatomic;
1306 if (PropertyAttributes)
1307 addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None,
1308 PropertyAttributes);
1310 DIEEntry *Entry = getDIEEntry(Element);
1312 Entry = createDIEEntry(ElemDie);
1313 insertDIEEntry(Element, Entry);
1319 if (CTy.isAppleBlockExtension())
1320 addFlag(&Buffer, dwarf::DW_AT_APPLE_block);
1322 DICompositeType ContainingType(resolve(CTy.getContainingType()));
1324 addDIEEntry(&Buffer, dwarf::DW_AT_containing_type,
1325 getOrCreateTypeDIE(ContainingType));
1327 if (CTy.isObjcClassComplete())
1328 addFlag(&Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
1330 // Add template parameters to a class, structure or union types.
1331 // FIXME: The support isn't in the metadata for this yet.
1332 if (Tag == dwarf::DW_TAG_class_type ||
1333 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
1334 addTemplateParams(Buffer, CTy.getTemplateParams());
1342 // Add name if not anonymous or intermediate type.
1344 addString(&Buffer, dwarf::DW_AT_name, Name);
1346 if (Tag == dwarf::DW_TAG_enumeration_type ||
1347 Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
1348 Tag == dwarf::DW_TAG_union_type) {
1349 // Add size if non-zero (derived types might be zero-sized.)
1350 // TODO: Do we care about size for enum forward declarations?
1352 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, Size);
1353 else if (!CTy.isForwardDecl())
1354 // Add zero size if it is not a forward declaration.
1355 addUInt(&Buffer, dwarf::DW_AT_byte_size, None, 0);
1357 // If we're a forward decl, say so.
1358 if (CTy.isForwardDecl())
1359 addFlag(&Buffer, dwarf::DW_AT_declaration);
1361 // Add source line info if available.
1362 if (!CTy.isForwardDecl())
1363 addSourceLine(&Buffer, CTy);
1365 // No harm in adding the runtime language to the declaration.
1366 unsigned RLang = CTy.getRunTimeLang();
1368 addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
1373 /// constructTemplateTypeParameterDIE - Construct new DIE for the given
1374 /// DITemplateTypeParameter.
1375 void DwarfUnit::constructTemplateTypeParameterDIE(DIE &Buffer,
1376 DITemplateTypeParameter TP) {
1378 createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
1379 // Add the type if it exists, it could be void and therefore no type.
1381 addType(ParamDIE, resolve(TP.getType()));
1382 if (!TP.getName().empty())
1383 addString(ParamDIE, dwarf::DW_AT_name, TP.getName());
1386 /// constructTemplateValueParameterDIE - Construct new DIE for the given
1387 /// DITemplateValueParameter.
1389 DwarfUnit::constructTemplateValueParameterDIE(DIE &Buffer,
1390 DITemplateValueParameter VP) {
1391 DIE *ParamDIE = createAndAddDIE(VP.getTag(), Buffer);
1393 // Add the type if there is one, template template and template parameter
1394 // packs will not have a type.
1395 if (VP.getTag() == dwarf::DW_TAG_template_value_parameter)
1396 addType(ParamDIE, resolve(VP.getType()));
1397 if (!VP.getName().empty())
1398 addString(ParamDIE, dwarf::DW_AT_name, VP.getName());
1399 if (Value *Val = VP.getValue()) {
1400 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val))
1401 addConstantValue(ParamDIE, CI,
1402 isUnsignedDIType(DD, resolve(VP.getType())));
1403 else if (GlobalValue *GV = dyn_cast<GlobalValue>(Val)) {
1404 // For declaration non-type template parameters (such as global values and
1406 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
1407 addOpAddress(Loc, Asm->getSymbol(GV));
1408 // Emit DW_OP_stack_value to use the address as the immediate value of the
1409 // parameter, rather than a pointer to it.
1410 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
1411 addBlock(ParamDIE, dwarf::DW_AT_location, Loc);
1412 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1413 assert(isa<MDString>(Val));
1414 addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
1415 cast<MDString>(Val)->getString());
1416 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1417 assert(isa<MDNode>(Val));
1418 DIArray A(cast<MDNode>(Val));
1419 addTemplateParams(*ParamDIE, A);
1424 /// getOrCreateNameSpace - Create a DIE for DINameSpace.
1425 DIE *DwarfUnit::getOrCreateNameSpace(DINameSpace NS) {
1426 // Construct the context before querying for the existence of the DIE in case
1427 // such construction creates the DIE.
1428 DIE *ContextDIE = getOrCreateContextDIE(NS.getContext());
1430 DIE *NDie = getDIE(NS);
1433 NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS);
1435 if (!NS.getName().empty()) {
1436 addString(NDie, dwarf::DW_AT_name, NS.getName());
1437 addAccelNamespace(NS.getName(), NDie);
1438 addGlobalName(NS.getName(), NDie, NS.getContext());
1440 addAccelNamespace("(anonymous namespace)", NDie);
1441 addSourceLine(NDie, NS);
1445 /// getOrCreateSubprogramDIE - Create new DIE using SP.
1446 DIE *DwarfUnit::getOrCreateSubprogramDIE(DISubprogram SP) {
1447 // Construct the context before querying for the existence of the DIE in case
1448 // such construction creates the DIE (as is the case for member function
1450 DIScope Context = resolve(SP.getContext());
1451 DIE *ContextDIE = getOrCreateContextDIE(Context);
1453 // Unique declarations based on the ODR, where applicable.
1454 SP = DISubprogram(DD->resolve(SP.getRef()));
1455 assert(SP.Verify());
1457 DIE *SPDie = getDIE(SP);
1461 DISubprogram SPDecl = SP.getFunctionDeclaration();
1462 if (SPDecl.isSubprogram())
1463 // Add subprogram definitions to the CU die directly.
1464 ContextDIE = UnitDie.get();
1466 // DW_TAG_inlined_subroutine may refer to this DIE.
1467 SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
1469 DIE *DeclDie = NULL;
1470 if (SPDecl.isSubprogram())
1471 DeclDie = getOrCreateSubprogramDIE(SPDecl);
1473 // Add function template parameters.
1474 addTemplateParams(*SPDie, SP.getTemplateParams());
1477 // Refer function declaration directly.
1478 addDIEEntry(SPDie, dwarf::DW_AT_specification, DeclDie);
1480 // Add the linkage name if we have one and it isn't in the Decl.
1481 StringRef LinkageName = SP.getLinkageName();
1482 if (!LinkageName.empty()) {
1483 if (SPDecl.isSubprogram() && !SPDecl.getLinkageName().empty())
1484 assert(SPDecl.getLinkageName() == SP.getLinkageName() &&
1485 "decl has a linkage name and it is different");
1487 addString(SPDie, dwarf::DW_AT_MIPS_linkage_name,
1488 GlobalValue::getRealLinkageName(LinkageName));
1491 // If this DIE is going to refer declaration info using AT_specification
1492 // then there is no need to add other attributes.
1496 // Constructors and operators for anonymous aggregates do not have names.
1497 if (!SP.getName().empty())
1498 addString(SPDie, dwarf::DW_AT_name, SP.getName());
1500 addSourceLine(SPDie, SP);
1502 // Add the prototype if we have a prototype and we have a C like
1504 uint16_t Language = getLanguage();
1505 if (SP.isPrototyped() &&
1506 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1507 Language == dwarf::DW_LANG_ObjC))
1508 addFlag(SPDie, dwarf::DW_AT_prototyped);
1510 DICompositeType SPTy = SP.getType();
1511 assert(SPTy.getTag() == dwarf::DW_TAG_subroutine_type &&
1512 "the type of a subprogram should be a subroutine");
1514 DIArray Args = SPTy.getTypeArray();
1515 // Add a return type. If this is a type like a C/C++ void type we don't add a
1517 if (Args.getElement(0))
1518 addType(SPDie, DIType(Args.getElement(0)));
1520 unsigned VK = SP.getVirtuality();
1522 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1523 DIELoc *Block = getDIELoc();
1524 addUInt(Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1525 addUInt(Block, dwarf::DW_FORM_udata, SP.getVirtualIndex());
1526 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
1527 ContainingTypeMap.insert(
1528 std::make_pair(SPDie, resolve(SP.getContainingType())));
1531 if (!SP.isDefinition()) {
1532 addFlag(SPDie, dwarf::DW_AT_declaration);
1534 // Add arguments. Do not add arguments for subprogram definition. They will
1535 // be handled while processing variables.
1536 constructSubprogramArguments(*SPDie, Args);
1539 if (SP.isArtificial())
1540 addFlag(SPDie, dwarf::DW_AT_artificial);
1542 if (!SP.isLocalToUnit())
1543 addFlag(SPDie, dwarf::DW_AT_external);
1545 if (SP.isOptimized())
1546 addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1548 if (unsigned isa = Asm->getISAEncoding()) {
1549 addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1552 if (SP.isLValueReference())
1553 addFlag(SPDie, dwarf::DW_AT_reference);
1555 if (SP.isRValueReference())
1556 addFlag(SPDie, dwarf::DW_AT_rvalue_reference);
1558 if (SP.isProtected())
1559 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1560 dwarf::DW_ACCESS_protected);
1561 else if (SP.isPrivate())
1562 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1563 dwarf::DW_ACCESS_private);
1565 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1566 dwarf::DW_ACCESS_public);
1568 if (SP.isExplicit())
1569 addFlag(SPDie, dwarf::DW_AT_explicit);
1574 // Return const expression if value is a GEP to access merged global
1576 // i8* getelementptr ({ i8, i8, i8, i8 }* @_MergedGlobals, i32 0, i32 0)
1577 static const ConstantExpr *getMergedGlobalExpr(const Value *V) {
1578 const ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(V);
1579 if (!CE || CE->getNumOperands() != 3 ||
1580 CE->getOpcode() != Instruction::GetElementPtr)
1583 // First operand points to a global struct.
1584 Value *Ptr = CE->getOperand(0);
1585 if (!isa<GlobalValue>(Ptr) ||
1586 !isa<StructType>(cast<PointerType>(Ptr->getType())->getElementType()))
1589 // Second operand is zero.
1590 const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(CE->getOperand(1));
1591 if (!CI || !CI->isZero())
1594 // Third operand is offset.
1595 if (!isa<ConstantInt>(CE->getOperand(2)))
1601 /// createGlobalVariableDIE - create global variable DIE.
1602 void DwarfCompileUnit::createGlobalVariableDIE(DIGlobalVariable GV) {
1603 // Check for pre-existence.
1607 assert(GV.isGlobalVariable());
1609 DIScope GVContext = GV.getContext();
1610 DIType GTy = DD->resolve(GV.getType());
1612 // If this is a static data member definition, some attributes belong
1613 // to the declaration DIE.
1614 DIE *VariableDIE = NULL;
1615 bool IsStaticMember = false;
1616 DIDerivedType SDMDecl = GV.getStaticDataMemberDeclaration();
1617 if (SDMDecl.Verify()) {
1618 assert(SDMDecl.isStaticMember() && "Expected static member decl");
1619 // We need the declaration DIE that is in the static member's class.
1620 VariableDIE = getOrCreateStaticMemberDIE(SDMDecl);
1621 IsStaticMember = true;
1624 // If this is not a static data member definition, create the variable
1625 // DIE and add the initial set of attributes to it.
1627 // Construct the context before querying for the existence of the DIE in
1628 // case such construction creates the DIE.
1629 DIE *ContextDIE = getOrCreateContextDIE(GVContext);
1632 VariableDIE = createAndAddDIE(GV.getTag(), *ContextDIE, GV);
1634 // Add name and type.
1635 addString(VariableDIE, dwarf::DW_AT_name, GV.getDisplayName());
1636 addType(VariableDIE, GTy);
1638 // Add scoping info.
1639 if (!GV.isLocalToUnit())
1640 addFlag(VariableDIE, dwarf::DW_AT_external);
1642 // Add line number info.
1643 addSourceLine(VariableDIE, GV);
1647 bool addToAccelTable = false;
1648 DIE *VariableSpecDIE = NULL;
1649 bool isGlobalVariable = GV.getGlobal() != NULL;
1650 if (isGlobalVariable) {
1651 addToAccelTable = true;
1652 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
1653 const MCSymbol *Sym = Asm->getSymbol(GV.getGlobal());
1654 if (GV.getGlobal()->isThreadLocal()) {
1655 // FIXME: Make this work with -gsplit-dwarf.
1656 unsigned PointerSize = Asm->getDataLayout().getPointerSize();
1657 assert((PointerSize == 4 || PointerSize == 8) &&
1658 "Add support for other sizes if necessary");
1659 // Based on GCC's support for TLS:
1660 if (!DD->useSplitDwarf()) {
1661 // 1) Start with a constNu of the appropriate pointer size
1662 addUInt(Loc, dwarf::DW_FORM_data1,
1663 PointerSize == 4 ? dwarf::DW_OP_const4u : dwarf::DW_OP_const8u);
1664 // 2) containing the (relocated) offset of the TLS variable
1665 // within the module's TLS block.
1666 addExpr(Loc, dwarf::DW_FORM_udata,
1667 Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym));
1669 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
1670 addUInt(Loc, dwarf::DW_FORM_udata,
1671 DU->getAddrPoolIndex(Sym, /* TLS */ true));
1673 // 3) followed by a custom OP to make the debugger do a TLS lookup.
1674 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_push_tls_address);
1676 DD->addArangeLabel(SymbolCU(this, Sym));
1677 addOpAddress(Loc, Sym);
1679 // Do not create specification DIE if context is either compile unit
1681 if (GVContext && GV.isDefinition() && !GVContext.isCompileUnit() &&
1682 !GVContext.isFile() && !DD->isSubprogramContext(GVContext)) {
1683 // Create specification DIE.
1684 VariableSpecDIE = createAndAddDIE(dwarf::DW_TAG_variable, *UnitDie);
1685 addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification, VariableDIE);
1686 addBlock(VariableSpecDIE, dwarf::DW_AT_location, Loc);
1687 // A static member's declaration is already flagged as such.
1688 if (!SDMDecl.Verify())
1689 addFlag(VariableDIE, dwarf::DW_AT_declaration);
1691 addBlock(VariableDIE, dwarf::DW_AT_location, Loc);
1693 // Add the linkage name.
1694 StringRef LinkageName = GV.getLinkageName();
1695 if (!LinkageName.empty())
1696 // From DWARF4: DIEs to which DW_AT_linkage_name may apply include:
1697 // TAG_common_block, TAG_constant, TAG_entry_point, TAG_subprogram and
1699 addString(IsStaticMember && VariableSpecDIE ? VariableSpecDIE
1701 DD->getDwarfVersion() >= 4 ? dwarf::DW_AT_linkage_name
1702 : dwarf::DW_AT_MIPS_linkage_name,
1703 GlobalValue::getRealLinkageName(LinkageName));
1704 } else if (const ConstantInt *CI =
1705 dyn_cast_or_null<ConstantInt>(GV.getConstant())) {
1706 // AT_const_value was added when the static member was created. To avoid
1707 // emitting AT_const_value multiple times, we only add AT_const_value when
1708 // it is not a static member.
1709 if (!IsStaticMember)
1710 addConstantValue(VariableDIE, CI, isUnsignedDIType(DD, GTy));
1711 } else if (const ConstantExpr *CE = getMergedGlobalExpr(GV->getOperand(11))) {
1712 addToAccelTable = true;
1713 // GV is a merged global.
1714 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
1715 Value *Ptr = CE->getOperand(0);
1716 MCSymbol *Sym = Asm->getSymbol(cast<GlobalValue>(Ptr));
1717 DD->addArangeLabel(SymbolCU(this, Sym));
1718 addOpAddress(Loc, Sym);
1719 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1720 SmallVector<Value *, 3> Idx(CE->op_begin() + 1, CE->op_end());
1721 addUInt(Loc, dwarf::DW_FORM_udata,
1722 Asm->getDataLayout().getIndexedOffset(Ptr->getType(), Idx));
1723 addUInt(Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1724 addBlock(VariableDIE, dwarf::DW_AT_location, Loc);
1727 if (addToAccelTable) {
1728 DIE *AddrDIE = VariableSpecDIE ? VariableSpecDIE : VariableDIE;
1729 addAccelName(GV.getName(), AddrDIE);
1731 // If the linkage name is different than the name, go ahead and output
1732 // that as well into the name table.
1733 if (GV.getLinkageName() != "" && GV.getName() != GV.getLinkageName())
1734 addAccelName(GV.getLinkageName(), AddrDIE);
1737 if (!GV.isLocalToUnit())
1738 addGlobalName(GV.getName(), VariableSpecDIE ? VariableSpecDIE : VariableDIE,
1742 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
1743 void DwarfUnit::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy) {
1744 DIE *DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
1745 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, IndexTy);
1747 // The LowerBound value defines the lower bounds which is typically zero for
1748 // C/C++. The Count value is the number of elements. Values are 64 bit. If
1749 // Count == -1 then the array is unbounded and we do not emit
1750 // DW_AT_lower_bound and DW_AT_upper_bound attributes. If LowerBound == 0 and
1751 // Count == 0, then the array has zero elements in which case we do not emit
1753 int64_t LowerBound = SR.getLo();
1754 int64_t DefaultLowerBound = getDefaultLowerBound();
1755 int64_t Count = SR.getCount();
1757 if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
1758 addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound);
1760 if (Count != -1 && Count != 0)
1761 // FIXME: An unbounded array should reference the expression that defines
1763 addUInt(DW_Subrange, dwarf::DW_AT_upper_bound, None,
1764 LowerBound + Count - 1);
1767 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
1768 void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, DICompositeType CTy) {
1770 addFlag(&Buffer, dwarf::DW_AT_GNU_vector);
1772 // Emit the element type.
1773 addType(&Buffer, resolve(CTy.getTypeDerivedFrom()));
1775 // Get an anonymous type for index type.
1776 // FIXME: This type should be passed down from the front end
1777 // as different languages may have different sizes for indexes.
1778 DIE *IdxTy = getIndexTyDie();
1780 // Construct an integer type to use for indexes.
1781 IdxTy = createAndAddDIE(dwarf::DW_TAG_base_type, *UnitDie);
1782 addString(IdxTy, dwarf::DW_AT_name, "sizetype");
1783 addUInt(IdxTy, dwarf::DW_AT_byte_size, None, sizeof(int64_t));
1784 addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1785 dwarf::DW_ATE_unsigned);
1786 setIndexTyDie(IdxTy);
1789 // Add subranges to array type.
1790 DIArray Elements = CTy.getTypeArray();
1791 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1792 DIDescriptor Element = Elements.getElement(i);
1793 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1794 constructSubrangeDIE(Buffer, DISubrange(Element), IdxTy);
1798 /// constructEnumTypeDIE - Construct an enum type DIE from DICompositeType.
1799 void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, DICompositeType CTy) {
1800 DIArray Elements = CTy.getTypeArray();
1802 // Add enumerators to enumeration type.
1803 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1804 DIEnumerator Enum(Elements.getElement(i));
1805 if (Enum.isEnumerator()) {
1806 DIE *Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
1807 StringRef Name = Enum.getName();
1808 addString(Enumerator, dwarf::DW_AT_name, Name);
1809 int64_t Value = Enum.getEnumValue();
1810 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
1814 DIType DTy = resolve(CTy.getTypeDerivedFrom());
1816 addType(&Buffer, DTy);
1817 addFlag(&Buffer, dwarf::DW_AT_enum_class);
1821 /// constructContainingTypeDIEs - Construct DIEs for types that contain
1823 void DwarfUnit::constructContainingTypeDIEs() {
1824 for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(),
1825 CE = ContainingTypeMap.end();
1827 DIE *SPDie = CI->first;
1828 DIDescriptor D(CI->second);
1831 DIE *NDie = getDIE(D);
1834 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, NDie);
1838 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
1839 DIE *DwarfUnit::constructVariableDIE(DbgVariable &DV, bool isScopeAbstract) {
1840 StringRef Name = DV.getName();
1842 // Define variable debug information entry.
1843 DIE *VariableDie = new DIE(DV.getTag());
1844 DbgVariable *AbsVar = DV.getAbstractVariable();
1845 DIE *AbsDIE = AbsVar ? AbsVar->getDIE() : NULL;
1847 addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin, AbsDIE);
1850 addString(VariableDie, dwarf::DW_AT_name, Name);
1851 addSourceLine(VariableDie, DV.getVariable());
1852 addType(VariableDie, DV.getType());
1855 if (DV.isArtificial())
1856 addFlag(VariableDie, dwarf::DW_AT_artificial);
1858 if (isScopeAbstract) {
1859 DV.setDIE(VariableDie);
1863 // Add variable address.
1865 unsigned Offset = DV.getDotDebugLocOffset();
1866 if (Offset != ~0U) {
1867 addLocationList(VariableDie, dwarf::DW_AT_location, Offset);
1868 DV.setDIE(VariableDie);
1872 // Check if variable is described by a DBG_VALUE instruction.
1873 if (const MachineInstr *DVInsn = DV.getMInsn()) {
1874 assert(DVInsn->getNumOperands() == 3);
1875 if (DVInsn->getOperand(0).isReg()) {
1876 const MachineOperand RegOp = DVInsn->getOperand(0);
1877 // If the second operand is an immediate, this is an indirect value.
1878 if (DVInsn->getOperand(1).isImm()) {
1879 MachineLocation Location(RegOp.getReg(),
1880 DVInsn->getOperand(1).getImm());
1881 addVariableAddress(DV, VariableDie, Location);
1882 } else if (RegOp.getReg())
1883 addVariableAddress(DV, VariableDie, MachineLocation(RegOp.getReg()));
1884 } else if (DVInsn->getOperand(0).isImm())
1885 addConstantValue(VariableDie, DVInsn->getOperand(0), DV.getType());
1886 else if (DVInsn->getOperand(0).isFPImm())
1887 addConstantFPValue(VariableDie, DVInsn->getOperand(0));
1888 else if (DVInsn->getOperand(0).isCImm())
1889 addConstantValue(VariableDie, DVInsn->getOperand(0).getCImm(),
1890 isUnsignedDIType(DD, DV.getType()));
1892 DV.setDIE(VariableDie);
1895 // .. else use frame index.
1896 int FI = DV.getFrameIndex();
1898 unsigned FrameReg = 0;
1899 const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
1900 int Offset = TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
1901 MachineLocation Location(FrameReg, Offset);
1902 addVariableAddress(DV, VariableDie, Location);
1906 DV.setDIE(VariableDie);
1910 /// constructMemberDIE - Construct member DIE from DIDerivedType.
1911 void DwarfUnit::constructMemberDIE(DIE &Buffer, DIDerivedType DT) {
1912 DIE *MemberDie = createAndAddDIE(DT.getTag(), Buffer);
1913 StringRef Name = DT.getName();
1915 addString(MemberDie, dwarf::DW_AT_name, Name);
1917 addType(MemberDie, resolve(DT.getTypeDerivedFrom()));
1919 addSourceLine(MemberDie, DT);
1921 if (DT.getTag() == dwarf::DW_TAG_inheritance && DT.isVirtual()) {
1923 // For C++, virtual base classes are not at fixed offset. Use following
1924 // expression to extract appropriate offset from vtable.
1925 // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1927 DIELoc *VBaseLocationDie = new (DIEValueAllocator) DIELoc();
1928 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1929 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1930 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1931 addUInt(VBaseLocationDie, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1932 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1933 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1934 addUInt(VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1936 addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
1938 uint64_t Size = DT.getSizeInBits();
1939 uint64_t FieldSize = getBaseTypeSize(DD, DT);
1940 uint64_t OffsetInBytes;
1942 if (Size != FieldSize) {
1943 // Handle bitfield, assume bytes are 8 bits.
1944 addUInt(MemberDie, dwarf::DW_AT_byte_size, None, FieldSize/8);
1945 addUInt(MemberDie, dwarf::DW_AT_bit_size, None, Size);
1947 uint64_t Offset = DT.getOffsetInBits();
1948 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1949 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1950 uint64_t FieldOffset = (HiMark - FieldSize);
1951 Offset -= FieldOffset;
1953 // Maybe we need to work from the other end.
1954 if (Asm->getDataLayout().isLittleEndian())
1955 Offset = FieldSize - (Offset + Size);
1956 addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset);
1958 // Here DW_AT_data_member_location points to the anonymous
1959 // field that includes this bit field.
1960 OffsetInBytes = FieldOffset >> 3;
1962 // This is not a bitfield.
1963 OffsetInBytes = DT.getOffsetInBits() >> 3;
1965 if (DD->getDwarfVersion() <= 2) {
1966 DIELoc *MemLocationDie = new (DIEValueAllocator) DIELoc();
1967 addUInt(MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1968 addUInt(MemLocationDie, dwarf::DW_FORM_udata, OffsetInBytes);
1969 addBlock(MemberDie, dwarf::DW_AT_data_member_location, MemLocationDie);
1971 addUInt(MemberDie, dwarf::DW_AT_data_member_location, None,
1975 if (DT.isProtected())
1976 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1977 dwarf::DW_ACCESS_protected);
1978 else if (DT.isPrivate())
1979 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1980 dwarf::DW_ACCESS_private);
1981 // Otherwise C++ member and base classes are considered public.
1983 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1984 dwarf::DW_ACCESS_public);
1986 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1987 dwarf::DW_VIRTUALITY_virtual);
1989 // Objective-C properties.
1990 if (MDNode *PNode = DT.getObjCProperty())
1991 if (DIEEntry *PropertyDie = getDIEEntry(PNode))
1992 MemberDie->addValue(dwarf::DW_AT_APPLE_property, dwarf::DW_FORM_ref4,
1995 if (DT.isArtificial())
1996 addFlag(MemberDie, dwarf::DW_AT_artificial);
1999 /// getOrCreateStaticMemberDIE - Create new DIE for C++ static member.
2000 DIE *DwarfUnit::getOrCreateStaticMemberDIE(DIDerivedType DT) {
2004 // Construct the context before querying for the existence of the DIE in case
2005 // such construction creates the DIE.
2006 DIE *ContextDIE = getOrCreateContextDIE(resolve(DT.getContext()));
2007 assert(dwarf::isType(ContextDIE->getTag()) &&
2008 "Static member should belong to a type.");
2010 DIE *StaticMemberDIE = getDIE(DT);
2011 if (StaticMemberDIE)
2012 return StaticMemberDIE;
2014 StaticMemberDIE = createAndAddDIE(DT.getTag(), *ContextDIE, DT);
2016 DIType Ty = resolve(DT.getTypeDerivedFrom());
2018 addString(StaticMemberDIE, dwarf::DW_AT_name, DT.getName());
2019 addType(StaticMemberDIE, Ty);
2020 addSourceLine(StaticMemberDIE, DT);
2021 addFlag(StaticMemberDIE, dwarf::DW_AT_external);
2022 addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
2024 // FIXME: We could omit private if the parent is a class_type, and
2025 // public if the parent is something else.
2026 if (DT.isProtected())
2027 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
2028 dwarf::DW_ACCESS_protected);
2029 else if (DT.isPrivate())
2030 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
2031 dwarf::DW_ACCESS_private);
2033 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
2034 dwarf::DW_ACCESS_public);
2036 if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT.getConstant()))
2037 addConstantValue(StaticMemberDIE, CI, isUnsignedDIType(DD, Ty));
2038 if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT.getConstant()))
2039 addConstantFPValue(StaticMemberDIE, CFP);
2041 return StaticMemberDIE;
2044 void DwarfUnit::emitHeader(const MCSymbol *ASectionSym) const {
2045 Asm->OutStreamer.AddComment("DWARF version number");
2046 Asm->EmitInt16(DD->getDwarfVersion());
2047 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
2048 // We share one abbreviations table across all units so it's always at the
2049 // start of the section. Use a relocatable offset where needed to ensure
2050 // linking doesn't invalidate that offset.
2052 Asm->EmitSectionOffset(ASectionSym, ASectionSym);
2054 // Use a constant value when no symbol is provided.
2056 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2057 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
2060 void DwarfUnit::addRange(RangeSpan Range) {
2061 // Only add a range for this unit if we're emitting full debug.
2062 if (getCUNode().getEmissionKind() == DIBuilder::FullDebug) {
2063 // If we have no current ranges just add the range and return, otherwise,
2064 // check the current section and CU against the previous section and CU we
2065 // emitted into and the subprogram was contained within. If these are the
2066 // same then extend our current range, otherwise add this as a new range.
2067 if (CURanges.size() == 0 ||
2068 this != DD->getPrevCU() ||
2069 Asm->getCurrentSection() != DD->getPrevSection()) {
2070 CURanges.push_back(Range);
2074 assert(&(CURanges.back().getEnd()->getSection()) ==
2075 &(Range.getEnd()->getSection()) &&
2076 "We can only append to a range in the same section!");
2077 CURanges.back().setEnd(Range.getEnd());
2081 void DwarfCompileUnit::initStmtList(MCSymbol *DwarfLineSectionSym) {
2082 // Define start line table label for each Compile Unit.
2083 MCSymbol *LineTableStartSym =
2084 Asm->OutStreamer.getDwarfLineTableSymbol(getUniqueID());
2086 stmtListIndex = UnitDie->getValues().size();
2088 // DW_AT_stmt_list is a offset of line number information for this
2089 // compile unit in debug_line section. For split dwarf this is
2090 // left in the skeleton CU and so not included.
2091 // The line table entries are not always emitted in assembly, so it
2092 // is not okay to use line_table_start here.
2093 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2094 addSectionLabel(UnitDie.get(), dwarf::DW_AT_stmt_list, LineTableStartSym);
2096 addSectionDelta(UnitDie.get(), dwarf::DW_AT_stmt_list, LineTableStartSym,
2097 DwarfLineSectionSym);
2100 void DwarfCompileUnit::applyStmtList(DIE &D) {
2101 D.addValue(dwarf::DW_AT_stmt_list,
2102 UnitDie->getAbbrev().getData()[stmtListIndex].getForm(),
2103 UnitDie->getValues()[stmtListIndex]);
2106 void DwarfTypeUnit::emitHeader(const MCSymbol *ASectionSym) const {
2107 DwarfUnit::emitHeader(ASectionSym);
2108 Asm->OutStreamer.AddComment("Type Signature");
2109 Asm->OutStreamer.EmitIntValue(TypeSignature, sizeof(TypeSignature));
2110 Asm->OutStreamer.AddComment("Type DIE Offset");
2111 // In a skeleton type unit there is no type DIE so emit a zero offset.
2112 Asm->OutStreamer.EmitIntValue(Ty ? Ty->getOffset() : 0,
2113 sizeof(Ty->getOffset()));
2116 void DwarfTypeUnit::initSection(const MCSection *Section) {
2117 assert(!this->Section);
2118 this->Section = Section;
2119 // Since each type unit is contained in its own COMDAT section, the begin
2120 // label and the section label are the same. Using the begin label emission in
2121 // DwarfDebug to emit the section label as well is slightly subtle/sneaky, but
2122 // the only other alternative of lazily constructing start-of-section labels
2123 // and storing a mapping in DwarfDebug (or AsmPrinter).
2124 this->SectionSym = this->LabelBegin =
2125 Asm->GetTempSymbol(Section->getLabelBeginName(), getUniqueID());
2127 Asm->GetTempSymbol(Section->getLabelEndName(), getUniqueID());
2128 this->LabelRange = Asm->GetTempSymbol("gnu_ranges", getUniqueID());