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