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