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