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