]> Gitweb @ Texas Instruments - Open Source Git Repositories - git.TI.com/gitweb - opencl/llvm.git/blob - lib/CodeGen/AsmPrinter/DwarfUnit.cpp
Omit DW_AT_artificial, DW_AT_external, and similar attributes under -gmlt
[opencl/llvm.git] / lib / CodeGen / AsmPrinter / DwarfUnit.cpp
1 //===-- llvm/CodeGen/DwarfUnit.cpp - Dwarf Type and Compile Units ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains support for constructing a dwarf compile unit.
11 //
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"
33 #include "llvm/Target/TargetSubtargetInfo.h"
35 using namespace llvm;
37 #define DEBUG_TYPE "dwarfdebug"
39 static cl::opt<bool>
40 GenerateDwarfTypeUnits("generate-type-units", cl::Hidden,
41                        cl::desc("Generate DWARF4 type units."),
42                        cl::init(false));
44 /// Unit - Unit constructor.
45 DwarfUnit::DwarfUnit(unsigned UID, dwarf::Tag UnitTag, DICompileUnit Node,
46                      AsmPrinter *A, DwarfDebug *DW, DwarfFile *DWU)
47     : UniqueID(UID), CUNode(Node), UnitDie(UnitTag), DebugInfoOffset(0), Asm(A),
48       DD(DW), DU(DWU), IndexTyDie(nullptr), Section(nullptr),
49       Skeleton(nullptr) {
50   assert(UnitTag == dwarf::DW_TAG_compile_unit ||
51          UnitTag == dwarf::DW_TAG_type_unit);
52   DIEIntegerOne = new (DIEValueAllocator) DIEInteger(1);
53 }
55 DwarfCompileUnit::DwarfCompileUnit(unsigned UID, DICompileUnit Node,
56                                    AsmPrinter *A, DwarfDebug *DW,
57                                    DwarfFile *DWU)
58     : DwarfUnit(UID, dwarf::DW_TAG_compile_unit, Node, A, DW, DWU) {
59   insertDIE(Node, &getUnitDie());
60 }
62 DwarfTypeUnit::DwarfTypeUnit(unsigned UID, DwarfCompileUnit &CU, AsmPrinter *A,
63                              DwarfDebug *DW, DwarfFile *DWU,
64                              MCDwarfDwoLineTable *SplitLineTable)
65     : DwarfUnit(UID, dwarf::DW_TAG_type_unit, CU.getCUNode(), A, DW, DWU),
66       CU(CU), SplitLineTable(SplitLineTable) {
67   if (SplitLineTable)
68     addSectionOffset(UnitDie, dwarf::DW_AT_stmt_list, 0);
69 }
71 /// ~Unit - Destructor for compile unit.
72 DwarfUnit::~DwarfUnit() {
73   for (unsigned j = 0, M = DIEBlocks.size(); j < M; ++j)
74     DIEBlocks[j]->~DIEBlock();
75   for (unsigned j = 0, M = DIELocs.size(); j < M; ++j)
76     DIELocs[j]->~DIELoc();
77 }
79 /// createDIEEntry - Creates a new DIEEntry to be a proxy for a debug
80 /// information entry.
81 DIEEntry *DwarfUnit::createDIEEntry(DIE &Entry) {
82   DIEEntry *Value = new (DIEValueAllocator) DIEEntry(Entry);
83   return Value;
84 }
86 /// getDefaultLowerBound - Return the default lower bound for an array. If the
87 /// DWARF version doesn't handle the language, return -1.
88 int64_t DwarfUnit::getDefaultLowerBound() const {
89   switch (getLanguage()) {
90   default:
91     break;
93   case dwarf::DW_LANG_C89:
94   case dwarf::DW_LANG_C99:
95   case dwarf::DW_LANG_C:
96   case dwarf::DW_LANG_C_plus_plus:
97   case dwarf::DW_LANG_ObjC:
98   case dwarf::DW_LANG_ObjC_plus_plus:
99     return 0;
101   case dwarf::DW_LANG_Fortran77:
102   case dwarf::DW_LANG_Fortran90:
103   case dwarf::DW_LANG_Fortran95:
104     return 1;
106   // The languages below have valid values only if the DWARF version >= 4.
107   case dwarf::DW_LANG_Java:
108   case dwarf::DW_LANG_Python:
109   case dwarf::DW_LANG_UPC:
110   case dwarf::DW_LANG_D:
111     if (dwarf::DWARF_VERSION >= 4)
112       return 0;
113     break;
115   case dwarf::DW_LANG_Ada83:
116   case dwarf::DW_LANG_Ada95:
117   case dwarf::DW_LANG_Cobol74:
118   case dwarf::DW_LANG_Cobol85:
119   case dwarf::DW_LANG_Modula2:
120   case dwarf::DW_LANG_Pascal83:
121   case dwarf::DW_LANG_PLI:
122     if (dwarf::DWARF_VERSION >= 4)
123       return 1;
124     break;
125   }
127   return -1;
130 /// Check whether the DIE for this MDNode can be shared across CUs.
131 static bool isShareableAcrossCUs(DIDescriptor D) {
132   // When the MDNode can be part of the type system, the DIE can be shared
133   // across CUs.
134   // Combining type units and cross-CU DIE sharing is lower value (since
135   // cross-CU DIE sharing is used in LTO and removes type redundancy at that
136   // level already) but may be implementable for some value in projects
137   // building multiple independent libraries with LTO and then linking those
138   // together.
139   return (D.isType() ||
140           (D.isSubprogram() && !DISubprogram(D).isDefinition())) &&
141          !GenerateDwarfTypeUnits;
144 /// getDIE - Returns the debug information entry map slot for the
145 /// specified debug variable. We delegate the request to DwarfDebug
146 /// when the DIE for this MDNode can be shared across CUs. The mappings
147 /// will be kept in DwarfDebug for shareable DIEs.
148 DIE *DwarfUnit::getDIE(DIDescriptor D) const {
149   if (isShareableAcrossCUs(D))
150     return DD->getDIE(D);
151   return MDNodeToDieMap.lookup(D);
154 /// insertDIE - Insert DIE into the map. We delegate the request to DwarfDebug
155 /// when the DIE for this MDNode can be shared across CUs. The mappings
156 /// will be kept in DwarfDebug for shareable DIEs.
157 void DwarfUnit::insertDIE(DIDescriptor Desc, DIE *D) {
158   if (isShareableAcrossCUs(Desc)) {
159     DD->insertDIE(Desc, D);
160     return;
161   }
162   MDNodeToDieMap.insert(std::make_pair(Desc, D));
165 /// addFlag - Add a flag that is true.
166 void DwarfUnit::addFlag(DIE &Die, dwarf::Attribute Attribute) {
167   if (DD->getDwarfVersion() >= 4)
168     Die.addValue(Attribute, dwarf::DW_FORM_flag_present, DIEIntegerOne);
169   else
170     Die.addValue(Attribute, dwarf::DW_FORM_flag, DIEIntegerOne);
173 /// addUInt - Add an unsigned integer attribute data and value.
174 ///
175 void DwarfUnit::addUInt(DIE &Die, dwarf::Attribute Attribute,
176                         Optional<dwarf::Form> Form, uint64_t Integer) {
177   if (!Form)
178     Form = DIEInteger::BestForm(false, Integer);
179   DIEValue *Value = Integer == 1 ? DIEIntegerOne : new (DIEValueAllocator)
180                         DIEInteger(Integer);
181   Die.addValue(Attribute, *Form, Value);
184 void DwarfUnit::addUInt(DIE &Block, dwarf::Form Form, uint64_t Integer) {
185   addUInt(Block, (dwarf::Attribute)0, Form, Integer);
188 /// addSInt - Add an signed integer attribute data and value.
189 ///
190 void DwarfUnit::addSInt(DIE &Die, dwarf::Attribute Attribute,
191                         Optional<dwarf::Form> Form, int64_t Integer) {
192   if (!Form)
193     Form = DIEInteger::BestForm(true, Integer);
194   DIEValue *Value = new (DIEValueAllocator) DIEInteger(Integer);
195   Die.addValue(Attribute, *Form, Value);
198 void DwarfUnit::addSInt(DIELoc &Die, Optional<dwarf::Form> Form,
199                         int64_t Integer) {
200   addSInt(Die, (dwarf::Attribute)0, Form, Integer);
203 /// addString - Add a string attribute data and value. We always emit a
204 /// reference to the string pool instead of immediate strings so that DIEs have
205 /// more predictable sizes. In the case of split dwarf we emit an index
206 /// into another table which gets us the static offset into the string
207 /// table.
208 void DwarfUnit::addString(DIE &Die, dwarf::Attribute Attribute,
209                           StringRef String) {
211   if (!DD->useSplitDwarf())
212     return addLocalString(Die, Attribute, String);
214   unsigned idx = DU->getStringPool().getIndex(*Asm, String);
215   DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
216   DIEValue *Str = new (DIEValueAllocator) DIEString(Value, String);
217   Die.addValue(Attribute, dwarf::DW_FORM_GNU_str_index, Str);
220 /// addLocalString - Add a string attribute data and value. This is guaranteed
221 /// to be in the local string pool instead of indirected.
222 void DwarfUnit::addLocalString(DIE &Die, dwarf::Attribute Attribute,
223                                StringRef String) {
224   MCSymbol *Symb = DU->getStringPool().getSymbol(*Asm, String);
225   DIEValue *Value;
226   if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
227     Value = new (DIEValueAllocator) DIELabel(Symb);
228   else {
229     MCSymbol *StringPool = DU->getStringPool().getSectionSymbol();
230     Value = new (DIEValueAllocator) DIEDelta(Symb, StringPool);
231   }
232   DIEValue *Str = new (DIEValueAllocator) DIEString(Value, String);
233   Die.addValue(Attribute, dwarf::DW_FORM_strp, Str);
236 /// addExpr - Add a Dwarf expression attribute data and value.
237 ///
238 void DwarfUnit::addExpr(DIELoc &Die, dwarf::Form Form, const MCExpr *Expr) {
239   DIEValue *Value = new (DIEValueAllocator) DIEExpr(Expr);
240   Die.addValue((dwarf::Attribute)0, Form, Value);
243 /// addLocationList - Add a Dwarf loclistptr attribute data and value.
244 ///
245 void DwarfUnit::addLocationList(DIE &Die, dwarf::Attribute Attribute,
246                                 unsigned Index) {
247   DIEValue *Value = new (DIEValueAllocator) DIELocList(Index);
248   dwarf::Form Form = DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
249                                                 : dwarf::DW_FORM_data4;
250   Die.addValue(Attribute, Form, Value);
253 /// addLabel - Add a Dwarf label attribute data and value.
254 ///
255 void DwarfUnit::addLabel(DIE &Die, dwarf::Attribute Attribute, dwarf::Form Form,
256                          const MCSymbol *Label) {
257   DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
258   Die.addValue(Attribute, Form, Value);
261 void DwarfUnit::addLabel(DIELoc &Die, dwarf::Form Form, const MCSymbol *Label) {
262   addLabel(Die, (dwarf::Attribute)0, Form, Label);
265 /// addSectionLabel - Add a Dwarf section label attribute data and value.
266 ///
267 void DwarfUnit::addSectionLabel(DIE &Die, dwarf::Attribute Attribute,
268                                 const MCSymbol *Label) {
269   if (DD->getDwarfVersion() >= 4)
270     addLabel(Die, Attribute, dwarf::DW_FORM_sec_offset, Label);
271   else
272     addLabel(Die, Attribute, dwarf::DW_FORM_data4, Label);
275 /// addSectionOffset - Add an offset into a section attribute data and value.
276 ///
277 void DwarfUnit::addSectionOffset(DIE &Die, dwarf::Attribute Attribute,
278                                  uint64_t Integer) {
279   if (DD->getDwarfVersion() >= 4)
280     addUInt(Die, Attribute, dwarf::DW_FORM_sec_offset, Integer);
281   else
282     addUInt(Die, Attribute, dwarf::DW_FORM_data4, Integer);
285 /// addLabelAddress - Add a dwarf label attribute data and value using
286 /// DW_FORM_addr or DW_FORM_GNU_addr_index.
287 ///
288 void DwarfCompileUnit::addLabelAddress(DIE &Die, dwarf::Attribute Attribute,
289                                        const MCSymbol *Label) {
291   if (!DD->useSplitDwarf())
292     return addLocalLabelAddress(Die, Attribute, Label);
294   if (Label)
295     DD->addArangeLabel(SymbolCU(this, Label));
297   unsigned idx = DD->getAddressPool().getIndex(Label);
298   DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
299   Die.addValue(Attribute, dwarf::DW_FORM_GNU_addr_index, Value);
302 void DwarfCompileUnit::addLocalLabelAddress(DIE &Die,
303                                             dwarf::Attribute Attribute,
304                                             const MCSymbol *Label) {
305   if (Label)
306     DD->addArangeLabel(SymbolCU(this, Label));
308   Die.addValue(Attribute, dwarf::DW_FORM_addr,
309                Label ? (DIEValue *)new (DIEValueAllocator) DIELabel(Label)
310                      : new (DIEValueAllocator) DIEInteger(0));
313 unsigned DwarfCompileUnit::getOrCreateSourceID(StringRef FileName, StringRef DirName) {
314   // If we print assembly, we can't separate .file entries according to
315   // compile units. Thus all files will belong to the default compile unit.
317   // FIXME: add a better feature test than hasRawTextSupport. Even better,
318   // extend .file to support this.
319   return Asm->OutStreamer.EmitDwarfFileDirective(
320       0, DirName, FileName,
321       Asm->OutStreamer.hasRawTextSupport() ? 0 : getUniqueID());
324 unsigned DwarfTypeUnit::getOrCreateSourceID(StringRef FileName, StringRef DirName) {
325   return SplitLineTable ? SplitLineTable->getFile(DirName, FileName)
326                         : getCU().getOrCreateSourceID(FileName, DirName);
329 /// addOpAddress - Add a dwarf op address data and value using the
330 /// form given and an op of either DW_FORM_addr or DW_FORM_GNU_addr_index.
331 ///
332 void DwarfUnit::addOpAddress(DIELoc &Die, const MCSymbol *Sym) {
333   if (!DD->useSplitDwarf()) {
334     addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
335     addLabel(Die, dwarf::DW_FORM_udata, Sym);
336   } else {
337     addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index);
338     addUInt(Die, dwarf::DW_FORM_GNU_addr_index,
339             DD->getAddressPool().getIndex(Sym));
340   }
343 /// addSectionDelta - Add a section label delta attribute data and value.
344 ///
345 void DwarfUnit::addSectionDelta(DIE &Die, dwarf::Attribute Attribute,
346                                 const MCSymbol *Hi, const MCSymbol *Lo) {
347   DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
348   Die.addValue(Attribute, DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
349                                                      : dwarf::DW_FORM_data4,
350                Value);
353 void DwarfUnit::addLabelDelta(DIE &Die, dwarf::Attribute Attribute,
354                               const MCSymbol *Hi, const MCSymbol *Lo) {
355   DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
356   Die.addValue(Attribute, dwarf::DW_FORM_data4, Value);
359 /// addDIEEntry - Add a DIE attribute data and value.
360 ///
361 void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute, DIE &Entry) {
362   addDIEEntry(Die, Attribute, createDIEEntry(Entry));
365 void DwarfUnit::addDIETypeSignature(DIE &Die, const DwarfTypeUnit &Type) {
366   // Flag the type unit reference as a declaration so that if it contains
367   // members (implicit special members, static data member definitions, member
368   // declarations for definitions in this CU, etc) consumers don't get confused
369   // and think this is a full definition.
370   addFlag(Die, dwarf::DW_AT_declaration);
372   Die.addValue(dwarf::DW_AT_signature, dwarf::DW_FORM_ref_sig8,
373                new (DIEValueAllocator) DIETypeSignature(Type));
376 void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute,
377                             DIEEntry *Entry) {
378   const DIE *DieCU = Die.getUnitOrNull();
379   const DIE *EntryCU = Entry->getEntry().getUnitOrNull();
380   if (!DieCU)
381     // We assume that Die belongs to this CU, if it is not linked to any CU yet.
382     DieCU = &getUnitDie();
383   if (!EntryCU)
384     EntryCU = &getUnitDie();
385   Die.addValue(Attribute,
386                EntryCU == DieCU ? dwarf::DW_FORM_ref4 : dwarf::DW_FORM_ref_addr,
387                Entry);
390 /// Create a DIE with the given Tag, add the DIE to its parent, and
391 /// call insertDIE if MD is not null.
392 DIE &DwarfUnit::createAndAddDIE(unsigned Tag, DIE &Parent, DIDescriptor N) {
393   assert(Tag != dwarf::DW_TAG_auto_variable &&
394          Tag != dwarf::DW_TAG_arg_variable);
395   Parent.addChild(make_unique<DIE>((dwarf::Tag)Tag));
396   DIE &Die = *Parent.getChildren().back();
397   if (N)
398     insertDIE(N, &Die);
399   return Die;
402 /// addBlock - Add block data.
403 ///
404 void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute, DIELoc *Loc) {
405   Loc->ComputeSize(Asm);
406   DIELocs.push_back(Loc); // Memoize so we can call the destructor later on.
407   Die.addValue(Attribute, Loc->BestForm(DD->getDwarfVersion()), Loc);
410 void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute,
411                          DIEBlock *Block) {
412   Block->ComputeSize(Asm);
413   DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
414   Die.addValue(Attribute, Block->BestForm(), Block);
417 /// addSourceLine - Add location information to specified debug information
418 /// entry.
419 void DwarfUnit::addSourceLine(DIE &Die, unsigned Line, StringRef File,
420                               StringRef Directory) {
421   if (Line == 0)
422     return;
424   unsigned FileID = getOrCreateSourceID(File, Directory);
425   assert(FileID && "Invalid file id");
426   addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
427   addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
430 /// addSourceLine - Add location information to specified debug information
431 /// entry.
432 void DwarfUnit::addSourceLine(DIE &Die, DIVariable V) {
433   assert(V.isVariable());
435   addSourceLine(Die, V.getLineNumber(), V.getContext().getFilename(),
436                 V.getContext().getDirectory());
439 /// addSourceLine - Add location information to specified debug information
440 /// entry.
441 void DwarfUnit::addSourceLine(DIE &Die, DIGlobalVariable G) {
442   assert(G.isGlobalVariable());
444   addSourceLine(Die, G.getLineNumber(), G.getFilename(), G.getDirectory());
447 /// addSourceLine - Add location information to specified debug information
448 /// entry.
449 void DwarfUnit::addSourceLine(DIE &Die, DISubprogram SP) {
450   assert(SP.isSubprogram());
452   addSourceLine(Die, SP.getLineNumber(), SP.getFilename(), SP.getDirectory());
455 /// addSourceLine - Add location information to specified debug information
456 /// entry.
457 void DwarfUnit::addSourceLine(DIE &Die, DIType Ty) {
458   assert(Ty.isType());
460   addSourceLine(Die, Ty.getLineNumber(), Ty.getFilename(), Ty.getDirectory());
463 /// addSourceLine - Add location information to specified debug information
464 /// entry.
465 void DwarfUnit::addSourceLine(DIE &Die, DIObjCProperty Ty) {
466   assert(Ty.isObjCProperty());
468   DIFile File = Ty.getFile();
469   addSourceLine(Die, Ty.getLineNumber(), File.getFilename(),
470                 File.getDirectory());
473 /// addSourceLine - Add location information to specified debug information
474 /// entry.
475 void DwarfUnit::addSourceLine(DIE &Die, DINameSpace NS) {
476   assert(NS.Verify());
478   addSourceLine(Die, NS.getLineNumber(), NS.getFilename(), NS.getDirectory());
481 /// addVariableAddress - Add DW_AT_location attribute for a
482 /// DbgVariable based on provided MachineLocation.
483 void DwarfUnit::addVariableAddress(const DbgVariable &DV, DIE &Die,
484                                    MachineLocation Location) {
485   if (DV.variableHasComplexAddress())
486     addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
487   else if (DV.isBlockByrefVariable())
488     addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location);
489   else
490     addAddress(Die, dwarf::DW_AT_location, Location,
491                DV.getVariable().isIndirect());
494 /// addRegisterOp - Add register operand.
495 // FIXME: Ideally, this would share the implementation with
496 // AsmPrinter::EmitDwarfRegOpPiece.
497 void DwarfUnit::addRegisterOpPiece(DIELoc &TheDie, unsigned Reg,
498                                    unsigned SizeInBits, unsigned OffsetInBits) {
499   const TargetRegisterInfo *RI = Asm->TM.getSubtargetImpl()->getRegisterInfo();
500   int DWReg = RI->getDwarfRegNum(Reg, false);
501   bool isSubRegister = DWReg < 0;
503   unsigned Idx = 0;
505   // Go up the super-register chain until we hit a valid dwarf register number.
506   for (MCSuperRegIterator SR(Reg, RI); SR.isValid() && DWReg < 0; ++SR) {
507     DWReg = RI->getDwarfRegNum(*SR, false);
508     if (DWReg >= 0)
509       Idx = RI->getSubRegIndex(*SR, Reg);
510   }
512   if (DWReg < 0) {
513     DEBUG(dbgs() << "Invalid Dwarf register number.\n");
514     addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_nop);
515     return;
516   }
518   // Emit register.
519   if (DWReg < 32)
520     addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + DWReg);
521   else {
522     addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
523     addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
524   }
526   // Emit mask.
527   bool isPiece = SizeInBits > 0;
528   if (isSubRegister || isPiece) {
529     const unsigned SizeOfByte = 8;
530     unsigned RegSizeInBits = RI->getSubRegIdxSize(Idx);
531     unsigned RegOffsetInBits = RI->getSubRegIdxOffset(Idx);
532     unsigned PieceSizeInBits = std::max(SizeInBits, RegSizeInBits);
533     unsigned PieceOffsetInBits = OffsetInBits ? OffsetInBits : RegOffsetInBits;
534     assert(RegSizeInBits >= SizeInBits && "register smaller than value");
536     if (RegOffsetInBits != PieceOffsetInBits) {
537       // Manually shift the value into place, since the DW_OP_piece
538       // describes the part of the variable, not the position of the
539       // subregister.
540       addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
541       addUInt(TheDie, dwarf::DW_FORM_data1, RegOffsetInBits);
542       addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_shr);
543     }
545     if (PieceOffsetInBits > 0 || PieceSizeInBits % SizeOfByte) {
546       assert(PieceSizeInBits > 0 && "piece has zero size");
547       addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_bit_piece);
548       addUInt(TheDie, dwarf::DW_FORM_data1, PieceSizeInBits);
549       addUInt(TheDie, dwarf::DW_FORM_data1, PieceOffsetInBits);
550      } else {
551       assert(PieceSizeInBits > 0 && "piece has zero size");
552       addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_piece);
553       addUInt(TheDie, dwarf::DW_FORM_data1, PieceSizeInBits/SizeOfByte);
554     }
555   }
558 /// addRegisterOffset - Add register offset.
559 void DwarfUnit::addRegisterOffset(DIELoc &TheDie, unsigned Reg,
560                                   int64_t Offset) {
561   const TargetRegisterInfo *RI = Asm->TM.getSubtargetImpl()->getRegisterInfo();
562   unsigned DWReg = RI->getDwarfRegNum(Reg, false);
563   const TargetRegisterInfo *TRI = Asm->TM.getSubtargetImpl()->getRegisterInfo();
564   if (Reg == TRI->getFrameRegister(*Asm->MF))
565     // If variable offset is based in frame register then use fbreg.
566     addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_fbreg);
567   else if (DWReg < 32)
568     addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + DWReg);
569   else {
570     addUInt(TheDie, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
571     addUInt(TheDie, dwarf::DW_FORM_udata, DWReg);
572   }
573   addSInt(TheDie, dwarf::DW_FORM_sdata, Offset);
576 /// addAddress - Add an address attribute to a die based on the location
577 /// provided.
578 void DwarfUnit::addAddress(DIE &Die, dwarf::Attribute Attribute,
579                            const MachineLocation &Location, bool Indirect) {
580   DIELoc *Loc = new (DIEValueAllocator) DIELoc();
582   if (Location.isReg() && !Indirect)
583     addRegisterOpPiece(*Loc, Location.getReg());
584   else {
585     addRegisterOffset(*Loc, Location.getReg(), Location.getOffset());
586     if (Indirect && !Location.isReg()) {
587       addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
588     }
589   }
591   // Now attach the location information to the DIE.
592   addBlock(Die, Attribute, Loc);
595 /// addComplexAddress - Start with the address based on the location provided,
596 /// and generate the DWARF information necessary to find the actual variable
597 /// given the extra address information encoded in the DbgVariable, starting
598 /// from the starting location.  Add the DWARF information to the die.
599 ///
600 void DwarfUnit::addComplexAddress(const DbgVariable &DV, DIE &Die,
601                                   dwarf::Attribute Attribute,
602                                   const MachineLocation &Location) {
603   DIELoc *Loc = new (DIEValueAllocator) DIELoc();
604   unsigned N = DV.getNumAddrElements();
605   unsigned i = 0;
606   if (Location.isReg()) {
607     if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
608       // If first address element is OpPlus then emit
609       // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
610       addRegisterOffset(*Loc, Location.getReg(), DV.getAddrElement(1));
611       i = 2;
612     } else if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpDeref) {
613         addRegisterOpPiece(*Loc, Location.getReg(),
614                            DV.getVariable().getPieceSize(),
615                            DV.getVariable().getPieceOffset());
616         i = 3;
617     } else
618       addRegisterOpPiece(*Loc, Location.getReg());
619   } else
620     addRegisterOffset(*Loc, Location.getReg(), Location.getOffset());
622   for (; i < N; ++i) {
623     uint64_t Element = DV.getAddrElement(i);
624     if (Element == DIBuilder::OpPlus) {
625       addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
626       addUInt(*Loc, dwarf::DW_FORM_udata, DV.getAddrElement(++i));
628     } else if (Element == DIBuilder::OpDeref) {
629       if (!Location.isReg())
630         addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
632     } else if (Element == DIBuilder::OpPiece) {
633       const unsigned SizeOfByte = 8;
634       unsigned PieceOffsetInBits = DV.getAddrElement(++i)*SizeOfByte;
635       unsigned PieceSizeInBits = DV.getAddrElement(++i)*SizeOfByte;
636       // Emit DW_OP_bit_piece Size Offset.
637       assert(PieceSizeInBits > 0 && "piece has zero size");
638       addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_bit_piece);
639       addUInt(*Loc, dwarf::DW_FORM_udata, PieceSizeInBits);
640       addUInt(*Loc, dwarf::DW_FORM_udata, PieceOffsetInBits);
642     } else
643       llvm_unreachable("unknown DIBuilder Opcode");
644   }
646   // Now attach the location information to the DIE.
647   addBlock(Die, Attribute, Loc);
650 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
651    VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
652    gives the variable VarName either the struct, or a pointer to the struct, as
653    its type.  This is necessary for various behind-the-scenes things the
654    compiler needs to do with by-reference variables in Blocks.
656    However, as far as the original *programmer* is concerned, the variable
657    should still have type 'SomeType', as originally declared.
659    The function getBlockByrefType dives into the __Block_byref_x_VarName
660    struct to find the original type of the variable, which is then assigned to
661    the variable's Debug Information Entry as its real type.  So far, so good.
662    However now the debugger will expect the variable VarName to have the type
663    SomeType.  So we need the location attribute for the variable to be an
664    expression that explains to the debugger how to navigate through the
665    pointers and struct to find the actual variable of type SomeType.
667    The following function does just that.  We start by getting
668    the "normal" location for the variable. This will be the location
669    of either the struct __Block_byref_x_VarName or the pointer to the
670    struct __Block_byref_x_VarName.
672    The struct will look something like:
674    struct __Block_byref_x_VarName {
675      ... <various fields>
676      struct __Block_byref_x_VarName *forwarding;
677      ... <various other fields>
678      SomeType VarName;
679      ... <maybe more fields>
680    };
682    If we are given the struct directly (as our starting point) we
683    need to tell the debugger to:
685    1).  Add the offset of the forwarding field.
687    2).  Follow that pointer to get the real __Block_byref_x_VarName
688    struct to use (the real one may have been copied onto the heap).
690    3).  Add the offset for the field VarName, to find the actual variable.
692    If we started with a pointer to the struct, then we need to
693    dereference that pointer first, before the other steps.
694    Translating this into DWARF ops, we will need to append the following
695    to the current location description for the variable:
697    DW_OP_deref                    -- optional, if we start with a pointer
698    DW_OP_plus_uconst <forward_fld_offset>
699    DW_OP_deref
700    DW_OP_plus_uconst <varName_fld_offset>
702    That is what this function does.  */
704 /// addBlockByrefAddress - Start with the address based on the location
705 /// provided, and generate the DWARF information necessary to find the
706 /// actual Block variable (navigating the Block struct) based on the
707 /// starting location.  Add the DWARF information to the die.  For
708 /// more information, read large comment just above here.
709 ///
710 void DwarfUnit::addBlockByrefAddress(const DbgVariable &DV, DIE &Die,
711                                      dwarf::Attribute Attribute,
712                                      const MachineLocation &Location) {
713   DIType Ty = DV.getType();
714   DIType TmpTy = Ty;
715   uint16_t Tag = Ty.getTag();
716   bool isPointer = false;
718   StringRef varName = DV.getName();
720   if (Tag == dwarf::DW_TAG_pointer_type) {
721     DIDerivedType DTy(Ty);
722     TmpTy = resolve(DTy.getTypeDerivedFrom());
723     isPointer = true;
724   }
726   DICompositeType blockStruct(TmpTy);
728   // Find the __forwarding field and the variable field in the __Block_byref
729   // struct.
730   DIArray Fields = blockStruct.getElements();
731   DIDerivedType varField;
732   DIDerivedType forwardingField;
734   for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
735     DIDerivedType DT(Fields.getElement(i));
736     StringRef fieldName = DT.getName();
737     if (fieldName == "__forwarding")
738       forwardingField = DT;
739     else if (fieldName == varName)
740       varField = DT;
741   }
743   // Get the offsets for the forwarding field and the variable field.
744   unsigned forwardingFieldOffset = forwardingField.getOffsetInBits() >> 3;
745   unsigned varFieldOffset = varField.getOffsetInBits() >> 2;
747   // Decode the original location, and use that as the start of the byref
748   // variable's location.
749   DIELoc *Loc = new (DIEValueAllocator) DIELoc();
751   if (Location.isReg())
752     addRegisterOpPiece(*Loc, Location.getReg());
753   else
754     addRegisterOffset(*Loc, Location.getReg(), Location.getOffset());
756   // If we started with a pointer to the __Block_byref... struct, then
757   // the first thing we need to do is dereference the pointer (DW_OP_deref).
758   if (isPointer)
759     addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
761   // Next add the offset for the '__forwarding' field:
762   // DW_OP_plus_uconst ForwardingFieldOffset.  Note there's no point in
763   // adding the offset if it's 0.
764   if (forwardingFieldOffset > 0) {
765     addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
766     addUInt(*Loc, dwarf::DW_FORM_udata, forwardingFieldOffset);
767   }
769   // Now dereference the __forwarding field to get to the real __Block_byref
770   // struct:  DW_OP_deref.
771   addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
773   // Now that we've got the real __Block_byref... struct, add the offset
774   // for the variable's field to get to the location of the actual variable:
775   // DW_OP_plus_uconst varFieldOffset.  Again, don't add if it's 0.
776   if (varFieldOffset > 0) {
777     addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
778     addUInt(*Loc, dwarf::DW_FORM_udata, varFieldOffset);
779   }
781   // Now attach the location information to the DIE.
782   addBlock(Die, Attribute, Loc);
785 /// Return true if type encoding is unsigned.
786 static bool isUnsignedDIType(DwarfDebug *DD, DIType Ty) {
787   DIDerivedType DTy(Ty);
788   if (DTy.isDerivedType()) {
789     dwarf::Tag T = (dwarf::Tag)Ty.getTag();
790     // Encode pointer constants as unsigned bytes. This is used at least for
791     // null pointer constant emission.
792     // FIXME: reference and rvalue_reference /probably/ shouldn't be allowed
793     // here, but accept them for now due to a bug in SROA producing bogus
794     // dbg.values.
795     if (T == dwarf::DW_TAG_pointer_type ||
796         T == dwarf::DW_TAG_ptr_to_member_type ||
797         T == dwarf::DW_TAG_reference_type ||
798         T == dwarf::DW_TAG_rvalue_reference_type)
799       return true;
800     assert(T == dwarf::DW_TAG_typedef || T == dwarf::DW_TAG_const_type ||
801            T == dwarf::DW_TAG_volatile_type ||
802            T == dwarf::DW_TAG_restrict_type ||
803            T == dwarf::DW_TAG_enumeration_type);
804     if (DITypeRef Deriv = DTy.getTypeDerivedFrom())
805       return isUnsignedDIType(DD, DD->resolve(Deriv));
806     // FIXME: Enums without a fixed underlying type have unknown signedness
807     // here, leading to incorrectly emitted constants.
808     assert(DTy.getTag() == dwarf::DW_TAG_enumeration_type);
809     return false;
810   }
812   DIBasicType BTy(Ty);
813   assert(BTy.isBasicType());
814   unsigned Encoding = BTy.getEncoding();
815   assert((Encoding == dwarf::DW_ATE_unsigned ||
816           Encoding == dwarf::DW_ATE_unsigned_char ||
817           Encoding == dwarf::DW_ATE_signed ||
818           Encoding == dwarf::DW_ATE_signed_char ||
819           Encoding == dwarf::DW_ATE_UTF || Encoding == dwarf::DW_ATE_boolean) &&
820          "Unsupported encoding");
821   return (Encoding == dwarf::DW_ATE_unsigned ||
822           Encoding == dwarf::DW_ATE_unsigned_char ||
823           Encoding == dwarf::DW_ATE_UTF || Encoding == dwarf::DW_ATE_boolean);
826 /// If this type is derived from a base type then return base type size.
827 static uint64_t getBaseTypeSize(DwarfDebug *DD, DIDerivedType Ty) {
828   unsigned Tag = Ty.getTag();
830   if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef &&
831       Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type &&
832       Tag != dwarf::DW_TAG_restrict_type)
833     return Ty.getSizeInBits();
835   DIType BaseType = DD->resolve(Ty.getTypeDerivedFrom());
837   // If this type is not derived from any type or the type is a declaration then
838   // take conservative approach.
839   if (!BaseType.isValid() || BaseType.isForwardDecl())
840     return Ty.getSizeInBits();
842   // If this is a derived type, go ahead and get the base type, unless it's a
843   // reference then it's just the size of the field. Pointer types have no need
844   // of this since they're a different type of qualification on the type.
845   if (BaseType.getTag() == dwarf::DW_TAG_reference_type ||
846       BaseType.getTag() == dwarf::DW_TAG_rvalue_reference_type)
847     return Ty.getSizeInBits();
849   if (BaseType.isDerivedType())
850     return getBaseTypeSize(DD, DIDerivedType(BaseType));
852   return BaseType.getSizeInBits();
855 /// addConstantFPValue - Add constant value entry in variable DIE.
856 void DwarfUnit::addConstantFPValue(DIE &Die, const MachineOperand &MO) {
857   assert(MO.isFPImm() && "Invalid machine operand!");
858   DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
859   APFloat FPImm = MO.getFPImm()->getValueAPF();
861   // Get the raw data form of the floating point.
862   const APInt FltVal = FPImm.bitcastToAPInt();
863   const char *FltPtr = (const char *)FltVal.getRawData();
865   int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
866   bool LittleEndian = Asm->getDataLayout().isLittleEndian();
867   int Incr = (LittleEndian ? 1 : -1);
868   int Start = (LittleEndian ? 0 : NumBytes - 1);
869   int Stop = (LittleEndian ? NumBytes : -1);
871   // Output the constant to DWARF one byte at a time.
872   for (; Start != Stop; Start += Incr)
873     addUInt(*Block, dwarf::DW_FORM_data1, (unsigned char)0xFF & FltPtr[Start]);
875   addBlock(Die, dwarf::DW_AT_const_value, Block);
878 /// addConstantFPValue - Add constant value entry in variable DIE.
879 void DwarfUnit::addConstantFPValue(DIE &Die, const ConstantFP *CFP) {
880   // Pass this down to addConstantValue as an unsigned bag of bits.
881   addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true);
884 /// addConstantValue - Add constant value entry in variable DIE.
885 void DwarfUnit::addConstantValue(DIE &Die, const ConstantInt *CI, DIType Ty) {
886   addConstantValue(Die, CI->getValue(), Ty);
889 /// addConstantValue - Add constant value entry in variable DIE.
890 void DwarfUnit::addConstantValue(DIE &Die, const MachineOperand &MO,
891                                  DIType Ty) {
892   assert(MO.isImm() && "Invalid machine operand!");
894   addConstantValue(Die, isUnsignedDIType(DD, Ty), MO.getImm());
897 void DwarfUnit::addConstantValue(DIE &Die, bool Unsigned, uint64_t Val) {
898   // FIXME: This is a bit conservative/simple - it emits negative values always
899   // sign extended to 64 bits rather than minimizing the number of bytes.
900   addUInt(Die, dwarf::DW_AT_const_value,
901           Unsigned ? dwarf::DW_FORM_udata : dwarf::DW_FORM_sdata, Val);
904 void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, DIType Ty) {
905   addConstantValue(Die, Val, isUnsignedDIType(DD, Ty));
908 // addConstantValue - Add constant value entry in variable DIE.
909 void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, bool Unsigned) {
910   unsigned CIBitWidth = Val.getBitWidth();
911   if (CIBitWidth <= 64) {
912     addConstantValue(Die, Unsigned,
913                      Unsigned ? Val.getZExtValue() : Val.getSExtValue());
914     return;
915   }
917   DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
919   // Get the raw data form of the large APInt.
920   const uint64_t *Ptr64 = Val.getRawData();
922   int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
923   bool LittleEndian = Asm->getDataLayout().isLittleEndian();
925   // Output the constant to DWARF one byte at a time.
926   for (int i = 0; i < NumBytes; i++) {
927     uint8_t c;
928     if (LittleEndian)
929       c = Ptr64[i / 8] >> (8 * (i & 7));
930     else
931       c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
932     addUInt(*Block, dwarf::DW_FORM_data1, c);
933   }
935   addBlock(Die, dwarf::DW_AT_const_value, Block);
938 /// addTemplateParams - Add template parameters into buffer.
939 void DwarfUnit::addTemplateParams(DIE &Buffer, DIArray TParams) {
940   // Add template parameters.
941   for (unsigned i = 0, e = TParams.getNumElements(); i != e; ++i) {
942     DIDescriptor Element = TParams.getElement(i);
943     if (Element.isTemplateTypeParameter())
944       constructTemplateTypeParameterDIE(Buffer,
945                                         DITemplateTypeParameter(Element));
946     else if (Element.isTemplateValueParameter())
947       constructTemplateValueParameterDIE(Buffer,
948                                          DITemplateValueParameter(Element));
949   }
952 /// getOrCreateContextDIE - Get context owner's DIE.
953 DIE *DwarfUnit::getOrCreateContextDIE(DIScope Context) {
954   if (!Context || Context.isFile())
955     return &getUnitDie();
956   if (Context.isType())
957     return getOrCreateTypeDIE(DIType(Context));
958   if (Context.isNameSpace())
959     return getOrCreateNameSpace(DINameSpace(Context));
960   if (Context.isSubprogram())
961     return getOrCreateSubprogramDIE(DISubprogram(Context));
962   return getDIE(Context);
965 DIE *DwarfUnit::createTypeDIE(DICompositeType Ty) {
966   DIScope Context = resolve(Ty.getContext());
967   DIE *ContextDIE = getOrCreateContextDIE(Context);
969   if (DIE *TyDIE = getDIE(Ty))
970     return TyDIE;
972   // Create new type.
973   DIE &TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
975   constructTypeDIE(TyDIE, Ty);
977   updateAcceleratorTables(Context, Ty, TyDIE);
978   return &TyDIE;
981 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
982 /// given DIType.
983 DIE *DwarfUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
984   if (!TyNode)
985     return nullptr;
987   DIType Ty(TyNode);
988   assert(Ty.isType());
989   assert(Ty == resolve(Ty.getRef()) &&
990          "type was not uniqued, possible ODR violation.");
992   // DW_TAG_restrict_type is not supported in DWARF2
993   if (Ty.getTag() == dwarf::DW_TAG_restrict_type && DD->getDwarfVersion() <= 2)
994     return getOrCreateTypeDIE(resolve(DIDerivedType(Ty).getTypeDerivedFrom()));
996   // Construct the context before querying for the existence of the DIE in case
997   // such construction creates the DIE.
998   DIScope Context = resolve(Ty.getContext());
999   DIE *ContextDIE = getOrCreateContextDIE(Context);
1000   assert(ContextDIE);
1002   if (DIE *TyDIE = getDIE(Ty))
1003     return TyDIE;
1005   // Create new type.
1006   DIE &TyDIE = createAndAddDIE(Ty.getTag(), *ContextDIE, Ty);
1008   updateAcceleratorTables(Context, Ty, TyDIE);
1010   if (Ty.isBasicType())
1011     constructTypeDIE(TyDIE, DIBasicType(Ty));
1012   else if (Ty.isCompositeType()) {
1013     DICompositeType CTy(Ty);
1014     if (GenerateDwarfTypeUnits && !Ty.isForwardDecl())
1015       if (MDString *TypeId = CTy.getIdentifier()) {
1016         DD->addDwarfTypeUnitType(getCU(), TypeId->getString(), TyDIE, CTy);
1017         // Skip updating the accelerator tables since this is not the full type.
1018         return &TyDIE;
1019       }
1020     constructTypeDIE(TyDIE, CTy);
1021   } else {
1022     assert(Ty.isDerivedType() && "Unknown kind of DIType");
1023     constructTypeDIE(TyDIE, DIDerivedType(Ty));
1024   }
1026   return &TyDIE;
1029 void DwarfUnit::updateAcceleratorTables(DIScope Context, DIType Ty,
1030                                         const DIE &TyDIE) {
1031   if (!Ty.getName().empty() && !Ty.isForwardDecl()) {
1032     bool IsImplementation = 0;
1033     if (Ty.isCompositeType()) {
1034       DICompositeType CT(Ty);
1035       // A runtime language of 0 actually means C/C++ and that any
1036       // non-negative value is some version of Objective-C/C++.
1037       IsImplementation = (CT.getRunTimeLang() == 0) || CT.isObjcClassComplete();
1038     }
1039     unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0;
1040     DD->addAccelType(Ty.getName(), TyDIE, Flags);
1042     if ((!Context || Context.isCompileUnit() || Context.isFile() ||
1043          Context.isNameSpace()) &&
1044         getCUNode().getEmissionKind() != DIBuilder::LineTablesOnly)
1045       GlobalTypes[getParentContextString(Context) + Ty.getName().str()] =
1046           &TyDIE;
1047   }
1050 /// addType - Add a new type attribute to the specified entity.
1051 void DwarfUnit::addType(DIE &Entity, DIType Ty, dwarf::Attribute Attribute) {
1052   assert(Ty && "Trying to add a type that doesn't exist?");
1054   // Check for pre-existence.
1055   DIEEntry *Entry = getDIEEntry(Ty);
1056   // If it exists then use the existing value.
1057   if (Entry) {
1058     addDIEEntry(Entity, Attribute, Entry);
1059     return;
1060   }
1062   // Construct type.
1063   DIE *Buffer = getOrCreateTypeDIE(Ty);
1065   // Set up proxy.
1066   Entry = createDIEEntry(*Buffer);
1067   insertDIEEntry(Ty, Entry);
1068   addDIEEntry(Entity, Attribute, Entry);
1071 /// addGlobalName - Add a new global name to the compile unit.
1072 void DwarfUnit::addGlobalName(StringRef Name, DIE &Die, DIScope Context) {
1073   if (getCUNode().getEmissionKind() == DIBuilder::LineTablesOnly)
1074     return;
1075   std::string FullName = getParentContextString(Context) + Name.str();
1076   GlobalNames[FullName] = &Die;
1079 /// getParentContextString - Walks the metadata parent chain in a language
1080 /// specific manner (using the compile unit language) and returns
1081 /// it as a string. This is done at the metadata level because DIEs may
1082 /// not currently have been added to the parent context and walking the
1083 /// DIEs looking for names is more expensive than walking the metadata.
1084 std::string DwarfUnit::getParentContextString(DIScope Context) const {
1085   if (!Context)
1086     return "";
1088   // FIXME: Decide whether to implement this for non-C++ languages.
1089   if (getLanguage() != dwarf::DW_LANG_C_plus_plus)
1090     return "";
1092   std::string CS;
1093   SmallVector<DIScope, 1> Parents;
1094   while (!Context.isCompileUnit()) {
1095     Parents.push_back(Context);
1096     if (Context.getContext())
1097       Context = resolve(Context.getContext());
1098     else
1099       // Structure, etc types will have a NULL context if they're at the top
1100       // level.
1101       break;
1102   }
1104   // Reverse iterate over our list to go from the outermost construct to the
1105   // innermost.
1106   for (SmallVectorImpl<DIScope>::reverse_iterator I = Parents.rbegin(),
1107                                                   E = Parents.rend();
1108        I != E; ++I) {
1109     DIScope Ctx = *I;
1110     StringRef Name = Ctx.getName();
1111     if (Name.empty() && Ctx.isNameSpace())
1112       Name = "(anonymous namespace)";
1113     if (!Name.empty()) {
1114       CS += Name;
1115       CS += "::";
1116     }
1117   }
1118   return CS;
1121 /// constructTypeDIE - Construct basic type die from DIBasicType.
1122 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
1123   // Get core information.
1124   StringRef Name = BTy.getName();
1125   // Add name if not anonymous or intermediate type.
1126   if (!Name.empty())
1127     addString(Buffer, dwarf::DW_AT_name, Name);
1129   // An unspecified type only has a name attribute.
1130   if (BTy.getTag() == dwarf::DW_TAG_unspecified_type)
1131     return;
1133   addUInt(Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1134           BTy.getEncoding());
1136   uint64_t Size = BTy.getSizeInBits() >> 3;
1137   addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
1140 /// constructTypeDIE - Construct derived type die from DIDerivedType.
1141 void DwarfUnit::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
1142   // Get core information.
1143   StringRef Name = DTy.getName();
1144   uint64_t Size = DTy.getSizeInBits() >> 3;
1145   uint16_t Tag = Buffer.getTag();
1147   // Map to main type, void will not have a type.
1148   DIType FromTy = resolve(DTy.getTypeDerivedFrom());
1149   if (FromTy)
1150     addType(Buffer, FromTy);
1152   // Add name if not anonymous or intermediate type.
1153   if (!Name.empty())
1154     addString(Buffer, dwarf::DW_AT_name, Name);
1156   // Add size if non-zero (derived types might be zero-sized.)
1157   if (Size && Tag != dwarf::DW_TAG_pointer_type)
1158     addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
1160   if (Tag == dwarf::DW_TAG_ptr_to_member_type)
1161     addDIEEntry(Buffer, dwarf::DW_AT_containing_type,
1162                 *getOrCreateTypeDIE(resolve(DTy.getClassType())));
1163   // Add source line info if available and TyDesc is not a forward declaration.
1164   if (!DTy.isForwardDecl())
1165     addSourceLine(Buffer, DTy);
1168 /// constructSubprogramArguments - Construct function argument DIEs.
1169 void DwarfUnit::constructSubprogramArguments(DIE &Buffer, DITypeArray Args) {
1170   for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1171     DIType Ty = resolve(Args.getElement(i));
1172     if (!Ty) {
1173       assert(i == N-1 && "Unspecified parameter must be the last argument");
1174       createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
1175     } else {
1176       DIE &Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
1177       addType(Arg, DIType(Ty));
1178       if (DIType(Ty).isArtificial())
1179         addFlag(Arg, dwarf::DW_AT_artificial);
1180     }
1181   }
1184 /// constructTypeDIE - Construct type DIE from DICompositeType.
1185 void DwarfUnit::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
1186   // Add name if not anonymous or intermediate type.
1187   StringRef Name = CTy.getName();
1189   uint64_t Size = CTy.getSizeInBits() >> 3;
1190   uint16_t Tag = Buffer.getTag();
1192   switch (Tag) {
1193   case dwarf::DW_TAG_array_type:
1194     constructArrayTypeDIE(Buffer, CTy);
1195     break;
1196   case dwarf::DW_TAG_enumeration_type:
1197     constructEnumTypeDIE(Buffer, CTy);
1198     break;
1199   case dwarf::DW_TAG_subroutine_type: {
1200     // Add return type. A void return won't have a type.
1201     DITypeArray Elements = DISubroutineType(CTy).getTypeArray();
1202     DIType RTy(resolve(Elements.getElement(0)));
1203     if (RTy)
1204       addType(Buffer, RTy);
1206     bool isPrototyped = true;
1207     if (Elements.getNumElements() == 2 &&
1208         !Elements.getElement(1))
1209       isPrototyped = false;
1211     constructSubprogramArguments(Buffer, Elements);
1213     // Add prototype flag if we're dealing with a C language and the
1214     // function has been prototyped.
1215     uint16_t Language = getLanguage();
1216     if (isPrototyped &&
1217         (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1218          Language == dwarf::DW_LANG_ObjC))
1219       addFlag(Buffer, dwarf::DW_AT_prototyped);
1221     if (CTy.isLValueReference())
1222       addFlag(Buffer, dwarf::DW_AT_reference);
1224     if (CTy.isRValueReference())
1225       addFlag(Buffer, dwarf::DW_AT_rvalue_reference);
1226   } break;
1227   case dwarf::DW_TAG_structure_type:
1228   case dwarf::DW_TAG_union_type:
1229   case dwarf::DW_TAG_class_type: {
1230     // Add elements to structure type.
1231     DIArray Elements = CTy.getElements();
1232     for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1233       DIDescriptor Element = Elements.getElement(i);
1234       if (Element.isSubprogram())
1235         getOrCreateSubprogramDIE(DISubprogram(Element));
1236       else if (Element.isDerivedType()) {
1237         DIDerivedType DDTy(Element);
1238         if (DDTy.getTag() == dwarf::DW_TAG_friend) {
1239           DIE &ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
1240           addType(ElemDie, resolve(DDTy.getTypeDerivedFrom()),
1241                   dwarf::DW_AT_friend);
1242         } else if (DDTy.isStaticMember()) {
1243           getOrCreateStaticMemberDIE(DDTy);
1244         } else {
1245           constructMemberDIE(Buffer, DDTy);
1246         }
1247       } else if (Element.isObjCProperty()) {
1248         DIObjCProperty Property(Element);
1249         DIE &ElemDie = createAndAddDIE(Property.getTag(), Buffer);
1250         StringRef PropertyName = Property.getObjCPropertyName();
1251         addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
1252         if (Property.getType())
1253           addType(ElemDie, Property.getType());
1254         addSourceLine(ElemDie, Property);
1255         StringRef GetterName = Property.getObjCPropertyGetterName();
1256         if (!GetterName.empty())
1257           addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
1258         StringRef SetterName = Property.getObjCPropertySetterName();
1259         if (!SetterName.empty())
1260           addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
1261         unsigned PropertyAttributes = 0;
1262         if (Property.isReadOnlyObjCProperty())
1263           PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readonly;
1264         if (Property.isReadWriteObjCProperty())
1265           PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readwrite;
1266         if (Property.isAssignObjCProperty())
1267           PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_assign;
1268         if (Property.isRetainObjCProperty())
1269           PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_retain;
1270         if (Property.isCopyObjCProperty())
1271           PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_copy;
1272         if (Property.isNonAtomicObjCProperty())
1273           PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_nonatomic;
1274         if (PropertyAttributes)
1275           addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None,
1276                   PropertyAttributes);
1278         DIEEntry *Entry = getDIEEntry(Element);
1279         if (!Entry) {
1280           Entry = createDIEEntry(ElemDie);
1281           insertDIEEntry(Element, Entry);
1282         }
1283       } else
1284         continue;
1285     }
1287     if (CTy.isAppleBlockExtension())
1288       addFlag(Buffer, dwarf::DW_AT_APPLE_block);
1290     DICompositeType ContainingType(resolve(CTy.getContainingType()));
1291     if (ContainingType)
1292       addDIEEntry(Buffer, dwarf::DW_AT_containing_type,
1293                   *getOrCreateTypeDIE(ContainingType));
1295     if (CTy.isObjcClassComplete())
1296       addFlag(Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
1298     // Add template parameters to a class, structure or union types.
1299     // FIXME: The support isn't in the metadata for this yet.
1300     if (Tag == dwarf::DW_TAG_class_type ||
1301         Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
1302       addTemplateParams(Buffer, CTy.getTemplateParams());
1304     break;
1305   }
1306   default:
1307     break;
1308   }
1310   // Add name if not anonymous or intermediate type.
1311   if (!Name.empty())
1312     addString(Buffer, dwarf::DW_AT_name, Name);
1314   if (Tag == dwarf::DW_TAG_enumeration_type ||
1315       Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
1316       Tag == dwarf::DW_TAG_union_type) {
1317     // Add size if non-zero (derived types might be zero-sized.)
1318     // TODO: Do we care about size for enum forward declarations?
1319     if (Size)
1320       addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
1321     else if (!CTy.isForwardDecl())
1322       // Add zero size if it is not a forward declaration.
1323       addUInt(Buffer, dwarf::DW_AT_byte_size, None, 0);
1325     // If we're a forward decl, say so.
1326     if (CTy.isForwardDecl())
1327       addFlag(Buffer, dwarf::DW_AT_declaration);
1329     // Add source line info if available.
1330     if (!CTy.isForwardDecl())
1331       addSourceLine(Buffer, CTy);
1333     // No harm in adding the runtime language to the declaration.
1334     unsigned RLang = CTy.getRunTimeLang();
1335     if (RLang)
1336       addUInt(Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
1337               RLang);
1338   }
1341 /// constructTemplateTypeParameterDIE - Construct new DIE for the given
1342 /// DITemplateTypeParameter.
1343 void DwarfUnit::constructTemplateTypeParameterDIE(DIE &Buffer,
1344                                                   DITemplateTypeParameter TP) {
1345   DIE &ParamDIE =
1346       createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
1347   // Add the type if it exists, it could be void and therefore no type.
1348   if (TP.getType())
1349     addType(ParamDIE, resolve(TP.getType()));
1350   if (!TP.getName().empty())
1351     addString(ParamDIE, dwarf::DW_AT_name, TP.getName());
1354 /// constructTemplateValueParameterDIE - Construct new DIE for the given
1355 /// DITemplateValueParameter.
1356 void
1357 DwarfUnit::constructTemplateValueParameterDIE(DIE &Buffer,
1358                                               DITemplateValueParameter VP) {
1359   DIE &ParamDIE = createAndAddDIE(VP.getTag(), Buffer);
1361   // Add the type if there is one, template template and template parameter
1362   // packs will not have a type.
1363   if (VP.getTag() == dwarf::DW_TAG_template_value_parameter)
1364     addType(ParamDIE, resolve(VP.getType()));
1365   if (!VP.getName().empty())
1366     addString(ParamDIE, dwarf::DW_AT_name, VP.getName());
1367   if (Value *Val = VP.getValue()) {
1368     if (ConstantInt *CI = dyn_cast<ConstantInt>(Val))
1369       addConstantValue(ParamDIE, CI, resolve(VP.getType()));
1370     else if (GlobalValue *GV = dyn_cast<GlobalValue>(Val)) {
1371       // For declaration non-type template parameters (such as global values and
1372       // functions)
1373       DIELoc *Loc = new (DIEValueAllocator) DIELoc();
1374       addOpAddress(*Loc, Asm->getSymbol(GV));
1375       // Emit DW_OP_stack_value to use the address as the immediate value of the
1376       // parameter, rather than a pointer to it.
1377       addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
1378       addBlock(ParamDIE, dwarf::DW_AT_location, Loc);
1379     } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1380       assert(isa<MDString>(Val));
1381       addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
1382                 cast<MDString>(Val)->getString());
1383     } else if (VP.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1384       assert(isa<MDNode>(Val));
1385       DIArray A(cast<MDNode>(Val));
1386       addTemplateParams(ParamDIE, A);
1387     }
1388   }
1391 /// getOrCreateNameSpace - Create a DIE for DINameSpace.
1392 DIE *DwarfUnit::getOrCreateNameSpace(DINameSpace NS) {
1393   // Construct the context before querying for the existence of the DIE in case
1394   // such construction creates the DIE.
1395   DIE *ContextDIE = getOrCreateContextDIE(NS.getContext());
1397   if (DIE *NDie = getDIE(NS))
1398     return NDie;
1399   DIE &NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS);
1401   StringRef Name = NS.getName();
1402   if (!Name.empty())
1403     addString(NDie, dwarf::DW_AT_name, NS.getName());
1404   else
1405     Name = "(anonymous namespace)";
1406   DD->addAccelNamespace(Name, NDie);
1407   addGlobalName(Name, NDie, NS.getContext());
1408   addSourceLine(NDie, NS);
1409   return &NDie;
1412 /// getOrCreateSubprogramDIE - Create new DIE using SP.
1413 DIE *DwarfUnit::getOrCreateSubprogramDIE(DISubprogram SP) {
1414   // Construct the context before querying for the existence of the DIE in case
1415   // such construction creates the DIE (as is the case for member function
1416   // declarations).
1417   DIE *ContextDIE = getOrCreateContextDIE(resolve(SP.getContext()));
1419   if (DIE *SPDie = getDIE(SP))
1420     return SPDie;
1422   if (DISubprogram SPDecl = SP.getFunctionDeclaration()) {
1423     // Add subprogram definitions to the CU die directly.
1424     ContextDIE = &getUnitDie();
1425     // Build the decl now to ensure it precedes the definition.
1426     getOrCreateSubprogramDIE(SPDecl);
1427   }
1429   // DW_TAG_inlined_subroutine may refer to this DIE.
1430   DIE &SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
1432   // Stop here and fill this in later, depending on whether or not this
1433   // subprogram turns out to have inlined instances or not.
1434   if (SP.isDefinition())
1435     return &SPDie;
1437   applySubprogramAttributes(SP, SPDie);
1438   return &SPDie;
1441 void DwarfUnit::applySubprogramAttributesToDefinition(DISubprogram SP, DIE &SPDie) {
1442   DISubprogram SPDecl = SP.getFunctionDeclaration();
1443   DIScope Context = resolve(SPDecl ? SPDecl.getContext() : SP.getContext());
1444   applySubprogramAttributes(SP, SPDie);
1445   addGlobalName(SP.getName(), SPDie, Context);
1448 void DwarfUnit::applySubprogramAttributes(DISubprogram SP, DIE &SPDie) {
1449   DIE *DeclDie = nullptr;
1450   StringRef DeclLinkageName;
1451   if (DISubprogram SPDecl = SP.getFunctionDeclaration()) {
1452     DeclDie = getDIE(SPDecl);
1453     assert(DeclDie && "This DIE should've already been constructed when the "
1454                       "definition DIE was created in "
1455                       "getOrCreateSubprogramDIE");
1456     DeclLinkageName = SPDecl.getLinkageName();
1457   }
1459   // Add function template parameters.
1460   addTemplateParams(SPDie, SP.getTemplateParams());
1462   // Add the linkage name if we have one and it isn't in the Decl.
1463   StringRef LinkageName = SP.getLinkageName();
1464   assert(((LinkageName.empty() || DeclLinkageName.empty()) ||
1465           LinkageName == DeclLinkageName) &&
1466          "decl has a linkage name and it is different");
1467   if (!LinkageName.empty() && DeclLinkageName.empty())
1468     addString(SPDie, dwarf::DW_AT_MIPS_linkage_name,
1469               GlobalValue::getRealLinkageName(LinkageName));
1471   if (DeclDie) {
1472     // Refer to the function declaration where all the other attributes will be
1473     // found.
1474     addDIEEntry(SPDie, dwarf::DW_AT_specification, *DeclDie);
1475     return;
1476   }
1478   // Constructors and operators for anonymous aggregates do not have names.
1479   if (!SP.getName().empty())
1480     addString(SPDie, dwarf::DW_AT_name, SP.getName());
1482   addSourceLine(SPDie, SP);
1484   // Add the prototype if we have a prototype and we have a C like
1485   // language.
1486   uint16_t Language = getLanguage();
1487   if (SP.isPrototyped() &&
1488       (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1489        Language == dwarf::DW_LANG_ObjC))
1490     addFlag(SPDie, dwarf::DW_AT_prototyped);
1492   DISubroutineType SPTy = SP.getType();
1493   assert(SPTy.getTag() == dwarf::DW_TAG_subroutine_type &&
1494          "the type of a subprogram should be a subroutine");
1496   DITypeArray Args = SPTy.getTypeArray();
1497   // Add a return type. If this is a type like a C/C++ void type we don't add a
1498   // return type.
1499   if (resolve(Args.getElement(0)))
1500     addType(SPDie, DIType(resolve(Args.getElement(0))));
1502   unsigned VK = SP.getVirtuality();
1503   if (VK) {
1504     addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1505     DIELoc *Block = getDIELoc();
1506     addUInt(*Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1507     addUInt(*Block, dwarf::DW_FORM_udata, SP.getVirtualIndex());
1508     addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
1509     ContainingTypeMap.insert(
1510         std::make_pair(&SPDie, resolve(SP.getContainingType())));
1511   }
1513   if (!SP.isDefinition()) {
1514     addFlag(SPDie, dwarf::DW_AT_declaration);
1516     // Add arguments. Do not add arguments for subprogram definition. They will
1517     // be handled while processing variables.
1518     constructSubprogramArguments(SPDie, Args);
1519   }
1521   if(getCUNode().getEmissionKind() == DIBuilder::LineTablesOnly)
1522     return;
1524   if (SP.isArtificial())
1525     addFlag(SPDie, dwarf::DW_AT_artificial);
1527   if (!SP.isLocalToUnit())
1528     addFlag(SPDie, dwarf::DW_AT_external);
1530   if (SP.isOptimized())
1531     addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1533   if (unsigned isa = Asm->getISAEncoding()) {
1534     addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1535   }
1537   if (SP.isLValueReference())
1538     addFlag(SPDie, dwarf::DW_AT_reference);
1540   if (SP.isRValueReference())
1541     addFlag(SPDie, dwarf::DW_AT_rvalue_reference);
1543   if (SP.isProtected())
1544     addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1545             dwarf::DW_ACCESS_protected);
1546   else if (SP.isPrivate())
1547     addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1548             dwarf::DW_ACCESS_private);
1549   else
1550     addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1551             dwarf::DW_ACCESS_public);
1553   if (SP.isExplicit())
1554     addFlag(SPDie, dwarf::DW_AT_explicit);
1557 void DwarfUnit::applyVariableAttributes(const DbgVariable &Var,
1558                                         DIE &VariableDie) {
1559   StringRef Name = Var.getName();
1560   if (!Name.empty())
1561     addString(VariableDie, dwarf::DW_AT_name, Name);
1562   addSourceLine(VariableDie, Var.getVariable());
1563   addType(VariableDie, Var.getType());
1564   if (Var.isArtificial())
1565     addFlag(VariableDie, dwarf::DW_AT_artificial);
1568 // Return const expression if value is a GEP to access merged global
1569 // constant. e.g.
1570 // i8* getelementptr ({ i8, i8, i8, i8 }* @_MergedGlobals, i32 0, i32 0)
1571 static const ConstantExpr *getMergedGlobalExpr(const Value *V) {
1572   const ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(V);
1573   if (!CE || CE->getNumOperands() != 3 ||
1574       CE->getOpcode() != Instruction::GetElementPtr)
1575     return nullptr;
1577   // First operand points to a global struct.
1578   Value *Ptr = CE->getOperand(0);
1579   if (!isa<GlobalValue>(Ptr) ||
1580       !isa<StructType>(cast<PointerType>(Ptr->getType())->getElementType()))
1581     return nullptr;
1583   // Second operand is zero.
1584   const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(CE->getOperand(1));
1585   if (!CI || !CI->isZero())
1586     return nullptr;
1588   // Third operand is offset.
1589   if (!isa<ConstantInt>(CE->getOperand(2)))
1590     return nullptr;
1592   return CE;
1595 /// createGlobalVariableDIE - create global variable DIE.
1596 void DwarfCompileUnit::createGlobalVariableDIE(DIGlobalVariable GV) {
1597   // Check for pre-existence.
1598   if (getDIE(GV))
1599     return;
1601   assert(GV.isGlobalVariable());
1603   DIScope GVContext = GV.getContext();
1604   DIType GTy = DD->resolve(GV.getType());
1606   // If this is a static data member definition, some attributes belong
1607   // to the declaration DIE.
1608   DIE *VariableDIE = nullptr;
1609   bool IsStaticMember = false;
1610   DIDerivedType SDMDecl = GV.getStaticDataMemberDeclaration();
1611   if (SDMDecl.Verify()) {
1612     assert(SDMDecl.isStaticMember() && "Expected static member decl");
1613     // We need the declaration DIE that is in the static member's class.
1614     VariableDIE = getOrCreateStaticMemberDIE(SDMDecl);
1615     IsStaticMember = true;
1616   }
1618   // If this is not a static data member definition, create the variable
1619   // DIE and add the initial set of attributes to it.
1620   if (!VariableDIE) {
1621     // Construct the context before querying for the existence of the DIE in
1622     // case such construction creates the DIE.
1623     DIE *ContextDIE = getOrCreateContextDIE(GVContext);
1625     // Add to map.
1626     VariableDIE = &createAndAddDIE(GV.getTag(), *ContextDIE, GV);
1628     // Add name and type.
1629     addString(*VariableDIE, dwarf::DW_AT_name, GV.getDisplayName());
1630     addType(*VariableDIE, GTy);
1632     // Add scoping info.
1633     if (!GV.isLocalToUnit())
1634       addFlag(*VariableDIE, dwarf::DW_AT_external);
1636     // Add line number info.
1637     addSourceLine(*VariableDIE, GV);
1638   }
1640   // Add location.
1641   bool addToAccelTable = false;
1642   DIE *VariableSpecDIE = nullptr;
1643   bool isGlobalVariable = GV.getGlobal() != nullptr;
1644   if (isGlobalVariable) {
1645     addToAccelTable = true;
1646     DIELoc *Loc = new (DIEValueAllocator) DIELoc();
1647     const MCSymbol *Sym = Asm->getSymbol(GV.getGlobal());
1648     if (GV.getGlobal()->isThreadLocal()) {
1649       // FIXME: Make this work with -gsplit-dwarf.
1650       unsigned PointerSize = Asm->getDataLayout().getPointerSize();
1651       assert((PointerSize == 4 || PointerSize == 8) &&
1652              "Add support for other sizes if necessary");
1653       // Based on GCC's support for TLS:
1654       if (!DD->useSplitDwarf()) {
1655         // 1) Start with a constNu of the appropriate pointer size
1656         addUInt(*Loc, dwarf::DW_FORM_data1,
1657                 PointerSize == 4 ? dwarf::DW_OP_const4u : dwarf::DW_OP_const8u);
1658         // 2) containing the (relocated) offset of the TLS variable
1659         //    within the module's TLS block.
1660         addExpr(*Loc, dwarf::DW_FORM_udata,
1661                 Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym));
1662       } else {
1663         addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
1664         addUInt(*Loc, dwarf::DW_FORM_udata,
1665                 DD->getAddressPool().getIndex(Sym, /* TLS */ true));
1666       }
1667       // 3) followed by a custom OP to make the debugger do a TLS lookup.
1668       addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_push_tls_address);
1669     } else {
1670       DD->addArangeLabel(SymbolCU(this, Sym));
1671       addOpAddress(*Loc, Sym);
1672     }
1673     // Do not create specification DIE if context is either compile unit
1674     // or a subprogram.
1675     if (GVContext && GV.isDefinition() && !GVContext.isCompileUnit() &&
1676         !GVContext.isFile() && !DD->isSubprogramContext(GVContext)) {
1677       // Create specification DIE.
1678       VariableSpecDIE = &createAndAddDIE(dwarf::DW_TAG_variable, UnitDie);
1679       addDIEEntry(*VariableSpecDIE, dwarf::DW_AT_specification, *VariableDIE);
1680       addBlock(*VariableSpecDIE, dwarf::DW_AT_location, Loc);
1681       // A static member's declaration is already flagged as such.
1682       if (!SDMDecl.Verify())
1683         addFlag(*VariableDIE, dwarf::DW_AT_declaration);
1684     } else {
1685       addBlock(*VariableDIE, dwarf::DW_AT_location, Loc);
1686     }
1687     // Add the linkage name.
1688     StringRef LinkageName = GV.getLinkageName();
1689     if (!LinkageName.empty())
1690       // From DWARF4: DIEs to which DW_AT_linkage_name may apply include:
1691       // TAG_common_block, TAG_constant, TAG_entry_point, TAG_subprogram and
1692       // TAG_variable.
1693       addString(IsStaticMember && VariableSpecDIE ? *VariableSpecDIE
1694                                                   : *VariableDIE,
1695                 DD->getDwarfVersion() >= 4 ? dwarf::DW_AT_linkage_name
1696                                            : dwarf::DW_AT_MIPS_linkage_name,
1697                 GlobalValue::getRealLinkageName(LinkageName));
1698   } else if (const ConstantInt *CI =
1699                  dyn_cast_or_null<ConstantInt>(GV.getConstant())) {
1700     // AT_const_value was added when the static member was created. To avoid
1701     // emitting AT_const_value multiple times, we only add AT_const_value when
1702     // it is not a static member.
1703     if (!IsStaticMember)
1704       addConstantValue(*VariableDIE, CI, GTy);
1705   } else if (const ConstantExpr *CE = getMergedGlobalExpr(GV->getOperand(11))) {
1706     addToAccelTable = true;
1707     // GV is a merged global.
1708     DIELoc *Loc = new (DIEValueAllocator) DIELoc();
1709     Value *Ptr = CE->getOperand(0);
1710     MCSymbol *Sym = Asm->getSymbol(cast<GlobalValue>(Ptr));
1711     DD->addArangeLabel(SymbolCU(this, Sym));
1712     addOpAddress(*Loc, Sym);
1713     addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1714     SmallVector<Value *, 3> Idx(CE->op_begin() + 1, CE->op_end());
1715     addUInt(*Loc, dwarf::DW_FORM_udata,
1716             Asm->getDataLayout().getIndexedOffset(Ptr->getType(), Idx));
1717     addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1718     addBlock(*VariableDIE, dwarf::DW_AT_location, Loc);
1719   }
1721   if (addToAccelTable) {
1722     DIE &AddrDIE = VariableSpecDIE ? *VariableSpecDIE : *VariableDIE;
1723     DD->addAccelName(GV.getName(), AddrDIE);
1725     // If the linkage name is different than the name, go ahead and output
1726     // that as well into the name table.
1727     if (GV.getLinkageName() != "" && GV.getName() != GV.getLinkageName())
1728       DD->addAccelName(GV.getLinkageName(), AddrDIE);
1729   }
1731   addGlobalName(GV.getName(), VariableSpecDIE ? *VariableSpecDIE : *VariableDIE,
1732                 GV.getContext());
1735 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
1736 void DwarfUnit::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy) {
1737   DIE &DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
1738   addDIEEntry(DW_Subrange, dwarf::DW_AT_type, *IndexTy);
1740   // The LowerBound value defines the lower bounds which is typically zero for
1741   // C/C++. The Count value is the number of elements.  Values are 64 bit. If
1742   // Count == -1 then the array is unbounded and we do not emit
1743   // DW_AT_lower_bound and DW_AT_upper_bound attributes. If LowerBound == 0 and
1744   // Count == 0, then the array has zero elements in which case we do not emit
1745   // an upper bound.
1746   int64_t LowerBound = SR.getLo();
1747   int64_t DefaultLowerBound = getDefaultLowerBound();
1748   int64_t Count = SR.getCount();
1750   if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
1751     addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound);
1753   if (Count != -1 && Count != 0)
1754     // FIXME: An unbounded array should reference the expression that defines
1755     // the array.
1756     addUInt(DW_Subrange, dwarf::DW_AT_upper_bound, None,
1757             LowerBound + Count - 1);
1760 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
1761 void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, DICompositeType CTy) {
1762   if (CTy.isVector())
1763     addFlag(Buffer, dwarf::DW_AT_GNU_vector);
1765   // Emit the element type.
1766   addType(Buffer, resolve(CTy.getTypeDerivedFrom()));
1768   // Get an anonymous type for index type.
1769   // FIXME: This type should be passed down from the front end
1770   // as different languages may have different sizes for indexes.
1771   DIE *IdxTy = getIndexTyDie();
1772   if (!IdxTy) {
1773     // Construct an integer type to use for indexes.
1774     IdxTy = &createAndAddDIE(dwarf::DW_TAG_base_type, UnitDie);
1775     addString(*IdxTy, dwarf::DW_AT_name, "sizetype");
1776     addUInt(*IdxTy, dwarf::DW_AT_byte_size, None, sizeof(int64_t));
1777     addUInt(*IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1778             dwarf::DW_ATE_unsigned);
1779     setIndexTyDie(IdxTy);
1780   }
1782   // Add subranges to array type.
1783   DIArray Elements = CTy.getElements();
1784   for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1785     DIDescriptor Element = Elements.getElement(i);
1786     if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1787       constructSubrangeDIE(Buffer, DISubrange(Element), IdxTy);
1788   }
1791 /// constructEnumTypeDIE - Construct an enum type DIE from DICompositeType.
1792 void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, DICompositeType CTy) {
1793   DIArray Elements = CTy.getElements();
1795   // Add enumerators to enumeration type.
1796   for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1797     DIEnumerator Enum(Elements.getElement(i));
1798     if (Enum.isEnumerator()) {
1799       DIE &Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
1800       StringRef Name = Enum.getName();
1801       addString(Enumerator, dwarf::DW_AT_name, Name);
1802       int64_t Value = Enum.getEnumValue();
1803       addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
1804               Value);
1805     }
1806   }
1807   DIType DTy = resolve(CTy.getTypeDerivedFrom());
1808   if (DTy) {
1809     addType(Buffer, DTy);
1810     addFlag(Buffer, dwarf::DW_AT_enum_class);
1811   }
1814 /// constructContainingTypeDIEs - Construct DIEs for types that contain
1815 /// vtables.
1816 void DwarfUnit::constructContainingTypeDIEs() {
1817   for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(),
1818                                                  CE = ContainingTypeMap.end();
1819        CI != CE; ++CI) {
1820     DIE &SPDie = *CI->first;
1821     DIDescriptor D(CI->second);
1822     if (!D)
1823       continue;
1824     DIE *NDie = getDIE(D);
1825     if (!NDie)
1826       continue;
1827     addDIEEntry(SPDie, dwarf::DW_AT_containing_type, *NDie);
1828   }
1831 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
1832 std::unique_ptr<DIE> DwarfUnit::constructVariableDIE(DbgVariable &DV,
1833                                                      bool Abstract) {
1834   auto D = constructVariableDIEImpl(DV, Abstract);
1835   DV.setDIE(*D);
1836   return D;
1839 std::unique_ptr<DIE> DwarfUnit::constructVariableDIEImpl(const DbgVariable &DV,
1840                                                          bool Abstract) {
1841   // Define variable debug information entry.
1842   auto VariableDie = make_unique<DIE>(DV.getTag());
1844   if (Abstract) {
1845     applyVariableAttributes(DV, *VariableDie);
1846     return VariableDie;
1847   }
1849   // Add variable address.
1851   unsigned Offset = DV.getDotDebugLocOffset();
1852   if (Offset != ~0U) {
1853     addLocationList(*VariableDie, dwarf::DW_AT_location, Offset);
1854     return VariableDie;
1855   }
1857   // Check if variable is described by a DBG_VALUE instruction.
1858   if (const MachineInstr *DVInsn = DV.getMInsn()) {
1859     assert(DVInsn->getNumOperands() == 3);
1860     if (DVInsn->getOperand(0).isReg()) {
1861       const MachineOperand RegOp = DVInsn->getOperand(0);
1862       // If the second operand is an immediate, this is an indirect value.
1863       if (DVInsn->getOperand(1).isImm()) {
1864         MachineLocation Location(RegOp.getReg(),
1865                                  DVInsn->getOperand(1).getImm());
1866         addVariableAddress(DV, *VariableDie, Location);
1867       } else if (RegOp.getReg())
1868         addVariableAddress(DV, *VariableDie, MachineLocation(RegOp.getReg()));
1869     } else if (DVInsn->getOperand(0).isImm())
1870       addConstantValue(*VariableDie, DVInsn->getOperand(0), DV.getType());
1871     else if (DVInsn->getOperand(0).isFPImm())
1872       addConstantFPValue(*VariableDie, DVInsn->getOperand(0));
1873     else if (DVInsn->getOperand(0).isCImm())
1874       addConstantValue(*VariableDie, DVInsn->getOperand(0).getCImm(),
1875                        DV.getType());
1877     return VariableDie;
1878   }
1880   // .. else use frame index.
1881   int FI = DV.getFrameIndex();
1882   if (FI != ~0) {
1883     unsigned FrameReg = 0;
1884     const TargetFrameLowering *TFI =
1885         Asm->TM.getSubtargetImpl()->getFrameLowering();
1886     int Offset = TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
1887     MachineLocation Location(FrameReg, Offset);
1888     addVariableAddress(DV, *VariableDie, Location);
1889   }
1891   return VariableDie;
1894 /// constructMemberDIE - Construct member DIE from DIDerivedType.
1895 void DwarfUnit::constructMemberDIE(DIE &Buffer, DIDerivedType DT) {
1896   DIE &MemberDie = createAndAddDIE(DT.getTag(), Buffer);
1897   StringRef Name = DT.getName();
1898   if (!Name.empty())
1899     addString(MemberDie, dwarf::DW_AT_name, Name);
1901   addType(MemberDie, resolve(DT.getTypeDerivedFrom()));
1903   addSourceLine(MemberDie, DT);
1905   if (DT.getTag() == dwarf::DW_TAG_inheritance && DT.isVirtual()) {
1907     // For C++, virtual base classes are not at fixed offset. Use following
1908     // expression to extract appropriate offset from vtable.
1909     // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1911     DIELoc *VBaseLocationDie = new (DIEValueAllocator) DIELoc();
1912     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1913     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1914     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1915     addUInt(*VBaseLocationDie, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1916     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1917     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1918     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1920     addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
1921   } else {
1922     uint64_t Size = DT.getSizeInBits();
1923     uint64_t FieldSize = getBaseTypeSize(DD, DT);
1924     uint64_t OffsetInBytes;
1926     if (Size != FieldSize) {
1927       // Handle bitfield, assume bytes are 8 bits.
1928       addUInt(MemberDie, dwarf::DW_AT_byte_size, None, FieldSize/8);
1929       addUInt(MemberDie, dwarf::DW_AT_bit_size, None, Size);
1931       uint64_t Offset = DT.getOffsetInBits();
1932       uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1933       uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1934       uint64_t FieldOffset = (HiMark - FieldSize);
1935       Offset -= FieldOffset;
1937       // Maybe we need to work from the other end.
1938       if (Asm->getDataLayout().isLittleEndian())
1939         Offset = FieldSize - (Offset + Size);
1940       addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset);
1942       // Here DW_AT_data_member_location points to the anonymous
1943       // field that includes this bit field.
1944       OffsetInBytes = FieldOffset >> 3;
1945     } else
1946       // This is not a bitfield.
1947       OffsetInBytes = DT.getOffsetInBits() >> 3;
1949     if (DD->getDwarfVersion() <= 2) {
1950       DIELoc *MemLocationDie = new (DIEValueAllocator) DIELoc();
1951       addUInt(*MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1952       addUInt(*MemLocationDie, dwarf::DW_FORM_udata, OffsetInBytes);
1953       addBlock(MemberDie, dwarf::DW_AT_data_member_location, MemLocationDie);
1954     } else
1955       addUInt(MemberDie, dwarf::DW_AT_data_member_location, None,
1956               OffsetInBytes);
1957   }
1959   if (DT.isProtected())
1960     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1961             dwarf::DW_ACCESS_protected);
1962   else if (DT.isPrivate())
1963     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1964             dwarf::DW_ACCESS_private);
1965   // Otherwise C++ member and base classes are considered public.
1966   else
1967     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1968             dwarf::DW_ACCESS_public);
1969   if (DT.isVirtual())
1970     addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1971             dwarf::DW_VIRTUALITY_virtual);
1973   // Objective-C properties.
1974   if (MDNode *PNode = DT.getObjCProperty())
1975     if (DIEEntry *PropertyDie = getDIEEntry(PNode))
1976       MemberDie.addValue(dwarf::DW_AT_APPLE_property, dwarf::DW_FORM_ref4,
1977                          PropertyDie);
1979   if (DT.isArtificial())
1980     addFlag(MemberDie, dwarf::DW_AT_artificial);
1983 /// getOrCreateStaticMemberDIE - Create new DIE for C++ static member.
1984 DIE *DwarfUnit::getOrCreateStaticMemberDIE(DIDerivedType DT) {
1985   if (!DT.Verify())
1986     return nullptr;
1988   // Construct the context before querying for the existence of the DIE in case
1989   // such construction creates the DIE.
1990   DIE *ContextDIE = getOrCreateContextDIE(resolve(DT.getContext()));
1991   assert(dwarf::isType(ContextDIE->getTag()) &&
1992          "Static member should belong to a type.");
1994   if (DIE *StaticMemberDIE = getDIE(DT))
1995     return StaticMemberDIE;
1997   DIE &StaticMemberDIE = createAndAddDIE(DT.getTag(), *ContextDIE, DT);
1999   DIType Ty = resolve(DT.getTypeDerivedFrom());
2001   addString(StaticMemberDIE, dwarf::DW_AT_name, DT.getName());
2002   addType(StaticMemberDIE, Ty);
2003   addSourceLine(StaticMemberDIE, DT);
2004   addFlag(StaticMemberDIE, dwarf::DW_AT_external);
2005   addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
2007   // FIXME: We could omit private if the parent is a class_type, and
2008   // public if the parent is something else.
2009   if (DT.isProtected())
2010     addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
2011             dwarf::DW_ACCESS_protected);
2012   else if (DT.isPrivate())
2013     addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
2014             dwarf::DW_ACCESS_private);
2015   else
2016     addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
2017             dwarf::DW_ACCESS_public);
2019   if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT.getConstant()))
2020     addConstantValue(StaticMemberDIE, CI, Ty);
2021   if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT.getConstant()))
2022     addConstantFPValue(StaticMemberDIE, CFP);
2024   return &StaticMemberDIE;
2027 void DwarfUnit::emitHeader(const MCSymbol *ASectionSym) const {
2028   Asm->OutStreamer.AddComment("DWARF version number");
2029   Asm->EmitInt16(DD->getDwarfVersion());
2030   Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
2031   // We share one abbreviations table across all units so it's always at the
2032   // start of the section. Use a relocatable offset where needed to ensure
2033   // linking doesn't invalidate that offset.
2034   if (ASectionSym)
2035     Asm->EmitSectionOffset(ASectionSym, ASectionSym);
2036   else
2037     // Use a constant value when no symbol is provided.
2038     Asm->EmitInt32(0);
2039   Asm->OutStreamer.AddComment("Address Size (in bytes)");
2040   Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
2043 void DwarfUnit::addRange(RangeSpan Range) {
2044   // Only add a range for this unit if we're emitting full debug.
2045   if (getCUNode().getEmissionKind() == DIBuilder::FullDebug) {
2046     // If we have no current ranges just add the range and return, otherwise,
2047     // check the current section and CU against the previous section and CU we
2048     // emitted into and the subprogram was contained within. If these are the
2049     // same then extend our current range, otherwise add this as a new range.
2050     if (CURanges.size() == 0 ||
2051         this != DD->getPrevCU() ||
2052         Asm->getCurrentSection() != DD->getPrevSection()) {
2053       CURanges.push_back(Range);
2054       return;
2055     }
2057     assert(&(CURanges.back().getEnd()->getSection()) ==
2058                &(Range.getEnd()->getSection()) &&
2059            "We can only append to a range in the same section!");
2060     CURanges.back().setEnd(Range.getEnd());
2061   }
2064 void DwarfCompileUnit::initStmtList(MCSymbol *DwarfLineSectionSym) {
2065   // Define start line table label for each Compile Unit.
2066   MCSymbol *LineTableStartSym =
2067       Asm->OutStreamer.getDwarfLineTableSymbol(getUniqueID());
2069   stmtListIndex = UnitDie.getValues().size();
2071   // DW_AT_stmt_list is a offset of line number information for this
2072   // compile unit in debug_line section. For split dwarf this is
2073   // left in the skeleton CU and so not included.
2074   // The line table entries are not always emitted in assembly, so it
2075   // is not okay to use line_table_start here.
2076   if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2077     addSectionLabel(UnitDie, dwarf::DW_AT_stmt_list, LineTableStartSym);
2078   else
2079     addSectionDelta(UnitDie, dwarf::DW_AT_stmt_list, LineTableStartSym,
2080                     DwarfLineSectionSym);
2083 void DwarfCompileUnit::applyStmtList(DIE &D) {
2084   D.addValue(dwarf::DW_AT_stmt_list,
2085              UnitDie.getAbbrev().getData()[stmtListIndex].getForm(),
2086              UnitDie.getValues()[stmtListIndex]);
2089 void DwarfTypeUnit::emitHeader(const MCSymbol *ASectionSym) const {
2090   DwarfUnit::emitHeader(ASectionSym);
2091   Asm->OutStreamer.AddComment("Type Signature");
2092   Asm->OutStreamer.EmitIntValue(TypeSignature, sizeof(TypeSignature));
2093   Asm->OutStreamer.AddComment("Type DIE Offset");
2094   // In a skeleton type unit there is no type DIE so emit a zero offset.
2095   Asm->OutStreamer.EmitIntValue(Ty ? Ty->getOffset() : 0,
2096                                 sizeof(Ty->getOffset()));
2099 void DwarfTypeUnit::initSection(const MCSection *Section) {
2100   assert(!this->Section);
2101   this->Section = Section;
2102   // Since each type unit is contained in its own COMDAT section, the begin
2103   // label and the section label are the same. Using the begin label emission in
2104   // DwarfDebug to emit the section label as well is slightly subtle/sneaky, but
2105   // the only other alternative of lazily constructing start-of-section labels
2106   // and storing a mapping in DwarfDebug (or AsmPrinter).
2107   this->SectionSym = this->LabelBegin =
2108       Asm->GetTempSymbol(Section->getLabelBeginName(), getUniqueID());
2109   this->LabelEnd =
2110       Asm->GetTempSymbol(Section->getLabelEndName(), getUniqueID());