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