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