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, dwarf::Tag UnitTag, DICompileUnit Node,
45 AsmPrinter *A, DwarfDebug *DW, DwarfFile *DWU)
46 : UniqueID(UID), CUNode(Node), UnitDie(UnitTag), DebugInfoOffset(0), Asm(A),
47 DD(DW), DU(DWU), IndexTyDie(nullptr), Section(nullptr),
49 assert(UnitTag == dwarf::DW_TAG_compile_unit ||
50 UnitTag == dwarf::DW_TAG_type_unit);
51 DIEIntegerOne = new (DIEValueAllocator) DIEInteger(1);
54 DwarfCompileUnit::DwarfCompileUnit(unsigned UID, DICompileUnit Node,
55 AsmPrinter *A, DwarfDebug *DW,
57 : DwarfUnit(UID, dwarf::DW_TAG_compile_unit, Node, A, DW, DWU) {
58 insertDIE(Node, &getUnitDie());
61 DwarfTypeUnit::DwarfTypeUnit(unsigned UID, DwarfCompileUnit &CU, AsmPrinter *A,
62 DwarfDebug *DW, DwarfFile *DWU,
63 MCDwarfDwoLineTable *SplitLineTable)
64 : DwarfUnit(UID, dwarf::DW_TAG_type_unit, CU.getCUNode(), A, DW, DWU),
65 CU(CU), SplitLineTable(SplitLineTable) {
67 addSectionOffset(UnitDie, dwarf::DW_AT_stmt_list, 0);
70 /// ~Unit - Destructor for compile unit.
71 DwarfUnit::~DwarfUnit() {
72 for (unsigned j = 0, M = DIEBlocks.size(); j < M; ++j)
73 DIEBlocks[j]->~DIEBlock();
74 for (unsigned j = 0, M = DIELocs.size(); j < M; ++j)
75 DIELocs[j]->~DIELoc();
78 /// createDIEEntry - Creates a new DIEEntry to be a proxy for a debug
79 /// information entry.
80 DIEEntry *DwarfUnit::createDIEEntry(DIE &Entry) {
81 DIEEntry *Value = new (DIEValueAllocator) DIEEntry(Entry);
85 /// getDefaultLowerBound - Return the default lower bound for an array. If the
86 /// DWARF version doesn't handle the language, return -1.
87 int64_t DwarfUnit::getDefaultLowerBound() const {
88 switch (getLanguage()) {
92 case dwarf::DW_LANG_C89:
93 case dwarf::DW_LANG_C99:
94 case dwarf::DW_LANG_C:
95 case dwarf::DW_LANG_C_plus_plus:
96 case dwarf::DW_LANG_ObjC:
97 case dwarf::DW_LANG_ObjC_plus_plus:
100 case dwarf::DW_LANG_Fortran77:
101 case dwarf::DW_LANG_Fortran90:
102 case dwarf::DW_LANG_Fortran95:
105 // The languages below have valid values only if the DWARF version >= 4.
106 case dwarf::DW_LANG_Java:
107 case dwarf::DW_LANG_Python:
108 case dwarf::DW_LANG_UPC:
109 case dwarf::DW_LANG_D:
110 if (dwarf::DWARF_VERSION >= 4)
114 case dwarf::DW_LANG_Ada83:
115 case dwarf::DW_LANG_Ada95:
116 case dwarf::DW_LANG_Cobol74:
117 case dwarf::DW_LANG_Cobol85:
118 case dwarf::DW_LANG_Modula2:
119 case dwarf::DW_LANG_Pascal83:
120 case dwarf::DW_LANG_PLI:
121 if (dwarf::DWARF_VERSION >= 4)
129 /// Check whether the DIE for this MDNode can be shared across CUs.
130 static bool isShareableAcrossCUs(DIDescriptor D) {
131 // When the MDNode can be part of the type system, the DIE can be shared
133 // Combining type units and cross-CU DIE sharing is lower value (since
134 // cross-CU DIE sharing is used in LTO and removes type redundancy at that
135 // level already) but may be implementable for some value in projects
136 // building multiple independent libraries with LTO and then linking those
138 return (D.isType() ||
139 (D.isSubprogram() && !DISubprogram(D).isDefinition())) &&
140 !GenerateDwarfTypeUnits;
143 /// getDIE - Returns the debug information entry map slot for the
144 /// specified debug variable. We delegate the request to DwarfDebug
145 /// when the DIE for this MDNode can be shared across CUs. The mappings
146 /// will be kept in DwarfDebug for shareable DIEs.
147 DIE *DwarfUnit::getDIE(DIDescriptor D) const {
148 if (isShareableAcrossCUs(D))
149 return DD->getDIE(D);
150 return MDNodeToDieMap.lookup(D);
153 /// insertDIE - Insert DIE into the map. We delegate the request to DwarfDebug
154 /// when the DIE for this MDNode can be shared across CUs. The mappings
155 /// will be kept in DwarfDebug for shareable DIEs.
156 void DwarfUnit::insertDIE(DIDescriptor Desc, DIE *D) {
157 if (isShareableAcrossCUs(Desc)) {
158 DD->insertDIE(Desc, D);
161 MDNodeToDieMap.insert(std::make_pair(Desc, D));
164 /// addFlag - Add a flag that is true.
165 void DwarfUnit::addFlag(DIE &Die, dwarf::Attribute Attribute) {
166 if (DD->getDwarfVersion() >= 4)
167 Die.addValue(Attribute, dwarf::DW_FORM_flag_present, DIEIntegerOne);
169 Die.addValue(Attribute, dwarf::DW_FORM_flag, DIEIntegerOne);
172 /// addUInt - Add an unsigned integer attribute data and value.
174 void DwarfUnit::addUInt(DIE &Die, dwarf::Attribute Attribute,
175 Optional<dwarf::Form> Form, uint64_t Integer) {
177 Form = DIEInteger::BestForm(false, Integer);
178 DIEValue *Value = Integer == 1 ? DIEIntegerOne : new (DIEValueAllocator)
180 Die.addValue(Attribute, *Form, Value);
183 void DwarfUnit::addUInt(DIE &Block, dwarf::Form Form, uint64_t Integer) {
184 addUInt(Block, (dwarf::Attribute)0, Form, Integer);
187 /// addSInt - Add an signed integer attribute data and value.
189 void DwarfUnit::addSInt(DIE &Die, dwarf::Attribute Attribute,
190 Optional<dwarf::Form> Form, int64_t Integer) {
192 Form = DIEInteger::BestForm(true, Integer);
193 DIEValue *Value = new (DIEValueAllocator) DIEInteger(Integer);
194 Die.addValue(Attribute, *Form, Value);
197 void DwarfUnit::addSInt(DIELoc &Die, Optional<dwarf::Form> Form,
199 addSInt(Die, (dwarf::Attribute)0, Form, Integer);
202 /// addString - Add a string attribute data and value. We always emit a
203 /// reference to the string pool instead of immediate strings so that DIEs have
204 /// more predictable sizes. In the case of split dwarf we emit an index
205 /// into another table which gets us the static offset into the string
207 void DwarfUnit::addString(DIE &Die, dwarf::Attribute Attribute,
210 if (!DD->useSplitDwarf())
211 return addLocalString(Die, Attribute, String);
213 unsigned idx = DU->getStringPool().getIndex(*Asm, String);
214 DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
215 DIEValue *Str = new (DIEValueAllocator) DIEString(Value, String);
216 Die.addValue(Attribute, dwarf::DW_FORM_GNU_str_index, Str);
219 /// addLocalString - Add a string attribute data and value. This is guaranteed
220 /// to be in the local string pool instead of indirected.
221 void DwarfUnit::addLocalString(DIE &Die, dwarf::Attribute Attribute,
223 MCSymbol *Symb = DU->getStringPool().getSymbol(*Asm, String);
225 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
226 Value = new (DIEValueAllocator) DIELabel(Symb);
228 MCSymbol *StringPool = DU->getStringPool().getSectionSymbol();
229 Value = new (DIEValueAllocator) DIEDelta(Symb, StringPool);
231 DIEValue *Str = new (DIEValueAllocator) DIEString(Value, String);
232 Die.addValue(Attribute, dwarf::DW_FORM_strp, Str);
235 /// addExpr - Add a Dwarf expression attribute data and value.
237 void DwarfUnit::addExpr(DIELoc &Die, dwarf::Form Form, const MCExpr *Expr) {
238 DIEValue *Value = new (DIEValueAllocator) DIEExpr(Expr);
239 Die.addValue((dwarf::Attribute)0, Form, Value);
242 /// addLocationList - Add a Dwarf loclistptr attribute data and value.
244 void DwarfUnit::addLocationList(DIE &Die, dwarf::Attribute Attribute,
246 DIEValue *Value = new (DIEValueAllocator) DIELocList(Index);
247 dwarf::Form Form = DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
248 : dwarf::DW_FORM_data4;
249 Die.addValue(Attribute, Form, Value);
252 /// addLabel - Add a Dwarf label attribute data and value.
254 void DwarfUnit::addLabel(DIE &Die, dwarf::Attribute Attribute, dwarf::Form Form,
255 const MCSymbol *Label) {
256 DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
257 Die.addValue(Attribute, Form, Value);
260 void DwarfUnit::addLabel(DIELoc &Die, dwarf::Form Form, const MCSymbol *Label) {
261 addLabel(Die, (dwarf::Attribute)0, Form, Label);
264 /// addSectionLabel - Add a Dwarf section label attribute data and value.
266 void DwarfUnit::addSectionLabel(DIE &Die, dwarf::Attribute Attribute,
267 const MCSymbol *Label) {
268 if (DD->getDwarfVersion() >= 4)
269 addLabel(Die, Attribute, dwarf::DW_FORM_sec_offset, Label);
271 addLabel(Die, Attribute, dwarf::DW_FORM_data4, Label);
274 /// addSectionOffset - Add an offset into a section attribute data and value.
276 void DwarfUnit::addSectionOffset(DIE &Die, dwarf::Attribute Attribute,
278 if (DD->getDwarfVersion() >= 4)
279 addUInt(Die, Attribute, dwarf::DW_FORM_sec_offset, Integer);
281 addUInt(Die, Attribute, dwarf::DW_FORM_data4, Integer);
284 /// addLabelAddress - Add a dwarf label attribute data and value using
285 /// DW_FORM_addr or DW_FORM_GNU_addr_index.
287 void DwarfCompileUnit::addLabelAddress(DIE &Die, dwarf::Attribute Attribute,
288 const MCSymbol *Label) {
290 if (!DD->useSplitDwarf())
291 return addLocalLabelAddress(Die, Attribute, Label);
294 DD->addArangeLabel(SymbolCU(this, Label));
296 unsigned idx = DD->getAddressPool().getIndex(Label);
297 DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
298 Die.addValue(Attribute, dwarf::DW_FORM_GNU_addr_index, Value);
301 void DwarfCompileUnit::addLocalLabelAddress(DIE &Die,
302 dwarf::Attribute Attribute,
303 const MCSymbol *Label) {
305 DD->addArangeLabel(SymbolCU(this, Label));
307 Die.addValue(Attribute, dwarf::DW_FORM_addr,
308 Label ? (DIEValue *)new (DIEValueAllocator) DIELabel(Label)
309 : new (DIEValueAllocator) DIEInteger(0));
312 unsigned DwarfCompileUnit::getOrCreateSourceID(StringRef FileName, StringRef DirName) {
313 // If we print assembly, we can't separate .file entries according to
314 // compile units. Thus all files will belong to the default compile unit.
316 // FIXME: add a better feature test than hasRawTextSupport. Even better,
317 // extend .file to support this.
318 return Asm->OutStreamer.EmitDwarfFileDirective(
319 0, DirName, FileName,
320 Asm->OutStreamer.hasRawTextSupport() ? 0 : getUniqueID());
323 unsigned DwarfTypeUnit::getOrCreateSourceID(StringRef FileName, StringRef DirName) {
324 return SplitLineTable ? SplitLineTable->getFile(DirName, FileName)
325 : getCU().getOrCreateSourceID(FileName, DirName);
328 /// addOpAddress - Add a dwarf op address data and value using the
329 /// form given and an op of either DW_FORM_addr or DW_FORM_GNU_addr_index.
331 void DwarfUnit::addOpAddress(DIELoc &Die, const MCSymbol *Sym) {
332 if (!DD->useSplitDwarf()) {
333 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
334 addLabel(Die, dwarf::DW_FORM_udata, Sym);
336 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index);
337 addUInt(Die, dwarf::DW_FORM_GNU_addr_index,
338 DD->getAddressPool().getIndex(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 Die.addValue(Attribute, DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
348 : dwarf::DW_FORM_data4,
352 void DwarfUnit::addLabelDelta(DIE &Die, dwarf::Attribute Attribute,
353 const MCSymbol *Hi, const MCSymbol *Lo) {
354 DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
355 Die.addValue(Attribute, dwarf::DW_FORM_data4, Value);
358 /// addDIEEntry - Add a DIE attribute data and value.
360 void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute, DIE &Entry) {
361 addDIEEntry(Die, Attribute, createDIEEntry(Entry));
364 void DwarfUnit::addDIETypeSignature(DIE &Die, const DwarfTypeUnit &Type) {
365 // Flag the type unit reference as a declaration so that if it contains
366 // members (implicit special members, static data member definitions, member
367 // declarations for definitions in this CU, etc) consumers don't get confused
368 // and think this is a full definition.
369 addFlag(Die, dwarf::DW_AT_declaration);
371 Die.addValue(dwarf::DW_AT_signature, dwarf::DW_FORM_ref_sig8,
372 new (DIEValueAllocator) DIETypeSignature(Type));
375 void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute,
377 const DIE *DieCU = Die.getUnitOrNull();
378 const DIE *EntryCU = Entry->getEntry().getUnitOrNull();
380 // We assume that Die belongs to this CU, if it is not linked to any CU yet.
381 DieCU = &getUnitDie();
383 EntryCU = &getUnitDie();
384 Die.addValue(Attribute,
385 EntryCU == DieCU ? dwarf::DW_FORM_ref4 : dwarf::DW_FORM_ref_addr,
389 /// Create a DIE with the given Tag, add the DIE to its parent, and
390 /// call insertDIE if MD is not null.
391 DIE &DwarfUnit::createAndAddDIE(unsigned Tag, DIE &Parent, DIDescriptor N) {
392 assert(Tag != dwarf::DW_TAG_auto_variable &&
393 Tag != dwarf::DW_TAG_arg_variable);
394 Parent.addChild(make_unique<DIE>((dwarf::Tag)Tag));
395 DIE &Die = *Parent.getChildren().back();
401 /// addBlock - Add block data.
403 void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute, DIELoc *Loc) {
404 Loc->ComputeSize(Asm);
405 DIELocs.push_back(Loc); // Memoize so we can call the destructor later on.
406 Die.addValue(Attribute, Loc->BestForm(DD->getDwarfVersion()), Loc);
409 void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute,
411 Block->ComputeSize(Asm);
412 DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
413 Die.addValue(Attribute, Block->BestForm(), Block);
416 /// addSourceLine - Add location information to specified debug information
418 void DwarfUnit::addSourceLine(DIE &Die, unsigned Line, StringRef File,
419 StringRef Directory) {
423 unsigned FileID = getOrCreateSourceID(File, Directory);
424 assert(FileID && "Invalid file id");
425 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
426 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
429 /// addSourceLine - Add location information to specified debug information
431 void DwarfUnit::addSourceLine(DIE &Die, DIVariable V) {
432 assert(V.isVariable());
434 addSourceLine(Die, V.getLineNumber(), V.getContext().getFilename(),
435 V.getContext().getDirectory());
438 /// addSourceLine - Add location information to specified debug information
440 void DwarfUnit::addSourceLine(DIE &Die, DIGlobalVariable G) {
441 assert(G.isGlobalVariable());
443 addSourceLine(Die, G.getLineNumber(), G.getFilename(), G.getDirectory());
446 /// addSourceLine - Add location information to specified debug information
448 void DwarfUnit::addSourceLine(DIE &Die, DISubprogram SP) {
449 assert(SP.isSubprogram());
451 addSourceLine(Die, SP.getLineNumber(), SP.getFilename(), SP.getDirectory());
454 /// addSourceLine - Add location information to specified debug information
456 void DwarfUnit::addSourceLine(DIE &Die, DIType Ty) {
459 addSourceLine(Die, Ty.getLineNumber(), Ty.getFilename(), Ty.getDirectory());
462 /// addSourceLine - Add location information to specified debug information
464 void DwarfUnit::addSourceLine(DIE &Die, DIObjCProperty Ty) {
465 assert(Ty.isObjCProperty());
467 DIFile File = Ty.getFile();
468 addSourceLine(Die, Ty.getLineNumber(), File.getFilename(),
469 File.getDirectory());
472 /// addSourceLine - Add location information to specified debug information
474 void DwarfUnit::addSourceLine(DIE &Die, DINameSpace NS) {
477 addSourceLine(Die, NS.getLineNumber(), NS.getFilename(), NS.getDirectory());
480 /// addVariableAddress - Add DW_AT_location attribute for a
481 /// DbgVariable based on provided MachineLocation.
482 void DwarfUnit::addVariableAddress(const DbgVariable &DV, DIE &Die,
483 MachineLocation Location) {
484 if (DV.variableHasComplexAddress())
485 addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
486 else if (DV.isBlockByrefVariable())
487 addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location);
489 addAddress(Die, dwarf::DW_AT_location, Location,
490 DV.getVariable().isIndirect());
493 /// addRegisterOp - Add register operand.
494 // FIXME: Ideally, this would share the implementation with
495 // AsmPrinter::EmitDwarfRegOpPiece.
496 void DwarfUnit::addRegisterOpPiece(DIELoc &TheDie, unsigned Reg,
497 unsigned SizeInBits, unsigned OffsetInBits) {
498 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
499 int DWReg = RI->getDwarfRegNum(Reg, false);
500 bool isSubRegister = DWReg < 0;
504 // Go up the super-register chain until we hit a valid dwarf register number.
505 for (MCSuperRegIterator SR(Reg, RI); SR.isValid() && DWReg < 0; ++SR) {
506 DWReg = RI->getDwarfRegNum(*SR, false);
508 Idx = RI->getSubRegIndex(*SR, Reg);
512 DEBUG(dbgs() << "Invalid Dwarf register number.\n");
513 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_nop);
519 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + DWReg);
521 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
522 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
526 bool isPiece = SizeInBits > 0;
527 if (isSubRegister || isPiece) {
528 const unsigned SizeOfByte = 8;
529 unsigned RegSizeInBits = RI->getSubRegIdxSize(Idx);
530 unsigned RegOffsetInBits = RI->getSubRegIdxOffset(Idx);
531 unsigned PieceSizeInBits = std::max(SizeInBits, RegSizeInBits);
532 unsigned PieceOffsetInBits = OffsetInBits ? OffsetInBits : RegOffsetInBits;
533 assert(RegSizeInBits >= SizeInBits && "register smaller than value");
535 if (RegOffsetInBits != PieceOffsetInBits) {
536 // Manually shift the value into place, since the DW_OP_piece
537 // describes the part of the variable, not the position of the
539 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
540 addUInt(TheDie, dwarf::DW_FORM_data1, RegOffsetInBits);
541 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_shr);
544 if (PieceOffsetInBits > 0 || PieceSizeInBits % SizeOfByte) {
545 assert(PieceSizeInBits > 0 && "piece has zero size");
546 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_bit_piece);
547 addUInt(TheDie, dwarf::DW_FORM_data1, PieceSizeInBits);
548 addUInt(TheDie, dwarf::DW_FORM_data1, PieceOffsetInBits);
550 assert(PieceSizeInBits > 0 && "piece has zero size");
551 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_piece);
552 addUInt(TheDie, dwarf::DW_FORM_data1, PieceSizeInBits/SizeOfByte);
557 /// addRegisterOffset - Add register offset.
558 void DwarfUnit::addRegisterOffset(DIELoc &TheDie, unsigned Reg,
560 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
561 unsigned DWReg = RI->getDwarfRegNum(Reg, false);
562 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
563 if (Reg == TRI->getFrameRegister(*Asm->MF))
564 // If variable offset is based in frame register then use fbreg.
565 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_fbreg);
567 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + DWReg);
569 addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
570 addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
572 addSInt(TheDie, dwarf::DW_FORM_sdata, Offset);
575 /// addAddress - Add an address attribute to a die based on the location
577 void DwarfUnit::addAddress(DIE &Die, dwarf::Attribute Attribute,
578 const MachineLocation &Location, bool Indirect) {
579 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
581 if (Location.isReg() && !Indirect)
582 addRegisterOpPiece(*Loc, Location.getReg());
584 addRegisterOffset(*Loc, Location.getReg(), Location.getOffset());
585 if (Indirect && !Location.isReg()) {
586 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
590 // Now attach the location information to the DIE.
591 addBlock(Die, Attribute, Loc);
594 /// addComplexAddress - Start with the address based on the location provided,
595 /// and generate the DWARF information necessary to find the actual variable
596 /// given the extra address information encoded in the DbgVariable, starting
597 /// from the starting location. Add the DWARF information to the die.
599 void DwarfUnit::addComplexAddress(const DbgVariable &DV, DIE &Die,
600 dwarf::Attribute Attribute,
601 const MachineLocation &Location) {
602 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
603 unsigned N = DV.getNumAddrElements();
605 if (Location.isReg()) {
606 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
607 // If first address element is OpPlus then emit
608 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
609 addRegisterOffset(*Loc, Location.getReg(), DV.getAddrElement(1));
611 } else if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpDeref) {
612 addRegisterOpPiece(*Loc, Location.getReg(),
613 DV.getVariable().getPieceSize(),
614 DV.getVariable().getPieceOffset());
617 addRegisterOpPiece(*Loc, Location.getReg());
619 addRegisterOffset(*Loc, Location.getReg(), Location.getOffset());
622 uint64_t Element = DV.getAddrElement(i);
623 if (Element == DIBuilder::OpPlus) {
624 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
625 addUInt(*Loc, dwarf::DW_FORM_udata, DV.getAddrElement(++i));
627 } else if (Element == DIBuilder::OpDeref) {
628 if (!Location.isReg())
629 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
631 } else if (Element == DIBuilder::OpPiece) {
632 const unsigned SizeOfByte = 8;
633 unsigned PieceOffsetInBits = DV.getAddrElement(++i)*SizeOfByte;
634 unsigned PieceSizeInBits = DV.getAddrElement(++i)*SizeOfByte;
635 // Emit DW_OP_bit_piece Size Offset.
636 assert(PieceSizeInBits > 0 && "piece has zero size");
637 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_bit_piece);
638 addUInt(*Loc, dwarf::DW_FORM_udata, PieceSizeInBits);
639 addUInt(*Loc, dwarf::DW_FORM_udata, PieceOffsetInBits);
642 llvm_unreachable("unknown DIBuilder Opcode");
645 // Now attach the location information to the DIE.
646 addBlock(Die, Attribute, Loc);
649 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
650 VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
651 gives the variable VarName either the struct, or a pointer to the struct, as
652 its type. This is necessary for various behind-the-scenes things the
653 compiler needs to do with by-reference variables in Blocks.
655 However, as far as the original *programmer* is concerned, the variable
656 should still have type 'SomeType', as originally declared.
658 The function getBlockByrefType dives into the __Block_byref_x_VarName
659 struct to find the original type of the variable, which is then assigned to
660 the variable's Debug Information Entry as its real type. So far, so good.
661 However now the debugger will expect the variable VarName to have the type
662 SomeType. So we need the location attribute for the variable to be an
663 expression that explains to the debugger how to navigate through the
664 pointers and struct to find the actual variable of type SomeType.
666 The following function does just that. We start by getting
667 the "normal" location for the variable. This will be the location
668 of either the struct __Block_byref_x_VarName or the pointer to the
669 struct __Block_byref_x_VarName.
671 The struct will look something like:
673 struct __Block_byref_x_VarName {
675 struct __Block_byref_x_VarName *forwarding;
676 ... <various other fields>
678 ... <maybe more fields>
681 If we are given the struct directly (as our starting point) we
682 need to tell the debugger to:
684 1). Add the offset of the forwarding field.
686 2). Follow that pointer to get the real __Block_byref_x_VarName
687 struct to use (the real one may have been copied onto the heap).
689 3). Add the offset for the field VarName, to find the actual variable.
691 If we started with a pointer to the struct, then we need to
692 dereference that pointer first, before the other steps.
693 Translating this into DWARF ops, we will need to append the following
694 to the current location description for the variable:
696 DW_OP_deref -- optional, if we start with a pointer
697 DW_OP_plus_uconst <forward_fld_offset>
699 DW_OP_plus_uconst <varName_fld_offset>
701 That is what this function does. */
703 /// addBlockByrefAddress - Start with the address based on the location
704 /// provided, and generate the DWARF information necessary to find the
705 /// actual Block variable (navigating the Block struct) based on the
706 /// starting location. Add the DWARF information to the die. For
707 /// more information, read large comment just above here.
709 void DwarfUnit::addBlockByrefAddress(const DbgVariable &DV, DIE &Die,
710 dwarf::Attribute Attribute,
711 const MachineLocation &Location) {
712 DIType Ty = DV.getType();
714 uint16_t Tag = Ty.getTag();
715 bool isPointer = false;
717 StringRef varName = DV.getName();
719 if (Tag == dwarf::DW_TAG_pointer_type) {
720 DIDerivedType DTy(Ty);
721 TmpTy = resolve(DTy.getTypeDerivedFrom());
725 DICompositeType blockStruct(TmpTy);
727 // Find the __forwarding field and the variable field in the __Block_byref
729 DIArray Fields = blockStruct.getElements();
730 DIDerivedType varField;
731 DIDerivedType forwardingField;
733 for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
734 DIDerivedType DT(Fields.getElement(i));
735 StringRef fieldName = DT.getName();
736 if (fieldName == "__forwarding")
737 forwardingField = DT;
738 else if (fieldName == varName)
742 // Get the offsets for the forwarding field and the variable field.
743 unsigned forwardingFieldOffset = forwardingField.getOffsetInBits() >> 3;
744 unsigned varFieldOffset = varField.getOffsetInBits() >> 2;
746 // Decode the original location, and use that as the start of the byref
747 // variable's location.
748 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
750 if (Location.isReg())
751 addRegisterOpPiece(*Loc, Location.getReg());
753 addRegisterOffset(*Loc, Location.getReg(), Location.getOffset());
755 // If we started with a pointer to the __Block_byref... struct, then
756 // the first thing we need to do is dereference the pointer (DW_OP_deref).
758 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
760 // Next add the offset for the '__forwarding' field:
761 // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in
762 // adding the offset if it's 0.
763 if (forwardingFieldOffset > 0) {
764 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
765 addUInt(*Loc, dwarf::DW_FORM_udata, forwardingFieldOffset);
768 // Now dereference the __forwarding field to get to the real __Block_byref
769 // struct: DW_OP_deref.
770 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
772 // Now that we've got the real __Block_byref... struct, add the offset
773 // for the variable's field to get to the location of the actual variable:
774 // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0.
775 if (varFieldOffset > 0) {
776 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
777 addUInt(*Loc, dwarf::DW_FORM_udata, varFieldOffset);
780 // Now attach the location information to the DIE.
781 addBlock(Die, Attribute, Loc);
784 /// Return true if type encoding is unsigned.
785 static bool isUnsignedDIType(DwarfDebug *DD, DIType Ty) {
786 DIDerivedType DTy(Ty);
787 if (DTy.isDerivedType()) {
788 dwarf::Tag T = (dwarf::Tag)Ty.getTag();
789 // Encode pointer constants as unsigned bytes. This is used at least for
790 // null pointer constant emission.
791 // FIXME: reference and rvalue_reference /probably/ shouldn't be allowed
792 // here, but accept them for now due to a bug in SROA producing bogus
794 if (T == dwarf::DW_TAG_pointer_type ||
795 T == dwarf::DW_TAG_ptr_to_member_type ||
796 T == dwarf::DW_TAG_reference_type ||
797 T == dwarf::DW_TAG_rvalue_reference_type)
799 assert(T == dwarf::DW_TAG_typedef || T == dwarf::DW_TAG_const_type ||
800 T == dwarf::DW_TAG_volatile_type ||
801 T == dwarf::DW_TAG_restrict_type ||
802 T == dwarf::DW_TAG_enumeration_type);
803 if (DITypeRef Deriv = DTy.getTypeDerivedFrom())
804 return isUnsignedDIType(DD, DD->resolve(Deriv));
805 // FIXME: Enums without a fixed underlying type have unknown signedness
806 // here, leading to incorrectly emitted constants.
807 assert(DTy.getTag() == dwarf::DW_TAG_enumeration_type);
812 assert(BTy.isBasicType());
813 unsigned Encoding = BTy.getEncoding();
814 assert((Encoding == dwarf::DW_ATE_unsigned ||
815 Encoding == dwarf::DW_ATE_unsigned_char ||
816 Encoding == dwarf::DW_ATE_signed ||
817 Encoding == dwarf::DW_ATE_signed_char ||
818 Encoding == dwarf::DW_ATE_UTF || Encoding == dwarf::DW_ATE_boolean) &&
819 "Unsupported encoding");
820 return (Encoding == dwarf::DW_ATE_unsigned ||
821 Encoding == dwarf::DW_ATE_unsigned_char ||
822 Encoding == dwarf::DW_ATE_UTF || Encoding == dwarf::DW_ATE_boolean);
825 /// If this type is derived from a base type then return base type size.
826 static uint64_t getBaseTypeSize(DwarfDebug *DD, DIDerivedType Ty) {
827 unsigned Tag = Ty.getTag();
829 if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef &&
830 Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type &&
831 Tag != dwarf::DW_TAG_restrict_type)
832 return Ty.getSizeInBits();
834 DIType BaseType = DD->resolve(Ty.getTypeDerivedFrom());
836 // If this type is not derived from any type or the type is a declaration then
837 // take conservative approach.
838 if (!BaseType.isValid() || BaseType.isForwardDecl())
839 return Ty.getSizeInBits();
841 // If this is a derived type, go ahead and get the base type, unless it's a
842 // reference then it's just the size of the field. Pointer types have no need
843 // of this since they're a different type of qualification on the type.
844 if (BaseType.getTag() == dwarf::DW_TAG_reference_type ||
845 BaseType.getTag() == dwarf::DW_TAG_rvalue_reference_type)
846 return Ty.getSizeInBits();
848 if (BaseType.isDerivedType())
849 return getBaseTypeSize(DD, DIDerivedType(BaseType));
851 return BaseType.getSizeInBits();
854 /// addConstantFPValue - Add constant value entry in variable DIE.
855 void DwarfUnit::addConstantFPValue(DIE &Die, const MachineOperand &MO) {
856 assert(MO.isFPImm() && "Invalid machine operand!");
857 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
858 APFloat FPImm = MO.getFPImm()->getValueAPF();
860 // Get the raw data form of the floating point.
861 const APInt FltVal = FPImm.bitcastToAPInt();
862 const char *FltPtr = (const char *)FltVal.getRawData();
864 int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
865 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
866 int Incr = (LittleEndian ? 1 : -1);
867 int Start = (LittleEndian ? 0 : NumBytes - 1);
868 int Stop = (LittleEndian ? NumBytes : -1);
870 // Output the constant to DWARF one byte at a time.
871 for (; Start != Stop; Start += Incr)
872 addUInt(*Block, dwarf::DW_FORM_data1, (unsigned char)0xFF & FltPtr[Start]);
874 addBlock(Die, dwarf::DW_AT_const_value, Block);
877 /// addConstantFPValue - Add constant value entry in variable DIE.
878 void DwarfUnit::addConstantFPValue(DIE &Die, const ConstantFP *CFP) {
879 // Pass this down to addConstantValue as an unsigned bag of bits.
880 addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true);
883 /// addConstantValue - Add constant value entry in variable DIE.
884 void DwarfUnit::addConstantValue(DIE &Die, const ConstantInt *CI, DIType Ty) {
885 addConstantValue(Die, CI->getValue(), Ty);
888 /// addConstantValue - Add constant value entry in variable DIE.
889 void DwarfUnit::addConstantValue(DIE &Die, const MachineOperand &MO,
891 assert(MO.isImm() && "Invalid machine operand!");
893 addConstantValue(Die, isUnsignedDIType(DD, Ty), MO.getImm());
896 void DwarfUnit::addConstantValue(DIE &Die, bool Unsigned, uint64_t Val) {
897 // FIXME: This is a bit conservative/simple - it emits negative values always
898 // sign extended to 64 bits rather than minimizing the number of bytes.
899 addUInt(Die, dwarf::DW_AT_const_value,
900 Unsigned ? dwarf::DW_FORM_udata : dwarf::DW_FORM_sdata, Val);
903 void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, DIType Ty) {
904 addConstantValue(Die, Val, isUnsignedDIType(DD, Ty));
907 // addConstantValue - Add constant value entry in variable DIE.
908 void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, bool Unsigned) {
909 unsigned CIBitWidth = Val.getBitWidth();
910 if (CIBitWidth <= 64) {
911 addConstantValue(Die, Unsigned,
912 Unsigned ? Val.getZExtValue() : Val.getSExtValue());
916 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
918 // Get the raw data form of the large APInt.
919 const uint64_t *Ptr64 = Val.getRawData();
921 int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
922 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
924 // Output the constant to DWARF one byte at a time.
925 for (int i = 0; i < NumBytes; i++) {
928 c = Ptr64[i / 8] >> (8 * (i & 7));
930 c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
931 addUInt(*Block, dwarf::DW_FORM_data1, c);
934 addBlock(Die, dwarf::DW_AT_const_value, Block);
937 /// addTemplateParams - Add template parameters into buffer.
938 void DwarfUnit::addTemplateParams(DIE &Buffer, DIArray TParams) {
939 // Add template parameters.
940 for (unsigned i = 0, e = TParams.getNumElements(); i != e; ++i) {
941 DIDescriptor Element = TParams.getElement(i);
942 if (Element.isTemplateTypeParameter())
943 constructTemplateTypeParameterDIE(Buffer,
944 DITemplateTypeParameter(Element));
945 else if (Element.isTemplateValueParameter())
946 constructTemplateValueParameterDIE(Buffer,
947 DITemplateValueParameter(Element));
951 /// getOrCreateContextDIE - Get context owner's DIE.
952 DIE *DwarfUnit::getOrCreateContextDIE(DIScope Context) {
953 if (!Context || Context.isFile())
954 return &getUnitDie();
955 if (Context.isType())
956 return getOrCreateTypeDIE(DIType(Context));
957 if (Context.isNameSpace())
958 return getOrCreateNameSpace(DINameSpace(Context));
959 if (Context.isSubprogram())
960 return getOrCreateSubprogramDIE(DISubprogram(Context));
961 return getDIE(Context);
964 DIE *DwarfUnit::createTypeDIE(DICompositeType Ty) {
965 DIScope Context = resolve(Ty.getContext());
966 DIE *ContextDIE = getOrCreateContextDIE(Context);
968 if (DIE *TyDIE = getDIE(Ty))
972 DIE &TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
974 constructTypeDIE(TyDIE, Ty);
976 updateAcceleratorTables(Context, Ty, TyDIE);
980 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
982 DIE *DwarfUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
988 assert(Ty == resolve(Ty.getRef()) &&
989 "type was not uniqued, possible ODR violation.");
991 // DW_TAG_restrict_type is not supported in DWARF2
992 if (Ty.getTag() == dwarf::DW_TAG_restrict_type && DD->getDwarfVersion() <= 2)
993 return getOrCreateTypeDIE(resolve(DIDerivedType(Ty).getTypeDerivedFrom()));
995 // Construct the context before querying for the existence of the DIE in case
996 // such construction creates the DIE.
997 DIScope Context = resolve(Ty.getContext());
998 DIE *ContextDIE = getOrCreateContextDIE(Context);
1001 if (DIE *TyDIE = getDIE(Ty))
1005 DIE &TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
1007 updateAcceleratorTables(Context, Ty, TyDIE);
1009 if (Ty.isBasicType())
1010 constructTypeDIE(TyDIE, DIBasicType(Ty));
1011 else if (Ty.isCompositeType()) {
1012 DICompositeType CTy(Ty);
1013 if (GenerateDwarfTypeUnits && !Ty.isForwardDecl())
1014 if (MDString *TypeId = CTy.getIdentifier()) {
1015 DD->addDwarfTypeUnitType(getCU(), TypeId->getString(), TyDIE, CTy);
1016 // Skip updating the accelerator tables since this is not the full type.
1019 constructTypeDIE(TyDIE, CTy);
1021 assert(Ty.isDerivedType() && "Unknown kind of DIType");
1022 constructTypeDIE(TyDIE, DIDerivedType(Ty));
1028 void DwarfUnit::updateAcceleratorTables(DIScope Context, DIType Ty,
1030 if (!Ty.getName().empty() && !Ty.isForwardDecl()) {
1031 bool IsImplementation = 0;
1032 if (Ty.isCompositeType()) {
1033 DICompositeType CT(Ty);
1034 // A runtime language of 0 actually means C/C++ and that any
1035 // non-negative value is some version of Objective-C/C++.
1036 IsImplementation = (CT.getRunTimeLang() == 0) || CT.isObjcClassComplete();
1038 unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0;
1039 DD->addAccelType(Ty.getName(), TyDIE, Flags);
1041 if ((!Context || Context.isCompileUnit() || Context.isFile() ||
1042 Context.isNameSpace()) &&
1043 getCUNode().getEmissionKind() != DIBuilder::LineTablesOnly)
1044 GlobalTypes[getParentContextString(Context) + Ty.getName().str()] =
1049 /// addType - Add a new type attribute to the specified entity.
1050 void DwarfUnit::addType(DIE &Entity, DIType Ty, dwarf::Attribute Attribute) {
1051 assert(Ty && "Trying to add a type that doesn't exist?");
1053 // Check for pre-existence.
1054 DIEEntry *Entry = getDIEEntry(Ty);
1055 // If it exists then use the existing value.
1057 addDIEEntry(Entity, Attribute, Entry);
1062 DIE *Buffer = getOrCreateTypeDIE(Ty);
1065 Entry = createDIEEntry(*Buffer);
1066 insertDIEEntry(Ty, Entry);
1067 addDIEEntry(Entity, Attribute, Entry);
1070 /// addGlobalName - Add a new global name to the compile unit.
1071 void DwarfUnit::addGlobalName(StringRef Name, DIE &Die, DIScope Context) {
1072 if (getCUNode().getEmissionKind() == DIBuilder::LineTablesOnly)
1074 std::string FullName = getParentContextString(Context) + Name.str();
1075 GlobalNames[FullName] = &Die;
1078 /// getParentContextString - Walks the metadata parent chain in a language
1079 /// specific manner (using the compile unit language) and returns
1080 /// it as a string. This is done at the metadata level because DIEs may
1081 /// not currently have been added to the parent context and walking the
1082 /// DIEs looking for names is more expensive than walking the metadata.
1083 std::string DwarfUnit::getParentContextString(DIScope Context) const {
1087 // FIXME: Decide whether to implement this for non-C++ languages.
1088 if (getLanguage() != dwarf::DW_LANG_C_plus_plus)
1092 SmallVector<DIScope, 1> Parents;
1093 while (!Context.isCompileUnit()) {
1094 Parents.push_back(Context);
1095 if (Context.getContext())
1096 Context = resolve(Context.getContext());
1098 // Structure, etc types will have a NULL context if they're at the top
1103 // Reverse iterate over our list to go from the outermost construct to the
1105 for (SmallVectorImpl<DIScope>::reverse_iterator I = Parents.rbegin(),
1109 StringRef Name = Ctx.getName();
1110 if (Name.empty() && Ctx.isNameSpace())
1111 Name = "(anonymous namespace)";
1112 if (!Name.empty()) {
1120 /// constructTypeDIE - Construct basic type die from DIBasicType.
1121 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
1122 // Get core information.
1123 StringRef Name = BTy.getName();
1124 // Add name if not anonymous or intermediate type.
1126 addString(Buffer, dwarf::DW_AT_name, Name);
1128 // An unspecified type only has a name attribute.
1129 if (BTy.getTag() == dwarf::DW_TAG_unspecified_type)
1132 addUInt(Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1135 uint64_t Size = BTy.getSizeInBits() >> 3;
1136 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
1139 /// constructTypeDIE - Construct derived type die from DIDerivedType.
1140 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
1141 // Get core information.
1142 StringRef Name = DTy.getName();
1143 uint64_t Size = DTy.getSizeInBits() >> 3;
1144 uint16_t Tag = Buffer.getTag();
1146 // Map to main type, void will not have a type.
1147 DIType FromTy = resolve(DTy.getTypeDerivedFrom());
1149 addType(Buffer, FromTy);
1151 // Add name if not anonymous or intermediate type.
1153 addString(Buffer, dwarf::DW_AT_name, Name);
1155 // Add size if non-zero (derived types might be zero-sized.)
1156 if (Size && Tag != dwarf::DW_TAG_pointer_type)
1157 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
1159 if (Tag == dwarf::DW_TAG_ptr_to_member_type)
1160 addDIEEntry(Buffer, dwarf::DW_AT_containing_type,
1161 *getOrCreateTypeDIE(resolve(DTy.getClassType())));
1162 // Add source line info if available and TyDesc is not a forward declaration.
1163 if (!DTy.isForwardDecl())
1164 addSourceLine(Buffer, DTy);
1167 /// constructSubprogramArguments - Construct function argument DIEs.
1168 void DwarfUnit::constructSubprogramArguments(DIE &Buffer, DITypeArray Args) {
1169 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1170 DIType Ty = resolve(Args.getElement(i));
1172 assert(i == N-1 && "Unspecified parameter must be the last argument");
1173 createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
1175 DIE &Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
1176 addType(Arg, DIType(Ty));
1177 if (DIType(Ty).isArtificial())
1178 addFlag(Arg, dwarf::DW_AT_artificial);
1183 /// constructTypeDIE - Construct type DIE from DICompositeType.
1184 void DwarfUnit::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
1185 // Add name if not anonymous or intermediate type.
1186 StringRef Name = CTy.getName();
1188 uint64_t Size = CTy.getSizeInBits() >> 3;
1189 uint16_t Tag = Buffer.getTag();
1192 case dwarf::DW_TAG_array_type:
1193 constructArrayTypeDIE(Buffer, CTy);
1195 case dwarf::DW_TAG_enumeration_type:
1196 constructEnumTypeDIE(Buffer, CTy);
1198 case dwarf::DW_TAG_subroutine_type: {
1199 // Add return type. A void return won't have a type.
1200 DITypeArray Elements = DISubroutineType(CTy).getTypeArray();
1201 DIType RTy(resolve(Elements.getElement(0)));
1203 addType(Buffer, RTy);
1205 bool isPrototyped = true;
1206 if (Elements.getNumElements() == 2 &&
1207 !Elements.getElement(1))
1208 isPrototyped = false;
1210 constructSubprogramArguments(Buffer, Elements);
1212 // Add prototype flag if we're dealing with a C language and the
1213 // function has been prototyped.
1214 uint16_t Language = getLanguage();
1216 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1217 Language == dwarf::DW_LANG_ObjC))
1218 addFlag(Buffer, dwarf::DW_AT_prototyped);
1220 if (CTy.isLValueReference())
1221 addFlag(Buffer, dwarf::DW_AT_reference);
1223 if (CTy.isRValueReference())
1224 addFlag(Buffer, dwarf::DW_AT_rvalue_reference);
1226 case dwarf::DW_TAG_structure_type:
1227 case dwarf::DW_TAG_union_type:
1228 case dwarf::DW_TAG_class_type: {
1229 // Add elements to structure type.
1230 DIArray Elements = CTy.getElements();
1231 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1232 DIDescriptor Element = Elements.getElement(i);
1233 if (Element.isSubprogram())
1234 getOrCreateSubprogramDIE(DISubprogram(Element));
1235 else if (Element.isDerivedType()) {
1236 DIDerivedType DDTy(Element);
1237 if (DDTy.getTag() == dwarf::DW_TAG_friend) {
1238 DIE &ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
1239 addType(ElemDie, resolve(DDTy.getTypeDerivedFrom()),
1240 dwarf::DW_AT_friend);
1241 } else if (DDTy.isStaticMember()) {
1242 getOrCreateStaticMemberDIE(DDTy);
1244 constructMemberDIE(Buffer, DDTy);
1246 } else if (Element.isObjCProperty()) {
1247 DIObjCProperty Property(Element);
1248 DIE &ElemDie = createAndAddDIE(Property.getTag(), Buffer);
1249 StringRef PropertyName = Property.getObjCPropertyName();
1250 addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
1251 if (Property.getType())
1252 addType(ElemDie, Property.getType());
1253 addSourceLine(ElemDie, Property);
1254 StringRef GetterName = Property.getObjCPropertyGetterName();
1255 if (!GetterName.empty())
1256 addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
1257 StringRef SetterName = Property.getObjCPropertySetterName();
1258 if (!SetterName.empty())
1259 addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
1260 unsigned PropertyAttributes = 0;
1261 if (Property.isReadOnlyObjCProperty())
1262 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readonly;
1263 if (Property.isReadWriteObjCProperty())
1264 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readwrite;
1265 if (Property.isAssignObjCProperty())
1266 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_assign;
1267 if (Property.isRetainObjCProperty())
1268 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_retain;
1269 if (Property.isCopyObjCProperty())
1270 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_copy;
1271 if (Property.isNonAtomicObjCProperty())
1272 PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_nonatomic;
1273 if (PropertyAttributes)
1274 addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None,
1275 PropertyAttributes);
1277 DIEEntry *Entry = getDIEEntry(Element);
1279 Entry = createDIEEntry(ElemDie);
1280 insertDIEEntry(Element, Entry);
1286 if (CTy.isAppleBlockExtension())
1287 addFlag(Buffer, dwarf::DW_AT_APPLE_block);
1289 DICompositeType ContainingType(resolve(CTy.getContainingType()));
1291 addDIEEntry(Buffer, dwarf::DW_AT_containing_type,
1292 *getOrCreateTypeDIE(ContainingType));
1294 if (CTy.isObjcClassComplete())
1295 addFlag(Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
1297 // Add template parameters to a class, structure or union types.
1298 // FIXME: The support isn't in the metadata for this yet.
1299 if (Tag == dwarf::DW_TAG_class_type ||
1300 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
1301 addTemplateParams(Buffer, CTy.getTemplateParams());
1309 // Add name if not anonymous or intermediate type.
1311 addString(Buffer, dwarf::DW_AT_name, Name);
1313 if (Tag == dwarf::DW_TAG_enumeration_type ||
1314 Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
1315 Tag == dwarf::DW_TAG_union_type) {
1316 // Add size if non-zero (derived types might be zero-sized.)
1317 // TODO: Do we care about size for enum forward declarations?
1319 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
1320 else if (!CTy.isForwardDecl())
1321 // Add zero size if it is not a forward declaration.
1322 addUInt(Buffer, dwarf::DW_AT_byte_size, None, 0);
1324 // If we're a forward decl, say so.
1325 if (CTy.isForwardDecl())
1326 addFlag(Buffer, dwarf::DW_AT_declaration);
1328 // Add source line info if available.
1329 if (!CTy.isForwardDecl())
1330 addSourceLine(Buffer, CTy);
1332 // No harm in adding the runtime language to the declaration.
1333 unsigned RLang = CTy.getRunTimeLang();
1335 addUInt(Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
1340 /// constructTemplateTypeParameterDIE - Construct new DIE for the given
1341 /// DITemplateTypeParameter.
1342 void DwarfUnit::constructTemplateTypeParameterDIE(DIE &Buffer,
1343 DITemplateTypeParameter TP) {
1345 createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
1346 // Add the type if it exists, it could be void and therefore no type.
1348 addType(ParamDIE, resolve(TP.getType()));
1349 if (!TP.getName().empty())
1350 addString(ParamDIE, dwarf::DW_AT_name, TP.getName());
1353 /// constructTemplateValueParameterDIE - Construct new DIE for the given
1354 /// DITemplateValueParameter.
1356 DwarfUnit::constructTemplateValueParameterDIE(DIE &Buffer,
1357 DITemplateValueParameter VP) {
1358 DIE &ParamDIE = createAndAddDIE(VP.getTag(), Buffer);
1360 // Add the type if there is one, template template and template parameter
1361 // packs will not have a type.
1362 if (VP.getTag() == dwarf::DW_TAG_template_value_parameter)
1363 addType(ParamDIE, resolve(VP.getType()));
1364 if (!VP.getName().empty())
1365 addString(ParamDIE, dwarf::DW_AT_name, VP.getName());
1366 if (Value *Val = VP.getValue()) {
1367 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val))
1368 addConstantValue(ParamDIE, CI, resolve(VP.getType()));
1369 else if (GlobalValue *GV = dyn_cast<GlobalValue>(Val)) {
1370 // For declaration non-type template parameters (such as global values and
1372 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
1373 addOpAddress(*Loc, Asm->getSymbol(GV));
1374 // Emit DW_OP_stack_value to use the address as the immediate value of the
1375 // parameter, rather than a pointer to it.
1376 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
1377 addBlock(ParamDIE, dwarf::DW_AT_location, Loc);
1378 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1379 assert(isa<MDString>(Val));
1380 addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
1381 cast<MDString>(Val)->getString());
1382 } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1383 assert(isa<MDNode>(Val));
1384 DIArray A(cast<MDNode>(Val));
1385 addTemplateParams(ParamDIE, A);
1390 /// getOrCreateNameSpace - Create a DIE for DINameSpace.
1391 DIE *DwarfUnit::getOrCreateNameSpace(DINameSpace NS) {
1392 // Construct the context before querying for the existence of the DIE in case
1393 // such construction creates the DIE.
1394 DIE *ContextDIE = getOrCreateContextDIE(NS.getContext());
1396 if (DIE *NDie = getDIE(NS))
1398 DIE &NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS);
1400 StringRef Name = NS.getName();
1402 addString(NDie, dwarf::DW_AT_name, NS.getName());
1404 Name = "(anonymous namespace)";
1405 DD->addAccelNamespace(Name, NDie);
1406 addGlobalName(Name, NDie, NS.getContext());
1407 addSourceLine(NDie, NS);
1411 /// getOrCreateSubprogramDIE - Create new DIE using SP.
1412 DIE *DwarfUnit::getOrCreateSubprogramDIE(DISubprogram SP) {
1413 // Construct the context before querying for the existence of the DIE in case
1414 // such construction creates the DIE (as is the case for member function
1416 DIE *ContextDIE = getOrCreateContextDIE(resolve(SP.getContext()));
1418 if (DIE *SPDie = getDIE(SP))
1421 if (DISubprogram SPDecl = SP.getFunctionDeclaration()) {
1422 // Add subprogram definitions to the CU die directly.
1423 ContextDIE = &getUnitDie();
1424 // Build the decl now to ensure it precedes the definition.
1425 getOrCreateSubprogramDIE(SPDecl);
1428 // DW_TAG_inlined_subroutine may refer to this DIE.
1429 DIE &SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
1431 // Stop here and fill this in later, depending on whether or not this
1432 // subprogram turns out to have inlined instances or not.
1433 if (SP.isDefinition())
1436 applySubprogramAttributes(SP, SPDie);
1440 void DwarfUnit::applySubprogramAttributesToDefinition(DISubprogram SP, DIE &SPDie) {
1441 DISubprogram SPDecl = SP.getFunctionDeclaration();
1442 DIScope Context = resolve(SPDecl ? SPDecl.getContext() : SP.getContext());
1443 applySubprogramAttributes(SP, SPDie);
1444 addGlobalName(SP.getName(), SPDie, Context);
1447 void DwarfUnit::applySubprogramAttributes(DISubprogram SP, DIE &SPDie) {
1448 DIE *DeclDie = nullptr;
1449 StringRef DeclLinkageName;
1450 if (DISubprogram SPDecl = SP.getFunctionDeclaration()) {
1451 DeclDie = getDIE(SPDecl);
1452 assert(DeclDie && "This DIE should've already been constructed when the "
1453 "definition DIE was created in "
1454 "getOrCreateSubprogramDIE");
1455 DeclLinkageName = SPDecl.getLinkageName();
1458 // Add function template parameters.
1459 addTemplateParams(SPDie, SP.getTemplateParams());
1461 // Add the linkage name if we have one and it isn't in the Decl.
1462 StringRef LinkageName = SP.getLinkageName();
1463 assert(((LinkageName.empty() || DeclLinkageName.empty()) ||
1464 LinkageName == DeclLinkageName) &&
1465 "decl has a linkage name and it is different");
1466 if (!LinkageName.empty() && DeclLinkageName.empty())
1467 addString(SPDie, dwarf::DW_AT_MIPS_linkage_name,
1468 GlobalValue::getRealLinkageName(LinkageName));
1471 // Refer to the function declaration where all the other attributes will be
1473 addDIEEntry(SPDie, dwarf::DW_AT_specification, *DeclDie);
1477 // Constructors and operators for anonymous aggregates do not have names.
1478 if (!SP.getName().empty())
1479 addString(SPDie, dwarf::DW_AT_name, SP.getName());
1481 addSourceLine(SPDie, SP);
1483 // Add the prototype if we have a prototype and we have a C like
1485 uint16_t Language = getLanguage();
1486 if (SP.isPrototyped() &&
1487 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1488 Language == dwarf::DW_LANG_ObjC))
1489 addFlag(SPDie, dwarf::DW_AT_prototyped);
1491 DISubroutineType SPTy = SP.getType();
1492 assert(SPTy.getTag() == dwarf::DW_TAG_subroutine_type &&
1493 "the type of a subprogram should be a subroutine");
1495 DITypeArray Args = SPTy.getTypeArray();
1496 // Add a return type. If this is a type like a C/C++ void type we don't add a
1498 if (resolve(Args.getElement(0)))
1499 addType(SPDie, DIType(resolve(Args.getElement(0))));
1501 unsigned VK = SP.getVirtuality();
1503 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1504 DIELoc *Block = getDIELoc();
1505 addUInt(*Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1506 addUInt(*Block, dwarf::DW_FORM_udata, SP.getVirtualIndex());
1507 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
1508 ContainingTypeMap.insert(
1509 std::make_pair(&SPDie, resolve(SP.getContainingType())));
1512 if (!SP.isDefinition()) {
1513 addFlag(SPDie, dwarf::DW_AT_declaration);
1515 // Add arguments. Do not add arguments for subprogram definition. They will
1516 // be handled while processing variables.
1517 constructSubprogramArguments(SPDie, Args);
1520 if (SP.isArtificial())
1521 addFlag(SPDie, dwarf::DW_AT_artificial);
1523 if (!SP.isLocalToUnit())
1524 addFlag(SPDie, dwarf::DW_AT_external);
1526 if (SP.isOptimized())
1527 addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1529 if (unsigned isa = Asm->getISAEncoding()) {
1530 addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1533 if (SP.isLValueReference())
1534 addFlag(SPDie, dwarf::DW_AT_reference);
1536 if (SP.isRValueReference())
1537 addFlag(SPDie, dwarf::DW_AT_rvalue_reference);
1539 if (SP.isProtected())
1540 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1541 dwarf::DW_ACCESS_protected);
1542 else if (SP.isPrivate())
1543 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1544 dwarf::DW_ACCESS_private);
1546 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1547 dwarf::DW_ACCESS_public);
1549 if (SP.isExplicit())
1550 addFlag(SPDie, dwarf::DW_AT_explicit);
1553 void DwarfUnit::applyVariableAttributes(const DbgVariable &Var,
1555 StringRef Name = Var.getName();
1557 addString(VariableDie, dwarf::DW_AT_name, Name);
1558 addSourceLine(VariableDie, Var.getVariable());
1559 addType(VariableDie, Var.getType());
1560 if (Var.isArtificial())
1561 addFlag(VariableDie, dwarf::DW_AT_artificial);
1564 // Return const expression if value is a GEP to access merged global
1566 // i8* getelementptr ({ i8, i8, i8, i8 }* @_MergedGlobals, i32 0, i32 0)
1567 static const ConstantExpr *getMergedGlobalExpr(const Value *V) {
1568 const ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(V);
1569 if (!CE || CE->getNumOperands() != 3 ||
1570 CE->getOpcode() != Instruction::GetElementPtr)
1573 // First operand points to a global struct.
1574 Value *Ptr = CE->getOperand(0);
1575 if (!isa<GlobalValue>(Ptr) ||
1576 !isa<StructType>(cast<PointerType>(Ptr->getType())->getElementType()))
1579 // Second operand is zero.
1580 const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(CE->getOperand(1));
1581 if (!CI || !CI->isZero())
1584 // Third operand is offset.
1585 if (!isa<ConstantInt>(CE->getOperand(2)))
1591 /// createGlobalVariableDIE - create global variable DIE.
1592 void DwarfCompileUnit::createGlobalVariableDIE(DIGlobalVariable GV) {
1593 // Check for pre-existence.
1597 assert(GV.isGlobalVariable());
1599 DIScope GVContext = GV.getContext();
1600 DIType GTy = DD->resolve(GV.getType());
1602 // If this is a static data member definition, some attributes belong
1603 // to the declaration DIE.
1604 DIE *VariableDIE = nullptr;
1605 bool IsStaticMember = false;
1606 DIDerivedType SDMDecl = GV.getStaticDataMemberDeclaration();
1607 if (SDMDecl.Verify()) {
1608 assert(SDMDecl.isStaticMember() && "Expected static member decl");
1609 // We need the declaration DIE that is in the static member's class.
1610 VariableDIE = getOrCreateStaticMemberDIE(SDMDecl);
1611 IsStaticMember = true;
1614 // If this is not a static data member definition, create the variable
1615 // DIE and add the initial set of attributes to it.
1617 // Construct the context before querying for the existence of the DIE in
1618 // case such construction creates the DIE.
1619 DIE *ContextDIE = getOrCreateContextDIE(GVContext);
1622 VariableDIE = &createAndAddDIE(GV.getTag(), *ContextDIE, GV);
1624 // Add name and type.
1625 addString(*VariableDIE, dwarf::DW_AT_name, GV.getDisplayName());
1626 addType(*VariableDIE, GTy);
1628 // Add scoping info.
1629 if (!GV.isLocalToUnit())
1630 addFlag(*VariableDIE, dwarf::DW_AT_external);
1632 // Add line number info.
1633 addSourceLine(*VariableDIE, GV);
1637 bool addToAccelTable = false;
1638 DIE *VariableSpecDIE = nullptr;
1639 bool isGlobalVariable = GV.getGlobal() != nullptr;
1640 if (isGlobalVariable) {
1641 addToAccelTable = true;
1642 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
1643 const MCSymbol *Sym = Asm->getSymbol(GV.getGlobal());
1644 if (GV.getGlobal()->isThreadLocal()) {
1645 // FIXME: Make this work with -gsplit-dwarf.
1646 unsigned PointerSize = Asm->getDataLayout().getPointerSize();
1647 assert((PointerSize == 4 || PointerSize == 8) &&
1648 "Add support for other sizes if necessary");
1649 // Based on GCC's support for TLS:
1650 if (!DD->useSplitDwarf()) {
1651 // 1) Start with a constNu of the appropriate pointer size
1652 addUInt(*Loc, dwarf::DW_FORM_data1,
1653 PointerSize == 4 ? dwarf::DW_OP_const4u : dwarf::DW_OP_const8u);
1654 // 2) containing the (relocated) offset of the TLS variable
1655 // within the module's TLS block.
1656 addExpr(*Loc, dwarf::DW_FORM_udata,
1657 Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym));
1659 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
1660 addUInt(*Loc, dwarf::DW_FORM_udata,
1661 DD->getAddressPool().getIndex(Sym, /* TLS */ true));
1663 // 3) followed by a custom OP to make the debugger do a TLS lookup.
1664 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_push_tls_address);
1666 DD->addArangeLabel(SymbolCU(this, Sym));
1667 addOpAddress(*Loc, Sym);
1669 // Do not create specification DIE if context is either compile unit
1671 if (GVContext && GV.isDefinition() && !GVContext.isCompileUnit() &&
1672 !GVContext.isFile() && !DD->isSubprogramContext(GVContext)) {
1673 // Create specification DIE.
1674 VariableSpecDIE = &createAndAddDIE(dwarf::DW_TAG_variable, UnitDie);
1675 addDIEEntry(*VariableSpecDIE, dwarf::DW_AT_specification, *VariableDIE);
1676 addBlock(*VariableSpecDIE, dwarf::DW_AT_location, Loc);
1677 // A static member's declaration is already flagged as such.
1678 if (!SDMDecl.Verify())
1679 addFlag(*VariableDIE, dwarf::DW_AT_declaration);
1681 addBlock(*VariableDIE, dwarf::DW_AT_location, Loc);
1683 // Add the linkage name.
1684 StringRef LinkageName = GV.getLinkageName();
1685 if (!LinkageName.empty())
1686 // From DWARF4: DIEs to which DW_AT_linkage_name may apply include:
1687 // TAG_common_block, TAG_constant, TAG_entry_point, TAG_subprogram and
1689 addString(IsStaticMember && VariableSpecDIE ? *VariableSpecDIE
1691 DD->getDwarfVersion() >= 4 ? dwarf::DW_AT_linkage_name
1692 : dwarf::DW_AT_MIPS_linkage_name,
1693 GlobalValue::getRealLinkageName(LinkageName));
1694 } else if (const ConstantInt *CI =
1695 dyn_cast_or_null<ConstantInt>(GV.getConstant())) {
1696 // AT_const_value was added when the static member was created. To avoid
1697 // emitting AT_const_value multiple times, we only add AT_const_value when
1698 // it is not a static member.
1699 if (!IsStaticMember)
1700 addConstantValue(*VariableDIE, CI, GTy);
1701 } else if (const ConstantExpr *CE = getMergedGlobalExpr(GV->getOperand(11))) {
1702 addToAccelTable = true;
1703 // GV is a merged global.
1704 DIELoc *Loc = new (DIEValueAllocator) DIELoc();
1705 Value *Ptr = CE->getOperand(0);
1706 MCSymbol *Sym = Asm->getSymbol(cast<GlobalValue>(Ptr));
1707 DD->addArangeLabel(SymbolCU(this, Sym));
1708 addOpAddress(*Loc, Sym);
1709 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1710 SmallVector<Value *, 3> Idx(CE->op_begin() + 1, CE->op_end());
1711 addUInt(*Loc, dwarf::DW_FORM_udata,
1712 Asm->getDataLayout().getIndexedOffset(Ptr->getType(), Idx));
1713 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1714 addBlock(*VariableDIE, dwarf::DW_AT_location, Loc);
1717 if (addToAccelTable) {
1718 DIE &AddrDIE = VariableSpecDIE ? *VariableSpecDIE : *VariableDIE;
1719 DD->addAccelName(GV.getName(), AddrDIE);
1721 // If the linkage name is different than the name, go ahead and output
1722 // that as well into the name table.
1723 if (GV.getLinkageName() != "" && GV.getName() != GV.getLinkageName())
1724 DD->addAccelName(GV.getLinkageName(), AddrDIE);
1727 addGlobalName(GV.getName(), VariableSpecDIE ? *VariableSpecDIE : *VariableDIE,
1731 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
1732 void DwarfUnit::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy) {
1733 DIE &DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
1734 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, *IndexTy);
1736 // The LowerBound value defines the lower bounds which is typically zero for
1737 // C/C++. The Count value is the number of elements. Values are 64 bit. If
1738 // Count == -1 then the array is unbounded and we do not emit
1739 // DW_AT_lower_bound and DW_AT_upper_bound attributes. If LowerBound == 0 and
1740 // Count == 0, then the array has zero elements in which case we do not emit
1742 int64_t LowerBound = SR.getLo();
1743 int64_t DefaultLowerBound = getDefaultLowerBound();
1744 int64_t Count = SR.getCount();
1746 if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
1747 addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound);
1749 if (Count != -1 && Count != 0)
1750 // FIXME: An unbounded array should reference the expression that defines
1752 addUInt(DW_Subrange, dwarf::DW_AT_upper_bound, None,
1753 LowerBound + Count - 1);
1756 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
1757 void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, DICompositeType CTy) {
1759 addFlag(Buffer, dwarf::DW_AT_GNU_vector);
1761 // Emit the element type.
1762 addType(Buffer, resolve(CTy.getTypeDerivedFrom()));
1764 // Get an anonymous type for index type.
1765 // FIXME: This type should be passed down from the front end
1766 // as different languages may have different sizes for indexes.
1767 DIE *IdxTy = getIndexTyDie();
1769 // Construct an integer type to use for indexes.
1770 IdxTy = &createAndAddDIE(dwarf::DW_TAG_base_type, UnitDie);
1771 addString(*IdxTy, dwarf::DW_AT_name, "sizetype");
1772 addUInt(*IdxTy, dwarf::DW_AT_byte_size, None, sizeof(int64_t));
1773 addUInt(*IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1774 dwarf::DW_ATE_unsigned);
1775 setIndexTyDie(IdxTy);
1778 // Add subranges to array type.
1779 DIArray Elements = CTy.getElements();
1780 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1781 DIDescriptor Element = Elements.getElement(i);
1782 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1783 constructSubrangeDIE(Buffer, DISubrange(Element), IdxTy);
1787 /// constructEnumTypeDIE - Construct an enum type DIE from DICompositeType.
1788 void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, DICompositeType CTy) {
1789 DIArray Elements = CTy.getElements();
1791 // Add enumerators to enumeration type.
1792 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1793 DIEnumerator Enum(Elements.getElement(i));
1794 if (Enum.isEnumerator()) {
1795 DIE &Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
1796 StringRef Name = Enum.getName();
1797 addString(Enumerator, dwarf::DW_AT_name, Name);
1798 int64_t Value = Enum.getEnumValue();
1799 addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
1803 DIType DTy = resolve(CTy.getTypeDerivedFrom());
1805 addType(Buffer, DTy);
1806 addFlag(Buffer, dwarf::DW_AT_enum_class);
1810 /// constructContainingTypeDIEs - Construct DIEs for types that contain
1812 void DwarfUnit::constructContainingTypeDIEs() {
1813 for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(),
1814 CE = ContainingTypeMap.end();
1816 DIE &SPDie = *CI->first;
1817 DIDescriptor D(CI->second);
1820 DIE *NDie = getDIE(D);
1823 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, *NDie);
1827 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
1828 std::unique_ptr<DIE> DwarfUnit::constructVariableDIE(DbgVariable &DV,
1830 auto D = constructVariableDIEImpl(DV, Abstract);
1835 std::unique_ptr<DIE> DwarfUnit::constructVariableDIEImpl(const DbgVariable &DV,
1837 // Define variable debug information entry.
1838 auto VariableDie = make_unique<DIE>(DV.getTag());
1841 applyVariableAttributes(DV, *VariableDie);
1845 // Add variable address.
1847 unsigned Offset = DV.getDotDebugLocOffset();
1848 if (Offset != ~0U) {
1849 addLocationList(*VariableDie, dwarf::DW_AT_location, Offset);
1853 // Check if variable is described by a DBG_VALUE instruction.
1854 if (const MachineInstr *DVInsn = DV.getMInsn()) {
1855 assert(DVInsn->getNumOperands() == 3);
1856 if (DVInsn->getOperand(0).isReg()) {
1857 const MachineOperand RegOp = DVInsn->getOperand(0);
1858 // If the second operand is an immediate, this is an indirect value.
1859 if (DVInsn->getOperand(1).isImm()) {
1860 MachineLocation Location(RegOp.getReg(),
1861 DVInsn->getOperand(1).getImm());
1862 addVariableAddress(DV, *VariableDie, Location);
1863 } else if (RegOp.getReg())
1864 addVariableAddress(DV, *VariableDie, MachineLocation(RegOp.getReg()));
1865 } else if (DVInsn->getOperand(0).isImm())
1866 addConstantValue(*VariableDie, DVInsn->getOperand(0), DV.getType());
1867 else if (DVInsn->getOperand(0).isFPImm())
1868 addConstantFPValue(*VariableDie, DVInsn->getOperand(0));
1869 else if (DVInsn->getOperand(0).isCImm())
1870 addConstantValue(*VariableDie, DVInsn->getOperand(0).getCImm(),
1876 // .. else use frame index.
1877 int FI = DV.getFrameIndex();
1879 unsigned FrameReg = 0;
1880 const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
1881 int Offset = TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
1882 MachineLocation Location(FrameReg, Offset);
1883 addVariableAddress(DV, *VariableDie, Location);
1889 /// constructMemberDIE - Construct member DIE from DIDerivedType.
1890 void DwarfUnit::constructMemberDIE(DIE &Buffer, DIDerivedType DT) {
1891 DIE &MemberDie = createAndAddDIE(DT.getTag(), Buffer);
1892 StringRef Name = DT.getName();
1894 addString(MemberDie, dwarf::DW_AT_name, Name);
1896 addType(MemberDie, resolve(DT.getTypeDerivedFrom()));
1898 addSourceLine(MemberDie, DT);
1900 if (DT.getTag() == dwarf::DW_TAG_inheritance && DT.isVirtual()) {
1902 // For C++, virtual base classes are not at fixed offset. Use following
1903 // expression to extract appropriate offset from vtable.
1904 // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1906 DIELoc *VBaseLocationDie = new (DIEValueAllocator) DIELoc();
1907 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1908 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1909 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1910 addUInt(*VBaseLocationDie, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1911 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1912 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1913 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1915 addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
1917 uint64_t Size = DT.getSizeInBits();
1918 uint64_t FieldSize = getBaseTypeSize(DD, DT);
1919 uint64_t OffsetInBytes;
1921 if (Size != FieldSize) {
1922 // Handle bitfield, assume bytes are 8 bits.
1923 addUInt(MemberDie, dwarf::DW_AT_byte_size, None, FieldSize/8);
1924 addUInt(MemberDie, dwarf::DW_AT_bit_size, None, Size);
1926 uint64_t Offset = DT.getOffsetInBits();
1927 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1928 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1929 uint64_t FieldOffset = (HiMark - FieldSize);
1930 Offset -= FieldOffset;
1932 // Maybe we need to work from the other end.
1933 if (Asm->getDataLayout().isLittleEndian())
1934 Offset = FieldSize - (Offset + Size);
1935 addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset);
1937 // Here DW_AT_data_member_location points to the anonymous
1938 // field that includes this bit field.
1939 OffsetInBytes = FieldOffset >> 3;
1941 // This is not a bitfield.
1942 OffsetInBytes = DT.getOffsetInBits() >> 3;
1944 if (DD->getDwarfVersion() <= 2) {
1945 DIELoc *MemLocationDie = new (DIEValueAllocator) DIELoc();
1946 addUInt(*MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1947 addUInt(*MemLocationDie, dwarf::DW_FORM_udata, OffsetInBytes);
1948 addBlock(MemberDie, dwarf::DW_AT_data_member_location, MemLocationDie);
1950 addUInt(MemberDie, dwarf::DW_AT_data_member_location, None,
1954 if (DT.isProtected())
1955 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1956 dwarf::DW_ACCESS_protected);
1957 else if (DT.isPrivate())
1958 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1959 dwarf::DW_ACCESS_private);
1960 // Otherwise C++ member and base classes are considered public.
1962 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1963 dwarf::DW_ACCESS_public);
1965 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1966 dwarf::DW_VIRTUALITY_virtual);
1968 // Objective-C properties.
1969 if (MDNode *PNode = DT.getObjCProperty())
1970 if (DIEEntry *PropertyDie = getDIEEntry(PNode))
1971 MemberDie.addValue(dwarf::DW_AT_APPLE_property, dwarf::DW_FORM_ref4,
1974 if (DT.isArtificial())
1975 addFlag(MemberDie, dwarf::DW_AT_artificial);
1978 /// getOrCreateStaticMemberDIE - Create new DIE for C++ static member.
1979 DIE *DwarfUnit::getOrCreateStaticMemberDIE(DIDerivedType DT) {
1983 // Construct the context before querying for the existence of the DIE in case
1984 // such construction creates the DIE.
1985 DIE *ContextDIE = getOrCreateContextDIE(resolve(DT.getContext()));
1986 assert(dwarf::isType(ContextDIE->getTag()) &&
1987 "Static member should belong to a type.");
1989 if (DIE *StaticMemberDIE = getDIE(DT))
1990 return StaticMemberDIE;
1992 DIE &StaticMemberDIE = createAndAddDIE(DT.getTag(), *ContextDIE, DT);
1994 DIType Ty = resolve(DT.getTypeDerivedFrom());
1996 addString(StaticMemberDIE, dwarf::DW_AT_name, DT.getName());
1997 addType(StaticMemberDIE, Ty);
1998 addSourceLine(StaticMemberDIE, DT);
1999 addFlag(StaticMemberDIE, dwarf::DW_AT_external);
2000 addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
2002 // FIXME: We could omit private if the parent is a class_type, and
2003 // public if the parent is something else.
2004 if (DT.isProtected())
2005 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
2006 dwarf::DW_ACCESS_protected);
2007 else if (DT.isPrivate())
2008 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
2009 dwarf::DW_ACCESS_private);
2011 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
2012 dwarf::DW_ACCESS_public);
2014 if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT.getConstant()))
2015 addConstantValue(StaticMemberDIE, CI, Ty);
2016 if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT.getConstant()))
2017 addConstantFPValue(StaticMemberDIE, CFP);
2019 return &StaticMemberDIE;
2022 void DwarfUnit::emitHeader(const MCSymbol *ASectionSym) const {
2023 Asm->OutStreamer.AddComment("DWARF version number");
2024 Asm->EmitInt16(DD->getDwarfVersion());
2025 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
2026 // We share one abbreviations table across all units so it's always at the
2027 // start of the section. Use a relocatable offset where needed to ensure
2028 // linking doesn't invalidate that offset.
2030 Asm->EmitSectionOffset(ASectionSym, ASectionSym);
2032 // Use a constant value when no symbol is provided.
2034 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2035 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
2038 void DwarfUnit::addRange(RangeSpan Range) {
2039 // Only add a range for this unit if we're emitting full debug.
2040 if (getCUNode().getEmissionKind() == DIBuilder::FullDebug) {
2041 // If we have no current ranges just add the range and return, otherwise,
2042 // check the current section and CU against the previous section and CU we
2043 // emitted into and the subprogram was contained within. If these are the
2044 // same then extend our current range, otherwise add this as a new range.
2045 if (CURanges.size() == 0 ||
2046 this != DD->getPrevCU() ||
2047 Asm->getCurrentSection() != DD->getPrevSection()) {
2048 CURanges.push_back(Range);
2052 assert(&(CURanges.back().getEnd()->getSection()) ==
2053 &(Range.getEnd()->getSection()) &&
2054 "We can only append to a range in the same section!");
2055 CURanges.back().setEnd(Range.getEnd());
2059 void DwarfCompileUnit::initStmtList(MCSymbol *DwarfLineSectionSym) {
2060 // Define start line table label for each Compile Unit.
2061 MCSymbol *LineTableStartSym =
2062 Asm->OutStreamer.getDwarfLineTableSymbol(getUniqueID());
2064 stmtListIndex = UnitDie.getValues().size();
2066 // DW_AT_stmt_list is a offset of line number information for this
2067 // compile unit in debug_line section. For split dwarf this is
2068 // left in the skeleton CU and so not included.
2069 // The line table entries are not always emitted in assembly, so it
2070 // is not okay to use line_table_start here.
2071 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2072 addSectionLabel(UnitDie, dwarf::DW_AT_stmt_list, LineTableStartSym);
2074 addSectionDelta(UnitDie, dwarf::DW_AT_stmt_list, LineTableStartSym,
2075 DwarfLineSectionSym);
2078 void DwarfCompileUnit::applyStmtList(DIE &D) {
2079 D.addValue(dwarf::DW_AT_stmt_list,
2080 UnitDie.getAbbrev().getData()[stmtListIndex].getForm(),
2081 UnitDie.getValues()[stmtListIndex]);
2084 void DwarfTypeUnit::emitHeader(const MCSymbol *ASectionSym) const {
2085 DwarfUnit::emitHeader(ASectionSym);
2086 Asm->OutStreamer.AddComment("Type Signature");
2087 Asm->OutStreamer.EmitIntValue(TypeSignature, sizeof(TypeSignature));
2088 Asm->OutStreamer.AddComment("Type DIE Offset");
2089 // In a skeleton type unit there is no type DIE so emit a zero offset.
2090 Asm->OutStreamer.EmitIntValue(Ty ? Ty->getOffset() : 0,
2091 sizeof(Ty->getOffset()));
2094 void DwarfTypeUnit::initSection(const MCSection *Section) {
2095 assert(!this->Section);
2096 this->Section = Section;
2097 // Since each type unit is contained in its own COMDAT section, the begin
2098 // label and the section label are the same. Using the begin label emission in
2099 // DwarfDebug to emit the section label as well is slightly subtle/sneaky, but
2100 // the only other alternative of lazily constructing start-of-section labels
2101 // and storing a mapping in DwarfDebug (or AsmPrinter).
2102 this->SectionSym = this->LabelBegin =
2103 Asm->GetTempSymbol(Section->getLabelBeginName(), getUniqueID());
2105 Asm->GetTempSymbol(Section->getLabelEndName(), getUniqueID());