xref: /freebsd/contrib/llvm-project/llvm/lib/CodeGen/AsmPrinter/DwarfUnit.cpp (revision 0b37c1590418417c894529d371800dfac71ef887)
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   if (!M->getSysRoot().empty())
1126     addString(MDie, dwarf::DW_AT_LLVM_sysroot, M->getSysRoot());
1127 
1128   return &MDie;
1129 }
1130 
1131 DIE *DwarfUnit::getOrCreateSubprogramDIE(const DISubprogram *SP, bool Minimal) {
1132   // Construct the context before querying for the existence of the DIE in case
1133   // such construction creates the DIE (as is the case for member function
1134   // declarations).
1135   DIE *ContextDIE =
1136       Minimal ? &getUnitDie() : getOrCreateContextDIE(SP->getScope());
1137 
1138   if (DIE *SPDie = getDIE(SP))
1139     return SPDie;
1140 
1141   if (auto *SPDecl = SP->getDeclaration()) {
1142     if (!Minimal) {
1143       // Add subprogram definitions to the CU die directly.
1144       ContextDIE = &getUnitDie();
1145       // Build the decl now to ensure it precedes the definition.
1146       getOrCreateSubprogramDIE(SPDecl);
1147     }
1148   }
1149 
1150   // DW_TAG_inlined_subroutine may refer to this DIE.
1151   DIE &SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
1152 
1153   // Stop here and fill this in later, depending on whether or not this
1154   // subprogram turns out to have inlined instances or not.
1155   if (SP->isDefinition())
1156     return &SPDie;
1157 
1158   static_cast<DwarfUnit *>(SPDie.getUnit())
1159       ->applySubprogramAttributes(SP, SPDie);
1160   return &SPDie;
1161 }
1162 
1163 bool DwarfUnit::applySubprogramDefinitionAttributes(const DISubprogram *SP,
1164                                                     DIE &SPDie) {
1165   DIE *DeclDie = nullptr;
1166   StringRef DeclLinkageName;
1167   if (auto *SPDecl = SP->getDeclaration()) {
1168     DeclDie = getDIE(SPDecl);
1169     assert(DeclDie && "This DIE should've already been constructed when the "
1170                       "definition DIE was created in "
1171                       "getOrCreateSubprogramDIE");
1172     // Look at the Decl's linkage name only if we emitted it.
1173     if (DD->useAllLinkageNames())
1174       DeclLinkageName = SPDecl->getLinkageName();
1175     unsigned DeclID = getOrCreateSourceID(SPDecl->getFile());
1176     unsigned DefID = getOrCreateSourceID(SP->getFile());
1177     if (DeclID != DefID)
1178       addUInt(SPDie, dwarf::DW_AT_decl_file, None, DefID);
1179 
1180     if (SP->getLine() != SPDecl->getLine())
1181       addUInt(SPDie, dwarf::DW_AT_decl_line, None, SP->getLine());
1182   }
1183 
1184   // Add function template parameters.
1185   addTemplateParams(SPDie, SP->getTemplateParams());
1186 
1187   // Add the linkage name if we have one and it isn't in the Decl.
1188   StringRef LinkageName = SP->getLinkageName();
1189   assert(((LinkageName.empty() || DeclLinkageName.empty()) ||
1190           LinkageName == DeclLinkageName) &&
1191          "decl has a linkage name and it is different");
1192   if (DeclLinkageName.empty() &&
1193       // Always emit it for abstract subprograms.
1194       (DD->useAllLinkageNames() || DU->getAbstractSPDies().lookup(SP)))
1195     addLinkageName(SPDie, LinkageName);
1196 
1197   if (!DeclDie)
1198     return false;
1199 
1200   // Refer to the function declaration where all the other attributes will be
1201   // found.
1202   addDIEEntry(SPDie, dwarf::DW_AT_specification, *DeclDie);
1203   return true;
1204 }
1205 
1206 void DwarfUnit::applySubprogramAttributes(const DISubprogram *SP, DIE &SPDie,
1207                                           bool SkipSPAttributes) {
1208   // If -fdebug-info-for-profiling is enabled, need to emit the subprogram
1209   // and its source location.
1210   bool SkipSPSourceLocation = SkipSPAttributes &&
1211                               !CUNode->getDebugInfoForProfiling();
1212   if (!SkipSPSourceLocation)
1213     if (applySubprogramDefinitionAttributes(SP, SPDie))
1214       return;
1215 
1216   // Constructors and operators for anonymous aggregates do not have names.
1217   if (!SP->getName().empty())
1218     addString(SPDie, dwarf::DW_AT_name, SP->getName());
1219 
1220   if (!SkipSPSourceLocation)
1221     addSourceLine(SPDie, SP);
1222 
1223   // Skip the rest of the attributes under -gmlt to save space.
1224   if (SkipSPAttributes)
1225     return;
1226 
1227   // Add the prototype if we have a prototype and we have a C like
1228   // language.
1229   uint16_t Language = getLanguage();
1230   if (SP->isPrototyped() &&
1231       (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1232        Language == dwarf::DW_LANG_ObjC))
1233     addFlag(SPDie, dwarf::DW_AT_prototyped);
1234 
1235   if (SP->isObjCDirect())
1236     addFlag(SPDie, dwarf::DW_AT_APPLE_objc_direct);
1237 
1238   unsigned CC = 0;
1239   DITypeRefArray Args;
1240   if (const DISubroutineType *SPTy = SP->getType()) {
1241     Args = SPTy->getTypeArray();
1242     CC = SPTy->getCC();
1243   }
1244 
1245   // Add a DW_AT_calling_convention if this has an explicit convention.
1246   if (CC && CC != dwarf::DW_CC_normal)
1247     addUInt(SPDie, dwarf::DW_AT_calling_convention, dwarf::DW_FORM_data1, CC);
1248 
1249   // Add a return type. If this is a type like a C/C++ void type we don't add a
1250   // return type.
1251   if (Args.size())
1252     if (auto Ty = Args[0])
1253       addType(SPDie, Ty);
1254 
1255   unsigned VK = SP->getVirtuality();
1256   if (VK) {
1257     addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1258     if (SP->getVirtualIndex() != -1u) {
1259       DIELoc *Block = getDIELoc();
1260       addUInt(*Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1261       addUInt(*Block, dwarf::DW_FORM_udata, SP->getVirtualIndex());
1262       addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
1263     }
1264     ContainingTypeMap.insert(std::make_pair(&SPDie, SP->getContainingType()));
1265   }
1266 
1267   if (!SP->isDefinition()) {
1268     addFlag(SPDie, dwarf::DW_AT_declaration);
1269 
1270     // Add arguments. Do not add arguments for subprogram definition. They will
1271     // be handled while processing variables.
1272     constructSubprogramArguments(SPDie, Args);
1273   }
1274 
1275   addThrownTypes(SPDie, SP->getThrownTypes());
1276 
1277   if (SP->isArtificial())
1278     addFlag(SPDie, dwarf::DW_AT_artificial);
1279 
1280   if (!SP->isLocalToUnit())
1281     addFlag(SPDie, dwarf::DW_AT_external);
1282 
1283   if (DD->useAppleExtensionAttributes()) {
1284     if (SP->isOptimized())
1285       addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1286 
1287     if (unsigned isa = Asm->getISAEncoding())
1288       addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1289   }
1290 
1291   if (SP->isLValueReference())
1292     addFlag(SPDie, dwarf::DW_AT_reference);
1293 
1294   if (SP->isRValueReference())
1295     addFlag(SPDie, dwarf::DW_AT_rvalue_reference);
1296 
1297   if (SP->isNoReturn())
1298     addFlag(SPDie, dwarf::DW_AT_noreturn);
1299 
1300   if (SP->isProtected())
1301     addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1302             dwarf::DW_ACCESS_protected);
1303   else if (SP->isPrivate())
1304     addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1305             dwarf::DW_ACCESS_private);
1306   else if (SP->isPublic())
1307     addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1308             dwarf::DW_ACCESS_public);
1309 
1310   if (SP->isExplicit())
1311     addFlag(SPDie, dwarf::DW_AT_explicit);
1312 
1313   if (SP->isMainSubprogram())
1314     addFlag(SPDie, dwarf::DW_AT_main_subprogram);
1315   if (SP->isPure())
1316     addFlag(SPDie, dwarf::DW_AT_pure);
1317   if (SP->isElemental())
1318     addFlag(SPDie, dwarf::DW_AT_elemental);
1319   if (SP->isRecursive())
1320     addFlag(SPDie, dwarf::DW_AT_recursive);
1321 
1322   if (DD->getDwarfVersion() >= 5 && SP->isDeleted())
1323     addFlag(SPDie, dwarf::DW_AT_deleted);
1324 }
1325 
1326 void DwarfUnit::constructSubrangeDIE(DIE &Buffer, const DISubrange *SR,
1327                                      DIE *IndexTy) {
1328   DIE &DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
1329   addDIEEntry(DW_Subrange, dwarf::DW_AT_type, *IndexTy);
1330 
1331   // The LowerBound value defines the lower bounds which is typically zero for
1332   // C/C++. The Count value is the number of elements.  Values are 64 bit. If
1333   // Count == -1 then the array is unbounded and we do not emit
1334   // DW_AT_lower_bound and DW_AT_count attributes.
1335   int64_t LowerBound = SR->getLowerBound();
1336   int64_t DefaultLowerBound = getDefaultLowerBound();
1337   int64_t Count = -1;
1338   if (auto *CI = SR->getCount().dyn_cast<ConstantInt*>())
1339     Count = CI->getSExtValue();
1340 
1341   if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
1342     addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound);
1343 
1344   if (auto *CV = SR->getCount().dyn_cast<DIVariable*>()) {
1345     if (auto *CountVarDIE = getDIE(CV))
1346       addDIEEntry(DW_Subrange, dwarf::DW_AT_count, *CountVarDIE);
1347   } else if (Count != -1)
1348     addUInt(DW_Subrange, dwarf::DW_AT_count, None, Count);
1349 }
1350 
1351 DIE *DwarfUnit::getIndexTyDie() {
1352   if (IndexTyDie)
1353     return IndexTyDie;
1354   // Construct an integer type to use for indexes.
1355   IndexTyDie = &createAndAddDIE(dwarf::DW_TAG_base_type, getUnitDie());
1356   StringRef Name = "__ARRAY_SIZE_TYPE__";
1357   addString(*IndexTyDie, dwarf::DW_AT_name, Name);
1358   addUInt(*IndexTyDie, dwarf::DW_AT_byte_size, None, sizeof(int64_t));
1359   addUInt(*IndexTyDie, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1360           dwarf::DW_ATE_unsigned);
1361   DD->addAccelType(*CUNode, Name, *IndexTyDie, /*Flags*/ 0);
1362   return IndexTyDie;
1363 }
1364 
1365 /// Returns true if the vector's size differs from the sum of sizes of elements
1366 /// the user specified.  This can occur if the vector has been rounded up to
1367 /// fit memory alignment constraints.
1368 static bool hasVectorBeenPadded(const DICompositeType *CTy) {
1369   assert(CTy && CTy->isVector() && "Composite type is not a vector");
1370   const uint64_t ActualSize = CTy->getSizeInBits();
1371 
1372   // Obtain the size of each element in the vector.
1373   DIType *BaseTy = CTy->getBaseType();
1374   assert(BaseTy && "Unknown vector element type.");
1375   const uint64_t ElementSize = BaseTy->getSizeInBits();
1376 
1377   // Locate the number of elements in the vector.
1378   const DINodeArray Elements = CTy->getElements();
1379   assert(Elements.size() == 1 &&
1380          Elements[0]->getTag() == dwarf::DW_TAG_subrange_type &&
1381          "Invalid vector element array, expected one element of type subrange");
1382   const auto Subrange = cast<DISubrange>(Elements[0]);
1383   const auto CI = Subrange->getCount().get<ConstantInt *>();
1384   const int32_t NumVecElements = CI->getSExtValue();
1385 
1386   // Ensure we found the element count and that the actual size is wide
1387   // enough to contain the requested size.
1388   assert(ActualSize >= (NumVecElements * ElementSize) && "Invalid vector size");
1389   return ActualSize != (NumVecElements * ElementSize);
1390 }
1391 
1392 void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
1393   if (CTy->isVector()) {
1394     addFlag(Buffer, dwarf::DW_AT_GNU_vector);
1395     if (hasVectorBeenPadded(CTy))
1396       addUInt(Buffer, dwarf::DW_AT_byte_size, None,
1397               CTy->getSizeInBits() / CHAR_BIT);
1398   }
1399 
1400   // Emit the element type.
1401   addType(Buffer, CTy->getBaseType());
1402 
1403   // Get an anonymous type for index type.
1404   // FIXME: This type should be passed down from the front end
1405   // as different languages may have different sizes for indexes.
1406   DIE *IdxTy = getIndexTyDie();
1407 
1408   // Add subranges to array type.
1409   DINodeArray Elements = CTy->getElements();
1410   for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
1411     // FIXME: Should this really be such a loose cast?
1412     if (auto *Element = dyn_cast_or_null<DINode>(Elements[i]))
1413       if (Element->getTag() == dwarf::DW_TAG_subrange_type)
1414         constructSubrangeDIE(Buffer, cast<DISubrange>(Element), IdxTy);
1415   }
1416 }
1417 
1418 void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
1419   const DIType *DTy = CTy->getBaseType();
1420   bool IsUnsigned = DTy && isUnsignedDIType(DD, DTy);
1421   if (DTy) {
1422     if (DD->getDwarfVersion() >= 3)
1423       addType(Buffer, DTy);
1424     if (DD->getDwarfVersion() >= 4 && (CTy->getFlags() & DINode::FlagEnumClass))
1425       addFlag(Buffer, dwarf::DW_AT_enum_class);
1426   }
1427 
1428   auto *Context = CTy->getScope();
1429   bool IndexEnumerators = !Context || isa<DICompileUnit>(Context) || isa<DIFile>(Context) ||
1430       isa<DINamespace>(Context) || isa<DICommonBlock>(Context);
1431   DINodeArray Elements = CTy->getElements();
1432 
1433   // Add enumerators to enumeration type.
1434   for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
1435     auto *Enum = dyn_cast_or_null<DIEnumerator>(Elements[i]);
1436     if (Enum) {
1437       DIE &Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
1438       StringRef Name = Enum->getName();
1439       addString(Enumerator, dwarf::DW_AT_name, Name);
1440       auto Value = static_cast<uint64_t>(Enum->getValue());
1441       addConstantValue(Enumerator, IsUnsigned, Value);
1442       if (IndexEnumerators)
1443         addGlobalName(Name, Enumerator, Context);
1444     }
1445   }
1446 }
1447 
1448 void DwarfUnit::constructContainingTypeDIEs() {
1449   for (auto CI = ContainingTypeMap.begin(), CE = ContainingTypeMap.end();
1450        CI != CE; ++CI) {
1451     DIE &SPDie = *CI->first;
1452     const DINode *D = CI->second;
1453     if (!D)
1454       continue;
1455     DIE *NDie = getDIE(D);
1456     if (!NDie)
1457       continue;
1458     addDIEEntry(SPDie, dwarf::DW_AT_containing_type, *NDie);
1459   }
1460 }
1461 
1462 DIE &DwarfUnit::constructMemberDIE(DIE &Buffer, const DIDerivedType *DT) {
1463   DIE &MemberDie = createAndAddDIE(DT->getTag(), Buffer);
1464   StringRef Name = DT->getName();
1465   if (!Name.empty())
1466     addString(MemberDie, dwarf::DW_AT_name, Name);
1467 
1468   if (DIType *Resolved = DT->getBaseType())
1469     addType(MemberDie, Resolved);
1470 
1471   addSourceLine(MemberDie, DT);
1472 
1473   if (DT->getTag() == dwarf::DW_TAG_inheritance && DT->isVirtual()) {
1474 
1475     // For C++, virtual base classes are not at fixed offset. Use following
1476     // expression to extract appropriate offset from vtable.
1477     // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1478 
1479     DIELoc *VBaseLocationDie = new (DIEValueAllocator) DIELoc;
1480     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1481     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1482     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1483     addUInt(*VBaseLocationDie, dwarf::DW_FORM_udata, DT->getOffsetInBits());
1484     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1485     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1486     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1487 
1488     addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
1489   } else {
1490     uint64_t Size = DT->getSizeInBits();
1491     uint64_t FieldSize = DD->getBaseTypeSize(DT);
1492     uint32_t AlignInBytes = DT->getAlignInBytes();
1493     uint64_t OffsetInBytes;
1494 
1495     bool IsBitfield = FieldSize && Size != FieldSize;
1496     if (IsBitfield) {
1497       // Handle bitfield, assume bytes are 8 bits.
1498       if (DD->useDWARF2Bitfields())
1499         addUInt(MemberDie, dwarf::DW_AT_byte_size, None, FieldSize/8);
1500       addUInt(MemberDie, dwarf::DW_AT_bit_size, None, Size);
1501 
1502       uint64_t Offset = DT->getOffsetInBits();
1503       // We can't use DT->getAlignInBits() here: AlignInBits for member type
1504       // is non-zero if and only if alignment was forced (e.g. _Alignas()),
1505       // which can't be done with bitfields. Thus we use FieldSize here.
1506       uint32_t AlignInBits = FieldSize;
1507       uint32_t AlignMask = ~(AlignInBits - 1);
1508       // The bits from the start of the storage unit to the start of the field.
1509       uint64_t StartBitOffset = Offset - (Offset & AlignMask);
1510       // The byte offset of the field's aligned storage unit inside the struct.
1511       OffsetInBytes = (Offset - StartBitOffset) / 8;
1512 
1513       if (DD->useDWARF2Bitfields()) {
1514         uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1515         uint64_t FieldOffset = (HiMark - FieldSize);
1516         Offset -= FieldOffset;
1517 
1518         // Maybe we need to work from the other end.
1519         if (Asm->getDataLayout().isLittleEndian())
1520           Offset = FieldSize - (Offset + Size);
1521 
1522         addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset);
1523         OffsetInBytes = FieldOffset >> 3;
1524       } else {
1525         addUInt(MemberDie, dwarf::DW_AT_data_bit_offset, None, Offset);
1526       }
1527     } else {
1528       // This is not a bitfield.
1529       OffsetInBytes = DT->getOffsetInBits() / 8;
1530       if (AlignInBytes)
1531         addUInt(MemberDie, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
1532                 AlignInBytes);
1533     }
1534 
1535     if (DD->getDwarfVersion() <= 2) {
1536       DIELoc *MemLocationDie = new (DIEValueAllocator) DIELoc;
1537       addUInt(*MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1538       addUInt(*MemLocationDie, dwarf::DW_FORM_udata, OffsetInBytes);
1539       addBlock(MemberDie, dwarf::DW_AT_data_member_location, MemLocationDie);
1540     } else if (!IsBitfield || DD->useDWARF2Bitfields())
1541       addUInt(MemberDie, dwarf::DW_AT_data_member_location, None,
1542               OffsetInBytes);
1543   }
1544 
1545   if (DT->isProtected())
1546     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1547             dwarf::DW_ACCESS_protected);
1548   else if (DT->isPrivate())
1549     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1550             dwarf::DW_ACCESS_private);
1551   // Otherwise C++ member and base classes are considered public.
1552   else if (DT->isPublic())
1553     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1554             dwarf::DW_ACCESS_public);
1555   if (DT->isVirtual())
1556     addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1557             dwarf::DW_VIRTUALITY_virtual);
1558 
1559   // Objective-C properties.
1560   if (DINode *PNode = DT->getObjCProperty())
1561     if (DIE *PDie = getDIE(PNode))
1562       MemberDie.addValue(DIEValueAllocator, dwarf::DW_AT_APPLE_property,
1563                          dwarf::DW_FORM_ref4, DIEEntry(*PDie));
1564 
1565   if (DT->isArtificial())
1566     addFlag(MemberDie, dwarf::DW_AT_artificial);
1567 
1568   return MemberDie;
1569 }
1570 
1571 DIE *DwarfUnit::getOrCreateStaticMemberDIE(const DIDerivedType *DT) {
1572   if (!DT)
1573     return nullptr;
1574 
1575   // Construct the context before querying for the existence of the DIE in case
1576   // such construction creates the DIE.
1577   DIE *ContextDIE = getOrCreateContextDIE(DT->getScope());
1578   assert(dwarf::isType(ContextDIE->getTag()) &&
1579          "Static member should belong to a type.");
1580 
1581   if (DIE *StaticMemberDIE = getDIE(DT))
1582     return StaticMemberDIE;
1583 
1584   DIE &StaticMemberDIE = createAndAddDIE(DT->getTag(), *ContextDIE, DT);
1585 
1586   const DIType *Ty = DT->getBaseType();
1587 
1588   addString(StaticMemberDIE, dwarf::DW_AT_name, DT->getName());
1589   addType(StaticMemberDIE, Ty);
1590   addSourceLine(StaticMemberDIE, DT);
1591   addFlag(StaticMemberDIE, dwarf::DW_AT_external);
1592   addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
1593 
1594   // FIXME: We could omit private if the parent is a class_type, and
1595   // public if the parent is something else.
1596   if (DT->isProtected())
1597     addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1598             dwarf::DW_ACCESS_protected);
1599   else if (DT->isPrivate())
1600     addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1601             dwarf::DW_ACCESS_private);
1602   else if (DT->isPublic())
1603     addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1604             dwarf::DW_ACCESS_public);
1605 
1606   if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT->getConstant()))
1607     addConstantValue(StaticMemberDIE, CI, Ty);
1608   if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT->getConstant()))
1609     addConstantFPValue(StaticMemberDIE, CFP);
1610 
1611   if (uint32_t AlignInBytes = DT->getAlignInBytes())
1612     addUInt(StaticMemberDIE, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
1613             AlignInBytes);
1614 
1615   return &StaticMemberDIE;
1616 }
1617 
1618 void DwarfUnit::emitCommonHeader(bool UseOffsets, dwarf::UnitType UT) {
1619   // Emit size of content not including length itself
1620   Asm->OutStreamer->AddComment("Length of Unit");
1621   if (!DD->useSectionsAsReferences()) {
1622     StringRef Prefix = isDwoUnit() ? "debug_info_dwo_" : "debug_info_";
1623     MCSymbol *BeginLabel = Asm->createTempSymbol(Prefix + "start");
1624     EndLabel = Asm->createTempSymbol(Prefix + "end");
1625     Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
1626     Asm->OutStreamer->EmitLabel(BeginLabel);
1627   } else
1628     Asm->emitInt32(getHeaderSize() + getUnitDie().getSize());
1629 
1630   Asm->OutStreamer->AddComment("DWARF version number");
1631   unsigned Version = DD->getDwarfVersion();
1632   Asm->emitInt16(Version);
1633 
1634   // DWARF v5 reorders the address size and adds a unit type.
1635   if (Version >= 5) {
1636     Asm->OutStreamer->AddComment("DWARF Unit Type");
1637     Asm->emitInt8(UT);
1638     Asm->OutStreamer->AddComment("Address Size (in bytes)");
1639     Asm->emitInt8(Asm->MAI->getCodePointerSize());
1640   }
1641 
1642   // We share one abbreviations table across all units so it's always at the
1643   // start of the section. Use a relocatable offset where needed to ensure
1644   // linking doesn't invalidate that offset.
1645   Asm->OutStreamer->AddComment("Offset Into Abbrev. Section");
1646   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1647   if (UseOffsets)
1648     Asm->emitInt32(0);
1649   else
1650     Asm->emitDwarfSymbolReference(
1651         TLOF.getDwarfAbbrevSection()->getBeginSymbol(), false);
1652 
1653   if (Version <= 4) {
1654     Asm->OutStreamer->AddComment("Address Size (in bytes)");
1655     Asm->emitInt8(Asm->MAI->getCodePointerSize());
1656   }
1657 }
1658 
1659 void DwarfTypeUnit::emitHeader(bool UseOffsets) {
1660   DwarfUnit::emitCommonHeader(UseOffsets,
1661                               DD->useSplitDwarf() ? dwarf::DW_UT_split_type
1662                                                   : dwarf::DW_UT_type);
1663   Asm->OutStreamer->AddComment("Type Signature");
1664   Asm->OutStreamer->EmitIntValue(TypeSignature, sizeof(TypeSignature));
1665   Asm->OutStreamer->AddComment("Type DIE Offset");
1666   // In a skeleton type unit there is no type DIE so emit a zero offset.
1667   Asm->OutStreamer->EmitIntValue(Ty ? Ty->getOffset() : 0,
1668                                  sizeof(Ty->getOffset()));
1669 }
1670 
1671 DIE::value_iterator
1672 DwarfUnit::addSectionDelta(DIE &Die, dwarf::Attribute Attribute,
1673                            const MCSymbol *Hi, const MCSymbol *Lo) {
1674   return Die.addValue(DIEValueAllocator, Attribute,
1675                       DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
1676                                                  : dwarf::DW_FORM_data4,
1677                       new (DIEValueAllocator) DIEDelta(Hi, Lo));
1678 }
1679 
1680 DIE::value_iterator
1681 DwarfUnit::addSectionLabel(DIE &Die, dwarf::Attribute Attribute,
1682                            const MCSymbol *Label, const MCSymbol *Sec) {
1683   if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
1684     return addLabel(Die, Attribute,
1685                     DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
1686                                                : dwarf::DW_FORM_data4,
1687                     Label);
1688   return addSectionDelta(Die, Attribute, Label, Sec);
1689 }
1690 
1691 bool DwarfTypeUnit::isDwoUnit() const {
1692   // Since there are no skeleton type units, all type units are dwo type units
1693   // when split DWARF is being used.
1694   return DD->useSplitDwarf();
1695 }
1696 
1697 void DwarfTypeUnit::addGlobalName(StringRef Name, const DIE &Die,
1698                                   const DIScope *Context) {
1699   getCU().addGlobalNameForTypeUnit(Name, Context);
1700 }
1701 
1702 void DwarfTypeUnit::addGlobalType(const DIType *Ty, const DIE &Die,
1703                                   const DIScope *Context) {
1704   getCU().addGlobalTypeUnitType(Ty, Context);
1705 }
1706 
1707 const MCSymbol *DwarfUnit::getCrossSectionRelativeBaseAddress() const {
1708   if (!Asm->MAI->doesDwarfUseRelocationsAcrossSections())
1709     return nullptr;
1710   if (isDwoUnit())
1711     return nullptr;
1712   return getSection()->getBeginSymbol();
1713 }
1714 
1715 void DwarfUnit::addStringOffsetsStart() {
1716   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1717   addSectionLabel(getUnitDie(), dwarf::DW_AT_str_offsets_base,
1718                   DU->getStringOffsetsStartSym(),
1719                   TLOF.getDwarfStrOffSection()->getBeginSymbol());
1720 }
1721 
1722 void DwarfUnit::addRnglistsBase() {
1723   assert(DD->getDwarfVersion() >= 5 &&
1724          "DW_AT_rnglists_base requires DWARF version 5 or later");
1725   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1726   addSectionLabel(getUnitDie(), dwarf::DW_AT_rnglists_base,
1727                   DU->getRnglistsTableBaseSym(),
1728                   TLOF.getDwarfRnglistsSection()->getBeginSymbol());
1729 }
1730 
1731 void DwarfTypeUnit::finishNonUnitTypeDIE(DIE& D, const DICompositeType *CTy) {
1732   addFlag(D, dwarf::DW_AT_declaration);
1733   StringRef Name = CTy->getName();
1734   if (!Name.empty())
1735     addString(D, dwarf::DW_AT_name, Name);
1736   getCU().createTypeDIE(CTy);
1737 }
1738