1 //===-- llvm/CodeGen/DwarfUnit.cpp - Dwarf Type and Compile Units ---------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains support for constructing a dwarf compile unit.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "DwarfUnit.h"
14 #include "AddressPool.h"
15 #include "DwarfCompileUnit.h"
16 #include "DwarfDebug.h"
17 #include "DwarfExpression.h"
18 #include "llvm/ADT/APFloat.h"
19 #include "llvm/ADT/APInt.h"
20 #include "llvm/ADT/None.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/iterator_range.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineOperand.h"
25 #include "llvm/CodeGen/TargetRegisterInfo.h"
26 #include "llvm/CodeGen/TargetSubtargetInfo.h"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/GlobalValue.h"
30 #include "llvm/IR/Metadata.h"
31 #include "llvm/MC/MCAsmInfo.h"
32 #include "llvm/MC/MCContext.h"
33 #include "llvm/MC/MCDwarf.h"
34 #include "llvm/MC/MCSection.h"
35 #include "llvm/MC/MCStreamer.h"
36 #include "llvm/MC/MachineLocation.h"
37 #include "llvm/Support/Casting.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Target/TargetLoweringObjectFile.h"
40 #include <cassert>
41 #include <cstdint>
42 #include <string>
43 #include <utility>
44 
45 using namespace llvm;
46 
47 #define DEBUG_TYPE "dwarfdebug"
48 
49 DIEDwarfExpression::DIEDwarfExpression(const AsmPrinter &AP,
50                                        DwarfCompileUnit &CU,
51                                        DIELoc &DIE)
52     : DwarfExpression(AP.getDwarfVersion(), CU), AP(AP),
53       DIE(DIE) {}
54 
55 void DIEDwarfExpression::emitOp(uint8_t Op, const char* Comment) {
56   CU.addUInt(DIE, dwarf::DW_FORM_data1, Op);
57 }
58 
59 void DIEDwarfExpression::emitSigned(int64_t Value) {
60   CU.addSInt(DIE, dwarf::DW_FORM_sdata, Value);
61 }
62 
63 void DIEDwarfExpression::emitUnsigned(uint64_t Value) {
64   CU.addUInt(DIE, dwarf::DW_FORM_udata, Value);
65 }
66 
67 void DIEDwarfExpression::emitBaseTypeRef(uint64_t Idx) {
68   CU.addBaseTypeRef(DIE, Idx);
69 }
70 
71 bool DIEDwarfExpression::isFrameRegister(const TargetRegisterInfo &TRI,
72                                          unsigned MachineReg) {
73   return MachineReg == TRI.getFrameRegister(*AP.MF);
74 }
75 
76 DwarfUnit::DwarfUnit(dwarf::Tag UnitTag, const DICompileUnit *Node,
77                      AsmPrinter *A, DwarfDebug *DW, DwarfFile *DWU)
78     : DIEUnit(A->getDwarfVersion(), A->MAI->getCodePointerSize(), UnitTag),
79       CUNode(Node), Asm(A), DD(DW), DU(DWU), IndexTyDie(nullptr) {
80 }
81 
82 DwarfTypeUnit::DwarfTypeUnit(DwarfCompileUnit &CU, AsmPrinter *A,
83                              DwarfDebug *DW, DwarfFile *DWU,
84                              MCDwarfDwoLineTable *SplitLineTable)
85     : DwarfUnit(dwarf::DW_TAG_type_unit, CU.getCUNode(), A, DW, DWU), CU(CU),
86       SplitLineTable(SplitLineTable) {
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 bool DwarfUnit::isShareableAcrossCUs(const DINode *D) const {
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   if (isDwoUnit() && !DD->shareAcrossDWOCUs())
184     return false;
185   return (isa<DIType>(D) ||
186           (isa<DISubprogram>(D) && !cast<DISubprogram>(D)->isDefinition())) &&
187          !DD->generateTypeUnits();
188 }
189 
190 DIE *DwarfUnit::getDIE(const DINode *D) const {
191   if (isShareableAcrossCUs(D))
192     return DU->getDIE(D);
193   return MDNodeToDieMap.lookup(D);
194 }
195 
196 void DwarfUnit::insertDIE(const DINode *Desc, DIE *D) {
197   if (isShareableAcrossCUs(Desc)) {
198     DU->insertDIE(Desc, D);
199     return;
200   }
201   MDNodeToDieMap.insert(std::make_pair(Desc, D));
202 }
203 
204 void DwarfUnit::addFlag(DIE &Die, dwarf::Attribute Attribute) {
205   if (DD->getDwarfVersion() >= 4)
206     Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_flag_present,
207                  DIEInteger(1));
208   else
209     Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_flag,
210                  DIEInteger(1));
211 }
212 
213 void DwarfUnit::addUInt(DIEValueList &Die, dwarf::Attribute Attribute,
214                         Optional<dwarf::Form> Form, uint64_t Integer) {
215   if (!Form)
216     Form = DIEInteger::BestForm(false, Integer);
217   assert(Form != dwarf::DW_FORM_implicit_const &&
218          "DW_FORM_implicit_const is used only for signed integers");
219   Die.addValue(DIEValueAllocator, Attribute, *Form, DIEInteger(Integer));
220 }
221 
222 void DwarfUnit::addUInt(DIEValueList &Block, dwarf::Form Form,
223                         uint64_t Integer) {
224   addUInt(Block, (dwarf::Attribute)0, Form, Integer);
225 }
226 
227 void DwarfUnit::addSInt(DIEValueList &Die, dwarf::Attribute Attribute,
228                         Optional<dwarf::Form> Form, int64_t Integer) {
229   if (!Form)
230     Form = DIEInteger::BestForm(true, Integer);
231   Die.addValue(DIEValueAllocator, Attribute, *Form, DIEInteger(Integer));
232 }
233 
234 void DwarfUnit::addSInt(DIELoc &Die, Optional<dwarf::Form> Form,
235                         int64_t Integer) {
236   addSInt(Die, (dwarf::Attribute)0, Form, Integer);
237 }
238 
239 void DwarfUnit::addString(DIE &Die, dwarf::Attribute Attribute,
240                           StringRef String) {
241   if (CUNode->isDebugDirectivesOnly())
242     return;
243 
244   if (DD->useInlineStrings()) {
245     Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_string,
246                  new (DIEValueAllocator)
247                      DIEInlineString(String, DIEValueAllocator));
248     return;
249   }
250   dwarf::Form IxForm =
251       isDwoUnit() ? dwarf::DW_FORM_GNU_str_index : dwarf::DW_FORM_strp;
252 
253   auto StringPoolEntry =
254       useSegmentedStringOffsetsTable() || IxForm == dwarf::DW_FORM_GNU_str_index
255           ? DU->getStringPool().getIndexedEntry(*Asm, String)
256           : DU->getStringPool().getEntry(*Asm, String);
257 
258   // For DWARF v5 and beyond, use the smallest strx? form possible.
259   if (useSegmentedStringOffsetsTable()) {
260     IxForm = dwarf::DW_FORM_strx1;
261     unsigned Index = StringPoolEntry.getIndex();
262     if (Index > 0xffffff)
263       IxForm = dwarf::DW_FORM_strx4;
264     else if (Index > 0xffff)
265       IxForm = dwarf::DW_FORM_strx3;
266     else if (Index > 0xff)
267       IxForm = dwarf::DW_FORM_strx2;
268   }
269   Die.addValue(DIEValueAllocator, Attribute, IxForm,
270                DIEString(StringPoolEntry));
271 }
272 
273 DIEValueList::value_iterator DwarfUnit::addLabel(DIEValueList &Die,
274                                                  dwarf::Attribute Attribute,
275                                                  dwarf::Form Form,
276                                                  const MCSymbol *Label) {
277   return Die.addValue(DIEValueAllocator, Attribute, Form, DIELabel(Label));
278 }
279 
280 void DwarfUnit::addLabel(DIELoc &Die, dwarf::Form Form, const MCSymbol *Label) {
281   addLabel(Die, (dwarf::Attribute)0, Form, Label);
282 }
283 
284 void DwarfUnit::addSectionOffset(DIE &Die, dwarf::Attribute Attribute,
285                                  uint64_t Integer) {
286   if (DD->getDwarfVersion() >= 4)
287     addUInt(Die, Attribute, dwarf::DW_FORM_sec_offset, Integer);
288   else
289     addUInt(Die, Attribute, dwarf::DW_FORM_data4, Integer);
290 }
291 
292 Optional<MD5::MD5Result> DwarfUnit::getMD5AsBytes(const DIFile *File) const {
293   assert(File);
294   if (DD->getDwarfVersion() < 5)
295     return None;
296   Optional<DIFile::ChecksumInfo<StringRef>> Checksum = File->getChecksum();
297   if (!Checksum || Checksum->Kind != DIFile::CSK_MD5)
298     return None;
299 
300   // Convert the string checksum to an MD5Result for the streamer.
301   // The verifier validates the checksum so we assume it's okay.
302   // An MD5 checksum is 16 bytes.
303   std::string ChecksumString = fromHex(Checksum->Value);
304   MD5::MD5Result CKMem;
305   std::copy(ChecksumString.begin(), ChecksumString.end(), CKMem.Bytes.data());
306   return CKMem;
307 }
308 
309 unsigned DwarfTypeUnit::getOrCreateSourceID(const DIFile *File) {
310   if (!SplitLineTable)
311     return getCU().getOrCreateSourceID(File);
312   if (!UsedLineTable) {
313     UsedLineTable = true;
314     // This is a split type unit that needs a line table.
315     addSectionOffset(getUnitDie(), dwarf::DW_AT_stmt_list, 0);
316   }
317   return SplitLineTable->getFile(File->getDirectory(), File->getFilename(),
318                                  getMD5AsBytes(File),
319                                  Asm->OutContext.getDwarfVersion(),
320                                  File->getSource());
321 }
322 
323 void DwarfUnit::addOpAddress(DIELoc &Die, const MCSymbol *Sym) {
324   if (DD->getDwarfVersion() >= 5) {
325     addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addrx);
326     addUInt(Die, dwarf::DW_FORM_addrx, DD->getAddressPool().getIndex(Sym));
327     return;
328   }
329 
330   if (DD->useSplitDwarf()) {
331     addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index);
332     addUInt(Die, dwarf::DW_FORM_GNU_addr_index,
333             DD->getAddressPool().getIndex(Sym));
334     return;
335   }
336 
337   addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
338   addLabel(Die, dwarf::DW_FORM_udata, Sym);
339 }
340 
341 void DwarfUnit::addLabelDelta(DIE &Die, dwarf::Attribute Attribute,
342                               const MCSymbol *Hi, const MCSymbol *Lo) {
343   Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_data4,
344                new (DIEValueAllocator) DIEDelta(Hi, Lo));
345 }
346 
347 void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute, DIE &Entry) {
348   addDIEEntry(Die, Attribute, DIEEntry(Entry));
349 }
350 
351 void DwarfUnit::addDIETypeSignature(DIE &Die, uint64_t Signature) {
352   // Flag the type unit reference as a declaration so that if it contains
353   // members (implicit special members, static data member definitions, member
354   // declarations for definitions in this CU, etc) consumers don't get confused
355   // and think this is a full definition.
356   addFlag(Die, dwarf::DW_AT_declaration);
357 
358   Die.addValue(DIEValueAllocator, dwarf::DW_AT_signature,
359                dwarf::DW_FORM_ref_sig8, DIEInteger(Signature));
360 }
361 
362 void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute,
363                             DIEEntry Entry) {
364   const DIEUnit *CU = Die.getUnit();
365   const DIEUnit *EntryCU = Entry.getEntry().getUnit();
366   if (!CU)
367     // We assume that Die belongs to this CU, if it is not linked to any CU yet.
368     CU = getUnitDie().getUnit();
369   if (!EntryCU)
370     EntryCU = getUnitDie().getUnit();
371   Die.addValue(DIEValueAllocator, Attribute,
372                EntryCU == CU ? dwarf::DW_FORM_ref4 : dwarf::DW_FORM_ref_addr,
373                Entry);
374 }
375 
376 DIE &DwarfUnit::createAndAddDIE(unsigned Tag, DIE &Parent, const DINode *N) {
377   DIE &Die = Parent.addChild(DIE::get(DIEValueAllocator, (dwarf::Tag)Tag));
378   if (N)
379     insertDIE(N, &Die);
380   return Die;
381 }
382 
383 void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute, DIELoc *Loc) {
384   Loc->ComputeSize(Asm);
385   DIELocs.push_back(Loc); // Memoize so we can call the destructor later on.
386   Die.addValue(DIEValueAllocator, Attribute,
387                Loc->BestForm(DD->getDwarfVersion()), Loc);
388 }
389 
390 void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute,
391                          DIEBlock *Block) {
392   Block->ComputeSize(Asm);
393   DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
394   Die.addValue(DIEValueAllocator, Attribute, Block->BestForm(), Block);
395 }
396 
397 void DwarfUnit::addSourceLine(DIE &Die, unsigned Line, const DIFile *File) {
398   if (Line == 0)
399     return;
400 
401   unsigned FileID = getOrCreateSourceID(File);
402   addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
403   addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
404 }
405 
406 void DwarfUnit::addSourceLine(DIE &Die, const DILocalVariable *V) {
407   assert(V);
408 
409   addSourceLine(Die, V->getLine(), V->getFile());
410 }
411 
412 void DwarfUnit::addSourceLine(DIE &Die, const DIGlobalVariable *G) {
413   assert(G);
414 
415   addSourceLine(Die, G->getLine(), G->getFile());
416 }
417 
418 void DwarfUnit::addSourceLine(DIE &Die, const DISubprogram *SP) {
419   assert(SP);
420 
421   addSourceLine(Die, SP->getLine(), SP->getFile());
422 }
423 
424 void DwarfUnit::addSourceLine(DIE &Die, const DILabel *L) {
425   assert(L);
426 
427   addSourceLine(Die, L->getLine(), L->getFile());
428 }
429 
430 void DwarfUnit::addSourceLine(DIE &Die, const DIType *Ty) {
431   assert(Ty);
432 
433   addSourceLine(Die, Ty->getLine(), Ty->getFile());
434 }
435 
436 void DwarfUnit::addSourceLine(DIE &Die, const DIObjCProperty *Ty) {
437   assert(Ty);
438 
439   addSourceLine(Die, Ty->getLine(), Ty->getFile());
440 }
441 
442 /// Return true if type encoding is unsigned.
443 static bool isUnsignedDIType(DwarfDebug *DD, const DIType *Ty) {
444   if (auto *CTy = dyn_cast<DICompositeType>(Ty)) {
445     // FIXME: Enums without a fixed underlying type have unknown signedness
446     // here, leading to incorrectly emitted constants.
447     if (CTy->getTag() == dwarf::DW_TAG_enumeration_type)
448       return false;
449 
450     // (Pieces of) aggregate types that get hacked apart by SROA may be
451     // represented by a constant. Encode them as unsigned bytes.
452     return true;
453   }
454 
455   if (auto *DTy = dyn_cast<DIDerivedType>(Ty)) {
456     dwarf::Tag T = (dwarf::Tag)Ty->getTag();
457     // Encode pointer constants as unsigned bytes. This is used at least for
458     // null pointer constant emission.
459     // FIXME: reference and rvalue_reference /probably/ shouldn't be allowed
460     // here, but accept them for now due to a bug in SROA producing bogus
461     // dbg.values.
462     if (T == dwarf::DW_TAG_pointer_type ||
463         T == dwarf::DW_TAG_ptr_to_member_type ||
464         T == dwarf::DW_TAG_reference_type ||
465         T == dwarf::DW_TAG_rvalue_reference_type)
466       return true;
467     assert(T == dwarf::DW_TAG_typedef || T == dwarf::DW_TAG_const_type ||
468            T == dwarf::DW_TAG_volatile_type ||
469            T == dwarf::DW_TAG_restrict_type || T == dwarf::DW_TAG_atomic_type);
470     DITypeRef Deriv = DTy->getBaseType();
471     assert(Deriv && "Expected valid base type");
472     return isUnsignedDIType(DD, DD->resolve(Deriv));
473   }
474 
475   auto *BTy = cast<DIBasicType>(Ty);
476   unsigned Encoding = BTy->getEncoding();
477   assert((Encoding == dwarf::DW_ATE_unsigned ||
478           Encoding == dwarf::DW_ATE_unsigned_char ||
479           Encoding == dwarf::DW_ATE_signed ||
480           Encoding == dwarf::DW_ATE_signed_char ||
481           Encoding == dwarf::DW_ATE_float || Encoding == dwarf::DW_ATE_UTF ||
482           Encoding == dwarf::DW_ATE_boolean ||
483           (Ty->getTag() == dwarf::DW_TAG_unspecified_type &&
484            Ty->getName() == "decltype(nullptr)")) &&
485          "Unsupported encoding");
486   return Encoding == dwarf::DW_ATE_unsigned ||
487          Encoding == dwarf::DW_ATE_unsigned_char ||
488          Encoding == dwarf::DW_ATE_UTF || Encoding == dwarf::DW_ATE_boolean ||
489          Ty->getTag() == dwarf::DW_TAG_unspecified_type;
490 }
491 
492 void DwarfUnit::addConstantFPValue(DIE &Die, const MachineOperand &MO) {
493   assert(MO.isFPImm() && "Invalid machine operand!");
494   DIEBlock *Block = new (DIEValueAllocator) DIEBlock;
495   APFloat FPImm = MO.getFPImm()->getValueAPF();
496 
497   // Get the raw data form of the floating point.
498   const APInt FltVal = FPImm.bitcastToAPInt();
499   const char *FltPtr = (const char *)FltVal.getRawData();
500 
501   int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
502   bool LittleEndian = Asm->getDataLayout().isLittleEndian();
503   int Incr = (LittleEndian ? 1 : -1);
504   int Start = (LittleEndian ? 0 : NumBytes - 1);
505   int Stop = (LittleEndian ? NumBytes : -1);
506 
507   // Output the constant to DWARF one byte at a time.
508   for (; Start != Stop; Start += Incr)
509     addUInt(*Block, dwarf::DW_FORM_data1, (unsigned char)0xFF & FltPtr[Start]);
510 
511   addBlock(Die, dwarf::DW_AT_const_value, Block);
512 }
513 
514 void DwarfUnit::addConstantFPValue(DIE &Die, const ConstantFP *CFP) {
515   // Pass this down to addConstantValue as an unsigned bag of bits.
516   addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true);
517 }
518 
519 void DwarfUnit::addConstantValue(DIE &Die, const ConstantInt *CI,
520                                  const DIType *Ty) {
521   addConstantValue(Die, CI->getValue(), Ty);
522 }
523 
524 void DwarfUnit::addConstantValue(DIE &Die, const MachineOperand &MO,
525                                  const DIType *Ty) {
526   assert(MO.isImm() && "Invalid machine operand!");
527 
528   addConstantValue(Die, isUnsignedDIType(DD, Ty), MO.getImm());
529 }
530 
531 void DwarfUnit::addConstantValue(DIE &Die, bool Unsigned, uint64_t Val) {
532   // FIXME: This is a bit conservative/simple - it emits negative values always
533   // sign extended to 64 bits rather than minimizing the number of bytes.
534   addUInt(Die, dwarf::DW_AT_const_value,
535           Unsigned ? dwarf::DW_FORM_udata : dwarf::DW_FORM_sdata, Val);
536 }
537 
538 void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, const DIType *Ty) {
539   addConstantValue(Die, Val, isUnsignedDIType(DD, Ty));
540 }
541 
542 void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, bool Unsigned) {
543   unsigned CIBitWidth = Val.getBitWidth();
544   if (CIBitWidth <= 64) {
545     addConstantValue(Die, Unsigned,
546                      Unsigned ? Val.getZExtValue() : Val.getSExtValue());
547     return;
548   }
549 
550   DIEBlock *Block = new (DIEValueAllocator) DIEBlock;
551 
552   // Get the raw data form of the large APInt.
553   const uint64_t *Ptr64 = Val.getRawData();
554 
555   int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
556   bool LittleEndian = Asm->getDataLayout().isLittleEndian();
557 
558   // Output the constant to DWARF one byte at a time.
559   for (int i = 0; i < NumBytes; i++) {
560     uint8_t c;
561     if (LittleEndian)
562       c = Ptr64[i / 8] >> (8 * (i & 7));
563     else
564       c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
565     addUInt(*Block, dwarf::DW_FORM_data1, c);
566   }
567 
568   addBlock(Die, dwarf::DW_AT_const_value, Block);
569 }
570 
571 void DwarfUnit::addLinkageName(DIE &Die, StringRef LinkageName) {
572   if (!LinkageName.empty())
573     addString(Die,
574               DD->getDwarfVersion() >= 4 ? dwarf::DW_AT_linkage_name
575                                          : dwarf::DW_AT_MIPS_linkage_name,
576               GlobalValue::dropLLVMManglingEscape(LinkageName));
577 }
578 
579 void DwarfUnit::addTemplateParams(DIE &Buffer, DINodeArray TParams) {
580   // Add template parameters.
581   for (const auto *Element : TParams) {
582     if (auto *TTP = dyn_cast<DITemplateTypeParameter>(Element))
583       constructTemplateTypeParameterDIE(Buffer, TTP);
584     else if (auto *TVP = dyn_cast<DITemplateValueParameter>(Element))
585       constructTemplateValueParameterDIE(Buffer, TVP);
586   }
587 }
588 
589 /// Add thrown types.
590 void DwarfUnit::addThrownTypes(DIE &Die, DINodeArray ThrownTypes) {
591   for (const auto *Ty : ThrownTypes) {
592     DIE &TT = createAndAddDIE(dwarf::DW_TAG_thrown_type, Die);
593     addType(TT, cast<DIType>(Ty));
594   }
595 }
596 
597 DIE *DwarfUnit::getOrCreateContextDIE(const DIScope *Context) {
598   if (!Context || isa<DIFile>(Context))
599     return &getUnitDie();
600   if (auto *T = dyn_cast<DIType>(Context))
601     return getOrCreateTypeDIE(T);
602   if (auto *NS = dyn_cast<DINamespace>(Context))
603     return getOrCreateNameSpace(NS);
604   if (auto *SP = dyn_cast<DISubprogram>(Context))
605     return getOrCreateSubprogramDIE(SP);
606   if (auto *M = dyn_cast<DIModule>(Context))
607     return getOrCreateModule(M);
608   return getDIE(Context);
609 }
610 
611 DIE *DwarfUnit::createTypeDIE(const DICompositeType *Ty) {
612   auto *Context = resolve(Ty->getScope());
613   DIE *ContextDIE = getOrCreateContextDIE(Context);
614 
615   if (DIE *TyDIE = getDIE(Ty))
616     return TyDIE;
617 
618   // Create new type.
619   DIE &TyDIE = createAndAddDIE(Ty->getTag(), *ContextDIE, Ty);
620 
621   constructTypeDIE(TyDIE, cast<DICompositeType>(Ty));
622 
623   updateAcceleratorTables(Context, Ty, TyDIE);
624   return &TyDIE;
625 }
626 
627 DIE *DwarfUnit::createTypeDIE(const DIScope *Context, DIE &ContextDIE,
628                               const DIType *Ty) {
629   // Create new type.
630   DIE &TyDIE = createAndAddDIE(Ty->getTag(), ContextDIE, Ty);
631 
632   updateAcceleratorTables(Context, Ty, TyDIE);
633 
634   if (auto *BT = dyn_cast<DIBasicType>(Ty))
635     constructTypeDIE(TyDIE, BT);
636   else if (auto *STy = dyn_cast<DISubroutineType>(Ty))
637     constructTypeDIE(TyDIE, STy);
638   else if (auto *CTy = dyn_cast<DICompositeType>(Ty)) {
639     if (DD->generateTypeUnits() && !Ty->isForwardDecl()) {
640       // Skip updating the accelerator tables since this is not the full type.
641       if (MDString *TypeId = CTy->getRawIdentifier())
642         DD->addDwarfTypeUnitType(getCU(), TypeId->getString(), TyDIE, CTy);
643       else {
644         auto X = DD->enterNonTypeUnitContext();
645         finishNonUnitTypeDIE(TyDIE, CTy);
646       }
647       return &TyDIE;
648     }
649     constructTypeDIE(TyDIE, CTy);
650   } else {
651     constructTypeDIE(TyDIE, cast<DIDerivedType>(Ty));
652   }
653 
654   return &TyDIE;
655 }
656 
657 DIE *DwarfUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
658   if (!TyNode)
659     return nullptr;
660 
661   auto *Ty = cast<DIType>(TyNode);
662 
663   // DW_TAG_restrict_type is not supported in DWARF2
664   if (Ty->getTag() == dwarf::DW_TAG_restrict_type && DD->getDwarfVersion() <= 2)
665     return getOrCreateTypeDIE(resolve(cast<DIDerivedType>(Ty)->getBaseType()));
666 
667   // DW_TAG_atomic_type is not supported in DWARF < 5
668   if (Ty->getTag() == dwarf::DW_TAG_atomic_type && DD->getDwarfVersion() < 5)
669     return getOrCreateTypeDIE(resolve(cast<DIDerivedType>(Ty)->getBaseType()));
670 
671   // Construct the context before querying for the existence of the DIE in case
672   // such construction creates the DIE.
673   auto *Context = resolve(Ty->getScope());
674   DIE *ContextDIE = getOrCreateContextDIE(Context);
675   assert(ContextDIE);
676 
677   if (DIE *TyDIE = getDIE(Ty))
678     return TyDIE;
679 
680   return static_cast<DwarfUnit *>(ContextDIE->getUnit())
681       ->createTypeDIE(Context, *ContextDIE, Ty);
682 }
683 
684 void DwarfUnit::updateAcceleratorTables(const DIScope *Context,
685                                         const DIType *Ty, const DIE &TyDIE) {
686   if (!Ty->getName().empty() && !Ty->isForwardDecl()) {
687     bool IsImplementation = false;
688     if (auto *CT = dyn_cast<DICompositeType>(Ty)) {
689       // A runtime language of 0 actually means C/C++ and that any
690       // non-negative value is some version of Objective-C/C++.
691       IsImplementation = CT->getRuntimeLang() == 0 || CT->isObjcClassComplete();
692     }
693     unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0;
694     DD->addAccelType(*CUNode, Ty->getName(), TyDIE, Flags);
695 
696     if (!Context || isa<DICompileUnit>(Context) || isa<DIFile>(Context) ||
697         isa<DINamespace>(Context) || isa<DICommonBlock>(Context))
698       addGlobalType(Ty, TyDIE, Context);
699   }
700 }
701 
702 void DwarfUnit::addType(DIE &Entity, const DIType *Ty,
703                         dwarf::Attribute Attribute) {
704   assert(Ty && "Trying to add a type that doesn't exist?");
705   addDIEEntry(Entity, Attribute, DIEEntry(*getOrCreateTypeDIE(Ty)));
706 }
707 
708 std::string DwarfUnit::getParentContextString(const DIScope *Context) const {
709   if (!Context)
710     return "";
711 
712   // FIXME: Decide whether to implement this for non-C++ languages.
713   if (getLanguage() != dwarf::DW_LANG_C_plus_plus)
714     return "";
715 
716   std::string CS;
717   SmallVector<const DIScope *, 1> Parents;
718   while (!isa<DICompileUnit>(Context)) {
719     Parents.push_back(Context);
720     if (Context->getScope())
721       Context = resolve(Context->getScope());
722     else
723       // Structure, etc types will have a NULL context if they're at the top
724       // level.
725       break;
726   }
727 
728   // Reverse iterate over our list to go from the outermost construct to the
729   // innermost.
730   for (const DIScope *Ctx : make_range(Parents.rbegin(), Parents.rend())) {
731     StringRef Name = Ctx->getName();
732     if (Name.empty() && isa<DINamespace>(Ctx))
733       Name = "(anonymous namespace)";
734     if (!Name.empty()) {
735       CS += Name;
736       CS += "::";
737     }
738   }
739   return CS;
740 }
741 
742 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DIBasicType *BTy) {
743   // Get core information.
744   StringRef Name = BTy->getName();
745   // Add name if not anonymous or intermediate type.
746   if (!Name.empty())
747     addString(Buffer, dwarf::DW_AT_name, Name);
748 
749   // An unspecified type only has a name attribute.
750   if (BTy->getTag() == dwarf::DW_TAG_unspecified_type)
751     return;
752 
753   addUInt(Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
754           BTy->getEncoding());
755 
756   uint64_t Size = BTy->getSizeInBits() >> 3;
757   addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
758 
759   if (BTy->isBigEndian())
760     addUInt(Buffer, dwarf::DW_AT_endianity, None, dwarf::DW_END_big);
761   else if (BTy->isLittleEndian())
762     addUInt(Buffer, dwarf::DW_AT_endianity, None, dwarf::DW_END_little);
763 }
764 
765 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DIDerivedType *DTy) {
766   // Get core information.
767   StringRef Name = DTy->getName();
768   uint64_t Size = DTy->getSizeInBits() >> 3;
769   uint16_t Tag = Buffer.getTag();
770 
771   // Map to main type, void will not have a type.
772   const DIType *FromTy = resolve(DTy->getBaseType());
773   if (FromTy)
774     addType(Buffer, FromTy);
775 
776   // Add name if not anonymous or intermediate type.
777   if (!Name.empty())
778     addString(Buffer, dwarf::DW_AT_name, Name);
779 
780   // Add size if non-zero (derived types might be zero-sized.)
781   if (Size && Tag != dwarf::DW_TAG_pointer_type
782            && Tag != dwarf::DW_TAG_ptr_to_member_type
783            && Tag != dwarf::DW_TAG_reference_type
784            && Tag != dwarf::DW_TAG_rvalue_reference_type)
785     addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
786 
787   if (Tag == dwarf::DW_TAG_ptr_to_member_type)
788     addDIEEntry(
789         Buffer, dwarf::DW_AT_containing_type,
790         *getOrCreateTypeDIE(resolve(cast<DIDerivedType>(DTy)->getClassType())));
791   // Add source line info if available and TyDesc is not a forward declaration.
792   if (!DTy->isForwardDecl())
793     addSourceLine(Buffer, DTy);
794 
795   // If DWARF address space value is other than None, add it for pointer and
796   // reference types as DW_AT_address_class.
797   if (DTy->getDWARFAddressSpace() && (Tag == dwarf::DW_TAG_pointer_type ||
798                                       Tag == dwarf::DW_TAG_reference_type))
799     addUInt(Buffer, dwarf::DW_AT_address_class, dwarf::DW_FORM_data4,
800             DTy->getDWARFAddressSpace().getValue());
801 }
802 
803 void DwarfUnit::constructSubprogramArguments(DIE &Buffer, DITypeRefArray Args) {
804   for (unsigned i = 1, N = Args.size(); i < N; ++i) {
805     const DIType *Ty = resolve(Args[i]);
806     if (!Ty) {
807       assert(i == N-1 && "Unspecified parameter must be the last argument");
808       createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
809     } else {
810       DIE &Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
811       addType(Arg, Ty);
812       if (Ty->isArtificial())
813         addFlag(Arg, dwarf::DW_AT_artificial);
814     }
815   }
816 }
817 
818 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DISubroutineType *CTy) {
819   // Add return type.  A void return won't have a type.
820   auto Elements = cast<DISubroutineType>(CTy)->getTypeArray();
821   if (Elements.size())
822     if (auto RTy = resolve(Elements[0]))
823       addType(Buffer, RTy);
824 
825   bool isPrototyped = true;
826   if (Elements.size() == 2 && !Elements[1])
827     isPrototyped = false;
828 
829   constructSubprogramArguments(Buffer, Elements);
830 
831   // Add prototype flag if we're dealing with a C language and the function has
832   // been prototyped.
833   uint16_t Language = getLanguage();
834   if (isPrototyped &&
835       (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
836        Language == dwarf::DW_LANG_ObjC))
837     addFlag(Buffer, dwarf::DW_AT_prototyped);
838 
839   // Add a DW_AT_calling_convention if this has an explicit convention.
840   if (CTy->getCC() && CTy->getCC() != dwarf::DW_CC_normal)
841     addUInt(Buffer, dwarf::DW_AT_calling_convention, dwarf::DW_FORM_data1,
842             CTy->getCC());
843 
844   if (CTy->isLValueReference())
845     addFlag(Buffer, dwarf::DW_AT_reference);
846 
847   if (CTy->isRValueReference())
848     addFlag(Buffer, dwarf::DW_AT_rvalue_reference);
849 }
850 
851 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
852   // Add name if not anonymous or intermediate type.
853   StringRef Name = CTy->getName();
854 
855   uint64_t Size = CTy->getSizeInBits() >> 3;
856   uint16_t Tag = Buffer.getTag();
857 
858   switch (Tag) {
859   case dwarf::DW_TAG_array_type:
860     constructArrayTypeDIE(Buffer, CTy);
861     break;
862   case dwarf::DW_TAG_enumeration_type:
863     constructEnumTypeDIE(Buffer, CTy);
864     break;
865   case dwarf::DW_TAG_variant_part:
866   case dwarf::DW_TAG_structure_type:
867   case dwarf::DW_TAG_union_type:
868   case dwarf::DW_TAG_class_type: {
869     // Emit the discriminator for a variant part.
870     DIDerivedType *Discriminator = nullptr;
871     if (Tag == dwarf::DW_TAG_variant_part) {
872       Discriminator = CTy->getDiscriminator();
873       if (Discriminator) {
874         // DWARF says:
875         //    If the variant part has a discriminant, the discriminant is
876         //    represented by a separate debugging information entry which is
877         //    a child of the variant part entry.
878         DIE &DiscMember = constructMemberDIE(Buffer, Discriminator);
879         addDIEEntry(Buffer, dwarf::DW_AT_discr, DiscMember);
880       }
881     }
882 
883     // Add elements to structure type.
884     DINodeArray Elements = CTy->getElements();
885     for (const auto *Element : Elements) {
886       if (!Element)
887         continue;
888       if (auto *SP = dyn_cast<DISubprogram>(Element))
889         getOrCreateSubprogramDIE(SP);
890       else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
891         if (DDTy->getTag() == dwarf::DW_TAG_friend) {
892           DIE &ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
893           addType(ElemDie, resolve(DDTy->getBaseType()), dwarf::DW_AT_friend);
894         } else if (DDTy->isStaticMember()) {
895           getOrCreateStaticMemberDIE(DDTy);
896         } else if (Tag == dwarf::DW_TAG_variant_part) {
897           // When emitting a variant part, wrap each member in
898           // DW_TAG_variant.
899           DIE &Variant = createAndAddDIE(dwarf::DW_TAG_variant, Buffer);
900           if (const ConstantInt *CI =
901               dyn_cast_or_null<ConstantInt>(DDTy->getDiscriminantValue())) {
902             if (isUnsignedDIType(DD, resolve(Discriminator->getBaseType())))
903               addUInt(Variant, dwarf::DW_AT_discr_value, None, CI->getZExtValue());
904             else
905               addSInt(Variant, dwarf::DW_AT_discr_value, None, CI->getSExtValue());
906           }
907           constructMemberDIE(Variant, DDTy);
908         } else {
909           constructMemberDIE(Buffer, DDTy);
910         }
911       } else if (auto *Property = dyn_cast<DIObjCProperty>(Element)) {
912         DIE &ElemDie = createAndAddDIE(Property->getTag(), Buffer);
913         StringRef PropertyName = Property->getName();
914         addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
915         if (Property->getType())
916           addType(ElemDie, resolve(Property->getType()));
917         addSourceLine(ElemDie, Property);
918         StringRef GetterName = Property->getGetterName();
919         if (!GetterName.empty())
920           addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
921         StringRef SetterName = Property->getSetterName();
922         if (!SetterName.empty())
923           addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
924         if (unsigned PropertyAttributes = Property->getAttributes())
925           addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None,
926                   PropertyAttributes);
927       } else if (auto *Composite = dyn_cast<DICompositeType>(Element)) {
928         if (Composite->getTag() == dwarf::DW_TAG_variant_part) {
929           DIE &VariantPart = createAndAddDIE(Composite->getTag(), Buffer);
930           constructTypeDIE(VariantPart, Composite);
931         }
932       }
933     }
934 
935     if (CTy->isAppleBlockExtension())
936       addFlag(Buffer, dwarf::DW_AT_APPLE_block);
937 
938     // This is outside the DWARF spec, but GDB expects a DW_AT_containing_type
939     // inside C++ composite types to point to the base class with the vtable.
940     // Rust uses DW_AT_containing_type to link a vtable to the type
941     // for which it was created.
942     if (auto *ContainingType = resolve(CTy->getVTableHolder()))
943       addDIEEntry(Buffer, dwarf::DW_AT_containing_type,
944                   *getOrCreateTypeDIE(ContainingType));
945 
946     if (CTy->isObjcClassComplete())
947       addFlag(Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
948 
949     // Add template parameters to a class, structure or union types.
950     // FIXME: The support isn't in the metadata for this yet.
951     if (Tag == dwarf::DW_TAG_class_type ||
952         Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
953       addTemplateParams(Buffer, CTy->getTemplateParams());
954 
955     // Add the type's non-standard calling convention.
956     uint8_t CC = 0;
957     if (CTy->isTypePassByValue())
958       CC = dwarf::DW_CC_pass_by_value;
959     else if (CTy->isTypePassByReference())
960       CC = dwarf::DW_CC_pass_by_reference;
961     if (CC)
962       addUInt(Buffer, dwarf::DW_AT_calling_convention, dwarf::DW_FORM_data1,
963               CC);
964     break;
965   }
966   default:
967     break;
968   }
969 
970   // Add name if not anonymous or intermediate type.
971   if (!Name.empty())
972     addString(Buffer, dwarf::DW_AT_name, Name);
973 
974   if (Tag == dwarf::DW_TAG_enumeration_type ||
975       Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
976       Tag == dwarf::DW_TAG_union_type) {
977     // Add size if non-zero (derived types might be zero-sized.)
978     // TODO: Do we care about size for enum forward declarations?
979     if (Size)
980       addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
981     else if (!CTy->isForwardDecl())
982       // Add zero size if it is not a forward declaration.
983       addUInt(Buffer, dwarf::DW_AT_byte_size, None, 0);
984 
985     // If we're a forward decl, say so.
986     if (CTy->isForwardDecl())
987       addFlag(Buffer, dwarf::DW_AT_declaration);
988 
989     // Add source line info if available.
990     if (!CTy->isForwardDecl())
991       addSourceLine(Buffer, CTy);
992 
993     // No harm in adding the runtime language to the declaration.
994     unsigned RLang = CTy->getRuntimeLang();
995     if (RLang)
996       addUInt(Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
997               RLang);
998 
999     // Add align info if available.
1000     if (uint32_t AlignInBytes = CTy->getAlignInBytes())
1001       addUInt(Buffer, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
1002               AlignInBytes);
1003   }
1004 }
1005 
1006 void DwarfUnit::constructTemplateTypeParameterDIE(
1007     DIE &Buffer, const DITemplateTypeParameter *TP) {
1008   DIE &ParamDIE =
1009       createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
1010   // Add the type if it exists, it could be void and therefore no type.
1011   if (TP->getType())
1012     addType(ParamDIE, resolve(TP->getType()));
1013   if (!TP->getName().empty())
1014     addString(ParamDIE, dwarf::DW_AT_name, TP->getName());
1015 }
1016 
1017 void DwarfUnit::constructTemplateValueParameterDIE(
1018     DIE &Buffer, const DITemplateValueParameter *VP) {
1019   DIE &ParamDIE = createAndAddDIE(VP->getTag(), Buffer);
1020 
1021   // Add the type if there is one, template template and template parameter
1022   // packs will not have a type.
1023   if (VP->getTag() == dwarf::DW_TAG_template_value_parameter)
1024     addType(ParamDIE, resolve(VP->getType()));
1025   if (!VP->getName().empty())
1026     addString(ParamDIE, dwarf::DW_AT_name, VP->getName());
1027   if (Metadata *Val = VP->getValue()) {
1028     if (ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(Val))
1029       addConstantValue(ParamDIE, CI, resolve(VP->getType()));
1030     else if (GlobalValue *GV = mdconst::dyn_extract<GlobalValue>(Val)) {
1031       // We cannot describe the location of dllimport'd entities: the
1032       // computation of their address requires loads from the IAT.
1033       if (!GV->hasDLLImportStorageClass()) {
1034         // For declaration non-type template parameters (such as global values
1035         // and functions)
1036         DIELoc *Loc = new (DIEValueAllocator) DIELoc;
1037         addOpAddress(*Loc, Asm->getSymbol(GV));
1038         // Emit DW_OP_stack_value to use the address as the immediate value of
1039         // the parameter, rather than a pointer to it.
1040         addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
1041         addBlock(ParamDIE, dwarf::DW_AT_location, Loc);
1042       }
1043     } else if (VP->getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1044       assert(isa<MDString>(Val));
1045       addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
1046                 cast<MDString>(Val)->getString());
1047     } else if (VP->getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1048       addTemplateParams(ParamDIE, cast<MDTuple>(Val));
1049     }
1050   }
1051 }
1052 
1053 DIE *DwarfUnit::getOrCreateNameSpace(const DINamespace *NS) {
1054   // Construct the context before querying for the existence of the DIE in case
1055   // such construction creates the DIE.
1056   DIE *ContextDIE = getOrCreateContextDIE(NS->getScope());
1057 
1058   if (DIE *NDie = getDIE(NS))
1059     return NDie;
1060   DIE &NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS);
1061 
1062   StringRef Name = NS->getName();
1063   if (!Name.empty())
1064     addString(NDie, dwarf::DW_AT_name, NS->getName());
1065   else
1066     Name = "(anonymous namespace)";
1067   DD->addAccelNamespace(*CUNode, Name, NDie);
1068   addGlobalName(Name, NDie, NS->getScope());
1069   if (NS->getExportSymbols())
1070     addFlag(NDie, dwarf::DW_AT_export_symbols);
1071   return &NDie;
1072 }
1073 
1074 DIE *DwarfUnit::getOrCreateModule(const DIModule *M) {
1075   // Construct the context before querying for the existence of the DIE in case
1076   // such construction creates the DIE.
1077   DIE *ContextDIE = getOrCreateContextDIE(M->getScope());
1078 
1079   if (DIE *MDie = getDIE(M))
1080     return MDie;
1081   DIE &MDie = createAndAddDIE(dwarf::DW_TAG_module, *ContextDIE, M);
1082 
1083   if (!M->getName().empty()) {
1084     addString(MDie, dwarf::DW_AT_name, M->getName());
1085     addGlobalName(M->getName(), MDie, M->getScope());
1086   }
1087   if (!M->getConfigurationMacros().empty())
1088     addString(MDie, dwarf::DW_AT_LLVM_config_macros,
1089               M->getConfigurationMacros());
1090   if (!M->getIncludePath().empty())
1091     addString(MDie, dwarf::DW_AT_LLVM_include_path, M->getIncludePath());
1092   if (!M->getISysRoot().empty())
1093     addString(MDie, dwarf::DW_AT_LLVM_isysroot, M->getISysRoot());
1094 
1095   return &MDie;
1096 }
1097 
1098 DIE *DwarfUnit::getOrCreateSubprogramDIE(const DISubprogram *SP, bool Minimal) {
1099   // Construct the context before querying for the existence of the DIE in case
1100   // such construction creates the DIE (as is the case for member function
1101   // declarations).
1102   DIE *ContextDIE =
1103       Minimal ? &getUnitDie() : getOrCreateContextDIE(resolve(SP->getScope()));
1104 
1105   if (DIE *SPDie = getDIE(SP))
1106     return SPDie;
1107 
1108   if (auto *SPDecl = SP->getDeclaration()) {
1109     if (!Minimal) {
1110       // Add subprogram definitions to the CU die directly.
1111       ContextDIE = &getUnitDie();
1112       // Build the decl now to ensure it precedes the definition.
1113       getOrCreateSubprogramDIE(SPDecl);
1114     }
1115   }
1116 
1117   // DW_TAG_inlined_subroutine may refer to this DIE.
1118   DIE &SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
1119 
1120   // Stop here and fill this in later, depending on whether or not this
1121   // subprogram turns out to have inlined instances or not.
1122   if (SP->isDefinition())
1123     return &SPDie;
1124 
1125   static_cast<DwarfUnit *>(SPDie.getUnit())
1126       ->applySubprogramAttributes(SP, SPDie);
1127   return &SPDie;
1128 }
1129 
1130 bool DwarfUnit::applySubprogramDefinitionAttributes(const DISubprogram *SP,
1131                                                     DIE &SPDie) {
1132   DIE *DeclDie = nullptr;
1133   StringRef DeclLinkageName;
1134   if (auto *SPDecl = SP->getDeclaration()) {
1135     DeclDie = getDIE(SPDecl);
1136     assert(DeclDie && "This DIE should've already been constructed when the "
1137                       "definition DIE was created in "
1138                       "getOrCreateSubprogramDIE");
1139     // Look at the Decl's linkage name only if we emitted it.
1140     if (DD->useAllLinkageNames())
1141       DeclLinkageName = SPDecl->getLinkageName();
1142     unsigned DeclID = getOrCreateSourceID(SPDecl->getFile());
1143     unsigned DefID = getOrCreateSourceID(SP->getFile());
1144     if (DeclID != DefID)
1145       addUInt(SPDie, dwarf::DW_AT_decl_file, None, DefID);
1146 
1147     if (SP->getLine() != SPDecl->getLine())
1148       addUInt(SPDie, dwarf::DW_AT_decl_line, None, SP->getLine());
1149   }
1150 
1151   // Add function template parameters.
1152   addTemplateParams(SPDie, SP->getTemplateParams());
1153 
1154   // Add the linkage name if we have one and it isn't in the Decl.
1155   StringRef LinkageName = SP->getLinkageName();
1156   assert(((LinkageName.empty() || DeclLinkageName.empty()) ||
1157           LinkageName == DeclLinkageName) &&
1158          "decl has a linkage name and it is different");
1159   if (DeclLinkageName.empty() &&
1160       // Always emit it for abstract subprograms.
1161       (DD->useAllLinkageNames() || DU->getAbstractSPDies().lookup(SP)))
1162     addLinkageName(SPDie, LinkageName);
1163 
1164   if (!DeclDie)
1165     return false;
1166 
1167   // Refer to the function declaration where all the other attributes will be
1168   // found.
1169   addDIEEntry(SPDie, dwarf::DW_AT_specification, *DeclDie);
1170   return true;
1171 }
1172 
1173 void DwarfUnit::applySubprogramAttributes(const DISubprogram *SP, DIE &SPDie,
1174                                           bool SkipSPAttributes) {
1175   // If -fdebug-info-for-profiling is enabled, need to emit the subprogram
1176   // and its source location.
1177   bool SkipSPSourceLocation = SkipSPAttributes &&
1178                               !CUNode->getDebugInfoForProfiling();
1179   if (!SkipSPSourceLocation)
1180     if (applySubprogramDefinitionAttributes(SP, SPDie))
1181       return;
1182 
1183   // Constructors and operators for anonymous aggregates do not have names.
1184   if (!SP->getName().empty())
1185     addString(SPDie, dwarf::DW_AT_name, SP->getName());
1186 
1187   if (!SkipSPSourceLocation)
1188     addSourceLine(SPDie, SP);
1189 
1190   // Skip the rest of the attributes under -gmlt to save space.
1191   if (SkipSPAttributes)
1192     return;
1193 
1194   // Add the prototype if we have a prototype and we have a C like
1195   // language.
1196   uint16_t Language = getLanguage();
1197   if (SP->isPrototyped() &&
1198       (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1199        Language == dwarf::DW_LANG_ObjC))
1200     addFlag(SPDie, dwarf::DW_AT_prototyped);
1201 
1202   unsigned CC = 0;
1203   DITypeRefArray Args;
1204   if (const DISubroutineType *SPTy = SP->getType()) {
1205     Args = SPTy->getTypeArray();
1206     CC = SPTy->getCC();
1207   }
1208 
1209   // Add a DW_AT_calling_convention if this has an explicit convention.
1210   if (CC && CC != dwarf::DW_CC_normal)
1211     addUInt(SPDie, dwarf::DW_AT_calling_convention, dwarf::DW_FORM_data1, CC);
1212 
1213   // Add a return type. If this is a type like a C/C++ void type we don't add a
1214   // return type.
1215   if (Args.size())
1216     if (auto Ty = resolve(Args[0]))
1217       addType(SPDie, Ty);
1218 
1219   unsigned VK = SP->getVirtuality();
1220   if (VK) {
1221     addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1222     if (SP->getVirtualIndex() != -1u) {
1223       DIELoc *Block = getDIELoc();
1224       addUInt(*Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1225       addUInt(*Block, dwarf::DW_FORM_udata, SP->getVirtualIndex());
1226       addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
1227     }
1228     ContainingTypeMap.insert(
1229         std::make_pair(&SPDie, resolve(SP->getContainingType())));
1230   }
1231 
1232   if (!SP->isDefinition()) {
1233     addFlag(SPDie, dwarf::DW_AT_declaration);
1234 
1235     // Add arguments. Do not add arguments for subprogram definition. They will
1236     // be handled while processing variables.
1237     constructSubprogramArguments(SPDie, Args);
1238   }
1239 
1240   addThrownTypes(SPDie, SP->getThrownTypes());
1241 
1242   if (SP->isArtificial())
1243     addFlag(SPDie, dwarf::DW_AT_artificial);
1244 
1245   if (!SP->isLocalToUnit())
1246     addFlag(SPDie, dwarf::DW_AT_external);
1247 
1248   if (DD->useAppleExtensionAttributes()) {
1249     if (SP->isOptimized())
1250       addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1251 
1252     if (unsigned isa = Asm->getISAEncoding())
1253       addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1254   }
1255 
1256   if (SP->isLValueReference())
1257     addFlag(SPDie, dwarf::DW_AT_reference);
1258 
1259   if (SP->isRValueReference())
1260     addFlag(SPDie, dwarf::DW_AT_rvalue_reference);
1261 
1262   if (SP->isNoReturn())
1263     addFlag(SPDie, dwarf::DW_AT_noreturn);
1264 
1265   if (SP->isProtected())
1266     addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1267             dwarf::DW_ACCESS_protected);
1268   else if (SP->isPrivate())
1269     addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1270             dwarf::DW_ACCESS_private);
1271   else if (SP->isPublic())
1272     addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1273             dwarf::DW_ACCESS_public);
1274 
1275   if (SP->isExplicit())
1276     addFlag(SPDie, dwarf::DW_AT_explicit);
1277 
1278   if (SP->isMainSubprogram())
1279     addFlag(SPDie, dwarf::DW_AT_main_subprogram);
1280   if (SP->isPure())
1281     addFlag(SPDie, dwarf::DW_AT_pure);
1282   if (SP->isElemental())
1283     addFlag(SPDie, dwarf::DW_AT_elemental);
1284   if (SP->isRecursive())
1285     addFlag(SPDie, dwarf::DW_AT_recursive);
1286 }
1287 
1288 void DwarfUnit::constructSubrangeDIE(DIE &Buffer, const DISubrange *SR,
1289                                      DIE *IndexTy) {
1290   DIE &DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
1291   addDIEEntry(DW_Subrange, dwarf::DW_AT_type, *IndexTy);
1292 
1293   // The LowerBound value defines the lower bounds which is typically zero for
1294   // C/C++. The Count value is the number of elements.  Values are 64 bit. If
1295   // Count == -1 then the array is unbounded and we do not emit
1296   // DW_AT_lower_bound and DW_AT_count attributes.
1297   int64_t LowerBound = SR->getLowerBound();
1298   int64_t DefaultLowerBound = getDefaultLowerBound();
1299   int64_t Count = -1;
1300   if (auto *CI = SR->getCount().dyn_cast<ConstantInt*>())
1301     Count = CI->getSExtValue();
1302 
1303   if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
1304     addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound);
1305 
1306   if (auto *CV = SR->getCount().dyn_cast<DIVariable*>()) {
1307     if (auto *CountVarDIE = getDIE(CV))
1308       addDIEEntry(DW_Subrange, dwarf::DW_AT_count, *CountVarDIE);
1309   } else if (Count != -1)
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   StringRef Name = "__ARRAY_SIZE_TYPE__";
1319   addString(*IndexTyDie, dwarf::DW_AT_name, Name);
1320   addUInt(*IndexTyDie, dwarf::DW_AT_byte_size, None, sizeof(int64_t));
1321   addUInt(*IndexTyDie, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1322           dwarf::DW_ATE_unsigned);
1323   DD->addAccelType(*CUNode, Name, *IndexTyDie, /*Flags*/ 0);
1324   return IndexTyDie;
1325 }
1326 
1327 /// Returns true if the vector's size differs from the sum of sizes of elements
1328 /// the user specified.  This can occur if the vector has been rounded up to
1329 /// fit memory alignment constraints.
1330 static bool hasVectorBeenPadded(const DICompositeType *CTy) {
1331   assert(CTy && CTy->isVector() && "Composite type is not a vector");
1332   const uint64_t ActualSize = CTy->getSizeInBits();
1333 
1334   // Obtain the size of each element in the vector.
1335   DIType *BaseTy = CTy->getBaseType().resolve();
1336   assert(BaseTy && "Unknown vector element type.");
1337   const uint64_t ElementSize = BaseTy->getSizeInBits();
1338 
1339   // Locate the number of elements in the vector.
1340   const DINodeArray Elements = CTy->getElements();
1341   assert(Elements.size() == 1 &&
1342          Elements[0]->getTag() == dwarf::DW_TAG_subrange_type &&
1343          "Invalid vector element array, expected one element of type subrange");
1344   const auto Subrange = cast<DISubrange>(Elements[0]);
1345   const auto CI = Subrange->getCount().get<ConstantInt *>();
1346   const int32_t NumVecElements = CI->getSExtValue();
1347 
1348   // Ensure we found the element count and that the actual size is wide
1349   // enough to contain the requested size.
1350   assert(ActualSize >= (NumVecElements * ElementSize) && "Invalid vector size");
1351   return ActualSize != (NumVecElements * ElementSize);
1352 }
1353 
1354 void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
1355   if (CTy->isVector()) {
1356     addFlag(Buffer, dwarf::DW_AT_GNU_vector);
1357     if (hasVectorBeenPadded(CTy))
1358       addUInt(Buffer, dwarf::DW_AT_byte_size, None,
1359               CTy->getSizeInBits() / CHAR_BIT);
1360   }
1361 
1362   // Emit the element type.
1363   addType(Buffer, resolve(CTy->getBaseType()));
1364 
1365   // Get an anonymous type for index type.
1366   // FIXME: This type should be passed down from the front end
1367   // as different languages may have different sizes for indexes.
1368   DIE *IdxTy = getIndexTyDie();
1369 
1370   // Add subranges to array type.
1371   DINodeArray Elements = CTy->getElements();
1372   for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
1373     // FIXME: Should this really be such a loose cast?
1374     if (auto *Element = dyn_cast_or_null<DINode>(Elements[i]))
1375       if (Element->getTag() == dwarf::DW_TAG_subrange_type)
1376         constructSubrangeDIE(Buffer, cast<DISubrange>(Element), IdxTy);
1377   }
1378 }
1379 
1380 void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
1381   const DIType *DTy = resolve(CTy->getBaseType());
1382   bool IsUnsigned = DTy && isUnsignedDIType(DD, DTy);
1383   if (DTy) {
1384     if (DD->getDwarfVersion() >= 3)
1385       addType(Buffer, DTy);
1386     if (DD->getDwarfVersion() >= 4 && (CTy->getFlags() & DINode::FlagEnumClass))
1387       addFlag(Buffer, dwarf::DW_AT_enum_class);
1388   }
1389 
1390   DINodeArray Elements = CTy->getElements();
1391 
1392   // Add enumerators to enumeration type.
1393   for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
1394     auto *Enum = dyn_cast_or_null<DIEnumerator>(Elements[i]);
1395     if (Enum) {
1396       DIE &Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
1397       StringRef Name = Enum->getName();
1398       addString(Enumerator, dwarf::DW_AT_name, Name);
1399       auto Value = static_cast<uint64_t>(Enum->getValue());
1400       addConstantValue(Enumerator, IsUnsigned, Value);
1401     }
1402   }
1403 }
1404 
1405 void DwarfUnit::constructContainingTypeDIEs() {
1406   for (auto CI = ContainingTypeMap.begin(), CE = ContainingTypeMap.end();
1407        CI != CE; ++CI) {
1408     DIE &SPDie = *CI->first;
1409     const DINode *D = CI->second;
1410     if (!D)
1411       continue;
1412     DIE *NDie = getDIE(D);
1413     if (!NDie)
1414       continue;
1415     addDIEEntry(SPDie, dwarf::DW_AT_containing_type, *NDie);
1416   }
1417 }
1418 
1419 DIE &DwarfUnit::constructMemberDIE(DIE &Buffer, const DIDerivedType *DT) {
1420   DIE &MemberDie = createAndAddDIE(DT->getTag(), Buffer);
1421   StringRef Name = DT->getName();
1422   if (!Name.empty())
1423     addString(MemberDie, dwarf::DW_AT_name, Name);
1424 
1425   if (DIType *Resolved = resolve(DT->getBaseType()))
1426     addType(MemberDie, Resolved);
1427 
1428   addSourceLine(MemberDie, DT);
1429 
1430   if (DT->getTag() == dwarf::DW_TAG_inheritance && DT->isVirtual()) {
1431 
1432     // For C++, virtual base classes are not at fixed offset. Use following
1433     // expression to extract appropriate offset from vtable.
1434     // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1435 
1436     DIELoc *VBaseLocationDie = new (DIEValueAllocator) DIELoc;
1437     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1438     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1439     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1440     addUInt(*VBaseLocationDie, dwarf::DW_FORM_udata, DT->getOffsetInBits());
1441     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1442     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1443     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1444 
1445     addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
1446   } else {
1447     uint64_t Size = DT->getSizeInBits();
1448     uint64_t FieldSize = DD->getBaseTypeSize(DT);
1449     uint32_t AlignInBytes = DT->getAlignInBytes();
1450     uint64_t OffsetInBytes;
1451 
1452     bool IsBitfield = FieldSize && Size != FieldSize;
1453     if (IsBitfield) {
1454       // Handle bitfield, assume bytes are 8 bits.
1455       if (DD->useDWARF2Bitfields())
1456         addUInt(MemberDie, dwarf::DW_AT_byte_size, None, FieldSize/8);
1457       addUInt(MemberDie, dwarf::DW_AT_bit_size, None, Size);
1458 
1459       uint64_t Offset = DT->getOffsetInBits();
1460       // We can't use DT->getAlignInBits() here: AlignInBits for member type
1461       // is non-zero if and only if alignment was forced (e.g. _Alignas()),
1462       // which can't be done with bitfields. Thus we use FieldSize here.
1463       uint32_t AlignInBits = FieldSize;
1464       uint32_t AlignMask = ~(AlignInBits - 1);
1465       // The bits from the start of the storage unit to the start of the field.
1466       uint64_t StartBitOffset = Offset - (Offset & AlignMask);
1467       // The byte offset of the field's aligned storage unit inside the struct.
1468       OffsetInBytes = (Offset - StartBitOffset) / 8;
1469 
1470       if (DD->useDWARF2Bitfields()) {
1471         uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1472         uint64_t FieldOffset = (HiMark - FieldSize);
1473         Offset -= FieldOffset;
1474 
1475         // Maybe we need to work from the other end.
1476         if (Asm->getDataLayout().isLittleEndian())
1477           Offset = FieldSize - (Offset + Size);
1478 
1479         addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset);
1480         OffsetInBytes = FieldOffset >> 3;
1481       } else {
1482         addUInt(MemberDie, dwarf::DW_AT_data_bit_offset, None, Offset);
1483       }
1484     } else {
1485       // This is not a bitfield.
1486       OffsetInBytes = DT->getOffsetInBits() / 8;
1487       if (AlignInBytes)
1488         addUInt(MemberDie, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
1489                 AlignInBytes);
1490     }
1491 
1492     if (DD->getDwarfVersion() <= 2) {
1493       DIELoc *MemLocationDie = new (DIEValueAllocator) DIELoc;
1494       addUInt(*MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1495       addUInt(*MemLocationDie, dwarf::DW_FORM_udata, OffsetInBytes);
1496       addBlock(MemberDie, dwarf::DW_AT_data_member_location, MemLocationDie);
1497     } else if (!IsBitfield || DD->useDWARF2Bitfields())
1498       addUInt(MemberDie, dwarf::DW_AT_data_member_location, None,
1499               OffsetInBytes);
1500   }
1501 
1502   if (DT->isProtected())
1503     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1504             dwarf::DW_ACCESS_protected);
1505   else if (DT->isPrivate())
1506     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1507             dwarf::DW_ACCESS_private);
1508   // Otherwise C++ member and base classes are considered public.
1509   else if (DT->isPublic())
1510     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1511             dwarf::DW_ACCESS_public);
1512   if (DT->isVirtual())
1513     addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1514             dwarf::DW_VIRTUALITY_virtual);
1515 
1516   // Objective-C properties.
1517   if (DINode *PNode = DT->getObjCProperty())
1518     if (DIE *PDie = getDIE(PNode))
1519       MemberDie.addValue(DIEValueAllocator, dwarf::DW_AT_APPLE_property,
1520                          dwarf::DW_FORM_ref4, DIEEntry(*PDie));
1521 
1522   if (DT->isArtificial())
1523     addFlag(MemberDie, dwarf::DW_AT_artificial);
1524 
1525   return MemberDie;
1526 }
1527 
1528 DIE *DwarfUnit::getOrCreateStaticMemberDIE(const DIDerivedType *DT) {
1529   if (!DT)
1530     return nullptr;
1531 
1532   // Construct the context before querying for the existence of the DIE in case
1533   // such construction creates the DIE.
1534   DIE *ContextDIE = getOrCreateContextDIE(resolve(DT->getScope()));
1535   assert(dwarf::isType(ContextDIE->getTag()) &&
1536          "Static member should belong to a type.");
1537 
1538   if (DIE *StaticMemberDIE = getDIE(DT))
1539     return StaticMemberDIE;
1540 
1541   DIE &StaticMemberDIE = createAndAddDIE(DT->getTag(), *ContextDIE, DT);
1542 
1543   const DIType *Ty = resolve(DT->getBaseType());
1544 
1545   addString(StaticMemberDIE, dwarf::DW_AT_name, DT->getName());
1546   addType(StaticMemberDIE, Ty);
1547   addSourceLine(StaticMemberDIE, DT);
1548   addFlag(StaticMemberDIE, dwarf::DW_AT_external);
1549   addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
1550 
1551   // FIXME: We could omit private if the parent is a class_type, and
1552   // public if the parent is something else.
1553   if (DT->isProtected())
1554     addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1555             dwarf::DW_ACCESS_protected);
1556   else if (DT->isPrivate())
1557     addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1558             dwarf::DW_ACCESS_private);
1559   else if (DT->isPublic())
1560     addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1561             dwarf::DW_ACCESS_public);
1562 
1563   if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT->getConstant()))
1564     addConstantValue(StaticMemberDIE, CI, Ty);
1565   if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT->getConstant()))
1566     addConstantFPValue(StaticMemberDIE, CFP);
1567 
1568   if (uint32_t AlignInBytes = DT->getAlignInBytes())
1569     addUInt(StaticMemberDIE, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
1570             AlignInBytes);
1571 
1572   return &StaticMemberDIE;
1573 }
1574 
1575 void DwarfUnit::emitCommonHeader(bool UseOffsets, dwarf::UnitType UT) {
1576   // Emit size of content not including length itself
1577   Asm->OutStreamer->AddComment("Length of Unit");
1578   if (!DD->useSectionsAsReferences()) {
1579     StringRef Prefix = isDwoUnit() ? "debug_info_dwo_" : "debug_info_";
1580     MCSymbol *BeginLabel = Asm->createTempSymbol(Prefix + "start");
1581     EndLabel = Asm->createTempSymbol(Prefix + "end");
1582     Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
1583     Asm->OutStreamer->EmitLabel(BeginLabel);
1584   } else
1585     Asm->emitInt32(getHeaderSize() + getUnitDie().getSize());
1586 
1587   Asm->OutStreamer->AddComment("DWARF version number");
1588   unsigned Version = DD->getDwarfVersion();
1589   Asm->emitInt16(Version);
1590 
1591   // DWARF v5 reorders the address size and adds a unit type.
1592   if (Version >= 5) {
1593     Asm->OutStreamer->AddComment("DWARF Unit Type");
1594     Asm->emitInt8(UT);
1595     Asm->OutStreamer->AddComment("Address Size (in bytes)");
1596     Asm->emitInt8(Asm->MAI->getCodePointerSize());
1597   }
1598 
1599   // We share one abbreviations table across all units so it's always at the
1600   // start of the section. Use a relocatable offset where needed to ensure
1601   // linking doesn't invalidate that offset.
1602   Asm->OutStreamer->AddComment("Offset Into Abbrev. Section");
1603   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1604   if (UseOffsets)
1605     Asm->emitInt32(0);
1606   else
1607     Asm->emitDwarfSymbolReference(
1608         TLOF.getDwarfAbbrevSection()->getBeginSymbol(), false);
1609 
1610   if (Version <= 4) {
1611     Asm->OutStreamer->AddComment("Address Size (in bytes)");
1612     Asm->emitInt8(Asm->MAI->getCodePointerSize());
1613   }
1614 }
1615 
1616 void DwarfTypeUnit::emitHeader(bool UseOffsets) {
1617   DwarfUnit::emitCommonHeader(UseOffsets,
1618                               DD->useSplitDwarf() ? dwarf::DW_UT_split_type
1619                                                   : dwarf::DW_UT_type);
1620   Asm->OutStreamer->AddComment("Type Signature");
1621   Asm->OutStreamer->EmitIntValue(TypeSignature, sizeof(TypeSignature));
1622   Asm->OutStreamer->AddComment("Type DIE Offset");
1623   // In a skeleton type unit there is no type DIE so emit a zero offset.
1624   Asm->OutStreamer->EmitIntValue(Ty ? Ty->getOffset() : 0,
1625                                  sizeof(Ty->getOffset()));
1626 }
1627 
1628 DIE::value_iterator
1629 DwarfUnit::addSectionDelta(DIE &Die, dwarf::Attribute Attribute,
1630                            const MCSymbol *Hi, const MCSymbol *Lo) {
1631   return Die.addValue(DIEValueAllocator, Attribute,
1632                       DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
1633                                                  : dwarf::DW_FORM_data4,
1634                       new (DIEValueAllocator) DIEDelta(Hi, Lo));
1635 }
1636 
1637 DIE::value_iterator
1638 DwarfUnit::addSectionLabel(DIE &Die, dwarf::Attribute Attribute,
1639                            const MCSymbol *Label, const MCSymbol *Sec) {
1640   if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
1641     return addLabel(Die, Attribute,
1642                     DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
1643                                                : dwarf::DW_FORM_data4,
1644                     Label);
1645   return addSectionDelta(Die, Attribute, Label, Sec);
1646 }
1647 
1648 bool DwarfTypeUnit::isDwoUnit() const {
1649   // Since there are no skeleton type units, all type units are dwo type units
1650   // when split DWARF is being used.
1651   return DD->useSplitDwarf();
1652 }
1653 
1654 void DwarfTypeUnit::addGlobalName(StringRef Name, const DIE &Die,
1655                                   const DIScope *Context) {
1656   getCU().addGlobalNameForTypeUnit(Name, Context);
1657 }
1658 
1659 void DwarfTypeUnit::addGlobalType(const DIType *Ty, const DIE &Die,
1660                                   const DIScope *Context) {
1661   getCU().addGlobalTypeUnitType(Ty, Context);
1662 }
1663 
1664 const MCSymbol *DwarfUnit::getCrossSectionRelativeBaseAddress() const {
1665   if (!Asm->MAI->doesDwarfUseRelocationsAcrossSections())
1666     return nullptr;
1667   if (isDwoUnit())
1668     return nullptr;
1669   return getSection()->getBeginSymbol();
1670 }
1671 
1672 void DwarfUnit::addStringOffsetsStart() {
1673   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1674   addSectionLabel(getUnitDie(), dwarf::DW_AT_str_offsets_base,
1675                   DU->getStringOffsetsStartSym(),
1676                   TLOF.getDwarfStrOffSection()->getBeginSymbol());
1677 }
1678 
1679 void DwarfUnit::addRnglistsBase() {
1680   assert(DD->getDwarfVersion() >= 5 &&
1681          "DW_AT_rnglists_base requires DWARF version 5 or later");
1682   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1683   addSectionLabel(getUnitDie(), dwarf::DW_AT_rnglists_base,
1684                   DU->getRnglistsTableBaseSym(),
1685                   TLOF.getDwarfRnglistsSection()->getBeginSymbol());
1686 }
1687 
1688 void DwarfUnit::addLoclistsBase() {
1689   assert(DD->getDwarfVersion() >= 5 &&
1690          "DW_AT_loclists_base requires DWARF version 5 or later");
1691   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1692   addSectionLabel(getUnitDie(), dwarf::DW_AT_loclists_base,
1693                   DU->getLoclistsTableBaseSym(),
1694                   TLOF.getDwarfLoclistsSection()->getBeginSymbol());
1695 }
1696 
1697 void DwarfTypeUnit::finishNonUnitTypeDIE(DIE& D, const DICompositeType *CTy) {
1698   addFlag(D, dwarf::DW_AT_declaration);
1699   StringRef Name = CTy->getName();
1700   if (!Name.empty())
1701     addString(D, dwarf::DW_AT_name, Name);
1702   getCU().createTypeDIE(CTy);
1703 }
1704