DwarfUnit.cpp revision 360784
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
45using namespace llvm;
46
47#define DEBUG_TYPE "dwarfdebug"
48
49DIEDwarfExpression::DIEDwarfExpression(const AsmPrinter &AP,
50                                       DwarfCompileUnit &CU, DIELoc &DIE)
51    : DwarfExpression(AP.getDwarfVersion(), CU), AP(AP), OutDIE(DIE) {}
52
53void DIEDwarfExpression::emitOp(uint8_t Op, const char* Comment) {
54  CU.addUInt(getActiveDIE(), dwarf::DW_FORM_data1, Op);
55}
56
57void DIEDwarfExpression::emitSigned(int64_t Value) {
58  CU.addSInt(getActiveDIE(), dwarf::DW_FORM_sdata, Value);
59}
60
61void DIEDwarfExpression::emitUnsigned(uint64_t Value) {
62  CU.addUInt(getActiveDIE(), dwarf::DW_FORM_udata, Value);
63}
64
65void DIEDwarfExpression::emitData1(uint8_t Value) {
66  CU.addUInt(getActiveDIE(), dwarf::DW_FORM_data1, Value);
67}
68
69void DIEDwarfExpression::emitBaseTypeRef(uint64_t Idx) {
70  CU.addBaseTypeRef(getActiveDIE(), Idx);
71}
72
73void DIEDwarfExpression::enableTemporaryBuffer() {
74  assert(!IsBuffering && "Already buffering?");
75  IsBuffering = true;
76}
77
78void DIEDwarfExpression::disableTemporaryBuffer() { IsBuffering = false; }
79
80unsigned DIEDwarfExpression::getTemporaryBufferSize() {
81  return TmpDIE.ComputeSize(&AP);
82}
83
84void DIEDwarfExpression::commitTemporaryBuffer() { OutDIE.takeValues(TmpDIE); }
85
86bool DIEDwarfExpression::isFrameRegister(const TargetRegisterInfo &TRI,
87                                         unsigned MachineReg) {
88  return MachineReg == TRI.getFrameRegister(*AP.MF);
89}
90
91DwarfUnit::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
97DwarfTypeUnit::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
104DwarfUnit::~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
111int64_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.
190bool 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
205DIE *DwarfUnit::getDIE(const DINode *D) const {
206  if (isShareableAcrossCUs(D))
207    return DU->getDIE(D);
208  return MDNodeToDieMap.lookup(D);
209}
210
211void 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
219void DwarfUnit::insertDIE(DIE *D) {
220  MDNodeToDieMap.insert(std::make_pair(nullptr, D));
221}
222
223void 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
232void 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
241void DwarfUnit::addUInt(DIEValueList &Block, dwarf::Form Form,
242                        uint64_t Integer) {
243  addUInt(Block, (dwarf::Attribute)0, Form, Integer);
244}
245
246void 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
253void DwarfUnit::addSInt(DIELoc &Die, Optional<dwarf::Form> Form,
254                        int64_t Integer) {
255  addSInt(Die, (dwarf::Attribute)0, Form, Integer);
256}
257
258void 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
292DIEValueList::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
299void DwarfUnit::addLabel(DIELoc &Die, dwarf::Form Form, const MCSymbol *Label) {
300  addLabel(Die, (dwarf::Attribute)0, Form, Label);
301}
302
303void 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
311Optional<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
328unsigned 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
342void 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
360void 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
366void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute, DIE &Entry) {
367  addDIEEntry(Die, Attribute, DIEEntry(Entry));
368}
369
370void 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
381void 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
395DIE &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
402void 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
409void 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
416void 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
425void DwarfUnit::addSourceLine(DIE &Die, const DILocalVariable *V) {
426  assert(V);
427
428  addSourceLine(Die, V->getLine(), V->getFile());
429}
430
431void DwarfUnit::addSourceLine(DIE &Die, const DIGlobalVariable *G) {
432  assert(G);
433
434  addSourceLine(Die, G->getLine(), G->getFile());
435}
436
437void DwarfUnit::addSourceLine(DIE &Die, const DISubprogram *SP) {
438  assert(SP);
439
440  addSourceLine(Die, SP->getLine(), SP->getFile());
441}
442
443void DwarfUnit::addSourceLine(DIE &Die, const DILabel *L) {
444  assert(L);
445
446  addSourceLine(Die, L->getLine(), L->getFile());
447}
448
449void DwarfUnit::addSourceLine(DIE &Die, const DIType *Ty) {
450  assert(Ty);
451
452  addSourceLine(Die, Ty->getLine(), Ty->getFile());
453}
454
455void 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.
462static 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
510void 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
532void 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
537void DwarfUnit::addConstantValue(DIE &Die, const ConstantInt *CI,
538                                 const DIType *Ty) {
539  addConstantValue(Die, CI->getValue(), Ty);
540}
541
542void 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
549void DwarfUnit::addConstantValue(DIE &Die, uint64_t Val, const DIType *Ty) {
550  addConstantValue(Die, isUnsignedDIType(DD, Ty), Val);
551}
552
553void 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
560void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, const DIType *Ty) {
561  addConstantValue(Die, Val, isUnsignedDIType(DD, Ty));
562}
563
564void 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
593void 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
601void 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.
612void 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
619DIE *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
633DIE *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
649DIE *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
680DIE *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
707void 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
725void 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
731std::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
765void 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
788void 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  // If alignment is specified for a typedef , create and insert DW_AT_alignment
804  // attribute in DW_TAG_typedef DIE.
805  if (Tag == dwarf::DW_TAG_typedef && DD->getDwarfVersion() >= 5) {
806    uint32_t AlignInBytes = DTy->getAlignInBytes();
807    if (AlignInBytes > 0)
808      addUInt(Buffer, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
809              AlignInBytes);
810  }
811
812  // Add size if non-zero (derived types might be zero-sized.)
813  if (Size && Tag != dwarf::DW_TAG_pointer_type
814           && Tag != dwarf::DW_TAG_ptr_to_member_type
815           && Tag != dwarf::DW_TAG_reference_type
816           && Tag != dwarf::DW_TAG_rvalue_reference_type)
817    addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
818
819  if (Tag == dwarf::DW_TAG_ptr_to_member_type)
820    addDIEEntry(Buffer, dwarf::DW_AT_containing_type,
821                *getOrCreateTypeDIE(cast<DIDerivedType>(DTy)->getClassType()));
822  // Add source line info if available and TyDesc is not a forward declaration.
823  if (!DTy->isForwardDecl())
824    addSourceLine(Buffer, DTy);
825
826  // If DWARF address space value is other than None, add it.  The IR
827  // verifier checks that DWARF address space only exists for pointer
828  // or reference types.
829  if (DTy->getDWARFAddressSpace())
830    addUInt(Buffer, dwarf::DW_AT_address_class, dwarf::DW_FORM_data4,
831            DTy->getDWARFAddressSpace().getValue());
832}
833
834void DwarfUnit::constructSubprogramArguments(DIE &Buffer, DITypeRefArray Args) {
835  for (unsigned i = 1, N = Args.size(); i < N; ++i) {
836    const DIType *Ty = Args[i];
837    if (!Ty) {
838      assert(i == N-1 && "Unspecified parameter must be the last argument");
839      createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
840    } else {
841      DIE &Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
842      addType(Arg, Ty);
843      if (Ty->isArtificial())
844        addFlag(Arg, dwarf::DW_AT_artificial);
845    }
846  }
847}
848
849void DwarfUnit::constructTypeDIE(DIE &Buffer, const DISubroutineType *CTy) {
850  // Add return type.  A void return won't have a type.
851  auto Elements = cast<DISubroutineType>(CTy)->getTypeArray();
852  if (Elements.size())
853    if (auto RTy = Elements[0])
854      addType(Buffer, RTy);
855
856  bool isPrototyped = true;
857  if (Elements.size() == 2 && !Elements[1])
858    isPrototyped = false;
859
860  constructSubprogramArguments(Buffer, Elements);
861
862  // Add prototype flag if we're dealing with a C language and the function has
863  // been prototyped.
864  uint16_t Language = getLanguage();
865  if (isPrototyped &&
866      (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
867       Language == dwarf::DW_LANG_ObjC))
868    addFlag(Buffer, dwarf::DW_AT_prototyped);
869
870  // Add a DW_AT_calling_convention if this has an explicit convention.
871  if (CTy->getCC() && CTy->getCC() != dwarf::DW_CC_normal)
872    addUInt(Buffer, dwarf::DW_AT_calling_convention, dwarf::DW_FORM_data1,
873            CTy->getCC());
874
875  if (CTy->isLValueReference())
876    addFlag(Buffer, dwarf::DW_AT_reference);
877
878  if (CTy->isRValueReference())
879    addFlag(Buffer, dwarf::DW_AT_rvalue_reference);
880}
881
882void DwarfUnit::constructTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
883  // Add name if not anonymous or intermediate type.
884  StringRef Name = CTy->getName();
885
886  uint64_t Size = CTy->getSizeInBits() >> 3;
887  uint16_t Tag = Buffer.getTag();
888
889  switch (Tag) {
890  case dwarf::DW_TAG_array_type:
891    constructArrayTypeDIE(Buffer, CTy);
892    break;
893  case dwarf::DW_TAG_enumeration_type:
894    constructEnumTypeDIE(Buffer, CTy);
895    break;
896  case dwarf::DW_TAG_variant_part:
897  case dwarf::DW_TAG_structure_type:
898  case dwarf::DW_TAG_union_type:
899  case dwarf::DW_TAG_class_type: {
900    // Emit the discriminator for a variant part.
901    DIDerivedType *Discriminator = nullptr;
902    if (Tag == dwarf::DW_TAG_variant_part) {
903      Discriminator = CTy->getDiscriminator();
904      if (Discriminator) {
905        // DWARF says:
906        //    If the variant part has a discriminant, the discriminant is
907        //    represented by a separate debugging information entry which is
908        //    a child of the variant part entry.
909        DIE &DiscMember = constructMemberDIE(Buffer, Discriminator);
910        addDIEEntry(Buffer, dwarf::DW_AT_discr, DiscMember);
911      }
912    }
913
914    // Add elements to structure type.
915    DINodeArray Elements = CTy->getElements();
916    for (const auto *Element : Elements) {
917      if (!Element)
918        continue;
919      if (auto *SP = dyn_cast<DISubprogram>(Element))
920        getOrCreateSubprogramDIE(SP);
921      else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
922        if (DDTy->getTag() == dwarf::DW_TAG_friend) {
923          DIE &ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
924          addType(ElemDie, DDTy->getBaseType(), dwarf::DW_AT_friend);
925        } else if (DDTy->isStaticMember()) {
926          getOrCreateStaticMemberDIE(DDTy);
927        } else if (Tag == dwarf::DW_TAG_variant_part) {
928          // When emitting a variant part, wrap each member in
929          // DW_TAG_variant.
930          DIE &Variant = createAndAddDIE(dwarf::DW_TAG_variant, Buffer);
931          if (const ConstantInt *CI =
932              dyn_cast_or_null<ConstantInt>(DDTy->getDiscriminantValue())) {
933            if (isUnsignedDIType(DD, Discriminator->getBaseType()))
934              addUInt(Variant, dwarf::DW_AT_discr_value, None, CI->getZExtValue());
935            else
936              addSInt(Variant, dwarf::DW_AT_discr_value, None, CI->getSExtValue());
937          }
938          constructMemberDIE(Variant, DDTy);
939        } else {
940          constructMemberDIE(Buffer, DDTy);
941        }
942      } else if (auto *Property = dyn_cast<DIObjCProperty>(Element)) {
943        DIE &ElemDie = createAndAddDIE(Property->getTag(), Buffer);
944        StringRef PropertyName = Property->getName();
945        addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
946        if (Property->getType())
947          addType(ElemDie, Property->getType());
948        addSourceLine(ElemDie, Property);
949        StringRef GetterName = Property->getGetterName();
950        if (!GetterName.empty())
951          addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
952        StringRef SetterName = Property->getSetterName();
953        if (!SetterName.empty())
954          addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
955        if (unsigned PropertyAttributes = Property->getAttributes())
956          addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None,
957                  PropertyAttributes);
958      } else if (auto *Composite = dyn_cast<DICompositeType>(Element)) {
959        if (Composite->getTag() == dwarf::DW_TAG_variant_part) {
960          DIE &VariantPart = createAndAddDIE(Composite->getTag(), Buffer);
961          constructTypeDIE(VariantPart, Composite);
962        }
963      }
964    }
965
966    if (CTy->isAppleBlockExtension())
967      addFlag(Buffer, dwarf::DW_AT_APPLE_block);
968
969    if (CTy->getExportSymbols())
970      addFlag(Buffer, dwarf::DW_AT_export_symbols);
971
972    // This is outside the DWARF spec, but GDB expects a DW_AT_containing_type
973    // inside C++ composite types to point to the base class with the vtable.
974    // Rust uses DW_AT_containing_type to link a vtable to the type
975    // for which it was created.
976    if (auto *ContainingType = CTy->getVTableHolder())
977      addDIEEntry(Buffer, dwarf::DW_AT_containing_type,
978                  *getOrCreateTypeDIE(ContainingType));
979
980    if (CTy->isObjcClassComplete())
981      addFlag(Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
982
983    // Add template parameters to a class, structure or union types.
984    // FIXME: The support isn't in the metadata for this yet.
985    if (Tag == dwarf::DW_TAG_class_type ||
986        Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
987      addTemplateParams(Buffer, CTy->getTemplateParams());
988
989    // Add the type's non-standard calling convention.
990    uint8_t CC = 0;
991    if (CTy->isTypePassByValue())
992      CC = dwarf::DW_CC_pass_by_value;
993    else if (CTy->isTypePassByReference())
994      CC = dwarf::DW_CC_pass_by_reference;
995    if (CC)
996      addUInt(Buffer, dwarf::DW_AT_calling_convention, dwarf::DW_FORM_data1,
997              CC);
998    break;
999  }
1000  default:
1001    break;
1002  }
1003
1004  // Add name if not anonymous or intermediate type.
1005  if (!Name.empty())
1006    addString(Buffer, dwarf::DW_AT_name, Name);
1007
1008  if (Tag == dwarf::DW_TAG_enumeration_type ||
1009      Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
1010      Tag == dwarf::DW_TAG_union_type) {
1011    // Add size if non-zero (derived types might be zero-sized.)
1012    // TODO: Do we care about size for enum forward declarations?
1013    if (Size)
1014      addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
1015    else if (!CTy->isForwardDecl())
1016      // Add zero size if it is not a forward declaration.
1017      addUInt(Buffer, dwarf::DW_AT_byte_size, None, 0);
1018
1019    // If we're a forward decl, say so.
1020    if (CTy->isForwardDecl())
1021      addFlag(Buffer, dwarf::DW_AT_declaration);
1022
1023    // Add source line info if available.
1024    if (!CTy->isForwardDecl())
1025      addSourceLine(Buffer, CTy);
1026
1027    // No harm in adding the runtime language to the declaration.
1028    unsigned RLang = CTy->getRuntimeLang();
1029    if (RLang)
1030      addUInt(Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
1031              RLang);
1032
1033    // Add align info if available.
1034    if (uint32_t AlignInBytes = CTy->getAlignInBytes())
1035      addUInt(Buffer, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
1036              AlignInBytes);
1037  }
1038}
1039
1040void DwarfUnit::constructTemplateTypeParameterDIE(
1041    DIE &Buffer, const DITemplateTypeParameter *TP) {
1042  DIE &ParamDIE =
1043      createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
1044  // Add the type if it exists, it could be void and therefore no type.
1045  if (TP->getType())
1046    addType(ParamDIE, TP->getType());
1047  if (!TP->getName().empty())
1048    addString(ParamDIE, dwarf::DW_AT_name, TP->getName());
1049}
1050
1051void DwarfUnit::constructTemplateValueParameterDIE(
1052    DIE &Buffer, const DITemplateValueParameter *VP) {
1053  DIE &ParamDIE = createAndAddDIE(VP->getTag(), Buffer);
1054
1055  // Add the type if there is one, template template and template parameter
1056  // packs will not have a type.
1057  if (VP->getTag() == dwarf::DW_TAG_template_value_parameter)
1058    addType(ParamDIE, VP->getType());
1059  if (!VP->getName().empty())
1060    addString(ParamDIE, dwarf::DW_AT_name, VP->getName());
1061  if (Metadata *Val = VP->getValue()) {
1062    if (ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(Val))
1063      addConstantValue(ParamDIE, CI, VP->getType());
1064    else if (GlobalValue *GV = mdconst::dyn_extract<GlobalValue>(Val)) {
1065      // We cannot describe the location of dllimport'd entities: the
1066      // computation of their address requires loads from the IAT.
1067      if (!GV->hasDLLImportStorageClass()) {
1068        // For declaration non-type template parameters (such as global values
1069        // and functions)
1070        DIELoc *Loc = new (DIEValueAllocator) DIELoc;
1071        addOpAddress(*Loc, Asm->getSymbol(GV));
1072        // Emit DW_OP_stack_value to use the address as the immediate value of
1073        // the parameter, rather than a pointer to it.
1074        addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
1075        addBlock(ParamDIE, dwarf::DW_AT_location, Loc);
1076      }
1077    } else if (VP->getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1078      assert(isa<MDString>(Val));
1079      addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
1080                cast<MDString>(Val)->getString());
1081    } else if (VP->getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1082      addTemplateParams(ParamDIE, cast<MDTuple>(Val));
1083    }
1084  }
1085}
1086
1087DIE *DwarfUnit::getOrCreateNameSpace(const DINamespace *NS) {
1088  // Construct the context before querying for the existence of the DIE in case
1089  // such construction creates the DIE.
1090  DIE *ContextDIE = getOrCreateContextDIE(NS->getScope());
1091
1092  if (DIE *NDie = getDIE(NS))
1093    return NDie;
1094  DIE &NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS);
1095
1096  StringRef Name = NS->getName();
1097  if (!Name.empty())
1098    addString(NDie, dwarf::DW_AT_name, NS->getName());
1099  else
1100    Name = "(anonymous namespace)";
1101  DD->addAccelNamespace(*CUNode, Name, NDie);
1102  addGlobalName(Name, NDie, NS->getScope());
1103  if (NS->getExportSymbols())
1104    addFlag(NDie, dwarf::DW_AT_export_symbols);
1105  return &NDie;
1106}
1107
1108DIE *DwarfUnit::getOrCreateModule(const DIModule *M) {
1109  // Construct the context before querying for the existence of the DIE in case
1110  // such construction creates the DIE.
1111  DIE *ContextDIE = getOrCreateContextDIE(M->getScope());
1112
1113  if (DIE *MDie = getDIE(M))
1114    return MDie;
1115  DIE &MDie = createAndAddDIE(dwarf::DW_TAG_module, *ContextDIE, M);
1116
1117  if (!M->getName().empty()) {
1118    addString(MDie, dwarf::DW_AT_name, M->getName());
1119    addGlobalName(M->getName(), MDie, M->getScope());
1120  }
1121  if (!M->getConfigurationMacros().empty())
1122    addString(MDie, dwarf::DW_AT_LLVM_config_macros,
1123              M->getConfigurationMacros());
1124  if (!M->getIncludePath().empty())
1125    addString(MDie, dwarf::DW_AT_LLVM_include_path, M->getIncludePath());
1126  if (!M->getSysRoot().empty())
1127    addString(MDie, dwarf::DW_AT_LLVM_sysroot, M->getSysRoot());
1128
1129  return &MDie;
1130}
1131
1132DIE *DwarfUnit::getOrCreateSubprogramDIE(const DISubprogram *SP, bool Minimal) {
1133  // Construct the context before querying for the existence of the DIE in case
1134  // such construction creates the DIE (as is the case for member function
1135  // declarations).
1136  DIE *ContextDIE =
1137      Minimal ? &getUnitDie() : getOrCreateContextDIE(SP->getScope());
1138
1139  if (DIE *SPDie = getDIE(SP))
1140    return SPDie;
1141
1142  if (auto *SPDecl = SP->getDeclaration()) {
1143    if (!Minimal) {
1144      // Add subprogram definitions to the CU die directly.
1145      ContextDIE = &getUnitDie();
1146      // Build the decl now to ensure it precedes the definition.
1147      getOrCreateSubprogramDIE(SPDecl);
1148    }
1149  }
1150
1151  // DW_TAG_inlined_subroutine may refer to this DIE.
1152  DIE &SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
1153
1154  // Stop here and fill this in later, depending on whether or not this
1155  // subprogram turns out to have inlined instances or not.
1156  if (SP->isDefinition())
1157    return &SPDie;
1158
1159  static_cast<DwarfUnit *>(SPDie.getUnit())
1160      ->applySubprogramAttributes(SP, SPDie);
1161  return &SPDie;
1162}
1163
1164bool DwarfUnit::applySubprogramDefinitionAttributes(const DISubprogram *SP,
1165                                                    DIE &SPDie) {
1166  DIE *DeclDie = nullptr;
1167  StringRef DeclLinkageName;
1168  if (auto *SPDecl = SP->getDeclaration()) {
1169    DeclDie = getDIE(SPDecl);
1170    assert(DeclDie && "This DIE should've already been constructed when the "
1171                      "definition DIE was created in "
1172                      "getOrCreateSubprogramDIE");
1173    // Look at the Decl's linkage name only if we emitted it.
1174    if (DD->useAllLinkageNames())
1175      DeclLinkageName = SPDecl->getLinkageName();
1176    unsigned DeclID = getOrCreateSourceID(SPDecl->getFile());
1177    unsigned DefID = getOrCreateSourceID(SP->getFile());
1178    if (DeclID != DefID)
1179      addUInt(SPDie, dwarf::DW_AT_decl_file, None, DefID);
1180
1181    if (SP->getLine() != SPDecl->getLine())
1182      addUInt(SPDie, dwarf::DW_AT_decl_line, None, SP->getLine());
1183  }
1184
1185  // Add function template parameters.
1186  addTemplateParams(SPDie, SP->getTemplateParams());
1187
1188  // Add the linkage name if we have one and it isn't in the Decl.
1189  StringRef LinkageName = SP->getLinkageName();
1190  assert(((LinkageName.empty() || DeclLinkageName.empty()) ||
1191          LinkageName == DeclLinkageName) &&
1192         "decl has a linkage name and it is different");
1193  if (DeclLinkageName.empty() &&
1194      // Always emit it for abstract subprograms.
1195      (DD->useAllLinkageNames() || DU->getAbstractSPDies().lookup(SP)))
1196    addLinkageName(SPDie, LinkageName);
1197
1198  if (!DeclDie)
1199    return false;
1200
1201  // Refer to the function declaration where all the other attributes will be
1202  // found.
1203  addDIEEntry(SPDie, dwarf::DW_AT_specification, *DeclDie);
1204  return true;
1205}
1206
1207void DwarfUnit::applySubprogramAttributes(const DISubprogram *SP, DIE &SPDie,
1208                                          bool SkipSPAttributes) {
1209  // If -fdebug-info-for-profiling is enabled, need to emit the subprogram
1210  // and its source location.
1211  bool SkipSPSourceLocation = SkipSPAttributes &&
1212                              !CUNode->getDebugInfoForProfiling();
1213  if (!SkipSPSourceLocation)
1214    if (applySubprogramDefinitionAttributes(SP, SPDie))
1215      return;
1216
1217  // Constructors and operators for anonymous aggregates do not have names.
1218  if (!SP->getName().empty())
1219    addString(SPDie, dwarf::DW_AT_name, SP->getName());
1220
1221  if (!SkipSPSourceLocation)
1222    addSourceLine(SPDie, SP);
1223
1224  // Skip the rest of the attributes under -gmlt to save space.
1225  if (SkipSPAttributes)
1226    return;
1227
1228  // Add the prototype if we have a prototype and we have a C like
1229  // language.
1230  uint16_t Language = getLanguage();
1231  if (SP->isPrototyped() &&
1232      (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1233       Language == dwarf::DW_LANG_ObjC))
1234    addFlag(SPDie, dwarf::DW_AT_prototyped);
1235
1236  if (SP->isObjCDirect())
1237    addFlag(SPDie, dwarf::DW_AT_APPLE_objc_direct);
1238
1239  unsigned CC = 0;
1240  DITypeRefArray Args;
1241  if (const DISubroutineType *SPTy = SP->getType()) {
1242    Args = SPTy->getTypeArray();
1243    CC = SPTy->getCC();
1244  }
1245
1246  // Add a DW_AT_calling_convention if this has an explicit convention.
1247  if (CC && CC != dwarf::DW_CC_normal)
1248    addUInt(SPDie, dwarf::DW_AT_calling_convention, dwarf::DW_FORM_data1, CC);
1249
1250  // Add a return type. If this is a type like a C/C++ void type we don't add a
1251  // return type.
1252  if (Args.size())
1253    if (auto Ty = Args[0])
1254      addType(SPDie, Ty);
1255
1256  unsigned VK = SP->getVirtuality();
1257  if (VK) {
1258    addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1259    if (SP->getVirtualIndex() != -1u) {
1260      DIELoc *Block = getDIELoc();
1261      addUInt(*Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1262      addUInt(*Block, dwarf::DW_FORM_udata, SP->getVirtualIndex());
1263      addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
1264    }
1265    ContainingTypeMap.insert(std::make_pair(&SPDie, SP->getContainingType()));
1266  }
1267
1268  if (!SP->isDefinition()) {
1269    addFlag(SPDie, dwarf::DW_AT_declaration);
1270
1271    // Add arguments. Do not add arguments for subprogram definition. They will
1272    // be handled while processing variables.
1273    constructSubprogramArguments(SPDie, Args);
1274  }
1275
1276  addThrownTypes(SPDie, SP->getThrownTypes());
1277
1278  if (SP->isArtificial())
1279    addFlag(SPDie, dwarf::DW_AT_artificial);
1280
1281  if (!SP->isLocalToUnit())
1282    addFlag(SPDie, dwarf::DW_AT_external);
1283
1284  if (DD->useAppleExtensionAttributes()) {
1285    if (SP->isOptimized())
1286      addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1287
1288    if (unsigned isa = Asm->getISAEncoding())
1289      addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1290  }
1291
1292  if (SP->isLValueReference())
1293    addFlag(SPDie, dwarf::DW_AT_reference);
1294
1295  if (SP->isRValueReference())
1296    addFlag(SPDie, dwarf::DW_AT_rvalue_reference);
1297
1298  if (SP->isNoReturn())
1299    addFlag(SPDie, dwarf::DW_AT_noreturn);
1300
1301  if (SP->isProtected())
1302    addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1303            dwarf::DW_ACCESS_protected);
1304  else if (SP->isPrivate())
1305    addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1306            dwarf::DW_ACCESS_private);
1307  else if (SP->isPublic())
1308    addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1309            dwarf::DW_ACCESS_public);
1310
1311  if (SP->isExplicit())
1312    addFlag(SPDie, dwarf::DW_AT_explicit);
1313
1314  if (SP->isMainSubprogram())
1315    addFlag(SPDie, dwarf::DW_AT_main_subprogram);
1316  if (SP->isPure())
1317    addFlag(SPDie, dwarf::DW_AT_pure);
1318  if (SP->isElemental())
1319    addFlag(SPDie, dwarf::DW_AT_elemental);
1320  if (SP->isRecursive())
1321    addFlag(SPDie, dwarf::DW_AT_recursive);
1322
1323  if (DD->getDwarfVersion() >= 5 && SP->isDeleted())
1324    addFlag(SPDie, dwarf::DW_AT_deleted);
1325}
1326
1327void DwarfUnit::constructSubrangeDIE(DIE &Buffer, const DISubrange *SR,
1328                                     DIE *IndexTy) {
1329  DIE &DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
1330  addDIEEntry(DW_Subrange, dwarf::DW_AT_type, *IndexTy);
1331
1332  // The LowerBound value defines the lower bounds which is typically zero for
1333  // C/C++. The Count value is the number of elements.  Values are 64 bit. If
1334  // Count == -1 then the array is unbounded and we do not emit
1335  // DW_AT_lower_bound and DW_AT_count attributes.
1336  int64_t LowerBound = SR->getLowerBound();
1337  int64_t DefaultLowerBound = getDefaultLowerBound();
1338  int64_t Count = -1;
1339  if (auto *CI = SR->getCount().dyn_cast<ConstantInt*>())
1340    Count = CI->getSExtValue();
1341
1342  if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
1343    addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound);
1344
1345  if (auto *CV = SR->getCount().dyn_cast<DIVariable*>()) {
1346    if (auto *CountVarDIE = getDIE(CV))
1347      addDIEEntry(DW_Subrange, dwarf::DW_AT_count, *CountVarDIE);
1348  } else if (Count != -1)
1349    addUInt(DW_Subrange, dwarf::DW_AT_count, None, Count);
1350}
1351
1352DIE *DwarfUnit::getIndexTyDie() {
1353  if (IndexTyDie)
1354    return IndexTyDie;
1355  // Construct an integer type to use for indexes.
1356  IndexTyDie = &createAndAddDIE(dwarf::DW_TAG_base_type, getUnitDie());
1357  StringRef Name = "__ARRAY_SIZE_TYPE__";
1358  addString(*IndexTyDie, dwarf::DW_AT_name, Name);
1359  addUInt(*IndexTyDie, dwarf::DW_AT_byte_size, None, sizeof(int64_t));
1360  addUInt(*IndexTyDie, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1361          dwarf::DW_ATE_unsigned);
1362  DD->addAccelType(*CUNode, Name, *IndexTyDie, /*Flags*/ 0);
1363  return IndexTyDie;
1364}
1365
1366/// Returns true if the vector's size differs from the sum of sizes of elements
1367/// the user specified.  This can occur if the vector has been rounded up to
1368/// fit memory alignment constraints.
1369static bool hasVectorBeenPadded(const DICompositeType *CTy) {
1370  assert(CTy && CTy->isVector() && "Composite type is not a vector");
1371  const uint64_t ActualSize = CTy->getSizeInBits();
1372
1373  // Obtain the size of each element in the vector.
1374  DIType *BaseTy = CTy->getBaseType();
1375  assert(BaseTy && "Unknown vector element type.");
1376  const uint64_t ElementSize = BaseTy->getSizeInBits();
1377
1378  // Locate the number of elements in the vector.
1379  const DINodeArray Elements = CTy->getElements();
1380  assert(Elements.size() == 1 &&
1381         Elements[0]->getTag() == dwarf::DW_TAG_subrange_type &&
1382         "Invalid vector element array, expected one element of type subrange");
1383  const auto Subrange = cast<DISubrange>(Elements[0]);
1384  const auto CI = Subrange->getCount().get<ConstantInt *>();
1385  const int32_t NumVecElements = CI->getSExtValue();
1386
1387  // Ensure we found the element count and that the actual size is wide
1388  // enough to contain the requested size.
1389  assert(ActualSize >= (NumVecElements * ElementSize) && "Invalid vector size");
1390  return ActualSize != (NumVecElements * ElementSize);
1391}
1392
1393void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
1394  if (CTy->isVector()) {
1395    addFlag(Buffer, dwarf::DW_AT_GNU_vector);
1396    if (hasVectorBeenPadded(CTy))
1397      addUInt(Buffer, dwarf::DW_AT_byte_size, None,
1398              CTy->getSizeInBits() / CHAR_BIT);
1399  }
1400
1401  // Emit the element type.
1402  addType(Buffer, CTy->getBaseType());
1403
1404  // Get an anonymous type for index type.
1405  // FIXME: This type should be passed down from the front end
1406  // as different languages may have different sizes for indexes.
1407  DIE *IdxTy = getIndexTyDie();
1408
1409  // Add subranges to array type.
1410  DINodeArray Elements = CTy->getElements();
1411  for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
1412    // FIXME: Should this really be such a loose cast?
1413    if (auto *Element = dyn_cast_or_null<DINode>(Elements[i]))
1414      if (Element->getTag() == dwarf::DW_TAG_subrange_type)
1415        constructSubrangeDIE(Buffer, cast<DISubrange>(Element), IdxTy);
1416  }
1417}
1418
1419void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
1420  const DIType *DTy = CTy->getBaseType();
1421  bool IsUnsigned = DTy && isUnsignedDIType(DD, DTy);
1422  if (DTy) {
1423    if (DD->getDwarfVersion() >= 3)
1424      addType(Buffer, DTy);
1425    if (DD->getDwarfVersion() >= 4 && (CTy->getFlags() & DINode::FlagEnumClass))
1426      addFlag(Buffer, dwarf::DW_AT_enum_class);
1427  }
1428
1429  auto *Context = CTy->getScope();
1430  bool IndexEnumerators = !Context || isa<DICompileUnit>(Context) || isa<DIFile>(Context) ||
1431      isa<DINamespace>(Context) || isa<DICommonBlock>(Context);
1432  DINodeArray Elements = CTy->getElements();
1433
1434  // Add enumerators to enumeration type.
1435  for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
1436    auto *Enum = dyn_cast_or_null<DIEnumerator>(Elements[i]);
1437    if (Enum) {
1438      DIE &Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
1439      StringRef Name = Enum->getName();
1440      addString(Enumerator, dwarf::DW_AT_name, Name);
1441      auto Value = static_cast<uint64_t>(Enum->getValue());
1442      addConstantValue(Enumerator, IsUnsigned, Value);
1443      if (IndexEnumerators)
1444        addGlobalName(Name, Enumerator, Context);
1445    }
1446  }
1447}
1448
1449void DwarfUnit::constructContainingTypeDIEs() {
1450  for (auto CI = ContainingTypeMap.begin(), CE = ContainingTypeMap.end();
1451       CI != CE; ++CI) {
1452    DIE &SPDie = *CI->first;
1453    const DINode *D = CI->second;
1454    if (!D)
1455      continue;
1456    DIE *NDie = getDIE(D);
1457    if (!NDie)
1458      continue;
1459    addDIEEntry(SPDie, dwarf::DW_AT_containing_type, *NDie);
1460  }
1461}
1462
1463DIE &DwarfUnit::constructMemberDIE(DIE &Buffer, const DIDerivedType *DT) {
1464  DIE &MemberDie = createAndAddDIE(DT->getTag(), Buffer);
1465  StringRef Name = DT->getName();
1466  if (!Name.empty())
1467    addString(MemberDie, dwarf::DW_AT_name, Name);
1468
1469  if (DIType *Resolved = DT->getBaseType())
1470    addType(MemberDie, Resolved);
1471
1472  addSourceLine(MemberDie, DT);
1473
1474  if (DT->getTag() == dwarf::DW_TAG_inheritance && DT->isVirtual()) {
1475
1476    // For C++, virtual base classes are not at fixed offset. Use following
1477    // expression to extract appropriate offset from vtable.
1478    // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1479
1480    DIELoc *VBaseLocationDie = new (DIEValueAllocator) DIELoc;
1481    addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1482    addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1483    addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1484    addUInt(*VBaseLocationDie, dwarf::DW_FORM_udata, DT->getOffsetInBits());
1485    addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1486    addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1487    addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1488
1489    addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
1490  } else {
1491    uint64_t Size = DT->getSizeInBits();
1492    uint64_t FieldSize = DD->getBaseTypeSize(DT);
1493    uint32_t AlignInBytes = DT->getAlignInBytes();
1494    uint64_t OffsetInBytes;
1495
1496    bool IsBitfield = FieldSize && Size != FieldSize;
1497    if (IsBitfield) {
1498      // Handle bitfield, assume bytes are 8 bits.
1499      if (DD->useDWARF2Bitfields())
1500        addUInt(MemberDie, dwarf::DW_AT_byte_size, None, FieldSize/8);
1501      addUInt(MemberDie, dwarf::DW_AT_bit_size, None, Size);
1502
1503      uint64_t Offset = DT->getOffsetInBits();
1504      // We can't use DT->getAlignInBits() here: AlignInBits for member type
1505      // is non-zero if and only if alignment was forced (e.g. _Alignas()),
1506      // which can't be done with bitfields. Thus we use FieldSize here.
1507      uint32_t AlignInBits = FieldSize;
1508      uint32_t AlignMask = ~(AlignInBits - 1);
1509      // The bits from the start of the storage unit to the start of the field.
1510      uint64_t StartBitOffset = Offset - (Offset & AlignMask);
1511      // The byte offset of the field's aligned storage unit inside the struct.
1512      OffsetInBytes = (Offset - StartBitOffset) / 8;
1513
1514      if (DD->useDWARF2Bitfields()) {
1515        uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1516        uint64_t FieldOffset = (HiMark - FieldSize);
1517        Offset -= FieldOffset;
1518
1519        // Maybe we need to work from the other end.
1520        if (Asm->getDataLayout().isLittleEndian())
1521          Offset = FieldSize - (Offset + Size);
1522
1523        addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset);
1524        OffsetInBytes = FieldOffset >> 3;
1525      } else {
1526        addUInt(MemberDie, dwarf::DW_AT_data_bit_offset, None, Offset);
1527      }
1528    } else {
1529      // This is not a bitfield.
1530      OffsetInBytes = DT->getOffsetInBits() / 8;
1531      if (AlignInBytes)
1532        addUInt(MemberDie, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
1533                AlignInBytes);
1534    }
1535
1536    if (DD->getDwarfVersion() <= 2) {
1537      DIELoc *MemLocationDie = new (DIEValueAllocator) DIELoc;
1538      addUInt(*MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1539      addUInt(*MemLocationDie, dwarf::DW_FORM_udata, OffsetInBytes);
1540      addBlock(MemberDie, dwarf::DW_AT_data_member_location, MemLocationDie);
1541    } else if (!IsBitfield || DD->useDWARF2Bitfields())
1542      addUInt(MemberDie, dwarf::DW_AT_data_member_location, None,
1543              OffsetInBytes);
1544  }
1545
1546  if (DT->isProtected())
1547    addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1548            dwarf::DW_ACCESS_protected);
1549  else if (DT->isPrivate())
1550    addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1551            dwarf::DW_ACCESS_private);
1552  // Otherwise C++ member and base classes are considered public.
1553  else if (DT->isPublic())
1554    addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1555            dwarf::DW_ACCESS_public);
1556  if (DT->isVirtual())
1557    addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1558            dwarf::DW_VIRTUALITY_virtual);
1559
1560  // Objective-C properties.
1561  if (DINode *PNode = DT->getObjCProperty())
1562    if (DIE *PDie = getDIE(PNode))
1563      MemberDie.addValue(DIEValueAllocator, dwarf::DW_AT_APPLE_property,
1564                         dwarf::DW_FORM_ref4, DIEEntry(*PDie));
1565
1566  if (DT->isArtificial())
1567    addFlag(MemberDie, dwarf::DW_AT_artificial);
1568
1569  return MemberDie;
1570}
1571
1572DIE *DwarfUnit::getOrCreateStaticMemberDIE(const DIDerivedType *DT) {
1573  if (!DT)
1574    return nullptr;
1575
1576  // Construct the context before querying for the existence of the DIE in case
1577  // such construction creates the DIE.
1578  DIE *ContextDIE = getOrCreateContextDIE(DT->getScope());
1579  assert(dwarf::isType(ContextDIE->getTag()) &&
1580         "Static member should belong to a type.");
1581
1582  if (DIE *StaticMemberDIE = getDIE(DT))
1583    return StaticMemberDIE;
1584
1585  DIE &StaticMemberDIE = createAndAddDIE(DT->getTag(), *ContextDIE, DT);
1586
1587  const DIType *Ty = DT->getBaseType();
1588
1589  addString(StaticMemberDIE, dwarf::DW_AT_name, DT->getName());
1590  addType(StaticMemberDIE, Ty);
1591  addSourceLine(StaticMemberDIE, DT);
1592  addFlag(StaticMemberDIE, dwarf::DW_AT_external);
1593  addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
1594
1595  // FIXME: We could omit private if the parent is a class_type, and
1596  // public if the parent is something else.
1597  if (DT->isProtected())
1598    addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1599            dwarf::DW_ACCESS_protected);
1600  else if (DT->isPrivate())
1601    addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1602            dwarf::DW_ACCESS_private);
1603  else if (DT->isPublic())
1604    addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1605            dwarf::DW_ACCESS_public);
1606
1607  if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT->getConstant()))
1608    addConstantValue(StaticMemberDIE, CI, Ty);
1609  if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT->getConstant()))
1610    addConstantFPValue(StaticMemberDIE, CFP);
1611
1612  if (uint32_t AlignInBytes = DT->getAlignInBytes())
1613    addUInt(StaticMemberDIE, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
1614            AlignInBytes);
1615
1616  return &StaticMemberDIE;
1617}
1618
1619void DwarfUnit::emitCommonHeader(bool UseOffsets, dwarf::UnitType UT) {
1620  // Emit size of content not including length itself
1621  Asm->OutStreamer->AddComment("Length of Unit");
1622  if (!DD->useSectionsAsReferences()) {
1623    StringRef Prefix = isDwoUnit() ? "debug_info_dwo_" : "debug_info_";
1624    MCSymbol *BeginLabel = Asm->createTempSymbol(Prefix + "start");
1625    EndLabel = Asm->createTempSymbol(Prefix + "end");
1626    Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
1627    Asm->OutStreamer->EmitLabel(BeginLabel);
1628  } else
1629    Asm->emitInt32(getHeaderSize() + getUnitDie().getSize());
1630
1631  Asm->OutStreamer->AddComment("DWARF version number");
1632  unsigned Version = DD->getDwarfVersion();
1633  Asm->emitInt16(Version);
1634
1635  // DWARF v5 reorders the address size and adds a unit type.
1636  if (Version >= 5) {
1637    Asm->OutStreamer->AddComment("DWARF Unit Type");
1638    Asm->emitInt8(UT);
1639    Asm->OutStreamer->AddComment("Address Size (in bytes)");
1640    Asm->emitInt8(Asm->MAI->getCodePointerSize());
1641  }
1642
1643  // We share one abbreviations table across all units so it's always at the
1644  // start of the section. Use a relocatable offset where needed to ensure
1645  // linking doesn't invalidate that offset.
1646  Asm->OutStreamer->AddComment("Offset Into Abbrev. Section");
1647  const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1648  if (UseOffsets)
1649    Asm->emitInt32(0);
1650  else
1651    Asm->emitDwarfSymbolReference(
1652        TLOF.getDwarfAbbrevSection()->getBeginSymbol(), false);
1653
1654  if (Version <= 4) {
1655    Asm->OutStreamer->AddComment("Address Size (in bytes)");
1656    Asm->emitInt8(Asm->MAI->getCodePointerSize());
1657  }
1658}
1659
1660void DwarfTypeUnit::emitHeader(bool UseOffsets) {
1661  DwarfUnit::emitCommonHeader(UseOffsets,
1662                              DD->useSplitDwarf() ? dwarf::DW_UT_split_type
1663                                                  : dwarf::DW_UT_type);
1664  Asm->OutStreamer->AddComment("Type Signature");
1665  Asm->OutStreamer->EmitIntValue(TypeSignature, sizeof(TypeSignature));
1666  Asm->OutStreamer->AddComment("Type DIE Offset");
1667  // In a skeleton type unit there is no type DIE so emit a zero offset.
1668  Asm->OutStreamer->EmitIntValue(Ty ? Ty->getOffset() : 0,
1669                                 sizeof(Ty->getOffset()));
1670}
1671
1672DIE::value_iterator
1673DwarfUnit::addSectionDelta(DIE &Die, dwarf::Attribute Attribute,
1674                           const MCSymbol *Hi, const MCSymbol *Lo) {
1675  return Die.addValue(DIEValueAllocator, Attribute,
1676                      DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
1677                                                 : dwarf::DW_FORM_data4,
1678                      new (DIEValueAllocator) DIEDelta(Hi, Lo));
1679}
1680
1681DIE::value_iterator
1682DwarfUnit::addSectionLabel(DIE &Die, dwarf::Attribute Attribute,
1683                           const MCSymbol *Label, const MCSymbol *Sec) {
1684  if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
1685    return addLabel(Die, Attribute,
1686                    DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
1687                                               : dwarf::DW_FORM_data4,
1688                    Label);
1689  return addSectionDelta(Die, Attribute, Label, Sec);
1690}
1691
1692bool DwarfTypeUnit::isDwoUnit() const {
1693  // Since there are no skeleton type units, all type units are dwo type units
1694  // when split DWARF is being used.
1695  return DD->useSplitDwarf();
1696}
1697
1698void DwarfTypeUnit::addGlobalName(StringRef Name, const DIE &Die,
1699                                  const DIScope *Context) {
1700  getCU().addGlobalNameForTypeUnit(Name, Context);
1701}
1702
1703void DwarfTypeUnit::addGlobalType(const DIType *Ty, const DIE &Die,
1704                                  const DIScope *Context) {
1705  getCU().addGlobalTypeUnitType(Ty, Context);
1706}
1707
1708const MCSymbol *DwarfUnit::getCrossSectionRelativeBaseAddress() const {
1709  if (!Asm->MAI->doesDwarfUseRelocationsAcrossSections())
1710    return nullptr;
1711  if (isDwoUnit())
1712    return nullptr;
1713  return getSection()->getBeginSymbol();
1714}
1715
1716void DwarfUnit::addStringOffsetsStart() {
1717  const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1718  addSectionLabel(getUnitDie(), dwarf::DW_AT_str_offsets_base,
1719                  DU->getStringOffsetsStartSym(),
1720                  TLOF.getDwarfStrOffSection()->getBeginSymbol());
1721}
1722
1723void DwarfUnit::addRnglistsBase() {
1724  assert(DD->getDwarfVersion() >= 5 &&
1725         "DW_AT_rnglists_base requires DWARF version 5 or later");
1726  const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1727  addSectionLabel(getUnitDie(), dwarf::DW_AT_rnglists_base,
1728                  DU->getRnglistsTableBaseSym(),
1729                  TLOF.getDwarfRnglistsSection()->getBeginSymbol());
1730}
1731
1732void DwarfTypeUnit::finishNonUnitTypeDIE(DIE& D, const DICompositeType *CTy) {
1733  addFlag(D, dwarf::DW_AT_declaration);
1734  StringRef Name = CTy->getName();
1735  if (!Name.empty())
1736    addString(D, dwarf::DW_AT_name, Name);
1737  getCU().createTypeDIE(CTy);
1738}
1739