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