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