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(nullptr), Section(nullptr),
49 DIEIntegerOne = new (DIEValueAllocator) DIEInteger(1);
52 DwarfCompileUnit::DwarfCompileUnit(unsigned UID, DIE *D, DICompileUnit Node,
53 AsmPrinter *A, DwarfDebug *DW,
55 : DwarfUnit(UID, D, Node, A, DW, DWU) {
59 DwarfTypeUnit::DwarfTypeUnit(unsigned UID, DIE *D, DwarfCompileUnit &CU,
60 AsmPrinter *A, DwarfDebug *DW, DwarfFile *DWU,
61 MCDwarfDwoLineTable *SplitLineTable)
62 : DwarfUnit(UID, D, CU.getCUNode(), A, DW, DWU), CU(CU),
63 SplitLineTable(SplitLineTable) {
65 addSectionOffset(*UnitDie, dwarf::DW_AT_stmt_list, 0);
68 /// ~Unit - Destructor for compile unit.
69 DwarfUnit::~DwarfUnit() {
70 for (unsigned j = 0, M = DIEBlocks.size(); j < M; ++j)
71 DIEBlocks[j]->~DIEBlock();
72 for (unsigned j = 0, M = DIELocs.size(); j < M; ++j)
73 DIELocs[j]->~DIELoc();
76 /// createDIEEntry - Creates a new DIEEntry to be a proxy for a debug
77 /// information entry.
78 DIEEntry *DwarfUnit::createDIEEntry(DIE *Entry) {
79 DIEEntry *Value = new (DIEValueAllocator) DIEEntry(Entry);
83 /// getDefaultLowerBound - Return the default lower bound for an array. If the
84 /// DWARF version doesn't handle the language, return -1.
85 int64_t DwarfUnit::getDefaultLowerBound() const {
86 switch (getLanguage()) {
90 case dwarf::DW_LANG_C89:
91 case dwarf::DW_LANG_C99:
92 case dwarf::DW_LANG_C:
93 case dwarf::DW_LANG_C_plus_plus:
94 case dwarf::DW_LANG_ObjC:
95 case dwarf::DW_LANG_ObjC_plus_plus:
98 case dwarf::DW_LANG_Fortran77:
99 case dwarf::DW_LANG_Fortran90:
100 case dwarf::DW_LANG_Fortran95:
103 // The languages below have valid values only if the DWARF version >= 4.
104 case dwarf::DW_LANG_Java:
105 case dwarf::DW_LANG_Python:
106 case dwarf::DW_LANG_UPC:
107 case dwarf::DW_LANG_D:
108 if (dwarf::DWARF_VERSION >= 4)
112 case dwarf::DW_LANG_Ada83:
113 case dwarf::DW_LANG_Ada95:
114 case dwarf::DW_LANG_Cobol74:
115 case dwarf::DW_LANG_Cobol85:
116 case dwarf::DW_LANG_Modula2:
117 case dwarf::DW_LANG_Pascal83:
118 case dwarf::DW_LANG_PLI:
119 if (dwarf::DWARF_VERSION >= 4)
127 /// Check whether the DIE for this MDNode can be shared across CUs.
128 static bool isShareableAcrossCUs(DIDescriptor D) {
129 // When the MDNode can be part of the type system, the DIE can be shared
131 // Combining type units and cross-CU DIE sharing is lower value (since
132 // cross-CU DIE sharing is used in LTO and removes type redundancy at that
133 // level already) but may be implementable for some value in projects
134 // building multiple independent libraries with LTO and then linking those
136 return (D.isType() ||
137 (D.isSubprogram() && !DISubprogram(D).isDefinition())) &&
138 !GenerateDwarfTypeUnits;
141 /// getDIE - Returns the debug information entry map slot for the
142 /// specified debug variable. We delegate the request to DwarfDebug
143 /// when the DIE for this MDNode can be shared across CUs. The mappings
144 /// will be kept in DwarfDebug for shareable DIEs.
145 DIE *DwarfUnit::getDIE(DIDescriptor D) const {
146 if (isShareableAcrossCUs(D))
147 return DD->getDIE(D);
148 return MDNodeToDieMap.lookup(D);
151 /// insertDIE - Insert DIE into the map. We delegate the request to DwarfDebug
152 /// when the DIE for this MDNode can be shared across CUs. The mappings
153 /// will be kept in DwarfDebug for shareable DIEs.
154 void DwarfUnit::insertDIE(DIDescriptor Desc, DIE *D) {
155 if (isShareableAcrossCUs(Desc)) {
156 DD->insertDIE(Desc, D);
159 MDNodeToDieMap.insert(std::make_pair(Desc, D));
162 /// addFlag - Add a flag that is true.
163 void DwarfUnit::addFlag(DIE &Die, dwarf::Attribute Attribute) {
164 if (DD->getDwarfVersion() >= 4)
165 Die.addValue(Attribute, dwarf::DW_FORM_flag_present, DIEIntegerOne);
167 Die.addValue(Attribute, dwarf::DW_FORM_flag, DIEIntegerOne);
170 /// addUInt - Add an unsigned integer attribute data and value.
172 void DwarfUnit::addUInt(DIE &Die, dwarf::Attribute Attribute,
173 Optional<dwarf::Form> Form, uint64_t Integer) {
175 Form = DIEInteger::BestForm(false, Integer);
176 DIEValue *Value = Integer == 1 ? DIEIntegerOne : new (DIEValueAllocator)
178 Die.addValue(Attribute, *Form, Value);
181 void DwarfUnit::addUInt(DIE &Block, dwarf::Form Form, uint64_t Integer) {
182 addUInt(Block, (dwarf::Attribute)0, Form, Integer);
185 /// addSInt - Add an signed integer attribute data and value.
187 void DwarfUnit::addSInt(DIE &Die, dwarf::Attribute Attribute,
188 Optional<dwarf::Form> Form, int64_t Integer) {
190 Form = DIEInteger::BestForm(true, Integer);
191 DIEValue *Value = new (DIEValueAllocator) DIEInteger(Integer);
192 Die.addValue(Attribute, *Form, Value);
195 void DwarfUnit::addSInt(DIELoc &Die, Optional<dwarf::Form> Form,
197 addSInt(Die, (dwarf::Attribute)0, Form, Integer);
200 /// addString - Add a string attribute data and value. We always emit a
201 /// reference to the string pool instead of immediate strings so that DIEs have
202 /// more predictable sizes. In the case of split dwarf we emit an index
203 /// into another table which gets us the static offset into the string
205 void DwarfUnit::addString(DIE &Die, dwarf::Attribute Attribute,
208 if (!DD->useSplitDwarf())
209 return addLocalString(Die, Attribute, String);
211 unsigned idx = DU->getStringPoolIndex(String);
212 DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
213 DIEValue *Str = new (DIEValueAllocator) DIEString(Value, String);
214 Die.addValue(Attribute, dwarf::DW_FORM_GNU_str_index, Str);
217 /// addLocalString - Add a string attribute data and value. This is guaranteed
218 /// to be in the local string pool instead of indirected.
219 void DwarfUnit::addLocalString(DIE &Die, dwarf::Attribute Attribute,
221 MCSymbol *Symb = DU->getStringPoolEntry(String);
223 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
224 Value = new (DIEValueAllocator) DIELabel(Symb);
226 MCSymbol *StringPool = DU->getStringPoolSym();
227 Value = new (DIEValueAllocator) DIEDelta(Symb, StringPool);
229 DIEValue *Str = new (DIEValueAllocator) DIEString(Value, String);
230 Die.addValue(Attribute, dwarf::DW_FORM_strp, Str);
233 /// addExpr - Add a Dwarf expression attribute data and value.
235 void DwarfUnit::addExpr(DIELoc &Die, dwarf::Form Form, const MCExpr *Expr) {
236 DIEValue *Value = new (DIEValueAllocator) DIEExpr(Expr);
237 Die.addValue((dwarf::Attribute)0, Form, Value);
240 /// addLocationList - Add a Dwarf loclistptr attribute data and value.
242 void DwarfUnit::addLocationList(DIE &Die, dwarf::Attribute Attribute,
244 DIEValue *Value = new (DIEValueAllocator) DIELocList(Index);
245 dwarf::Form Form = DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
246 : dwarf::DW_FORM_data4;
247 Die.addValue(Attribute, Form, Value);
250 /// addLabel - Add a Dwarf label attribute data and value.
252 void DwarfUnit::addLabel(DIE &Die, dwarf::Attribute Attribute, dwarf::Form Form,
253 const MCSymbol *Label) {
254 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
255 Die.addValue(Attribute, Form, Value);
258 void DwarfUnit::addLabel(DIELoc &Die, dwarf::Form Form, const MCSymbol *Label) {
259 addLabel(Die, (dwarf::Attribute)0, Form, Label);
262 /// addSectionLabel - Add a Dwarf section label attribute data and value.
264 void DwarfUnit::addSectionLabel(DIE &Die, dwarf::Attribute Attribute,
265 const MCSymbol *Label) {
266 if (DD->getDwarfVersion() >= 4)
267 addLabel(Die, Attribute, dwarf::DW_FORM_sec_offset, Label);
269 addLabel(Die, Attribute, dwarf::DW_FORM_data4, Label);
272 /// addSectionOffset - Add an offset into a section attribute data and value.
274 void DwarfUnit::addSectionOffset(DIE &Die, dwarf::Attribute Attribute,
276 if (DD->getDwarfVersion() >= 4)
277 addUInt(Die, Attribute, dwarf::DW_FORM_sec_offset, Integer);
279 addUInt(Die, Attribute, dwarf::DW_FORM_data4, Integer);
282 /// addLabelAddress - Add a dwarf label attribute data and value using
283 /// DW_FORM_addr or DW_FORM_GNU_addr_index.
285 void DwarfCompileUnit::addLabelAddress(DIE &Die, dwarf::Attribute Attribute,
286 const MCSymbol *Label) {
288 if (!DD->useSplitDwarf())
289 return addLocalLabelAddress(Die, Attribute, Label);
292 DD->addArangeLabel(SymbolCU(this, Label));
294 unsigned idx = DD->getAddressPool().getIndex(Label);
295 DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
296 Die.addValue(Attribute, dwarf::DW_FORM_GNU_addr_index, Value);
299 void DwarfCompileUnit::addLocalLabelAddress(DIE &Die,
300 dwarf::Attribute Attribute,
301 const MCSymbol *Label) {
303 DD->addArangeLabel(SymbolCU(this, Label));
305 Die.addValue(Attribute, dwarf::DW_FORM_addr,
306 Label ? (DIEValue *)new (DIEValueAllocator) DIELabel(Label)
307 : new (DIEValueAllocator) DIEInteger(0));
310 unsigned DwarfCompileUnit::getOrCreateSourceID(StringRef FileName, StringRef DirName) {
311 // If we print assembly, we can't separate .file entries according to
312 // compile units. Thus all files will belong to the default compile unit.
314 // FIXME: add a better feature test than hasRawTextSupport. Even better,
315 // extend .file to support this.
316 return Asm->OutStreamer.EmitDwarfFileDirective(
317 0, DirName, FileName,
318 Asm->OutStreamer.hasRawTextSupport() ? 0 : getUniqueID());
321 unsigned DwarfTypeUnit::getOrCreateSourceID(StringRef FileName, StringRef DirName) {
322 return SplitLineTable ? SplitLineTable->getFile(DirName, FileName)
323 : getCU().getOrCreateSourceID(FileName, DirName);
326 /// addOpAddress - Add a dwarf op address data and value using the
327 /// form given and an op of either DW_FORM_addr or DW_FORM_GNU_addr_index.
329 void DwarfUnit::addOpAddress(DIELoc &Die, const MCSymbol *Sym) {
330 if (!DD->useSplitDwarf()) {
331 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
332 addLabel(Die, dwarf::DW_FORM_udata, Sym);
334 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index);
335 addUInt(Die, dwarf::DW_FORM_GNU_addr_index,
336 DD->getAddressPool().getIndex(Sym));
340 /// addSectionDelta - Add a section label delta attribute data and value.
342 void DwarfUnit::addSectionDelta(DIE &Die, dwarf::Attribute Attribute,
343 const MCSymbol *Hi, const MCSymbol *Lo) {
344 DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
345 Die.addValue(Attribute, DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
346 : dwarf::DW_FORM_data4,
350 void DwarfUnit::addLabelDelta(DIE &Die, dwarf::Attribute Attribute,
351 const MCSymbol *Hi, const MCSymbol *Lo) {
352 DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
353 Die.addValue(Attribute, dwarf::DW_FORM_data4, Value);
356 /// addDIEEntry - Add a DIE attribute data and value.
358 void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute, DIE *Entry) {
359 addDIEEntry(Die, Attribute, createDIEEntry(Entry));
362 void DwarfUnit::addDIETypeSignature(DIE &Die, const DwarfTypeUnit &Type) {
363 Die.addValue(dwarf::DW_AT_signature, dwarf::DW_FORM_ref_sig8,
364 new (DIEValueAllocator) DIETypeSignature(Type));
367 void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute,
369 const DIE *DieCU = Die.getUnitOrNull();
370 const DIE *EntryCU = Entry->getEntry()->getUnitOrNull();
372 // We assume that Die belongs to this CU, if it is not linked to any CU yet.
373 DieCU = &getUnitDie();
375 EntryCU = &getUnitDie();
376 Die.addValue(Attribute,
377 EntryCU == DieCU ? dwarf::DW_FORM_ref4 : dwarf::DW_FORM_ref_addr,
381 /// Create a DIE with the given Tag, add the DIE to its parent, and
382 /// call insertDIE if MD is not null.
383 DIE *DwarfUnit::createAndAddDIE(unsigned Tag, DIE &Parent, DIDescriptor N) {
384 assert(Tag != dwarf::DW_TAG_auto_variable &&
385 Tag != dwarf::DW_TAG_arg_variable);
386 DIE *Die = new DIE((dwarf::Tag)Tag);
387 Parent.addChild(Die);
393 /// addBlock - Add block data.
395 void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute, DIELoc *Loc) {
396 Loc->ComputeSize(Asm);
397 DIELocs.push_back(Loc); // Memoize so we can call the destructor later on.
398 Die.addValue(Attribute, Loc->BestForm(DD->getDwarfVersion()), Loc);
401 void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute,
403 Block->ComputeSize(Asm);
404 DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
405 Die.addValue(Attribute, Block->BestForm(), Block);
408 /// addSourceLine - Add location information to specified debug information
410 void DwarfUnit::addSourceLine(DIE &Die, unsigned Line, StringRef File,
411 StringRef Directory) {
415 unsigned FileID = getOrCreateSourceID(File, Directory);
416 assert(FileID && "Invalid file id");
417 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
418 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
421 /// addSourceLine - Add location information to specified debug information
423 void DwarfUnit::addSourceLine(DIE &Die, DIVariable V) {
424 assert(V.isVariable());
426 addSourceLine(Die, V.getLineNumber(), V.getContext().getFilename(),
427 V.getContext().getDirectory());
430 /// addSourceLine - Add location information to specified debug information
432 void DwarfUnit::addSourceLine(DIE &Die, DIGlobalVariable G) {
433 assert(G.isGlobalVariable());
435 addSourceLine(Die, G.getLineNumber(), G.getFilename(), G.getDirectory());
438 /// addSourceLine - Add location information to specified debug information
440 void DwarfUnit::addSourceLine(DIE &Die, DISubprogram SP) {
441 assert(SP.isSubprogram());
443 addSourceLine(Die, SP.getLineNumber(), SP.getFilename(), SP.getDirectory());
446 /// addSourceLine - Add location information to specified debug information
448 void DwarfUnit::addSourceLine(DIE &Die, DIType Ty) {
451 addSourceLine(Die, Ty.getLineNumber(), Ty.getFilename(), Ty.getDirectory());
454 /// addSourceLine - Add location information to specified debug information
456 void DwarfUnit::addSourceLine(DIE &Die, DIObjCProperty Ty) {
457 assert(Ty.isObjCProperty());
459 DIFile File = Ty.getFile();
460 addSourceLine(Die, Ty.getLineNumber(), File.getFilename(),
461 File.getDirectory());
464 /// addSourceLine - Add location information to specified debug information
466 void DwarfUnit::addSourceLine(DIE &Die, DINameSpace NS) {
469 addSourceLine(Die, NS.getLineNumber(), NS.getFilename(), NS.getDirectory());
472 /// addVariableAddress - Add DW_AT_location attribute for a
473 /// DbgVariable based on provided MachineLocation.
474 void DwarfUnit::addVariableAddress(const DbgVariable &DV, DIE &Die,
475 MachineLocation Location) {
476 if (DV.variableHasComplexAddress())
477 addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
478 else if (DV.isBlockByrefVariable())
479 addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location);
481 addAddress(Die, dwarf::DW_AT_location, Location,
482 DV.getVariable().isIndirect());
485 /// addRegisterOp - Add register operand.
486 void DwarfUnit::addRegisterOp(DIELoc &TheDie, unsigned Reg) {
487 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
488 int DWReg = RI->getDwarfRegNum(Reg, false);
489 bool isSubRegister = DWReg < 0;
493 // Go up the super-register chain until we hit a valid dwarf register number.
494 for (MCSuperRegIterator SR(Reg, RI); SR.isValid() && DWReg < 0; ++SR) {
495 DWReg = RI->getDwarfRegNum(*SR, false);
497 Idx = RI->getSubRegIndex(*SR, Reg);
501 DEBUG(dbgs() << "Invalid Dwarf register number.\n");
502 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_nop);
508 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + DWReg);
510 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
511 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
516 unsigned Size = RI->getSubRegIdxSize(Idx);
517 unsigned Offset = RI->getSubRegIdxOffset(Idx);
519 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_bit_piece);
520 addUInt(TheDie, dwarf::DW_FORM_data1, Size);
521 addUInt(TheDie, dwarf::DW_FORM_data1, Offset);
523 unsigned ByteSize = Size / 8; // Assuming 8 bits per byte.
524 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_piece);
525 addUInt(TheDie, dwarf::DW_FORM_data1, ByteSize);
530 /// addRegisterOffset - Add register offset.
531 void DwarfUnit::addRegisterOffset(DIELoc &TheDie, unsigned Reg,
533 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
534 unsigned DWReg = RI->getDwarfRegNum(Reg, false);
535 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
536 if (Reg == TRI->getFrameRegister(*Asm->MF))
537 // If variable offset is based in frame register then use fbreg.
538 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_fbreg);
540 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + DWReg);
542 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
543 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
545 addSInt(TheDie, dwarf::DW_FORM_sdata, Offset);
548 /// addAddress - Add an address attribute to a die based on the location
550 void DwarfUnit::addAddress(DIE &Die, dwarf::Attribute Attribute,
551 const MachineLocation &Location, bool Indirect) {
552 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
554 if (Location.isReg() && !Indirect)
555 addRegisterOp(*Loc, Location.getReg());
557 addRegisterOffset(*Loc, Location.getReg(), Location.getOffset());
558 if (Indirect && !Location.isReg()) {
559 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
563 // Now attach the location information to the DIE.
564 addBlock(Die, Attribute, Loc);
567 /// addComplexAddress - Start with the address based on the location provided,
568 /// and generate the DWARF information necessary to find the actual variable
569 /// given the extra address information encoded in the DbgVariable, starting
570 /// from the starting location. Add the DWARF information to the die.
572 void DwarfUnit::addComplexAddress(const DbgVariable &DV, DIE &Die,
573 dwarf::Attribute Attribute,
574 const MachineLocation &Location) {
575 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
576 unsigned N = DV.getNumAddrElements();
578 if (Location.isReg()) {
579 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
580 // If first address element is OpPlus then emit
581 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
582 addRegisterOffset(*Loc, Location.getReg(), DV.getAddrElement(1));
585 addRegisterOp(*Loc, Location.getReg());
587 addRegisterOffset(*Loc, Location.getReg(), Location.getOffset());
590 uint64_t Element = DV.getAddrElement(i);
591 if (Element == DIBuilder::OpPlus) {
592 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
593 addUInt(*Loc, dwarf::DW_FORM_udata, DV.getAddrElement(++i));
594 } else if (Element == DIBuilder::OpDeref) {
595 if (!Location.isReg())
596 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
598 llvm_unreachable("unknown DIBuilder Opcode");
601 // Now attach the location information to the DIE.
602 addBlock(Die, Attribute, Loc);
605 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
606 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
607 gives the variable VarName either the struct, or a pointer to the struct, as
608 its type. This is necessary for various behind-the-scenes things the
609 compiler needs to do with by-reference variables in Blocks.
611 However, as far as the original *programmer* is concerned, the variable
612 should still have type 'SomeType', as originally declared.
614 The function getBlockByrefType dives into the __Block_byref_x_VarName
615 struct to find the original type of the variable, which is then assigned to
616 the variable's Debug Information Entry as its real type. So far, so good.
617 However now the debugger will expect the variable VarName to have the type
618 SomeType. So we need the location attribute for the variable to be an
619 expression that explains to the debugger how to navigate through the
620 pointers and struct to find the actual variable of type SomeType.
622 The following function does just that. We start by getting
623 the "normal" location for the variable. This will be the location
624 of either the struct __Block_byref_x_VarName or the pointer to the
625 struct __Block_byref_x_VarName.
627 The struct will look something like:
629 struct __Block_byref_x_VarName {
631 struct __Block_byref_x_VarName *forwarding;
632 ... <various other fields>
634 ... <maybe more fields>
637 If we are given the struct directly (as our starting point) we
638 need to tell the debugger to:
640 1). Add the offset of the forwarding field.
642 2). Follow that pointer to get the real __Block_byref_x_VarName
643 struct to use (the real one may have been copied onto the heap).
645 3). Add the offset for the field VarName, to find the actual variable.
647 If we started with a pointer to the struct, then we need to
648 dereference that pointer first, before the other steps.
649 Translating this into DWARF ops, we will need to append the following
650 to the current location description for the variable:
652 DW_OP_deref -- optional, if we start with a pointer
653 DW_OP_plus_uconst <forward_fld_offset>
655 DW_OP_plus_uconst <varName_fld_offset>
657 That is what this function does. */
659 /// addBlockByrefAddress - Start with the address based on the location
660 /// provided, and generate the DWARF information necessary to find the
661 /// actual Block variable (navigating the Block struct) based on the
662 /// starting location. Add the DWARF information to the die. For
663 /// more information, read large comment just above here.
665 void DwarfUnit::addBlockByrefAddress(const DbgVariable &DV, DIE &Die,
666 dwarf::Attribute Attribute,
667 const MachineLocation &Location) {
668 DIType Ty = DV.getType();
670 uint16_t Tag = Ty.getTag();
671 bool isPointer = false;
673 StringRef varName = DV.getName();
675 if (Tag == dwarf::DW_TAG_pointer_type) {
676 DIDerivedType DTy(Ty);
677 TmpTy = resolve(DTy.getTypeDerivedFrom());
681 DICompositeType blockStruct(TmpTy);
683 // Find the __forwarding field and the variable field in the __Block_byref
685 DIArray Fields = blockStruct.getTypeArray();
686 DIDerivedType varField;
687 DIDerivedType forwardingField;
689 for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
690 DIDerivedType DT(Fields.getElement(i));
691 StringRef fieldName = DT.getName();
692 if (fieldName == "__forwarding")
693 forwardingField = DT;
694 else if (fieldName == varName)
698 // Get the offsets for the forwarding field and the variable field.
699 unsigned forwardingFieldOffset = forwardingField.getOffsetInBits() >> 3;
700 unsigned varFieldOffset = varField.getOffsetInBits() >> 2;
702 // Decode the original location, and use that as the start of the byref
703 // variable's location.
704 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
706 if (Location.isReg())
707 addRegisterOp(*Loc, Location.getReg());
709 addRegisterOffset(*Loc, Location.getReg(), Location.getOffset());
711 // If we started with a pointer to the __Block_byref... struct, then
712 // the first thing we need to do is dereference the pointer (DW_OP_deref).
714 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
716 // Next add the offset for the '__forwarding' field:
717 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
718 // adding the offset if it's 0.
719 if (forwardingFieldOffset > 0) {
720 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
721 addUInt(*Loc, dwarf::DW_FORM_udata, forwardingFieldOffset);
724 // Now dereference the __forwarding field to get to the real __Block_byref
725 // struct: DW_OP_deref.
726 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
728 // Now that we've got the real __Block_byref... struct, add the offset
729 // for the variable's field to get to the location of the actual variable:
730 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
731 if (varFieldOffset > 0) {
732 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
733 addUInt(*Loc, dwarf::DW_FORM_udata, varFieldOffset);
736 // Now attach the location information to the DIE.
737 addBlock(Die, Attribute, Loc);
740 /// isTypeSigned - Return true if the type is signed.
741 static bool isTypeSigned(DwarfDebug *DD, DIType Ty, int *SizeInBits) {
742 if (Ty.isDerivedType())
743 return isTypeSigned(DD, DD->resolve(DIDerivedType(Ty).getTypeDerivedFrom()),
745 if (Ty.isBasicType())
746 if (DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed ||
747 DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed_char) {
748 *SizeInBits = Ty.getSizeInBits();
754 /// Return true if type encoding is unsigned.
755 static bool isUnsignedDIType(DwarfDebug *DD, DIType Ty) {
756 DIDerivedType DTy(Ty);
757 if (DTy.isDerivedType())
758 return isUnsignedDIType(DD, DD->resolve(DTy.getTypeDerivedFrom()));
761 if (BTy.isBasicType()) {
762 unsigned Encoding = BTy.getEncoding();
763 if (Encoding == dwarf::DW_ATE_unsigned ||
764 Encoding == dwarf::DW_ATE_unsigned_char ||
765 Encoding == dwarf::DW_ATE_boolean)
771 /// If this type is derived from a base type then return base type size.
772 static uint64_t getBaseTypeSize(DwarfDebug *DD, DIDerivedType Ty) {
773 unsigned Tag = Ty.getTag();
775 if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef &&
776 Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type &&
777 Tag != dwarf::DW_TAG_restrict_type)
778 return Ty.getSizeInBits();
780 DIType BaseType = DD->resolve(Ty.getTypeDerivedFrom());
782 // If this type is not derived from any type or the type is a declaration then
783 // take conservative approach.
784 if (!BaseType.isValid() || BaseType.isForwardDecl())
785 return Ty.getSizeInBits();
787 // If this is a derived type, go ahead and get the base type, unless it's a
788 // reference then it's just the size of the field. Pointer types have no need
789 // of this since they're a different type of qualification on the type.
790 if (BaseType.getTag() == dwarf::DW_TAG_reference_type ||
791 BaseType.getTag() == dwarf::DW_TAG_rvalue_reference_type)
792 return Ty.getSizeInBits();
794 if (BaseType.isDerivedType())
795 return getBaseTypeSize(DD, DIDerivedType(BaseType));
797 return BaseType.getSizeInBits();
800 /// addConstantValue - Add constant value entry in variable DIE.
801 void DwarfUnit::addConstantValue(DIE &Die, const MachineOperand &MO,
803 // FIXME: This is a bit conservative/simple - it emits negative values at
804 // their maximum bit width which is a bit unfortunate (& doesn't prefer
805 // udata/sdata over dataN as suggested by the DWARF spec)
806 assert(MO.isImm() && "Invalid machine operand!");
808 bool SignedConstant = isTypeSigned(DD, Ty, &SizeInBits);
811 // If we're a signed constant definitely use sdata.
812 if (SignedConstant) {
813 addSInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, MO.getImm());
817 // Else use data for now unless it's larger than we can deal with.
818 switch (SizeInBits) {
820 Form = dwarf::DW_FORM_data1;
823 Form = dwarf::DW_FORM_data2;
826 Form = dwarf::DW_FORM_data4;
829 Form = dwarf::DW_FORM_data8;
832 Form = dwarf::DW_FORM_udata;
833 addUInt(Die, dwarf::DW_AT_const_value, Form, MO.getImm());
836 addUInt(Die, dwarf::DW_AT_const_value, Form, MO.getImm());
839 /// addConstantFPValue - Add constant value entry in variable DIE.
840 void DwarfUnit::addConstantFPValue(DIE &Die, const MachineOperand &MO) {
841 assert(MO.isFPImm() && "Invalid machine operand!");
842 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
843 APFloat FPImm = MO.getFPImm()->getValueAPF();
845 // Get the raw data form of the floating point.
846 const APInt FltVal = FPImm.bitcastToAPInt();
847 const char *FltPtr = (const char *)FltVal.getRawData();
849 int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
850 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
851 int Incr = (LittleEndian ? 1 : -1);
852 int Start = (LittleEndian ? 0 : NumBytes - 1);
853 int Stop = (LittleEndian ? NumBytes : -1);
855 // Output the constant to DWARF one byte at a time.
856 for (; Start != Stop; Start += Incr)
857 addUInt(*Block, dwarf::DW_FORM_data1, (unsigned char)0xFF & FltPtr[Start]);
859 addBlock(Die, dwarf::DW_AT_const_value, Block);
862 /// addConstantFPValue - Add constant value entry in variable DIE.
863 void DwarfUnit::addConstantFPValue(DIE &Die, const ConstantFP *CFP) {
864 // Pass this down to addConstantValue as an unsigned bag of bits.
865 addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true);
868 /// addConstantValue - Add constant value entry in variable DIE.
869 void DwarfUnit::addConstantValue(DIE &Die, const ConstantInt *CI,
871 addConstantValue(Die, CI->getValue(), Unsigned);
874 // addConstantValue - Add constant value entry in variable DIE.
875 void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, bool Unsigned) {
876 unsigned CIBitWidth = Val.getBitWidth();
877 if (CIBitWidth <= 64) {
878 // If we're a signed constant definitely use sdata.
880 addSInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
885 // Else use data for now unless it's larger than we can deal with.
887 switch (CIBitWidth) {
889 Form = dwarf::DW_FORM_data1;
892 Form = dwarf::DW_FORM_data2;
895 Form = dwarf::DW_FORM_data4;
898 Form = dwarf::DW_FORM_data8;
901 addUInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_udata,
905 addUInt(Die, dwarf::DW_AT_const_value, Form, Val.getZExtValue());
909 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
911 // Get the raw data form of the large APInt.
912 const uint64_t *Ptr64 = Val.getRawData();
914 int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
915 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
917 // Output the constant to DWARF one byte at a time.
918 for (int i = 0; i < NumBytes; i++) {
921 c = Ptr64[i / 8] >> (8 * (i & 7));
923 c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
924 addUInt(*Block, dwarf::DW_FORM_data1, c);
927 addBlock(Die, dwarf::DW_AT_const_value, Block);
930 /// addTemplateParams - Add template parameters into buffer.
931 void DwarfUnit::addTemplateParams(DIE &Buffer, DIArray TParams) {
932 // Add template parameters.
933 for (unsigned i = 0, e = TParams.getNumElements(); i != e; ++i) {
934 DIDescriptor Element = TParams.getElement(i);
935 if (Element.isTemplateTypeParameter())
936 constructTemplateTypeParameterDIE(Buffer,
937 DITemplateTypeParameter(Element));
938 else if (Element.isTemplateValueParameter())
939 constructTemplateValueParameterDIE(Buffer,
940 DITemplateValueParameter(Element));
944 /// getOrCreateContextDIE - Get context owner's DIE.
945 DIE *DwarfUnit::getOrCreateContextDIE(DIScope Context) {
946 if (!Context || Context.isFile())
947 return &getUnitDie();
948 if (Context.isType())
949 return getOrCreateTypeDIE(DIType(Context));
950 if (Context.isNameSpace())
951 return getOrCreateNameSpace(DINameSpace(Context));
952 if (Context.isSubprogram())
953 return getOrCreateSubprogramDIE(DISubprogram(Context));
954 return getDIE(Context);
957 DIE *DwarfUnit::createTypeDIE(DICompositeType Ty) {
958 DIScope Context = resolve(Ty.getContext());
959 DIE *ContextDIE = getOrCreateContextDIE(Context);
961 DIE *TyDIE = getDIE(Ty);
966 TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
968 constructTypeDIE(*TyDIE, Ty);
970 updateAcceleratorTables(Context, Ty, TyDIE);
974 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
976 DIE *DwarfUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
982 assert(Ty == resolve(Ty.getRef()) &&
983 "type was not uniqued, possible ODR violation.");
985 // DW_TAG_restrict_type is not supported in DWARF2
986 if (Ty.getTag() == dwarf::DW_TAG_restrict_type && DD->getDwarfVersion() <= 2)
987 return getOrCreateTypeDIE(resolve(DIDerivedType(Ty).getTypeDerivedFrom()));
989 // Construct the context before querying for the existence of the DIE in case
990 // such construction creates the DIE.
991 DIScope Context = resolve(Ty.getContext());
992 DIE *ContextDIE = getOrCreateContextDIE(Context);
995 if (DIE *TyDIE = getDIE(Ty))
999 DIE &TyDIE = *createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
1001 updateAcceleratorTables(Context, Ty, &TyDIE);
1003 if (Ty.isBasicType())
1004 constructTypeDIE(TyDIE, DIBasicType(Ty));
1005 else if (Ty.isCompositeType()) {
1006 DICompositeType CTy(Ty);
1007 if (GenerateDwarfTypeUnits && !Ty.isForwardDecl())
1008 if (MDString *TypeId = CTy.getIdentifier()) {
1009 DD->addDwarfTypeUnitType(getCU(), TypeId->getString(), TyDIE, CTy);
1010 // Skip updating the accelerator tables since this is not the full type.
1013 constructTypeDIE(TyDIE, CTy);
1015 assert(Ty.isDerivedType() && "Unknown kind of DIType");
1016 constructTypeDIE(TyDIE, DIDerivedType(Ty));
1022 void DwarfUnit::updateAcceleratorTables(DIScope Context, DIType Ty,
1024 if (!Ty.getName().empty() && !Ty.isForwardDecl()) {
1025 bool IsImplementation = 0;
1026 if (Ty.isCompositeType()) {
1027 DICompositeType CT(Ty);
1028 // A runtime language of 0 actually means C/C++ and that any
1029 // non-negative value is some version of Objective-C/C++.
1030 IsImplementation = (CT.getRunTimeLang() == 0) || CT.isObjcClassComplete();
1032 unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0;
1033 DD->addAccelType(Ty.getName(), TyDIE, Flags);
1035 if ((!Context || Context.isCompileUnit() || Context.isFile() ||
1036 Context.isNameSpace()) &&
1037 getCUNode().getEmissionKind() != DIBuilder::LineTablesOnly)
1038 GlobalTypes[getParentContextString(Context) + Ty.getName().str()] = TyDIE;
1042 /// addType - Add a new type attribute to the specified entity.
1043 void DwarfUnit::addType(DIE &Entity, DIType Ty, dwarf::Attribute Attribute) {
1044 assert(Ty && "Trying to add a type that doesn't exist?");
1046 // Check for pre-existence.
1047 DIEEntry *Entry = getDIEEntry(Ty);
1048 // If it exists then use the existing value.
1050 addDIEEntry(Entity, Attribute, Entry);
1055 DIE *Buffer = getOrCreateTypeDIE(Ty);
1058 Entry = createDIEEntry(Buffer);
1059 insertDIEEntry(Ty, Entry);
1060 addDIEEntry(Entity, Attribute, Entry);
1063 /// addGlobalName - Add a new global name to the compile unit.
1064 void DwarfUnit::addGlobalName(StringRef Name, DIE &Die, DIScope Context) {
1065 if (getCUNode().getEmissionKind() == DIBuilder::LineTablesOnly)
1067 std::string FullName = getParentContextString(Context) + Name.str();
1068 GlobalNames[FullName] = &Die;
1071 /// getParentContextString - Walks the metadata parent chain in a language
1072 /// specific manner (using the compile unit language) and returns
1073 /// it as a string. This is done at the metadata level because DIEs may
1074 /// not currently have been added to the parent context and walking the
1075 /// DIEs looking for names is more expensive than walking the metadata.
1076 std::string DwarfUnit::getParentContextString(DIScope Context) const {
1080 // FIXME: Decide whether to implement this for non-C++ languages.
1081 if (getLanguage() != dwarf::DW_LANG_C_plus_plus)
1085 SmallVector<DIScope, 1> Parents;
1086 while (!Context.isCompileUnit()) {
1087 Parents.push_back(Context);
1088 if (Context.getContext())
1089 Context = resolve(Context.getContext());
1091 // Structure, etc types will have a NULL context if they're at the top
1096 // Reverse iterate over our list to go from the outermost construct to the
1098 for (SmallVectorImpl<DIScope>::reverse_iterator I = Parents.rbegin(),
1102 StringRef Name = Ctx.getName();
1103 if (!Name.empty()) {
1111 /// constructTypeDIE - Construct basic type die from DIBasicType.
1112 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
1113 // Get core information.
1114 StringRef Name = BTy.getName();
1115 // Add name if not anonymous or intermediate type.
1117 addString(Buffer, dwarf::DW_AT_name, Name);
1119 // An unspecified type only has a name attribute.
1120 if (BTy.getTag() == dwarf::DW_TAG_unspecified_type)
1123 addUInt(Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1126 uint64_t Size = BTy.getSizeInBits() >> 3;
1127 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
1130 /// constructTypeDIE - Construct derived type die from DIDerivedType.
1131 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
1132 // Get core information.
1133 StringRef Name = DTy.getName();
1134 uint64_t Size = DTy.getSizeInBits() >> 3;
1135 uint16_t Tag = Buffer.getTag();
1137 // Map to main type, void will not have a type.
1138 DIType FromTy = resolve(DTy.getTypeDerivedFrom());
1140 addType(Buffer, FromTy);
1142 // Add name if not anonymous or intermediate type.
1144 addString(Buffer, dwarf::DW_AT_name, Name);
1146 // Add size if non-zero (derived types might be zero-sized.)
1147 if (Size && Tag != dwarf::DW_TAG_pointer_type)
1148 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
1150 if (Tag == dwarf::DW_TAG_ptr_to_member_type)
1151 addDIEEntry(Buffer, dwarf::DW_AT_containing_type,
1152 getOrCreateTypeDIE(resolve(DTy.getClassType())));
1153 // Add source line info if available and TyDesc is not a forward declaration.
1154 if (!DTy.isForwardDecl())
1155 addSourceLine(Buffer, DTy);
1158 /// constructSubprogramArguments - Construct function argument DIEs.
1159 void DwarfUnit::constructSubprogramArguments(DIE &Buffer, DIArray Args) {
1160 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1161 DIDescriptor Ty = Args.getElement(i);
1162 if (Ty.isUnspecifiedParameter()) {
1163 assert(i == N-1 && "Unspecified parameter must be the last argument");
1164 createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
1166 DIE *Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
1167 addType(*Arg, DIType(Ty));
1168 if (DIType(Ty).isArtificial())
1169 addFlag(*Arg, dwarf::DW_AT_artificial);
1174 /// constructTypeDIE - Construct type DIE from DICompositeType.
1175 void DwarfUnit::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
1176 // Add name if not anonymous or intermediate type.
1177 StringRef Name = CTy.getName();
1179 uint64_t Size = CTy.getSizeInBits() >> 3;
1180 uint16_t Tag = Buffer.getTag();
1183 case dwarf::DW_TAG_array_type:
1184 constructArrayTypeDIE(Buffer, CTy);
1186 case dwarf::DW_TAG_enumeration_type:
1187 constructEnumTypeDIE(Buffer, CTy);
1189 case dwarf::DW_TAG_subroutine_type: {
1190 // Add return type. A void return won't have a type.
1191 DIArray Elements = CTy.getTypeArray();
1192 DIType RTy(Elements.getElement(0));
1194 addType(Buffer, RTy);
1196 bool isPrototyped = true;
1197 if (Elements.getNumElements() == 2 &&
1198 Elements.getElement(1).isUnspecifiedParameter())
1199 isPrototyped = false;
1201 constructSubprogramArguments(Buffer, Elements);
1203 // Add prototype flag if we're dealing with a C language and the
1204 // function has been prototyped.
1205 uint16_t Language = getLanguage();
1207 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1208 Language == dwarf::DW_LANG_ObjC))
1209 addFlag(Buffer, dwarf::DW_AT_prototyped);
1211 if (CTy.isLValueReference())
1212 addFlag(Buffer, dwarf::DW_AT_reference);
1214 if (CTy.isRValueReference())
1215 addFlag(Buffer, dwarf::DW_AT_rvalue_reference);
1217 case dwarf::DW_TAG_structure_type:
1218 case dwarf::DW_TAG_union_type:
1219 case dwarf::DW_TAG_class_type: {
1220 // Add elements to structure type.
1221 DIArray Elements = CTy.getTypeArray();
1222 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1223 DIDescriptor Element = Elements.getElement(i);
1224 if (Element.isSubprogram())
1225 getOrCreateSubprogramDIE(DISubprogram(Element));
1226 else if (Element.isDerivedType()) {
1227 DIDerivedType DDTy(Element);
1228 if (DDTy.getTag() == dwarf::DW_TAG_friend) {
1229 DIE &ElemDie = *createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
1230 addType(ElemDie, resolve(DDTy.getTypeDerivedFrom()),
1231 dwarf::DW_AT_friend);
1232 } else if (DDTy.isStaticMember()) {
1233 getOrCreateStaticMemberDIE(DDTy);
1235 constructMemberDIE(Buffer, DDTy);
1237 } else if (Element.isObjCProperty()) {
1238 DIObjCProperty Property(Element);
1239 DIE &ElemDie = *createAndAddDIE(Property.getTag(), Buffer);
1240 StringRef PropertyName = Property.getObjCPropertyName();
1241 addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
1242 if (Property.getType())
1243 addType(ElemDie, Property.getType());
1244 addSourceLine(ElemDie, Property);
1245 StringRef GetterName = Property.getObjCPropertyGetterName();
1246 if (!GetterName.empty())
1247 addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
1248 StringRef SetterName = Property.getObjCPropertySetterName();
1249 if (!SetterName.empty())
1250 addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
1251 unsigned PropertyAttributes = 0;
1252 if (Property.isReadOnlyObjCProperty())
1253 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readonly;
1254 if (Property.isReadWriteObjCProperty())
1255 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readwrite;
1256 if (Property.isAssignObjCProperty())
1257 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_assign;
1258 if (Property.isRetainObjCProperty())
1259 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_retain;
1260 if (Property.isCopyObjCProperty())
1261 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_copy;
1262 if (Property.isNonAtomicObjCProperty())
1263 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_nonatomic;
1264 if (PropertyAttributes)
1265 addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None,
1266 PropertyAttributes);
1268 DIEEntry *Entry = getDIEEntry(Element);
1270 Entry = createDIEEntry(&ElemDie);
1271 insertDIEEntry(Element, Entry);
1277 if (CTy.isAppleBlockExtension())
1278 addFlag(Buffer, dwarf::DW_AT_APPLE_block);
1280 DICompositeType ContainingType(resolve(CTy.getContainingType()));
1282 addDIEEntry(Buffer, dwarf::DW_AT_containing_type,
1283 getOrCreateTypeDIE(ContainingType));
1285 if (CTy.isObjcClassComplete())
1286 addFlag(Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
1288 // Add template parameters to a class, structure or union types.
1289 // FIXME: The support isn't in the metadata for this yet.
1290 if (Tag == dwarf::DW_TAG_class_type ||
1291 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
1292 addTemplateParams(Buffer, CTy.getTemplateParams());
1300 // Add name if not anonymous or intermediate type.
1302 addString(Buffer, dwarf::DW_AT_name, Name);
1304 if (Tag == dwarf::DW_TAG_enumeration_type ||
1305 Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
1306 Tag == dwarf::DW_TAG_union_type) {
1307 // Add size if non-zero (derived types might be zero-sized.)
1308 // TODO: Do we care about size for enum forward declarations?
1310 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
1311 else if (!CTy.isForwardDecl())
1312 // Add zero size if it is not a forward declaration.
1313 addUInt(Buffer, dwarf::DW_AT_byte_size, None, 0);
1315 // If we're a forward decl, say so.
1316 if (CTy.isForwardDecl())
1317 addFlag(Buffer, dwarf::DW_AT_declaration);
1319 // Add source line info if available.
1320 if (!CTy.isForwardDecl())
1321 addSourceLine(Buffer, CTy);
1323 // No harm in adding the runtime language to the declaration.
1324 unsigned RLang = CTy.getRunTimeLang();
1326 addUInt(Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
1331 /// constructTemplateTypeParameterDIE - Construct new DIE for the given
1332 /// DITemplateTypeParameter.
1333 void DwarfUnit::constructTemplateTypeParameterDIE(DIE &Buffer,
1334 DITemplateTypeParameter TP) {
1336 *createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
1337 // Add the type if it exists, it could be void and therefore no type.
1339 addType(ParamDIE, resolve(TP.getType()));
1340 if (!TP.getName().empty())
1341 addString(ParamDIE, dwarf::DW_AT_name, TP.getName());
1344 /// constructTemplateValueParameterDIE - Construct new DIE for the given
1345 /// DITemplateValueParameter.
1347 DwarfUnit::constructTemplateValueParameterDIE(DIE &Buffer,
1348 DITemplateValueParameter VP) {
1349 DIE &ParamDIE = *createAndAddDIE(VP.getTag(), Buffer);
1351 // Add the type if there is one, template template and template parameter
1352 // packs will not have a type.
1353 if (VP.getTag() == dwarf::DW_TAG_template_value_parameter)
1354 addType(ParamDIE, resolve(VP.getType()));
1355 if (!VP.getName().empty())
1356 addString(ParamDIE, dwarf::DW_AT_name, VP.getName());
1357 if (Value *Val = VP.getValue()) {
1358 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val))
1359 addConstantValue(ParamDIE, CI,
1360 isUnsignedDIType(DD, resolve(VP.getType())));
1361 else if (GlobalValue *GV = dyn_cast<GlobalValue>(Val)) {
1362 // For declaration non-type template parameters (such as global values and
1364 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
1365 addOpAddress(*Loc, Asm->getSymbol(GV));
1366 // Emit DW_OP_stack_value to use the address as the immediate value of the
1367 // parameter, rather than a pointer to it.
1368 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
1369 addBlock(ParamDIE, dwarf::DW_AT_location, Loc);
1370 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1371 assert(isa<MDString>(Val));
1372 addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
1373 cast<MDString>(Val)->getString());
1374 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1375 assert(isa<MDNode>(Val));
1376 DIArray A(cast<MDNode>(Val));
1377 addTemplateParams(ParamDIE, A);
1382 /// getOrCreateNameSpace - Create a DIE for DINameSpace.
1383 DIE *DwarfUnit::getOrCreateNameSpace(DINameSpace NS) {
1384 // Construct the context before querying for the existence of the DIE in case
1385 // such construction creates the DIE.
1386 DIE *ContextDIE = getOrCreateContextDIE(NS.getContext());
1388 if (DIE *NDie = getDIE(NS))
1390 DIE &NDie = *createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS);
1392 if (!NS.getName().empty()) {
1393 addString(NDie, dwarf::DW_AT_name, NS.getName());
1394 DD->addAccelNamespace(NS.getName(), &NDie);
1395 addGlobalName(NS.getName(), NDie, NS.getContext());
1397 DD->addAccelNamespace("(anonymous namespace)", &NDie);
1398 addSourceLine(NDie, NS);
1402 /// getOrCreateSubprogramDIE - Create new DIE using SP.
1403 DIE *DwarfUnit::getOrCreateSubprogramDIE(DISubprogram SP) {
1404 // Construct the context before querying for the existence of the DIE in case
1405 // such construction creates the DIE (as is the case for member function
1407 DIScope Context = resolve(SP.getContext());
1408 DIE *ContextDIE = getOrCreateContextDIE(Context);
1410 // Unique declarations based on the ODR, where applicable.
1411 SP = DISubprogram(DD->resolve(SP.getRef()));
1412 assert(SP.Verify());
1414 if (DIE *SPDie = getDIE(SP))
1417 DISubprogram SPDecl = SP.getFunctionDeclaration();
1418 if (SPDecl.isSubprogram())
1419 // Add subprogram definitions to the CU die directly.
1420 ContextDIE = UnitDie.get();
1422 // DW_TAG_inlined_subroutine may refer to this DIE.
1423 DIE &SPDie = *createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
1425 DIE *DeclDie = nullptr;
1426 if (SPDecl.isSubprogram())
1427 DeclDie = getOrCreateSubprogramDIE(SPDecl);
1429 // Add function template parameters.
1430 addTemplateParams(SPDie, SP.getTemplateParams());
1433 // Refer function declaration directly.
1434 addDIEEntry(SPDie, dwarf::DW_AT_specification, DeclDie);
1436 // Add the linkage name if we have one and it isn't in the Decl.
1437 StringRef LinkageName = SP.getLinkageName();
1438 if (!LinkageName.empty()) {
1439 if (SPDecl.isSubprogram() && !SPDecl.getLinkageName().empty())
1440 assert(SPDecl.getLinkageName() == SP.getLinkageName() &&
1441 "decl has a linkage name and it is different");
1443 addString(SPDie, dwarf::DW_AT_MIPS_linkage_name,
1444 GlobalValue::getRealLinkageName(LinkageName));
1447 // If this DIE is going to refer declaration info using AT_specification
1448 // then there is no need to add other attributes.
1452 // Constructors and operators for anonymous aggregates do not have names.
1453 if (!SP.getName().empty())
1454 addString(SPDie, dwarf::DW_AT_name, SP.getName());
1456 addSourceLine(SPDie, SP);
1458 // Add the prototype if we have a prototype and we have a C like
1460 uint16_t Language = getLanguage();
1461 if (SP.isPrototyped() &&
1462 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1463 Language == dwarf::DW_LANG_ObjC))
1464 addFlag(SPDie, dwarf::DW_AT_prototyped);
1466 DICompositeType SPTy = SP.getType();
1467 assert(SPTy.getTag() == dwarf::DW_TAG_subroutine_type &&
1468 "the type of a subprogram should be a subroutine");
1470 DIArray Args = SPTy.getTypeArray();
1471 // Add a return type. If this is a type like a C/C++ void type we don't add a
1473 if (Args.getElement(0))
1474 addType(SPDie, DIType(Args.getElement(0)));
1476 unsigned VK = SP.getVirtuality();
1478 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1479 DIELoc *Block = getDIELoc();
1480 addUInt(*Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1481 addUInt(*Block, dwarf::DW_FORM_udata, SP.getVirtualIndex());
1482 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
1483 ContainingTypeMap.insert(
1484 std::make_pair(&SPDie, resolve(SP.getContainingType())));
1487 if (!SP.isDefinition()) {
1488 addFlag(SPDie, dwarf::DW_AT_declaration);
1490 // Add arguments. Do not add arguments for subprogram definition. They will
1491 // be handled while processing variables.
1492 constructSubprogramArguments(SPDie, Args);
1495 if (SP.isArtificial())
1496 addFlag(SPDie, dwarf::DW_AT_artificial);
1498 if (!SP.isLocalToUnit())
1499 addFlag(SPDie, dwarf::DW_AT_external);
1501 if (SP.isOptimized())
1502 addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1504 if (unsigned isa = Asm->getISAEncoding()) {
1505 addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1508 if (SP.isLValueReference())
1509 addFlag(SPDie, dwarf::DW_AT_reference);
1511 if (SP.isRValueReference())
1512 addFlag(SPDie, dwarf::DW_AT_rvalue_reference);
1514 if (SP.isProtected())
1515 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1516 dwarf::DW_ACCESS_protected);
1517 else if (SP.isPrivate())
1518 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1519 dwarf::DW_ACCESS_private);
1521 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1522 dwarf::DW_ACCESS_public);
1524 if (SP.isExplicit())
1525 addFlag(SPDie, dwarf::DW_AT_explicit);
1530 // Return const expression if value is a GEP to access merged global
1532 // i8* getelementptr ({ i8, i8, i8, i8 }* @_MergedGlobals, i32 0, i32 0)
1533 static const ConstantExpr *getMergedGlobalExpr(const Value *V) {
1534 const ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(V);
1535 if (!CE || CE->getNumOperands() != 3 ||
1536 CE->getOpcode() != Instruction::GetElementPtr)
1539 // First operand points to a global struct.
1540 Value *Ptr = CE->getOperand(0);
1541 if (!isa<GlobalValue>(Ptr) ||
1542 !isa<StructType>(cast<PointerType>(Ptr->getType())->getElementType()))
1545 // Second operand is zero.
1546 const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(CE->getOperand(1));
1547 if (!CI || !CI->isZero())
1550 // Third operand is offset.
1551 if (!isa<ConstantInt>(CE->getOperand(2)))
1557 /// createGlobalVariableDIE - create global variable DIE.
1558 void DwarfCompileUnit::createGlobalVariableDIE(DIGlobalVariable GV) {
1559 // Check for pre-existence.
1563 assert(GV.isGlobalVariable());
1565 DIScope GVContext = GV.getContext();
1566 DIType GTy = DD->resolve(GV.getType());
1568 // If this is a static data member definition, some attributes belong
1569 // to the declaration DIE.
1570 DIE *VariableDIE = nullptr;
1571 bool IsStaticMember = false;
1572 DIDerivedType SDMDecl = GV.getStaticDataMemberDeclaration();
1573 if (SDMDecl.Verify()) {
1574 assert(SDMDecl.isStaticMember() && "Expected static member decl");
1575 // We need the declaration DIE that is in the static member's class.
1576 VariableDIE = getOrCreateStaticMemberDIE(SDMDecl);
1577 IsStaticMember = true;
1580 // If this is not a static data member definition, create the variable
1581 // DIE and add the initial set of attributes to it.
1583 // Construct the context before querying for the existence of the DIE in
1584 // case such construction creates the DIE.
1585 DIE *ContextDIE = getOrCreateContextDIE(GVContext);
1588 VariableDIE = createAndAddDIE(GV.getTag(), *ContextDIE, GV);
1590 // Add name and type.
1591 addString(*VariableDIE, dwarf::DW_AT_name, GV.getDisplayName());
1592 addType(*VariableDIE, GTy);
1594 // Add scoping info.
1595 if (!GV.isLocalToUnit())
1596 addFlag(*VariableDIE, dwarf::DW_AT_external);
1598 // Add line number info.
1599 addSourceLine(*VariableDIE, GV);
1603 bool addToAccelTable = false;
1604 DIE *VariableSpecDIE = nullptr;
1605 bool isGlobalVariable = GV.getGlobal() != nullptr;
1606 if (isGlobalVariable) {
1607 addToAccelTable = true;
1608 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
1609 const MCSymbol *Sym = Asm->getSymbol(GV.getGlobal());
1610 if (GV.getGlobal()->isThreadLocal()) {
1611 // FIXME: Make this work with -gsplit-dwarf.
1612 unsigned PointerSize = Asm->getDataLayout().getPointerSize();
1613 assert((PointerSize == 4 || PointerSize == 8) &&
1614 "Add support for other sizes if necessary");
1615 // Based on GCC's support for TLS:
1616 if (!DD->useSplitDwarf()) {
1617 // 1) Start with a constNu of the appropriate pointer size
1618 addUInt(*Loc, dwarf::DW_FORM_data1,
1619 PointerSize == 4 ? dwarf::DW_OP_const4u : dwarf::DW_OP_const8u);
1620 // 2) containing the (relocated) offset of the TLS variable
1621 // within the module's TLS block.
1622 addExpr(*Loc, dwarf::DW_FORM_udata,
1623 Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym));
1625 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
1626 addUInt(*Loc, dwarf::DW_FORM_udata,
1627 DD->getAddressPool().getIndex(Sym, /* TLS */ true));
1629 // 3) followed by a custom OP to make the debugger do a TLS lookup.
1630 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_push_tls_address);
1632 DD->addArangeLabel(SymbolCU(this, Sym));
1633 addOpAddress(*Loc, Sym);
1635 // Do not create specification DIE if context is either compile unit
1637 if (GVContext && GV.isDefinition() && !GVContext.isCompileUnit() &&
1638 !GVContext.isFile() && !DD->isSubprogramContext(GVContext)) {
1639 // Create specification DIE.
1640 VariableSpecDIE = createAndAddDIE(dwarf::DW_TAG_variable, *UnitDie);
1641 addDIEEntry(*VariableSpecDIE, dwarf::DW_AT_specification, VariableDIE);
1642 addBlock(*VariableSpecDIE, dwarf::DW_AT_location, Loc);
1643 // A static member's declaration is already flagged as such.
1644 if (!SDMDecl.Verify())
1645 addFlag(*VariableDIE, dwarf::DW_AT_declaration);
1647 addBlock(*VariableDIE, dwarf::DW_AT_location, Loc);
1649 // Add the linkage name.
1650 StringRef LinkageName = GV.getLinkageName();
1651 if (!LinkageName.empty())
1652 // From DWARF4: DIEs to which DW_AT_linkage_name may apply include:
1653 // TAG_common_block, TAG_constant, TAG_entry_point, TAG_subprogram and
1655 addString(IsStaticMember && VariableSpecDIE ? *VariableSpecDIE
1657 DD->getDwarfVersion() >= 4 ? dwarf::DW_AT_linkage_name
1658 : dwarf::DW_AT_MIPS_linkage_name,
1659 GlobalValue::getRealLinkageName(LinkageName));
1660 } else if (const ConstantInt *CI =
1661 dyn_cast_or_null<ConstantInt>(GV.getConstant())) {
1662 // AT_const_value was added when the static member was created. To avoid
1663 // emitting AT_const_value multiple times, we only add AT_const_value when
1664 // it is not a static member.
1665 if (!IsStaticMember)
1666 addConstantValue(*VariableDIE, CI, isUnsignedDIType(DD, GTy));
1667 } else if (const ConstantExpr *CE = getMergedGlobalExpr(GV->getOperand(11))) {
1668 addToAccelTable = true;
1669 // GV is a merged global.
1670 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
1671 Value *Ptr = CE->getOperand(0);
1672 MCSymbol *Sym = Asm->getSymbol(cast<GlobalValue>(Ptr));
1673 DD->addArangeLabel(SymbolCU(this, Sym));
1674 addOpAddress(*Loc, Sym);
1675 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1676 SmallVector<Value *, 3> Idx(CE->op_begin() + 1, CE->op_end());
1677 addUInt(*Loc, dwarf::DW_FORM_udata,
1678 Asm->getDataLayout().getIndexedOffset(Ptr->getType(), Idx));
1679 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1680 addBlock(*VariableDIE, dwarf::DW_AT_location, Loc);
1683 if (addToAccelTable) {
1684 DIE *AddrDIE = VariableSpecDIE ? VariableSpecDIE : VariableDIE;
1685 DD->addAccelName(GV.getName(), AddrDIE);
1687 // If the linkage name is different than the name, go ahead and output
1688 // that as well into the name table.
1689 if (GV.getLinkageName() != "" && GV.getName() != GV.getLinkageName())
1690 DD->addAccelName(GV.getLinkageName(), AddrDIE);
1693 if (!GV.isLocalToUnit())
1694 addGlobalName(GV.getName(),
1695 VariableSpecDIE ? *VariableSpecDIE : *VariableDIE,
1699 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
1700 void DwarfUnit::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy) {
1701 DIE &DW_Subrange = *createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
1702 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, IndexTy);
1704 // The LowerBound value defines the lower bounds which is typically zero for
1705 // C/C++. The Count value is the number of elements. Values are 64 bit. If
1706 // Count == -1 then the array is unbounded and we do not emit
1707 // DW_AT_lower_bound and DW_AT_upper_bound attributes. If LowerBound == 0 and
1708 // Count == 0, then the array has zero elements in which case we do not emit
1710 int64_t LowerBound = SR.getLo();
1711 int64_t DefaultLowerBound = getDefaultLowerBound();
1712 int64_t Count = SR.getCount();
1714 if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
1715 addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound);
1717 if (Count != -1 && Count != 0)
1718 // FIXME: An unbounded array should reference the expression that defines
1720 addUInt(DW_Subrange, dwarf::DW_AT_upper_bound, None,
1721 LowerBound + Count - 1);
1724 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
1725 void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, DICompositeType CTy) {
1727 addFlag(Buffer, dwarf::DW_AT_GNU_vector);
1729 // Emit the element type.
1730 addType(Buffer, resolve(CTy.getTypeDerivedFrom()));
1732 // Get an anonymous type for index type.
1733 // FIXME: This type should be passed down from the front end
1734 // as different languages may have different sizes for indexes.
1735 DIE *IdxTy = getIndexTyDie();
1737 // Construct an integer type to use for indexes.
1738 IdxTy = createAndAddDIE(dwarf::DW_TAG_base_type, *UnitDie);
1739 addString(*IdxTy, dwarf::DW_AT_name, "sizetype");
1740 addUInt(*IdxTy, dwarf::DW_AT_byte_size, None, sizeof(int64_t));
1741 addUInt(*IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1742 dwarf::DW_ATE_unsigned);
1743 setIndexTyDie(IdxTy);
1746 // Add subranges to array type.
1747 DIArray Elements = CTy.getTypeArray();
1748 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1749 DIDescriptor Element = Elements.getElement(i);
1750 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1751 constructSubrangeDIE(Buffer, DISubrange(Element), IdxTy);
1755 /// constructEnumTypeDIE - Construct an enum type DIE from DICompositeType.
1756 void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, DICompositeType CTy) {
1757 DIArray Elements = CTy.getTypeArray();
1759 // Add enumerators to enumeration type.
1760 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1761 DIEnumerator Enum(Elements.getElement(i));
1762 if (Enum.isEnumerator()) {
1763 DIE &Enumerator = *createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
1764 StringRef Name = Enum.getName();
1765 addString(Enumerator, dwarf::DW_AT_name, Name);
1766 int64_t Value = Enum.getEnumValue();
1767 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
1771 DIType DTy = resolve(CTy.getTypeDerivedFrom());
1773 addType(Buffer, DTy);
1774 addFlag(Buffer, dwarf::DW_AT_enum_class);
1778 /// constructContainingTypeDIEs - Construct DIEs for types that contain
1780 void DwarfUnit::constructContainingTypeDIEs() {
1781 for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(),
1782 CE = ContainingTypeMap.end();
1784 DIE &SPDie = *CI->first;
1785 DIDescriptor D(CI->second);
1788 DIE *NDie = getDIE(D);
1791 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, NDie);
1795 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
1796 DIE *DwarfUnit::constructVariableDIE(DbgVariable &DV, bool isScopeAbstract) {
1797 auto D = constructVariableDIEImpl(DV, isScopeAbstract);
1802 DIE *DwarfUnit::constructVariableDIEImpl(const DbgVariable &DV,
1803 bool isScopeAbstract) {
1804 StringRef Name = DV.getName();
1806 // Define variable debug information entry.
1807 DIE *VariableDie = new DIE(DV.getTag());
1808 DbgVariable *AbsVar = DV.getAbstractVariable();
1809 DIE *AbsDIE = AbsVar ? AbsVar->getDIE() : nullptr;
1811 addDIEEntry(*VariableDie, dwarf::DW_AT_abstract_origin, AbsDIE);
1814 addString(*VariableDie, dwarf::DW_AT_name, Name);
1815 addSourceLine(*VariableDie, DV.getVariable());
1816 addType(*VariableDie, DV.getType());
1819 if (DV.isArtificial())
1820 addFlag(*VariableDie, dwarf::DW_AT_artificial);
1822 if (isScopeAbstract)
1825 // Add variable address.
1827 unsigned Offset = DV.getDotDebugLocOffset();
1828 if (Offset != ~0U) {
1829 addLocationList(*VariableDie, dwarf::DW_AT_location, Offset);
1833 // Check if variable is described by a DBG_VALUE instruction.
1834 if (const MachineInstr *DVInsn = DV.getMInsn()) {
1835 assert(DVInsn->getNumOperands() == 3);
1836 if (DVInsn->getOperand(0).isReg()) {
1837 const MachineOperand RegOp = DVInsn->getOperand(0);
1838 // If the second operand is an immediate, this is an indirect value.
1839 if (DVInsn->getOperand(1).isImm()) {
1840 MachineLocation Location(RegOp.getReg(),
1841 DVInsn->getOperand(1).getImm());
1842 addVariableAddress(DV, *VariableDie, Location);
1843 } else if (RegOp.getReg())
1844 addVariableAddress(DV, *VariableDie, MachineLocation(RegOp.getReg()));
1845 } else if (DVInsn->getOperand(0).isImm())
1846 addConstantValue(*VariableDie, DVInsn->getOperand(0), DV.getType());
1847 else if (DVInsn->getOperand(0).isFPImm())
1848 addConstantFPValue(*VariableDie, DVInsn->getOperand(0));
1849 else if (DVInsn->getOperand(0).isCImm())
1850 addConstantValue(*VariableDie, DVInsn->getOperand(0).getCImm(),
1851 isUnsignedDIType(DD, DV.getType()));
1856 // .. else use frame index.
1857 int FI = DV.getFrameIndex();
1859 unsigned FrameReg = 0;
1860 const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
1861 int Offset = TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
1862 MachineLocation Location(FrameReg, Offset);
1863 addVariableAddress(DV, *VariableDie, Location);
1869 /// constructMemberDIE - Construct member DIE from DIDerivedType.
1870 void DwarfUnit::constructMemberDIE(DIE &Buffer, DIDerivedType DT) {
1871 DIE &MemberDie = *createAndAddDIE(DT.getTag(), Buffer);
1872 StringRef Name = DT.getName();
1874 addString(MemberDie, dwarf::DW_AT_name, Name);
1876 addType(MemberDie, resolve(DT.getTypeDerivedFrom()));
1878 addSourceLine(MemberDie, DT);
1880 if (DT.getTag() == dwarf::DW_TAG_inheritance && DT.isVirtual()) {
1882 // For C++, virtual base classes are not at fixed offset. Use following
1883 // expression to extract appropriate offset from vtable.
1884 // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1886 DIELoc *VBaseLocationDie = new (DIEValueAllocator) DIELoc();
1887 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1888 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1889 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1890 addUInt(*VBaseLocationDie, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1891 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1892 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1893 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1895 addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
1897 uint64_t Size = DT.getSizeInBits();
1898 uint64_t FieldSize = getBaseTypeSize(DD, DT);
1899 uint64_t OffsetInBytes;
1901 if (Size != FieldSize) {
1902 // Handle bitfield, assume bytes are 8 bits.
1903 addUInt(MemberDie, dwarf::DW_AT_byte_size, None, FieldSize/8);
1904 addUInt(MemberDie, dwarf::DW_AT_bit_size, None, Size);
1906 uint64_t Offset = DT.getOffsetInBits();
1907 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1908 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1909 uint64_t FieldOffset = (HiMark - FieldSize);
1910 Offset -= FieldOffset;
1912 // Maybe we need to work from the other end.
1913 if (Asm->getDataLayout().isLittleEndian())
1914 Offset = FieldSize - (Offset + Size);
1915 addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset);
1917 // Here DW_AT_data_member_location points to the anonymous
1918 // field that includes this bit field.
1919 OffsetInBytes = FieldOffset >> 3;
1921 // This is not a bitfield.
1922 OffsetInBytes = DT.getOffsetInBits() >> 3;
1924 if (DD->getDwarfVersion() <= 2) {
1925 DIELoc *MemLocationDie = new (DIEValueAllocator) DIELoc();
1926 addUInt(*MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1927 addUInt(*MemLocationDie, dwarf::DW_FORM_udata, OffsetInBytes);
1928 addBlock(MemberDie, dwarf::DW_AT_data_member_location, MemLocationDie);
1930 addUInt(MemberDie, dwarf::DW_AT_data_member_location, None,
1934 if (DT.isProtected())
1935 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1936 dwarf::DW_ACCESS_protected);
1937 else if (DT.isPrivate())
1938 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1939 dwarf::DW_ACCESS_private);
1940 // Otherwise C++ member and base classes are considered public.
1942 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1943 dwarf::DW_ACCESS_public);
1945 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1946 dwarf::DW_VIRTUALITY_virtual);
1948 // Objective-C properties.
1949 if (MDNode *PNode = DT.getObjCProperty())
1950 if (DIEEntry *PropertyDie = getDIEEntry(PNode))
1951 MemberDie.addValue(dwarf::DW_AT_APPLE_property, dwarf::DW_FORM_ref4,
1954 if (DT.isArtificial())
1955 addFlag(MemberDie, dwarf::DW_AT_artificial);
1958 /// getOrCreateStaticMemberDIE - Create new DIE for C++ static member.
1959 DIE *DwarfUnit::getOrCreateStaticMemberDIE(DIDerivedType DT) {
1963 // Construct the context before querying for the existence of the DIE in case
1964 // such construction creates the DIE.
1965 DIE *ContextDIE = getOrCreateContextDIE(resolve(DT.getContext()));
1966 assert(dwarf::isType(ContextDIE->getTag()) &&
1967 "Static member should belong to a type.");
1969 if (DIE *StaticMemberDIE = getDIE(DT))
1970 return StaticMemberDIE;
1972 DIE &StaticMemberDIE = *createAndAddDIE(DT.getTag(), *ContextDIE, DT);
1974 DIType Ty = resolve(DT.getTypeDerivedFrom());
1976 addString(StaticMemberDIE, dwarf::DW_AT_name, DT.getName());
1977 addType(StaticMemberDIE, Ty);
1978 addSourceLine(StaticMemberDIE, DT);
1979 addFlag(StaticMemberDIE, dwarf::DW_AT_external);
1980 addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
1982 // FIXME: We could omit private if the parent is a class_type, and
1983 // public if the parent is something else.
1984 if (DT.isProtected())
1985 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1986 dwarf::DW_ACCESS_protected);
1987 else if (DT.isPrivate())
1988 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1989 dwarf::DW_ACCESS_private);
1991 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1992 dwarf::DW_ACCESS_public);
1994 if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT.getConstant()))
1995 addConstantValue(StaticMemberDIE, CI, isUnsignedDIType(DD, Ty));
1996 if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT.getConstant()))
1997 addConstantFPValue(StaticMemberDIE, CFP);
1999 return &StaticMemberDIE;
2002 void DwarfUnit::emitHeader(const MCSymbol *ASectionSym) const {
2003 Asm->OutStreamer.AddComment("DWARF version number");
2004 Asm->EmitInt16(DD->getDwarfVersion());
2005 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
2006 // We share one abbreviations table across all units so it's always at the
2007 // start of the section. Use a relocatable offset where needed to ensure
2008 // linking doesn't invalidate that offset.
2010 Asm->EmitSectionOffset(ASectionSym, ASectionSym);
2012 // Use a constant value when no symbol is provided.
2014 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2015 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
2018 void DwarfUnit::addRange(RangeSpan Range) {
2019 // Only add a range for this unit if we're emitting full debug.
2020 if (getCUNode().getEmissionKind() == DIBuilder::FullDebug) {
2021 // If we have no current ranges just add the range and return, otherwise,
2022 // check the current section and CU against the previous section and CU we
2023 // emitted into and the subprogram was contained within. If these are the
2024 // same then extend our current range, otherwise add this as a new range.
2025 if (CURanges.size() == 0 ||
2026 this != DD->getPrevCU() ||
2027 Asm->getCurrentSection() != DD->getPrevSection()) {
2028 CURanges.push_back(Range);
2032 assert(&(CURanges.back().getEnd()->getSection()) ==
2033 &(Range.getEnd()->getSection()) &&
2034 "We can only append to a range in the same section!");
2035 CURanges.back().setEnd(Range.getEnd());
2039 void DwarfCompileUnit::initStmtList(MCSymbol *DwarfLineSectionSym) {
2040 // Define start line table label for each Compile Unit.
2041 MCSymbol *LineTableStartSym =
2042 Asm->OutStreamer.getDwarfLineTableSymbol(getUniqueID());
2044 stmtListIndex = UnitDie->getValues().size();
2046 // DW_AT_stmt_list is a offset of line number information for this
2047 // compile unit in debug_line section. For split dwarf this is
2048 // left in the skeleton CU and so not included.
2049 // The line table entries are not always emitted in assembly, so it
2050 // is not okay to use line_table_start here.
2051 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2052 addSectionLabel(*UnitDie, dwarf::DW_AT_stmt_list, LineTableStartSym);
2054 addSectionDelta(*UnitDie, dwarf::DW_AT_stmt_list, LineTableStartSym,
2055 DwarfLineSectionSym);
2058 void DwarfCompileUnit::applyStmtList(DIE &D) {
2059 D.addValue(dwarf::DW_AT_stmt_list,
2060 UnitDie->getAbbrev().getData()[stmtListIndex].getForm(),
2061 UnitDie->getValues()[stmtListIndex]);
2064 void DwarfTypeUnit::emitHeader(const MCSymbol *ASectionSym) const {
2065 DwarfUnit::emitHeader(ASectionSym);
2066 Asm->OutStreamer.AddComment("Type Signature");
2067 Asm->OutStreamer.EmitIntValue(TypeSignature, sizeof(TypeSignature));
2068 Asm->OutStreamer.AddComment("Type DIE Offset");
2069 // In a skeleton type unit there is no type DIE so emit a zero offset.
2070 Asm->OutStreamer.EmitIntValue(Ty ? Ty->getOffset() : 0,
2071 sizeof(Ty->getOffset()));
2074 void DwarfTypeUnit::initSection(const MCSection *Section) {
2075 assert(!this->Section);
2076 this->Section = Section;
2077 // Since each type unit is contained in its own COMDAT section, the begin
2078 // label and the section label are the same. Using the begin label emission in
2079 // DwarfDebug to emit the section label as well is slightly subtle/sneaky, but
2080 // the only other alternative of lazily constructing start-of-section labels
2081 // and storing a mapping in DwarfDebug (or AsmPrinter).
2082 this->SectionSym = this->LabelBegin =
2083 Asm->GetTempSymbol(Section->getLabelBeginName(), getUniqueID());
2085 Asm->GetTempSymbol(Section->getLabelEndName(), getUniqueID());
2086 this->LabelRange = Asm->GetTempSymbol("gnu_ranges", getUniqueID());