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 //===----------------------------------------------------------------------===//
13 
14 #include "DwarfUnit.h"
15 #include "AddressPool.h"
16 #include "DwarfCompileUnit.h"
17 #include "DwarfDebug.h"
18 #include "DwarfExpression.h"
19 #include "llvm/ADT/APFloat.h"
20 #include "llvm/ADT/APInt.h"
21 #include "llvm/ADT/iterator_range.h"
22 #include "llvm/ADT/None.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineOperand.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/GlobalValue.h"
28 #include "llvm/IR/Metadata.h"
29 #include "llvm/MC/MachineLocation.h"
30 #include "llvm/MC/MCDwarf.h"
31 #include "llvm/MC/MCSection.h"
32 #include "llvm/MC/MCStreamer.h"
33 #include "llvm/Support/Casting.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Target/TargetLoweringObjectFile.h"
36 #include "llvm/Target/TargetRegisterInfo.h"
37 #include "llvm/Target/TargetSubtargetInfo.h"
38 #include <cassert>
39 #include <cstdint>
40 #include <string>
41 #include <utility>
42 
43 using namespace llvm;
44 
45 #define DEBUG_TYPE "dwarfdebug"
46 
47 static cl::opt<bool>
48 GenerateDwarfTypeUnits("generate-type-units", cl::Hidden,
49                        cl::desc("Generate DWARF4 type units."),
50                        cl::init(false));
51 
52 DIEDwarfExpression::DIEDwarfExpression(const AsmPrinter &AP, DwarfUnit &DU,
53                                        DIELoc &DIE)
54     : DwarfExpression(AP.getDwarfVersion()), AP(AP), DU(DU),
55       DIE(DIE) {}
56 
57 void DIEDwarfExpression::EmitOp(uint8_t Op, const char* Comment) {
58   DU.addUInt(DIE, dwarf::DW_FORM_data1, Op);
59 }
60 
61 void DIEDwarfExpression::EmitSigned(int64_t Value) {
62   DU.addSInt(DIE, dwarf::DW_FORM_sdata, Value);
63 }
64 
65 void DIEDwarfExpression::EmitUnsigned(uint64_t Value) {
66   DU.addUInt(DIE, dwarf::DW_FORM_udata, Value);
67 }
68 
69 bool DIEDwarfExpression::isFrameRegister(const TargetRegisterInfo &TRI,
70                                          unsigned MachineReg) {
71   return MachineReg == TRI.getFrameRegister(*AP.MF);
72 }
73 
74 DwarfUnit::DwarfUnit(dwarf::Tag UnitTag, const DICompileUnit *Node,
75                      AsmPrinter *A, DwarfDebug *DW, DwarfFile *DWU)
76     : DIEUnit(A->getDwarfVersion(), A->getPointerSize(), UnitTag), CUNode(Node),
77       Asm(A), DD(DW), DU(DWU), IndexTyDie(nullptr) {
78 }
79 
80 DwarfTypeUnit::DwarfTypeUnit(DwarfCompileUnit &CU, AsmPrinter *A,
81                              DwarfDebug *DW, DwarfFile *DWU,
82                              MCDwarfDwoLineTable *SplitLineTable)
83     : DwarfUnit(dwarf::DW_TAG_type_unit, CU.getCUNode(), A, DW, DWU), CU(CU),
84       SplitLineTable(SplitLineTable) {
85   if (SplitLineTable)
86     addSectionOffset(getUnitDie(), dwarf::DW_AT_stmt_list, 0);
87 }
88 
89 DwarfUnit::~DwarfUnit() {
90   for (unsigned j = 0, M = DIEBlocks.size(); j < M; ++j)
91     DIEBlocks[j]->~DIEBlock();
92   for (unsigned j = 0, M = DIELocs.size(); j < M; ++j)
93     DIELocs[j]->~DIELoc();
94 }
95 
96 int64_t DwarfUnit::getDefaultLowerBound() const {
97   switch (getLanguage()) {
98   default:
99     break;
100 
101   case dwarf::DW_LANG_C89:
102   case dwarf::DW_LANG_C99:
103   case dwarf::DW_LANG_C:
104   case dwarf::DW_LANG_C_plus_plus:
105   case dwarf::DW_LANG_ObjC:
106   case dwarf::DW_LANG_ObjC_plus_plus:
107     return 0;
108 
109   case dwarf::DW_LANG_Fortran77:
110   case dwarf::DW_LANG_Fortran90:
111   case dwarf::DW_LANG_Fortran95:
112     return 1;
113 
114   // The languages below have valid values only if the DWARF version >= 4.
115   case dwarf::DW_LANG_Java:
116   case dwarf::DW_LANG_Python:
117   case dwarf::DW_LANG_UPC:
118   case dwarf::DW_LANG_D:
119     if (dwarf::DWARF_VERSION >= 4)
120       return 0;
121     break;
122 
123   case dwarf::DW_LANG_Ada83:
124   case dwarf::DW_LANG_Ada95:
125   case dwarf::DW_LANG_Cobol74:
126   case dwarf::DW_LANG_Cobol85:
127   case dwarf::DW_LANG_Modula2:
128   case dwarf::DW_LANG_Pascal83:
129   case dwarf::DW_LANG_PLI:
130     if (dwarf::DWARF_VERSION >= 4)
131       return 1;
132     break;
133 
134   // The languages below have valid values only if the DWARF version >= 5.
135   case dwarf::DW_LANG_OpenCL:
136   case dwarf::DW_LANG_Go:
137   case dwarf::DW_LANG_Haskell:
138   case dwarf::DW_LANG_C_plus_plus_03:
139   case dwarf::DW_LANG_C_plus_plus_11:
140   case dwarf::DW_LANG_OCaml:
141   case dwarf::DW_LANG_Rust:
142   case dwarf::DW_LANG_C11:
143   case dwarf::DW_LANG_Swift:
144   case dwarf::DW_LANG_Dylan:
145   case dwarf::DW_LANG_C_plus_plus_14:
146     if (dwarf::DWARF_VERSION >= 5)
147       return 0;
148     break;
149 
150   case dwarf::DW_LANG_Modula3:
151   case dwarf::DW_LANG_Julia:
152   case dwarf::DW_LANG_Fortran03:
153   case dwarf::DW_LANG_Fortran08:
154     if (dwarf::DWARF_VERSION >= 5)
155       return 1;
156     break;
157   }
158 
159   return -1;
160 }
161 
162 /// Check whether the DIE for this MDNode can be shared across CUs.
163 static bool isShareableAcrossCUs(const DINode *D) {
164   // When the MDNode can be part of the type system, the DIE can be shared
165   // across CUs.
166   // Combining type units and cross-CU DIE sharing is lower value (since
167   // cross-CU DIE sharing is used in LTO and removes type redundancy at that
168   // level already) but may be implementable for some value in projects
169   // building multiple independent libraries with LTO and then linking those
170   // together.
171   return (isa<DIType>(D) ||
172           (isa<DISubprogram>(D) && !cast<DISubprogram>(D)->isDefinition())) &&
173          !GenerateDwarfTypeUnits;
174 }
175 
176 DIE *DwarfUnit::getDIE(const DINode *D) const {
177   if (isShareableAcrossCUs(D))
178     return DU->getDIE(D);
179   return MDNodeToDieMap.lookup(D);
180 }
181 
182 void DwarfUnit::insertDIE(const DINode *Desc, DIE *D) {
183   if (isShareableAcrossCUs(Desc)) {
184     DU->insertDIE(Desc, D);
185     return;
186   }
187   MDNodeToDieMap.insert(std::make_pair(Desc, D));
188 }
189 
190 void DwarfUnit::addFlag(DIE &Die, dwarf::Attribute Attribute) {
191   if (DD->getDwarfVersion() >= 4)
192     Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_flag_present,
193                  DIEInteger(1));
194   else
195     Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_flag,
196                  DIEInteger(1));
197 }
198 
199 void DwarfUnit::addUInt(DIEValueList &Die, dwarf::Attribute Attribute,
200                         Optional<dwarf::Form> Form, uint64_t Integer) {
201   if (!Form)
202     Form = DIEInteger::BestForm(false, Integer);
203   Die.addValue(DIEValueAllocator, Attribute, *Form, DIEInteger(Integer));
204 }
205 
206 void DwarfUnit::addUInt(DIEValueList &Block, dwarf::Form Form,
207                         uint64_t Integer) {
208   addUInt(Block, (dwarf::Attribute)0, Form, Integer);
209 }
210 
211 void DwarfUnit::addSInt(DIEValueList &Die, dwarf::Attribute Attribute,
212                         Optional<dwarf::Form> Form, int64_t Integer) {
213   if (!Form)
214     Form = DIEInteger::BestForm(true, Integer);
215   Die.addValue(DIEValueAllocator, Attribute, *Form, DIEInteger(Integer));
216 }
217 
218 void DwarfUnit::addSInt(DIELoc &Die, Optional<dwarf::Form> Form,
219                         int64_t Integer) {
220   addSInt(Die, (dwarf::Attribute)0, Form, Integer);
221 }
222 
223 void DwarfUnit::addString(DIE &Die, dwarf::Attribute Attribute,
224                           StringRef String) {
225   Die.addValue(DIEValueAllocator, Attribute,
226                isDwoUnit() ? dwarf::DW_FORM_GNU_str_index : dwarf::DW_FORM_strp,
227                DIEString(DU->getStringPool().getEntry(*Asm, String)));
228 }
229 
230 DIEValueList::value_iterator DwarfUnit::addLabel(DIEValueList &Die,
231                                                  dwarf::Attribute Attribute,
232                                                  dwarf::Form Form,
233                                                  const MCSymbol *Label) {
234   return Die.addValue(DIEValueAllocator, Attribute, Form, DIELabel(Label));
235 }
236 
237 void DwarfUnit::addLabel(DIELoc &Die, dwarf::Form Form, const MCSymbol *Label) {
238   addLabel(Die, (dwarf::Attribute)0, Form, Label);
239 }
240 
241 void DwarfUnit::addSectionOffset(DIE &Die, dwarf::Attribute Attribute,
242                                  uint64_t Integer) {
243   if (DD->getDwarfVersion() >= 4)
244     addUInt(Die, Attribute, dwarf::DW_FORM_sec_offset, Integer);
245   else
246     addUInt(Die, Attribute, dwarf::DW_FORM_data4, Integer);
247 }
248 
249 unsigned DwarfTypeUnit::getOrCreateSourceID(StringRef FileName, StringRef DirName) {
250   return SplitLineTable ? SplitLineTable->getFile(DirName, FileName)
251                         : getCU().getOrCreateSourceID(FileName, DirName);
252 }
253 
254 void DwarfUnit::addOpAddress(DIELoc &Die, const MCSymbol *Sym) {
255   if (!DD->useSplitDwarf()) {
256     addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
257     addLabel(Die, dwarf::DW_FORM_udata, Sym);
258   } else {
259     addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index);
260     addUInt(Die, dwarf::DW_FORM_GNU_addr_index,
261             DD->getAddressPool().getIndex(Sym));
262   }
263 }
264 
265 void DwarfUnit::addLabelDelta(DIE &Die, dwarf::Attribute Attribute,
266                               const MCSymbol *Hi, const MCSymbol *Lo) {
267   Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_data4,
268                new (DIEValueAllocator) DIEDelta(Hi, Lo));
269 }
270 
271 void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute, DIE &Entry) {
272   addDIEEntry(Die, Attribute, DIEEntry(Entry));
273 }
274 
275 void DwarfUnit::addDIETypeSignature(DIE &Die, uint64_t Signature) {
276   // Flag the type unit reference as a declaration so that if it contains
277   // members (implicit special members, static data member definitions, member
278   // declarations for definitions in this CU, etc) consumers don't get confused
279   // and think this is a full definition.
280   addFlag(Die, dwarf::DW_AT_declaration);
281 
282   Die.addValue(DIEValueAllocator, dwarf::DW_AT_signature,
283                dwarf::DW_FORM_ref_sig8, DIEInteger(Signature));
284 }
285 
286 void DwarfUnit::addDIETypeSignature(DIE &Die, dwarf::Attribute Attribute,
287                                     StringRef Identifier) {
288   uint64_t Signature = DD->makeTypeSignature(Identifier);
289   Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_ref_sig8,
290                DIEInteger(Signature));
291 }
292 
293 void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute,
294                             DIEEntry Entry) {
295   const DIEUnit *CU = Die.getUnit();
296   const DIEUnit *EntryCU = Entry.getEntry().getUnit();
297   if (!CU)
298     // We assume that Die belongs to this CU, if it is not linked to any CU yet.
299     CU = getUnitDie().getUnit();
300   if (!EntryCU)
301     EntryCU = getUnitDie().getUnit();
302   Die.addValue(DIEValueAllocator, Attribute,
303                EntryCU == CU ? dwarf::DW_FORM_ref4 : dwarf::DW_FORM_ref_addr,
304                Entry);
305 }
306 
307 DIE &DwarfUnit::createAndAddDIE(unsigned Tag, DIE &Parent, const DINode *N) {
308   DIE &Die = Parent.addChild(DIE::get(DIEValueAllocator, (dwarf::Tag)Tag));
309   if (N)
310     insertDIE(N, &Die);
311   return Die;
312 }
313 
314 void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute, DIELoc *Loc) {
315   Loc->ComputeSize(Asm);
316   DIELocs.push_back(Loc); // Memoize so we can call the destructor later on.
317   Die.addValue(DIEValueAllocator, Attribute,
318                Loc->BestForm(DD->getDwarfVersion()), Loc);
319 }
320 
321 void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute,
322                          DIEBlock *Block) {
323   Block->ComputeSize(Asm);
324   DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
325   Die.addValue(DIEValueAllocator, Attribute, Block->BestForm(), Block);
326 }
327 
328 void DwarfUnit::addSourceLine(DIE &Die, unsigned Line, StringRef File,
329                               StringRef Directory) {
330   if (Line == 0)
331     return;
332 
333   unsigned FileID = getOrCreateSourceID(File, Directory);
334   assert(FileID && "Invalid file id");
335   addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
336   addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
337 }
338 
339 void DwarfUnit::addSourceLine(DIE &Die, const DILocalVariable *V) {
340   assert(V);
341 
342   addSourceLine(Die, V->getLine(), V->getScope()->getFilename(),
343                 V->getScope()->getDirectory());
344 }
345 
346 void DwarfUnit::addSourceLine(DIE &Die, const DIGlobalVariable *G) {
347   assert(G);
348 
349   addSourceLine(Die, G->getLine(), G->getFilename(), G->getDirectory());
350 }
351 
352 void DwarfUnit::addSourceLine(DIE &Die, const DISubprogram *SP) {
353   assert(SP);
354 
355   addSourceLine(Die, SP->getLine(), SP->getFilename(), SP->getDirectory());
356 }
357 
358 void DwarfUnit::addSourceLine(DIE &Die, const DIType *Ty) {
359   assert(Ty);
360 
361   addSourceLine(Die, Ty->getLine(), Ty->getFilename(), Ty->getDirectory());
362 }
363 
364 void DwarfUnit::addSourceLine(DIE &Die, const DIObjCProperty *Ty) {
365   assert(Ty);
366 
367   addSourceLine(Die, Ty->getLine(), Ty->getFilename(), Ty->getDirectory());
368 }
369 
370 void DwarfUnit::addSourceLine(DIE &Die, const DINamespace *NS) {
371   addSourceLine(Die, NS->getLine(), NS->getFilename(), NS->getDirectory());
372 }
373 
374 bool DwarfUnit::addRegisterFragment(DIELoc &TheDie, unsigned Reg,
375                                     unsigned SizeInBits,
376                                     unsigned OffsetInBits) {
377   DIEDwarfExpression Expr(*Asm, *this, TheDie);
378   Expr.AddMachineRegFragment(*Asm->MF->getSubtarget().getRegisterInfo(), Reg,
379                              SizeInBits, OffsetInBits);
380   return true;
381 }
382 
383 bool DwarfUnit::addRegisterOffset(DIELoc &TheDie, unsigned Reg,
384                                   int64_t Offset) {
385   DIEDwarfExpression Expr(*Asm, *this, TheDie);
386   return Expr.AddMachineRegIndirect(*Asm->MF->getSubtarget().getRegisterInfo(),
387                                     Reg, Offset);
388 }
389 
390 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
391    VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
392    gives the variable VarName either the struct, or a pointer to the struct, as
393    its type.  This is necessary for various behind-the-scenes things the
394    compiler needs to do with by-reference variables in Blocks.
395 
396    However, as far as the original *programmer* is concerned, the variable
397    should still have type 'SomeType', as originally declared.
398 
399    The function getBlockByrefType dives into the __Block_byref_x_VarName
400    struct to find the original type of the variable, which is then assigned to
401    the variable's Debug Information Entry as its real type.  So far, so good.
402    However now the debugger will expect the variable VarName to have the type
403    SomeType.  So we need the location attribute for the variable to be an
404    expression that explains to the debugger how to navigate through the
405    pointers and struct to find the actual variable of type SomeType.
406 
407    The following function does just that.  We start by getting
408    the "normal" location for the variable. This will be the location
409    of either the struct __Block_byref_x_VarName or the pointer to the
410    struct __Block_byref_x_VarName.
411 
412    The struct will look something like:
413 
414    struct __Block_byref_x_VarName {
415      ... <various fields>
416      struct __Block_byref_x_VarName *forwarding;
417      ... <various other fields>
418      SomeType VarName;
419      ... <maybe more fields>
420    };
421 
422    If we are given the struct directly (as our starting point) we
423    need to tell the debugger to:
424 
425    1).  Add the offset of the forwarding field.
426 
427    2).  Follow that pointer to get the real __Block_byref_x_VarName
428    struct to use (the real one may have been copied onto the heap).
429 
430    3).  Add the offset for the field VarName, to find the actual variable.
431 
432    If we started with a pointer to the struct, then we need to
433    dereference that pointer first, before the other steps.
434    Translating this into DWARF ops, we will need to append the following
435    to the current location description for the variable:
436 
437    DW_OP_deref                    -- optional, if we start with a pointer
438    DW_OP_plus_uconst <forward_fld_offset>
439    DW_OP_deref
440    DW_OP_plus_uconst <varName_fld_offset>
441 
442    That is what this function does.  */
443 
444 void DwarfUnit::addBlockByrefAddress(const DbgVariable &DV, DIE &Die,
445                                      dwarf::Attribute Attribute,
446                                      const MachineLocation &Location) {
447   const DIType *Ty = DV.getType();
448   const DIType *TmpTy = Ty;
449   uint16_t Tag = Ty->getTag();
450   bool isPointer = false;
451 
452   StringRef varName = DV.getName();
453 
454   if (Tag == dwarf::DW_TAG_pointer_type) {
455     auto *DTy = cast<DIDerivedType>(Ty);
456     TmpTy = resolve(DTy->getBaseType());
457     isPointer = true;
458   }
459 
460   // Find the __forwarding field and the variable field in the __Block_byref
461   // struct.
462   DINodeArray Fields = cast<DICompositeType>(TmpTy)->getElements();
463   const DIDerivedType *varField = nullptr;
464   const DIDerivedType *forwardingField = nullptr;
465 
466   for (unsigned i = 0, N = Fields.size(); i < N; ++i) {
467     auto *DT = cast<DIDerivedType>(Fields[i]);
468     StringRef fieldName = DT->getName();
469     if (fieldName == "__forwarding")
470       forwardingField = DT;
471     else if (fieldName == varName)
472       varField = DT;
473   }
474 
475   // Get the offsets for the forwarding field and the variable field.
476   unsigned forwardingFieldOffset = forwardingField->getOffsetInBits() >> 3;
477   unsigned varFieldOffset = varField->getOffsetInBits() >> 2;
478 
479   // Decode the original location, and use that as the start of the byref
480   // variable's location.
481   DIELoc *Loc = new (DIEValueAllocator) DIELoc;
482 
483   bool validReg;
484   if (Location.isReg())
485     validReg = addRegisterFragment(*Loc, Location.getReg());
486   else
487     validReg = addRegisterOffset(*Loc, Location.getReg(), Location.getOffset());
488 
489   if (!validReg)
490     return;
491 
492   // If we started with a pointer to the __Block_byref... struct, then
493   // the first thing we need to do is dereference the pointer (DW_OP_deref).
494   if (isPointer)
495     addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
496 
497   // Next add the offset for the '__forwarding' field:
498   // DW_OP_plus_uconst ForwardingFieldOffset.  Note there's no point in
499   // adding the offset if it's 0.
500   if (forwardingFieldOffset > 0) {
501     addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
502     addUInt(*Loc, dwarf::DW_FORM_udata, forwardingFieldOffset);
503   }
504 
505   // Now dereference the __forwarding field to get to the real __Block_byref
506   // struct:  DW_OP_deref.
507   addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
508 
509   // Now that we've got the real __Block_byref... struct, add the offset
510   // for the variable's field to get to the location of the actual variable:
511   // DW_OP_plus_uconst varFieldOffset.  Again, don't add if it's 0.
512   if (varFieldOffset > 0) {
513     addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
514     addUInt(*Loc, dwarf::DW_FORM_udata, varFieldOffset);
515   }
516 
517   // Now attach the location information to the DIE.
518   addBlock(Die, Attribute, Loc);
519 }
520 
521 /// Return true if type encoding is unsigned.
522 static bool isUnsignedDIType(DwarfDebug *DD, const DIType *Ty) {
523   if (auto *CTy = dyn_cast<DICompositeType>(Ty)) {
524     // FIXME: Enums without a fixed underlying type have unknown signedness
525     // here, leading to incorrectly emitted constants.
526     if (CTy->getTag() == dwarf::DW_TAG_enumeration_type)
527       return false;
528 
529     // (Pieces of) aggregate types that get hacked apart by SROA may be
530     // represented by a constant. Encode them as unsigned bytes.
531     return true;
532   }
533 
534   if (auto *DTy = dyn_cast<DIDerivedType>(Ty)) {
535     dwarf::Tag T = (dwarf::Tag)Ty->getTag();
536     // Encode pointer constants as unsigned bytes. This is used at least for
537     // null pointer constant emission.
538     // FIXME: reference and rvalue_reference /probably/ shouldn't be allowed
539     // here, but accept them for now due to a bug in SROA producing bogus
540     // dbg.values.
541     if (T == dwarf::DW_TAG_pointer_type ||
542         T == dwarf::DW_TAG_ptr_to_member_type ||
543         T == dwarf::DW_TAG_reference_type ||
544         T == dwarf::DW_TAG_rvalue_reference_type)
545       return true;
546     assert(T == dwarf::DW_TAG_typedef || T == dwarf::DW_TAG_const_type ||
547            T == dwarf::DW_TAG_volatile_type ||
548            T == dwarf::DW_TAG_restrict_type || T == dwarf::DW_TAG_atomic_type);
549     DITypeRef Deriv = DTy->getBaseType();
550     assert(Deriv && "Expected valid base type");
551     return isUnsignedDIType(DD, DD->resolve(Deriv));
552   }
553 
554   auto *BTy = cast<DIBasicType>(Ty);
555   unsigned Encoding = BTy->getEncoding();
556   assert((Encoding == dwarf::DW_ATE_unsigned ||
557           Encoding == dwarf::DW_ATE_unsigned_char ||
558           Encoding == dwarf::DW_ATE_signed ||
559           Encoding == dwarf::DW_ATE_signed_char ||
560           Encoding == dwarf::DW_ATE_float || Encoding == dwarf::DW_ATE_UTF ||
561           Encoding == dwarf::DW_ATE_boolean ||
562           (Ty->getTag() == dwarf::DW_TAG_unspecified_type &&
563            Ty->getName() == "decltype(nullptr)")) &&
564          "Unsupported encoding");
565   return Encoding == dwarf::DW_ATE_unsigned ||
566          Encoding == dwarf::DW_ATE_unsigned_char ||
567          Encoding == dwarf::DW_ATE_UTF || Encoding == dwarf::DW_ATE_boolean ||
568          Ty->getTag() == dwarf::DW_TAG_unspecified_type;
569 }
570 
571 void DwarfUnit::addConstantFPValue(DIE &Die, const MachineOperand &MO) {
572   assert(MO.isFPImm() && "Invalid machine operand!");
573   DIEBlock *Block = new (DIEValueAllocator) DIEBlock;
574   APFloat FPImm = MO.getFPImm()->getValueAPF();
575 
576   // Get the raw data form of the floating point.
577   const APInt FltVal = FPImm.bitcastToAPInt();
578   const char *FltPtr = (const char *)FltVal.getRawData();
579 
580   int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
581   bool LittleEndian = Asm->getDataLayout().isLittleEndian();
582   int Incr = (LittleEndian ? 1 : -1);
583   int Start = (LittleEndian ? 0 : NumBytes - 1);
584   int Stop = (LittleEndian ? NumBytes : -1);
585 
586   // Output the constant to DWARF one byte at a time.
587   for (; Start != Stop; Start += Incr)
588     addUInt(*Block, dwarf::DW_FORM_data1, (unsigned char)0xFF & FltPtr[Start]);
589 
590   addBlock(Die, dwarf::DW_AT_const_value, Block);
591 }
592 
593 void DwarfUnit::addConstantFPValue(DIE &Die, const ConstantFP *CFP) {
594   // Pass this down to addConstantValue as an unsigned bag of bits.
595   addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true);
596 }
597 
598 void DwarfUnit::addConstantValue(DIE &Die, const ConstantInt *CI,
599                                  const DIType *Ty) {
600   addConstantValue(Die, CI->getValue(), Ty);
601 }
602 
603 void DwarfUnit::addConstantValue(DIE &Die, const MachineOperand &MO,
604                                  const DIType *Ty) {
605   assert(MO.isImm() && "Invalid machine operand!");
606 
607   addConstantValue(Die, isUnsignedDIType(DD, Ty), MO.getImm());
608 }
609 
610 void DwarfUnit::addConstantValue(DIE &Die, bool Unsigned, uint64_t Val) {
611   // FIXME: This is a bit conservative/simple - it emits negative values always
612   // sign extended to 64 bits rather than minimizing the number of bytes.
613   addUInt(Die, dwarf::DW_AT_const_value,
614           Unsigned ? dwarf::DW_FORM_udata : dwarf::DW_FORM_sdata, Val);
615 }
616 
617 void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, const DIType *Ty) {
618   addConstantValue(Die, Val, isUnsignedDIType(DD, Ty));
619 }
620 
621 void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, bool Unsigned) {
622   unsigned CIBitWidth = Val.getBitWidth();
623   if (CIBitWidth <= 64) {
624     addConstantValue(Die, Unsigned,
625                      Unsigned ? Val.getZExtValue() : Val.getSExtValue());
626     return;
627   }
628 
629   DIEBlock *Block = new (DIEValueAllocator) DIEBlock;
630 
631   // Get the raw data form of the large APInt.
632   const uint64_t *Ptr64 = Val.getRawData();
633 
634   int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
635   bool LittleEndian = Asm->getDataLayout().isLittleEndian();
636 
637   // Output the constant to DWARF one byte at a time.
638   for (int i = 0; i < NumBytes; i++) {
639     uint8_t c;
640     if (LittleEndian)
641       c = Ptr64[i / 8] >> (8 * (i & 7));
642     else
643       c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
644     addUInt(*Block, dwarf::DW_FORM_data1, c);
645   }
646 
647   addBlock(Die, dwarf::DW_AT_const_value, Block);
648 }
649 
650 void DwarfUnit::addLinkageName(DIE &Die, StringRef LinkageName) {
651   if (!LinkageName.empty())
652     addString(Die,
653               DD->getDwarfVersion() >= 4 ? dwarf::DW_AT_linkage_name
654                                          : dwarf::DW_AT_MIPS_linkage_name,
655               GlobalValue::getRealLinkageName(LinkageName));
656 }
657 
658 void DwarfUnit::addTemplateParams(DIE &Buffer, DINodeArray TParams) {
659   // Add template parameters.
660   for (const auto *Element : TParams) {
661     if (auto *TTP = dyn_cast<DITemplateTypeParameter>(Element))
662       constructTemplateTypeParameterDIE(Buffer, TTP);
663     else if (auto *TVP = dyn_cast<DITemplateValueParameter>(Element))
664       constructTemplateValueParameterDIE(Buffer, TVP);
665   }
666 }
667 
668 DIE *DwarfUnit::getOrCreateContextDIE(const DIScope *Context) {
669   if (!Context || isa<DIFile>(Context))
670     return &getUnitDie();
671   if (auto *T = dyn_cast<DIType>(Context))
672     return getOrCreateTypeDIE(T);
673   if (auto *NS = dyn_cast<DINamespace>(Context))
674     return getOrCreateNameSpace(NS);
675   if (auto *SP = dyn_cast<DISubprogram>(Context))
676     return getOrCreateSubprogramDIE(SP);
677   if (auto *M = dyn_cast<DIModule>(Context))
678     return getOrCreateModule(M);
679   return getDIE(Context);
680 }
681 
682 DIE *DwarfUnit::createTypeDIE(const DICompositeType *Ty) {
683   auto *Context = resolve(Ty->getScope());
684   DIE *ContextDIE = getOrCreateContextDIE(Context);
685 
686   if (DIE *TyDIE = getDIE(Ty))
687     return TyDIE;
688 
689   // Create new type.
690   DIE &TyDIE = createAndAddDIE(Ty->getTag(), *ContextDIE, Ty);
691 
692   constructTypeDIE(TyDIE, cast<DICompositeType>(Ty));
693 
694   if (!Ty->isExternalTypeRef())
695     updateAcceleratorTables(Context, Ty, TyDIE);
696   return &TyDIE;
697 }
698 
699 DIE *DwarfUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
700   if (!TyNode)
701     return nullptr;
702 
703   auto *Ty = cast<DIType>(TyNode);
704 
705   // DW_TAG_restrict_type is not supported in DWARF2
706   if (Ty->getTag() == dwarf::DW_TAG_restrict_type && DD->getDwarfVersion() <= 2)
707     return getOrCreateTypeDIE(resolve(cast<DIDerivedType>(Ty)->getBaseType()));
708 
709   // DW_TAG_atomic_type is not supported in DWARF < 5
710   if (Ty->getTag() == dwarf::DW_TAG_atomic_type && DD->getDwarfVersion() < 5)
711     return getOrCreateTypeDIE(resolve(cast<DIDerivedType>(Ty)->getBaseType()));
712 
713   // Construct the context before querying for the existence of the DIE in case
714   // such construction creates the DIE.
715   auto *Context = resolve(Ty->getScope());
716   DIE *ContextDIE = getOrCreateContextDIE(Context);
717   assert(ContextDIE);
718 
719   if (DIE *TyDIE = getDIE(Ty))
720     return TyDIE;
721 
722   // Create new type.
723   DIE &TyDIE = createAndAddDIE(Ty->getTag(), *ContextDIE, Ty);
724 
725   updateAcceleratorTables(Context, Ty, TyDIE);
726 
727   if (auto *BT = dyn_cast<DIBasicType>(Ty))
728     constructTypeDIE(TyDIE, BT);
729   else if (auto *STy = dyn_cast<DISubroutineType>(Ty))
730     constructTypeDIE(TyDIE, STy);
731   else if (auto *CTy = dyn_cast<DICompositeType>(Ty)) {
732     if (GenerateDwarfTypeUnits && !Ty->isForwardDecl())
733       if (MDString *TypeId = CTy->getRawIdentifier()) {
734         DD->addDwarfTypeUnitType(getCU(), TypeId->getString(), TyDIE, CTy);
735         // Skip updating the accelerator tables since this is not the full type.
736         return &TyDIE;
737       }
738     constructTypeDIE(TyDIE, CTy);
739   } else {
740     constructTypeDIE(TyDIE, cast<DIDerivedType>(Ty));
741   }
742 
743   return &TyDIE;
744 }
745 
746 void DwarfUnit::updateAcceleratorTables(const DIScope *Context,
747                                         const DIType *Ty, const DIE &TyDIE) {
748   if (!Ty->getName().empty() && !Ty->isForwardDecl()) {
749     bool IsImplementation = false;
750     if (auto *CT = dyn_cast<DICompositeType>(Ty)) {
751       // A runtime language of 0 actually means C/C++ and that any
752       // non-negative value is some version of Objective-C/C++.
753       IsImplementation = CT->getRuntimeLang() == 0 || CT->isObjcClassComplete();
754     }
755     unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0;
756     DD->addAccelType(Ty->getName(), TyDIE, Flags);
757 
758     if (!Context || isa<DICompileUnit>(Context) || isa<DIFile>(Context) ||
759         isa<DINamespace>(Context))
760       addGlobalType(Ty, TyDIE, Context);
761   }
762 }
763 
764 void DwarfUnit::addType(DIE &Entity, const DIType *Ty,
765                         dwarf::Attribute Attribute) {
766   assert(Ty && "Trying to add a type that doesn't exist?");
767   addDIEEntry(Entity, Attribute, DIEEntry(*getOrCreateTypeDIE(Ty)));
768 }
769 
770 std::string DwarfUnit::getParentContextString(const DIScope *Context) const {
771   if (!Context)
772     return "";
773 
774   // FIXME: Decide whether to implement this for non-C++ languages.
775   if (getLanguage() != dwarf::DW_LANG_C_plus_plus)
776     return "";
777 
778   std::string CS;
779   SmallVector<const DIScope *, 1> Parents;
780   while (!isa<DICompileUnit>(Context)) {
781     Parents.push_back(Context);
782     if (Context->getScope())
783       Context = resolve(Context->getScope());
784     else
785       // Structure, etc types will have a NULL context if they're at the top
786       // level.
787       break;
788   }
789 
790   // Reverse iterate over our list to go from the outermost construct to the
791   // innermost.
792   for (const DIScope *Ctx : make_range(Parents.rbegin(), Parents.rend())) {
793     StringRef Name = Ctx->getName();
794     if (Name.empty() && isa<DINamespace>(Ctx))
795       Name = "(anonymous namespace)";
796     if (!Name.empty()) {
797       CS += Name;
798       CS += "::";
799     }
800   }
801   return CS;
802 }
803 
804 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DIBasicType *BTy) {
805   // Get core information.
806   StringRef Name = BTy->getName();
807   // Add name if not anonymous or intermediate type.
808   if (!Name.empty())
809     addString(Buffer, dwarf::DW_AT_name, Name);
810 
811   // An unspecified type only has a name attribute.
812   if (BTy->getTag() == dwarf::DW_TAG_unspecified_type)
813     return;
814 
815   addUInt(Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
816           BTy->getEncoding());
817 
818   uint64_t Size = BTy->getSizeInBits() >> 3;
819   addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
820 }
821 
822 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DIDerivedType *DTy) {
823   // Get core information.
824   StringRef Name = DTy->getName();
825   uint64_t Size = DTy->getSizeInBits() >> 3;
826   uint16_t Tag = Buffer.getTag();
827 
828   // Map to main type, void will not have a type.
829   const DIType *FromTy = resolve(DTy->getBaseType());
830   if (FromTy)
831     addType(Buffer, FromTy);
832 
833   // Add name if not anonymous or intermediate type.
834   if (!Name.empty())
835     addString(Buffer, dwarf::DW_AT_name, Name);
836 
837   // Add size if non-zero (derived types might be zero-sized.)
838   if (Size && Tag != dwarf::DW_TAG_pointer_type
839            && Tag != dwarf::DW_TAG_ptr_to_member_type
840            && Tag != dwarf::DW_TAG_reference_type
841            && Tag != dwarf::DW_TAG_rvalue_reference_type)
842     addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
843 
844   if (Tag == dwarf::DW_TAG_ptr_to_member_type)
845     addDIEEntry(
846         Buffer, dwarf::DW_AT_containing_type,
847         *getOrCreateTypeDIE(resolve(cast<DIDerivedType>(DTy)->getClassType())));
848   // Add source line info if available and TyDesc is not a forward declaration.
849   if (!DTy->isForwardDecl())
850     addSourceLine(Buffer, DTy);
851 }
852 
853 void DwarfUnit::constructSubprogramArguments(DIE &Buffer, DITypeRefArray Args) {
854   for (unsigned i = 1, N = Args.size(); i < N; ++i) {
855     const DIType *Ty = resolve(Args[i]);
856     if (!Ty) {
857       assert(i == N-1 && "Unspecified parameter must be the last argument");
858       createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
859     } else {
860       DIE &Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
861       addType(Arg, Ty);
862       if (Ty->isArtificial())
863         addFlag(Arg, dwarf::DW_AT_artificial);
864     }
865   }
866 }
867 
868 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DISubroutineType *CTy) {
869   // Add return type.  A void return won't have a type.
870   auto Elements = cast<DISubroutineType>(CTy)->getTypeArray();
871   if (Elements.size())
872     if (auto RTy = resolve(Elements[0]))
873       addType(Buffer, RTy);
874 
875   bool isPrototyped = true;
876   if (Elements.size() == 2 && !Elements[1])
877     isPrototyped = false;
878 
879   constructSubprogramArguments(Buffer, Elements);
880 
881   // Add prototype flag if we're dealing with a C language and the function has
882   // been prototyped.
883   uint16_t Language = getLanguage();
884   if (isPrototyped &&
885       (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
886        Language == dwarf::DW_LANG_ObjC))
887     addFlag(Buffer, dwarf::DW_AT_prototyped);
888 
889   // Add a DW_AT_calling_convention if this has an explicit convention.
890   if (CTy->getCC() && CTy->getCC() != dwarf::DW_CC_normal)
891     addUInt(Buffer, dwarf::DW_AT_calling_convention, dwarf::DW_FORM_data1,
892             CTy->getCC());
893 
894   if (CTy->isLValueReference())
895     addFlag(Buffer, dwarf::DW_AT_reference);
896 
897   if (CTy->isRValueReference())
898     addFlag(Buffer, dwarf::DW_AT_rvalue_reference);
899 }
900 
901 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
902   if (CTy->isExternalTypeRef()) {
903     StringRef Identifier = CTy->getIdentifier();
904     assert(!Identifier.empty() && "external type ref without identifier");
905     addFlag(Buffer, dwarf::DW_AT_declaration);
906     return addDIETypeSignature(Buffer, dwarf::DW_AT_signature, Identifier);
907   }
908 
909   // Add name if not anonymous or intermediate type.
910   StringRef Name = CTy->getName();
911 
912   uint64_t Size = CTy->getSizeInBits() >> 3;
913   uint16_t Tag = Buffer.getTag();
914 
915   switch (Tag) {
916   case dwarf::DW_TAG_array_type:
917     constructArrayTypeDIE(Buffer, CTy);
918     break;
919   case dwarf::DW_TAG_enumeration_type:
920     constructEnumTypeDIE(Buffer, CTy);
921     break;
922   case dwarf::DW_TAG_structure_type:
923   case dwarf::DW_TAG_union_type:
924   case dwarf::DW_TAG_class_type: {
925     // Add elements to structure type.
926     DINodeArray Elements = CTy->getElements();
927     for (const auto *Element : Elements) {
928       if (!Element)
929         continue;
930       if (auto *SP = dyn_cast<DISubprogram>(Element))
931         getOrCreateSubprogramDIE(SP);
932       else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
933         if (DDTy->getTag() == dwarf::DW_TAG_friend) {
934           DIE &ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
935           addType(ElemDie, resolve(DDTy->getBaseType()), dwarf::DW_AT_friend);
936         } else if (DDTy->isStaticMember()) {
937           getOrCreateStaticMemberDIE(DDTy);
938         } else {
939           constructMemberDIE(Buffer, DDTy);
940         }
941       } else if (auto *Property = dyn_cast<DIObjCProperty>(Element)) {
942         DIE &ElemDie = createAndAddDIE(Property->getTag(), Buffer);
943         StringRef PropertyName = Property->getName();
944         addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
945         if (Property->getType())
946           addType(ElemDie, resolve(Property->getType()));
947         addSourceLine(ElemDie, Property);
948         StringRef GetterName = Property->getGetterName();
949         if (!GetterName.empty())
950           addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
951         StringRef SetterName = Property->getSetterName();
952         if (!SetterName.empty())
953           addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
954         if (unsigned PropertyAttributes = Property->getAttributes())
955           addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None,
956                   PropertyAttributes);
957       }
958     }
959 
960     if (CTy->isAppleBlockExtension())
961       addFlag(Buffer, dwarf::DW_AT_APPLE_block);
962 
963     // This is outside the DWARF spec, but GDB expects a DW_AT_containing_type
964     // inside C++ composite types to point to the base class with the vtable.
965     if (auto *ContainingType =
966             dyn_cast_or_null<DICompositeType>(resolve(CTy->getVTableHolder())))
967       addDIEEntry(Buffer, dwarf::DW_AT_containing_type,
968                   *getOrCreateTypeDIE(ContainingType));
969 
970     if (CTy->isObjcClassComplete())
971       addFlag(Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
972 
973     // Add template parameters to a class, structure or union types.
974     // FIXME: The support isn't in the metadata for this yet.
975     if (Tag == dwarf::DW_TAG_class_type ||
976         Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
977       addTemplateParams(Buffer, CTy->getTemplateParams());
978 
979     break;
980   }
981   default:
982     break;
983   }
984 
985   // Add name if not anonymous or intermediate type.
986   if (!Name.empty())
987     addString(Buffer, dwarf::DW_AT_name, Name);
988 
989   if (Tag == dwarf::DW_TAG_enumeration_type ||
990       Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
991       Tag == dwarf::DW_TAG_union_type) {
992     // Add size if non-zero (derived types might be zero-sized.)
993     // TODO: Do we care about size for enum forward declarations?
994     if (Size)
995       addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
996     else if (!CTy->isForwardDecl())
997       // Add zero size if it is not a forward declaration.
998       addUInt(Buffer, dwarf::DW_AT_byte_size, None, 0);
999 
1000     // If we're a forward decl, say so.
1001     if (CTy->isForwardDecl())
1002       addFlag(Buffer, dwarf::DW_AT_declaration);
1003 
1004     // Add source line info if available.
1005     if (!CTy->isForwardDecl())
1006       addSourceLine(Buffer, CTy);
1007 
1008     // No harm in adding the runtime language to the declaration.
1009     unsigned RLang = CTy->getRuntimeLang();
1010     if (RLang)
1011       addUInt(Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
1012               RLang);
1013 
1014     // Add align info if available.
1015     if (uint32_t AlignInBytes = CTy->getAlignInBytes())
1016       addUInt(Buffer, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
1017               AlignInBytes);
1018   }
1019 }
1020 
1021 void DwarfUnit::constructTemplateTypeParameterDIE(
1022     DIE &Buffer, const DITemplateTypeParameter *TP) {
1023   DIE &ParamDIE =
1024       createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
1025   // Add the type if it exists, it could be void and therefore no type.
1026   if (TP->getType())
1027     addType(ParamDIE, resolve(TP->getType()));
1028   if (!TP->getName().empty())
1029     addString(ParamDIE, dwarf::DW_AT_name, TP->getName());
1030 }
1031 
1032 void DwarfUnit::constructTemplateValueParameterDIE(
1033     DIE &Buffer, const DITemplateValueParameter *VP) {
1034   DIE &ParamDIE = createAndAddDIE(VP->getTag(), Buffer);
1035 
1036   // Add the type if there is one, template template and template parameter
1037   // packs will not have a type.
1038   if (VP->getTag() == dwarf::DW_TAG_template_value_parameter)
1039     addType(ParamDIE, resolve(VP->getType()));
1040   if (!VP->getName().empty())
1041     addString(ParamDIE, dwarf::DW_AT_name, VP->getName());
1042   if (Metadata *Val = VP->getValue()) {
1043     if (ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(Val))
1044       addConstantValue(ParamDIE, CI, resolve(VP->getType()));
1045     else if (GlobalValue *GV = mdconst::dyn_extract<GlobalValue>(Val)) {
1046       // We cannot describe the location of dllimport'd entities: the
1047       // computation of their address requires loads from the IAT.
1048       if (!GV->hasDLLImportStorageClass()) {
1049         // For declaration non-type template parameters (such as global values
1050         // and functions)
1051         DIELoc *Loc = new (DIEValueAllocator) DIELoc;
1052         addOpAddress(*Loc, Asm->getSymbol(GV));
1053         // Emit DW_OP_stack_value to use the address as the immediate value of
1054         // the parameter, rather than a pointer to it.
1055         addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
1056         addBlock(ParamDIE, dwarf::DW_AT_location, Loc);
1057       }
1058     } else if (VP->getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1059       assert(isa<MDString>(Val));
1060       addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
1061                 cast<MDString>(Val)->getString());
1062     } else if (VP->getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1063       addTemplateParams(ParamDIE, cast<MDTuple>(Val));
1064     }
1065   }
1066 }
1067 
1068 DIE *DwarfUnit::getOrCreateNameSpace(const DINamespace *NS) {
1069   // Construct the context before querying for the existence of the DIE in case
1070   // such construction creates the DIE.
1071   DIE *ContextDIE = getOrCreateContextDIE(NS->getScope());
1072 
1073   if (DIE *NDie = getDIE(NS))
1074     return NDie;
1075   DIE &NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS);
1076 
1077   StringRef Name = NS->getName();
1078   if (!Name.empty())
1079     addString(NDie, dwarf::DW_AT_name, NS->getName());
1080   else
1081     Name = "(anonymous namespace)";
1082   DD->addAccelNamespace(Name, NDie);
1083   addGlobalName(Name, NDie, NS->getScope());
1084   addSourceLine(NDie, NS);
1085   if (NS->getExportSymbols())
1086     addFlag(NDie, dwarf::DW_AT_export_symbols);
1087   return &NDie;
1088 }
1089 
1090 DIE *DwarfUnit::getOrCreateModule(const DIModule *M) {
1091   // Construct the context before querying for the existence of the DIE in case
1092   // such construction creates the DIE.
1093   DIE *ContextDIE = getOrCreateContextDIE(M->getScope());
1094 
1095   if (DIE *MDie = getDIE(M))
1096     return MDie;
1097   DIE &MDie = createAndAddDIE(dwarf::DW_TAG_module, *ContextDIE, M);
1098 
1099   if (!M->getName().empty()) {
1100     addString(MDie, dwarf::DW_AT_name, M->getName());
1101     addGlobalName(M->getName(), MDie, M->getScope());
1102   }
1103   if (!M->getConfigurationMacros().empty())
1104     addString(MDie, dwarf::DW_AT_LLVM_config_macros,
1105               M->getConfigurationMacros());
1106   if (!M->getIncludePath().empty())
1107     addString(MDie, dwarf::DW_AT_LLVM_include_path, M->getIncludePath());
1108   if (!M->getISysRoot().empty())
1109     addString(MDie, dwarf::DW_AT_LLVM_isysroot, M->getISysRoot());
1110 
1111   return &MDie;
1112 }
1113 
1114 DIE *DwarfUnit::getOrCreateSubprogramDIE(const DISubprogram *SP, bool Minimal) {
1115   // Construct the context before querying for the existence of the DIE in case
1116   // such construction creates the DIE (as is the case for member function
1117   // declarations).
1118   DIE *ContextDIE =
1119       Minimal ? &getUnitDie() : getOrCreateContextDIE(resolve(SP->getScope()));
1120 
1121   if (DIE *SPDie = getDIE(SP))
1122     return SPDie;
1123 
1124   if (auto *SPDecl = SP->getDeclaration()) {
1125     if (!Minimal) {
1126       // Add subprogram definitions to the CU die directly.
1127       ContextDIE = &getUnitDie();
1128       // Build the decl now to ensure it precedes the definition.
1129       getOrCreateSubprogramDIE(SPDecl);
1130     }
1131   }
1132 
1133   // DW_TAG_inlined_subroutine may refer to this DIE.
1134   DIE &SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
1135 
1136   // Stop here and fill this in later, depending on whether or not this
1137   // subprogram turns out to have inlined instances or not.
1138   if (SP->isDefinition())
1139     return &SPDie;
1140 
1141   applySubprogramAttributes(SP, SPDie);
1142   return &SPDie;
1143 }
1144 
1145 bool DwarfUnit::applySubprogramDefinitionAttributes(const DISubprogram *SP,
1146                                                     DIE &SPDie) {
1147   DIE *DeclDie = nullptr;
1148   StringRef DeclLinkageName;
1149   if (auto *SPDecl = SP->getDeclaration()) {
1150     DeclDie = getDIE(SPDecl);
1151     assert(DeclDie && "This DIE should've already been constructed when the "
1152                       "definition DIE was created in "
1153                       "getOrCreateSubprogramDIE");
1154     // Look at the Decl's linkage name only if we emitted it.
1155     if (DD->useAllLinkageNames())
1156       DeclLinkageName = SPDecl->getLinkageName();
1157     unsigned DeclID =
1158         getOrCreateSourceID(SPDecl->getFilename(), SPDecl->getDirectory());
1159     unsigned DefID = getOrCreateSourceID(SP->getFilename(), SP->getDirectory());
1160     if (DeclID != DefID)
1161       addUInt(SPDie, dwarf::DW_AT_decl_file, None, DefID);
1162 
1163     if (SP->getLine() != SPDecl->getLine())
1164       addUInt(SPDie, dwarf::DW_AT_decl_line, None, SP->getLine());
1165   }
1166 
1167   // Add function template parameters.
1168   addTemplateParams(SPDie, SP->getTemplateParams());
1169 
1170   // Add the linkage name if we have one and it isn't in the Decl.
1171   StringRef LinkageName = SP->getLinkageName();
1172   assert(((LinkageName.empty() || DeclLinkageName.empty()) ||
1173           LinkageName == DeclLinkageName) &&
1174          "decl has a linkage name and it is different");
1175   if (DeclLinkageName.empty() &&
1176       // Always emit it for abstract subprograms.
1177       (DD->useAllLinkageNames() || DU->getAbstractSPDies().lookup(SP)))
1178     addLinkageName(SPDie, LinkageName);
1179 
1180   if (!DeclDie)
1181     return false;
1182 
1183   // Refer to the function declaration where all the other attributes will be
1184   // found.
1185   addDIEEntry(SPDie, dwarf::DW_AT_specification, *DeclDie);
1186   return true;
1187 }
1188 
1189 void DwarfUnit::applySubprogramAttributes(const DISubprogram *SP, DIE &SPDie,
1190                                           bool Minimal) {
1191   if (!Minimal)
1192     if (applySubprogramDefinitionAttributes(SP, SPDie))
1193       return;
1194 
1195   // Constructors and operators for anonymous aggregates do not have names.
1196   if (!SP->getName().empty())
1197     addString(SPDie, dwarf::DW_AT_name, SP->getName());
1198 
1199   // Skip the rest of the attributes under -gmlt to save space.
1200   if (Minimal)
1201     return;
1202 
1203   addSourceLine(SPDie, SP);
1204 
1205   // Add the prototype if we have a prototype and we have a C like
1206   // language.
1207   uint16_t Language = getLanguage();
1208   if (SP->isPrototyped() &&
1209       (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1210        Language == dwarf::DW_LANG_ObjC))
1211     addFlag(SPDie, dwarf::DW_AT_prototyped);
1212 
1213   unsigned CC = 0;
1214   DITypeRefArray Args;
1215   if (const DISubroutineType *SPTy = SP->getType()) {
1216     Args = SPTy->getTypeArray();
1217     CC = SPTy->getCC();
1218   }
1219 
1220   // Add a DW_AT_calling_convention if this has an explicit convention.
1221   if (CC && CC != dwarf::DW_CC_normal)
1222     addUInt(SPDie, dwarf::DW_AT_calling_convention, dwarf::DW_FORM_data1, CC);
1223 
1224   // Add a return type. If this is a type like a C/C++ void type we don't add a
1225   // return type.
1226   if (Args.size())
1227     if (auto Ty = resolve(Args[0]))
1228       addType(SPDie, Ty);
1229 
1230   unsigned VK = SP->getVirtuality();
1231   if (VK) {
1232     addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1233     if (SP->getVirtualIndex() != -1u) {
1234       DIELoc *Block = getDIELoc();
1235       addUInt(*Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1236       addUInt(*Block, dwarf::DW_FORM_udata, SP->getVirtualIndex());
1237       addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
1238     }
1239     ContainingTypeMap.insert(
1240         std::make_pair(&SPDie, resolve(SP->getContainingType())));
1241   }
1242 
1243   if (!SP->isDefinition()) {
1244     addFlag(SPDie, dwarf::DW_AT_declaration);
1245 
1246     // Add arguments. Do not add arguments for subprogram definition. They will
1247     // be handled while processing variables.
1248     constructSubprogramArguments(SPDie, Args);
1249   }
1250 
1251   if (SP->isArtificial())
1252     addFlag(SPDie, dwarf::DW_AT_artificial);
1253 
1254   if (!SP->isLocalToUnit())
1255     addFlag(SPDie, dwarf::DW_AT_external);
1256 
1257   if (DD->useAppleExtensionAttributes()) {
1258     if (SP->isOptimized())
1259       addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1260 
1261     if (unsigned isa = Asm->getISAEncoding())
1262       addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1263   }
1264 
1265   if (SP->isLValueReference())
1266     addFlag(SPDie, dwarf::DW_AT_reference);
1267 
1268   if (SP->isRValueReference())
1269     addFlag(SPDie, dwarf::DW_AT_rvalue_reference);
1270 
1271   if (SP->isNoReturn())
1272     addFlag(SPDie, dwarf::DW_AT_noreturn);
1273 
1274   if (SP->isProtected())
1275     addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1276             dwarf::DW_ACCESS_protected);
1277   else if (SP->isPrivate())
1278     addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1279             dwarf::DW_ACCESS_private);
1280   else if (SP->isPublic())
1281     addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1282             dwarf::DW_ACCESS_public);
1283 
1284   if (SP->isExplicit())
1285     addFlag(SPDie, dwarf::DW_AT_explicit);
1286 
1287   if (SP->isMainSubprogram())
1288     addFlag(SPDie, dwarf::DW_AT_main_subprogram);
1289 }
1290 
1291 void DwarfUnit::constructSubrangeDIE(DIE &Buffer, const DISubrange *SR,
1292                                      DIE *IndexTy) {
1293   DIE &DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
1294   addDIEEntry(DW_Subrange, dwarf::DW_AT_type, *IndexTy);
1295 
1296   // The LowerBound value defines the lower bounds which is typically zero for
1297   // C/C++. The Count value is the number of elements.  Values are 64 bit. If
1298   // Count == -1 then the array is unbounded and we do not emit
1299   // DW_AT_lower_bound and DW_AT_count attributes.
1300   int64_t LowerBound = SR->getLowerBound();
1301   int64_t DefaultLowerBound = getDefaultLowerBound();
1302   int64_t Count = SR->getCount();
1303 
1304   if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
1305     addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound);
1306 
1307   if (Count != -1)
1308     // FIXME: An unbounded array should reference the expression that defines
1309     // the array.
1310     addUInt(DW_Subrange, dwarf::DW_AT_count, None, Count);
1311 }
1312 
1313 DIE *DwarfUnit::getIndexTyDie() {
1314   if (IndexTyDie)
1315     return IndexTyDie;
1316   // Construct an integer type to use for indexes.
1317   IndexTyDie = &createAndAddDIE(dwarf::DW_TAG_base_type, getUnitDie());
1318   addString(*IndexTyDie, dwarf::DW_AT_name, "sizetype");
1319   addUInt(*IndexTyDie, dwarf::DW_AT_byte_size, None, sizeof(int64_t));
1320   addUInt(*IndexTyDie, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1321           dwarf::DW_ATE_unsigned);
1322   return IndexTyDie;
1323 }
1324 
1325 void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
1326   if (CTy->isVector())
1327     addFlag(Buffer, dwarf::DW_AT_GNU_vector);
1328 
1329   // Emit the element type.
1330   addType(Buffer, resolve(CTy->getBaseType()));
1331 
1332   // Get an anonymous type for index type.
1333   // FIXME: This type should be passed down from the front end
1334   // as different languages may have different sizes for indexes.
1335   DIE *IdxTy = getIndexTyDie();
1336 
1337   // Add subranges to array type.
1338   DINodeArray Elements = CTy->getElements();
1339   for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
1340     // FIXME: Should this really be such a loose cast?
1341     if (auto *Element = dyn_cast_or_null<DINode>(Elements[i]))
1342       if (Element->getTag() == dwarf::DW_TAG_subrange_type)
1343         constructSubrangeDIE(Buffer, cast<DISubrange>(Element), IdxTy);
1344   }
1345 }
1346 
1347 void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
1348   DINodeArray Elements = CTy->getElements();
1349 
1350   // Add enumerators to enumeration type.
1351   for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
1352     auto *Enum = dyn_cast_or_null<DIEnumerator>(Elements[i]);
1353     if (Enum) {
1354       DIE &Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
1355       StringRef Name = Enum->getName();
1356       addString(Enumerator, dwarf::DW_AT_name, Name);
1357       int64_t Value = Enum->getValue();
1358       addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
1359               Value);
1360     }
1361   }
1362   const DIType *DTy = resolve(CTy->getBaseType());
1363   if (DTy) {
1364     addType(Buffer, DTy);
1365     addFlag(Buffer, dwarf::DW_AT_enum_class);
1366   }
1367 }
1368 
1369 void DwarfUnit::constructContainingTypeDIEs() {
1370   for (auto CI = ContainingTypeMap.begin(), CE = ContainingTypeMap.end();
1371        CI != CE; ++CI) {
1372     DIE &SPDie = *CI->first;
1373     const DINode *D = CI->second;
1374     if (!D)
1375       continue;
1376     DIE *NDie = getDIE(D);
1377     if (!NDie)
1378       continue;
1379     addDIEEntry(SPDie, dwarf::DW_AT_containing_type, *NDie);
1380   }
1381 }
1382 
1383 void DwarfUnit::constructMemberDIE(DIE &Buffer, const DIDerivedType *DT) {
1384   DIE &MemberDie = createAndAddDIE(DT->getTag(), Buffer);
1385   StringRef Name = DT->getName();
1386   if (!Name.empty())
1387     addString(MemberDie, dwarf::DW_AT_name, Name);
1388 
1389   addType(MemberDie, resolve(DT->getBaseType()));
1390 
1391   addSourceLine(MemberDie, DT);
1392 
1393   if (DT->getTag() == dwarf::DW_TAG_inheritance && DT->isVirtual()) {
1394 
1395     // For C++, virtual base classes are not at fixed offset. Use following
1396     // expression to extract appropriate offset from vtable.
1397     // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1398 
1399     DIELoc *VBaseLocationDie = new (DIEValueAllocator) DIELoc;
1400     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1401     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1402     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1403     addUInt(*VBaseLocationDie, dwarf::DW_FORM_udata, DT->getOffsetInBits());
1404     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1405     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1406     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1407 
1408     addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
1409   } else {
1410     uint64_t Size = DT->getSizeInBits();
1411     uint64_t FieldSize = DD->getBaseTypeSize(DT);
1412     uint32_t AlignInBytes = DT->getAlignInBytes();
1413     uint64_t OffsetInBytes;
1414 
1415     bool IsBitfield = FieldSize && Size != FieldSize;
1416     if (IsBitfield) {
1417       // Handle bitfield, assume bytes are 8 bits.
1418       if (DD->useDWARF2Bitfields())
1419         addUInt(MemberDie, dwarf::DW_AT_byte_size, None, FieldSize/8);
1420       addUInt(MemberDie, dwarf::DW_AT_bit_size, None, Size);
1421 
1422       uint64_t Offset = DT->getOffsetInBits();
1423       // We can't use DT->getAlignInBits() here: AlignInBits for member type
1424       // is non-zero if and only if alignment was forced (e.g. _Alignas()),
1425       // which can't be done with bitfields. Thus we use FieldSize here.
1426       uint32_t AlignInBits = FieldSize;
1427       uint32_t AlignMask = ~(AlignInBits - 1);
1428       // The bits from the start of the storage unit to the start of the field.
1429       uint64_t StartBitOffset = Offset - (Offset & AlignMask);
1430       // The byte offset of the field's aligned storage unit inside the struct.
1431       OffsetInBytes = (Offset - StartBitOffset) / 8;
1432 
1433       if (DD->useDWARF2Bitfields()) {
1434         uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1435         uint64_t FieldOffset = (HiMark - FieldSize);
1436         Offset -= FieldOffset;
1437 
1438         // Maybe we need to work from the other end.
1439         if (Asm->getDataLayout().isLittleEndian())
1440           Offset = FieldSize - (Offset + Size);
1441 
1442         addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset);
1443         OffsetInBytes = FieldOffset >> 3;
1444       } else {
1445         addUInt(MemberDie, dwarf::DW_AT_data_bit_offset, None, Offset);
1446       }
1447     } else {
1448       // This is not a bitfield.
1449       OffsetInBytes = DT->getOffsetInBits() / 8;
1450       if (AlignInBytes)
1451         addUInt(MemberDie, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
1452                 AlignInBytes);
1453     }
1454 
1455     if (DD->getDwarfVersion() <= 2) {
1456       DIELoc *MemLocationDie = new (DIEValueAllocator) DIELoc;
1457       addUInt(*MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1458       addUInt(*MemLocationDie, dwarf::DW_FORM_udata, OffsetInBytes);
1459       addBlock(MemberDie, dwarf::DW_AT_data_member_location, MemLocationDie);
1460     } else if (!IsBitfield || DD->useDWARF2Bitfields())
1461       addUInt(MemberDie, dwarf::DW_AT_data_member_location, None,
1462               OffsetInBytes);
1463   }
1464 
1465   if (DT->isProtected())
1466     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1467             dwarf::DW_ACCESS_protected);
1468   else if (DT->isPrivate())
1469     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1470             dwarf::DW_ACCESS_private);
1471   // Otherwise C++ member and base classes are considered public.
1472   else if (DT->isPublic())
1473     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1474             dwarf::DW_ACCESS_public);
1475   if (DT->isVirtual())
1476     addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1477             dwarf::DW_VIRTUALITY_virtual);
1478 
1479   // Objective-C properties.
1480   if (DINode *PNode = DT->getObjCProperty())
1481     if (DIE *PDie = getDIE(PNode))
1482       MemberDie.addValue(DIEValueAllocator, dwarf::DW_AT_APPLE_property,
1483                          dwarf::DW_FORM_ref4, DIEEntry(*PDie));
1484 
1485   if (DT->isArtificial())
1486     addFlag(MemberDie, dwarf::DW_AT_artificial);
1487 }
1488 
1489 DIE *DwarfUnit::getOrCreateStaticMemberDIE(const DIDerivedType *DT) {
1490   if (!DT)
1491     return nullptr;
1492 
1493   // Construct the context before querying for the existence of the DIE in case
1494   // such construction creates the DIE.
1495   DIE *ContextDIE = getOrCreateContextDIE(resolve(DT->getScope()));
1496   assert(dwarf::isType(ContextDIE->getTag()) &&
1497          "Static member should belong to a type.");
1498 
1499   if (DIE *StaticMemberDIE = getDIE(DT))
1500     return StaticMemberDIE;
1501 
1502   DIE &StaticMemberDIE = createAndAddDIE(DT->getTag(), *ContextDIE, DT);
1503 
1504   const DIType *Ty = resolve(DT->getBaseType());
1505 
1506   addString(StaticMemberDIE, dwarf::DW_AT_name, DT->getName());
1507   addType(StaticMemberDIE, Ty);
1508   addSourceLine(StaticMemberDIE, DT);
1509   addFlag(StaticMemberDIE, dwarf::DW_AT_external);
1510   addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
1511 
1512   // FIXME: We could omit private if the parent is a class_type, and
1513   // public if the parent is something else.
1514   if (DT->isProtected())
1515     addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1516             dwarf::DW_ACCESS_protected);
1517   else if (DT->isPrivate())
1518     addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1519             dwarf::DW_ACCESS_private);
1520   else if (DT->isPublic())
1521     addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1522             dwarf::DW_ACCESS_public);
1523 
1524   if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT->getConstant()))
1525     addConstantValue(StaticMemberDIE, CI, Ty);
1526   if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT->getConstant()))
1527     addConstantFPValue(StaticMemberDIE, CFP);
1528 
1529   if (uint32_t AlignInBytes = DT->getAlignInBytes())
1530     addUInt(StaticMemberDIE, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
1531             AlignInBytes);
1532 
1533   return &StaticMemberDIE;
1534 }
1535 
1536 void DwarfUnit::emitHeader(bool UseOffsets) {
1537   // Emit size of content not including length itself
1538   Asm->OutStreamer->AddComment("Length of Unit");
1539   Asm->EmitInt32(getHeaderSize() + getUnitDie().getSize());
1540 
1541   Asm->OutStreamer->AddComment("DWARF version number");
1542   Asm->EmitInt16(DD->getDwarfVersion());
1543   Asm->OutStreamer->AddComment("Offset Into Abbrev. Section");
1544 
1545   // We share one abbreviations table across all units so it's always at the
1546   // start of the section. Use a relocatable offset where needed to ensure
1547   // linking doesn't invalidate that offset.
1548   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1549   if (UseOffsets)
1550     Asm->EmitInt32(0);
1551   else
1552     Asm->emitDwarfSymbolReference(
1553         TLOF.getDwarfAbbrevSection()->getBeginSymbol(), false);
1554 
1555   Asm->OutStreamer->AddComment("Address Size (in bytes)");
1556   Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
1557 }
1558 
1559 void DwarfTypeUnit::emitHeader(bool UseOffsets) {
1560   DwarfUnit::emitHeader(UseOffsets);
1561   Asm->OutStreamer->AddComment("Type Signature");
1562   Asm->OutStreamer->EmitIntValue(TypeSignature, sizeof(TypeSignature));
1563   Asm->OutStreamer->AddComment("Type DIE Offset");
1564   // In a skeleton type unit there is no type DIE so emit a zero offset.
1565   Asm->OutStreamer->EmitIntValue(Ty ? Ty->getOffset() : 0,
1566                                  sizeof(Ty->getOffset()));
1567 }
1568 
1569 bool DwarfTypeUnit::isDwoUnit() const {
1570   // Since there are no skeleton type units, all type units are dwo type units
1571   // when split DWARF is being used.
1572   return DD->useSplitDwarf();
1573 }
1574