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