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