AsmPrinter: Emit the DwarfStringPool offset directly when possible
[oota-llvm.git] / lib / CodeGen / AsmPrinter / DwarfUnit.cpp
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 "DwarfAccelTable.h"
16 #include "DwarfCompileUnit.h"
17 #include "DwarfDebug.h"
18 #include "DwarfExpression.h"
19 #include "llvm/ADT/APFloat.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/DIBuilder.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/GlobalVariable.h"
25 #include "llvm/IR/Instructions.h"
26 #include "llvm/IR/Mangler.h"
27 #include "llvm/MC/MCAsmInfo.h"
28 #include "llvm/MC/MCContext.h"
29 #include "llvm/MC/MCSection.h"
30 #include "llvm/MC/MCStreamer.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Target/TargetFrameLowering.h"
33 #include "llvm/Target/TargetLoweringObjectFile.h"
34 #include "llvm/Target/TargetMachine.h"
35 #include "llvm/Target/TargetRegisterInfo.h"
36 #include "llvm/Target/TargetSubtargetInfo.h"
37
38 using namespace llvm;
39
40 #define DEBUG_TYPE "dwarfdebug"
41
42 static cl::opt<bool>
43 GenerateDwarfTypeUnits("generate-type-units", cl::Hidden,
44                        cl::desc("Generate DWARF4 type units."),
45                        cl::init(false));
46
47 DIEDwarfExpression::DIEDwarfExpression(const AsmPrinter &AP, DwarfUnit &DU,
48                                        DIELoc &DIE)
49     : DwarfExpression(*AP.MF->getSubtarget().getRegisterInfo(),
50                       AP.getDwarfDebug()->getDwarfVersion()),
51       AP(AP), DU(DU), DIE(DIE) {}
52
53 void DIEDwarfExpression::EmitOp(uint8_t Op, const char* Comment) {
54   DU.addUInt(DIE, dwarf::DW_FORM_data1, Op);
55 }
56 void DIEDwarfExpression::EmitSigned(int64_t Value) {
57   DU.addSInt(DIE, dwarf::DW_FORM_sdata, Value);
58 }
59 void DIEDwarfExpression::EmitUnsigned(uint64_t Value) {
60   DU.addUInt(DIE, dwarf::DW_FORM_udata, Value);
61 }
62 bool DIEDwarfExpression::isFrameRegister(unsigned MachineReg) {
63   return MachineReg == TRI.getFrameRegister(*AP.MF);
64 }
65
66 DwarfUnit::DwarfUnit(unsigned UID, dwarf::Tag UnitTag,
67                      const DICompileUnit *Node, AsmPrinter *A, DwarfDebug *DW,
68                      DwarfFile *DWU)
69     : UniqueID(UID), CUNode(Node), UnitDie(UnitTag), DebugInfoOffset(0), Asm(A),
70       DD(DW), DU(DWU), IndexTyDie(nullptr), Section(nullptr) {
71   assert(UnitTag == dwarf::DW_TAG_compile_unit ||
72          UnitTag == dwarf::DW_TAG_type_unit);
73   DIEIntegerOne = new (DIEValueAllocator) DIEInteger(1);
74 }
75
76 DwarfTypeUnit::DwarfTypeUnit(unsigned UID, DwarfCompileUnit &CU, AsmPrinter *A,
77                              DwarfDebug *DW, DwarfFile *DWU,
78                              MCDwarfDwoLineTable *SplitLineTable)
79     : DwarfUnit(UID, dwarf::DW_TAG_type_unit, CU.getCUNode(), A, DW, DWU),
80       CU(CU), SplitLineTable(SplitLineTable) {
81   if (SplitLineTable)
82     addSectionOffset(UnitDie, dwarf::DW_AT_stmt_list, 0);
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 DIEEntry *DwarfUnit::createDIEEntry(DIE &Entry) {
93   DIEEntry *Value = new (DIEValueAllocator) DIEEntry(Entry);
94   return Value;
95 }
96
97 int64_t DwarfUnit::getDefaultLowerBound() const {
98   switch (getLanguage()) {
99   default:
100     break;
101
102   case dwarf::DW_LANG_C89:
103   case dwarf::DW_LANG_C99:
104   case dwarf::DW_LANG_C:
105   case dwarf::DW_LANG_C_plus_plus:
106   case dwarf::DW_LANG_ObjC:
107   case dwarf::DW_LANG_ObjC_plus_plus:
108     return 0;
109
110   case dwarf::DW_LANG_Fortran77:
111   case dwarf::DW_LANG_Fortran90:
112   case dwarf::DW_LANG_Fortran95:
113     return 1;
114
115   // The languages below have valid values only if the DWARF version >= 4.
116   case dwarf::DW_LANG_Java:
117   case dwarf::DW_LANG_Python:
118   case dwarf::DW_LANG_UPC:
119   case dwarf::DW_LANG_D:
120     if (dwarf::DWARF_VERSION >= 4)
121       return 0;
122     break;
123
124   case dwarf::DW_LANG_Ada83:
125   case dwarf::DW_LANG_Ada95:
126   case dwarf::DW_LANG_Cobol74:
127   case dwarf::DW_LANG_Cobol85:
128   case dwarf::DW_LANG_Modula2:
129   case dwarf::DW_LANG_Pascal83:
130   case dwarf::DW_LANG_PLI:
131     if (dwarf::DWARF_VERSION >= 4)
132       return 1;
133     break;
134
135   // The languages below have valid values only if the DWARF version >= 5.
136   case dwarf::DW_LANG_OpenCL:
137   case dwarf::DW_LANG_Go:
138   case dwarf::DW_LANG_Haskell:
139   case dwarf::DW_LANG_C_plus_plus_03:
140   case dwarf::DW_LANG_C_plus_plus_11:
141   case dwarf::DW_LANG_OCaml:
142   case dwarf::DW_LANG_Rust:
143   case dwarf::DW_LANG_C11:
144   case dwarf::DW_LANG_Swift:
145   case dwarf::DW_LANG_Dylan:
146   case dwarf::DW_LANG_C_plus_plus_14:
147     if (dwarf::DWARF_VERSION >= 5)
148       return 0;
149     break;
150
151   case dwarf::DW_LANG_Modula3:
152   case dwarf::DW_LANG_Julia:
153   case dwarf::DW_LANG_Fortran03:
154   case dwarf::DW_LANG_Fortran08:
155     if (dwarf::DWARF_VERSION >= 5)
156       return 1;
157     break;
158   }
159
160   return -1;
161 }
162
163 /// Check whether the DIE for this MDNode can be shared across CUs.
164 static bool isShareableAcrossCUs(const DINode *D) {
165   // When the MDNode can be part of the type system, the DIE can be shared
166   // across CUs.
167   // Combining type units and cross-CU DIE sharing is lower value (since
168   // cross-CU DIE sharing is used in LTO and removes type redundancy at that
169   // level already) but may be implementable for some value in projects
170   // building multiple independent libraries with LTO and then linking those
171   // together.
172   return (isa<DIType>(D) ||
173           (isa<DISubprogram>(D) && !cast<DISubprogram>(D)->isDefinition())) &&
174          !GenerateDwarfTypeUnits;
175 }
176
177 DIE *DwarfUnit::getDIE(const DINode *D) const {
178   if (isShareableAcrossCUs(D))
179     return DU->getDIE(D);
180   return MDNodeToDieMap.lookup(D);
181 }
182
183 void DwarfUnit::insertDIE(const DINode *Desc, DIE *D) {
184   if (isShareableAcrossCUs(Desc)) {
185     DU->insertDIE(Desc, D);
186     return;
187   }
188   MDNodeToDieMap.insert(std::make_pair(Desc, D));
189 }
190
191 void DwarfUnit::addFlag(DIE &Die, dwarf::Attribute Attribute) {
192   if (DD->getDwarfVersion() >= 4)
193     Die.addValue(Attribute, dwarf::DW_FORM_flag_present, DIEIntegerOne);
194   else
195     Die.addValue(Attribute, dwarf::DW_FORM_flag, DIEIntegerOne);
196 }
197
198 void DwarfUnit::addUInt(DIE &Die, dwarf::Attribute Attribute,
199                         Optional<dwarf::Form> Form, uint64_t Integer) {
200   if (!Form)
201     Form = DIEInteger::BestForm(false, Integer);
202   DIEValue *Value = Integer == 1 ? DIEIntegerOne : new (DIEValueAllocator)
203                         DIEInteger(Integer);
204   Die.addValue(Attribute, *Form, Value);
205 }
206
207 void DwarfUnit::addUInt(DIE &Block, dwarf::Form Form, uint64_t Integer) {
208   addUInt(Block, (dwarf::Attribute)0, Form, Integer);
209 }
210
211 void DwarfUnit::addSInt(DIE &Die, dwarf::Attribute Attribute,
212                         Optional<dwarf::Form> Form, int64_t Integer) {
213   if (!Form)
214     Form = DIEInteger::BestForm(true, Integer);
215   DIEValue *Value = new (DIEValueAllocator) DIEInteger(Integer);
216   Die.addValue(Attribute, *Form, Value);
217 }
218
219 void DwarfUnit::addSInt(DIELoc &Die, Optional<dwarf::Form> Form,
220                         int64_t Integer) {
221   addSInt(Die, (dwarf::Attribute)0, Form, Integer);
222 }
223
224 void DwarfUnit::addString(DIE &Die, dwarf::Attribute Attribute,
225                           StringRef String) {
226   if (!isDwoUnit())
227     return addLocalString(Die, Attribute, String);
228
229   addIndexedString(Die, Attribute, String);
230 }
231
232 void DwarfUnit::addIndexedString(DIE &Die, dwarf::Attribute Attribute,
233                                  StringRef String) {
234   unsigned idx = DU->getStringPool().getIndex(*Asm, String);
235   DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
236   DIEValue *Str = new (DIEValueAllocator) DIEString(Value, String);
237   Die.addValue(Attribute, dwarf::DW_FORM_GNU_str_index, Str);
238 }
239
240 void DwarfUnit::addLocalString(DIE &Die, dwarf::Attribute Attribute,
241                                StringRef String) {
242   DIEValue *Value;
243   if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
244     Value = new (DIEValueAllocator)
245         DIELabel(DU->getStringPool().getSymbol(*Asm, String));
246   else
247     Value = new (DIEValueAllocator)
248         DIEInteger(DU->getStringPool().getOffset(*Asm, String));
249   DIEValue *Str = new (DIEValueAllocator) DIEString(Value, String);
250   Die.addValue(Attribute, dwarf::DW_FORM_strp, Str);
251 }
252
253 void DwarfUnit::addLabel(DIE &Die, dwarf::Attribute Attribute, dwarf::Form Form,
254                          const MCSymbol *Label) {
255   DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
256   Die.addValue(Attribute, Form, Value);
257 }
258
259 void DwarfUnit::addLabel(DIELoc &Die, dwarf::Form Form, const MCSymbol *Label) {
260   addLabel(Die, (dwarf::Attribute)0, Form, Label);
261 }
262
263 void DwarfUnit::addSectionOffset(DIE &Die, dwarf::Attribute Attribute,
264                                  uint64_t Integer) {
265   if (DD->getDwarfVersion() >= 4)
266     addUInt(Die, Attribute, dwarf::DW_FORM_sec_offset, Integer);
267   else
268     addUInt(Die, Attribute, dwarf::DW_FORM_data4, Integer);
269 }
270
271 unsigned DwarfTypeUnit::getOrCreateSourceID(StringRef FileName, StringRef DirName) {
272   return SplitLineTable ? SplitLineTable->getFile(DirName, FileName)
273                         : getCU().getOrCreateSourceID(FileName, DirName);
274 }
275
276 void DwarfUnit::addOpAddress(DIELoc &Die, const MCSymbol *Sym) {
277   if (!DD->useSplitDwarf()) {
278     addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
279     addLabel(Die, dwarf::DW_FORM_udata, Sym);
280   } else {
281     addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index);
282     addUInt(Die, dwarf::DW_FORM_GNU_addr_index,
283             DD->getAddressPool().getIndex(Sym));
284   }
285 }
286
287 void DwarfUnit::addLabelDelta(DIE &Die, dwarf::Attribute Attribute,
288                               const MCSymbol *Hi, const MCSymbol *Lo) {
289   DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
290   Die.addValue(Attribute, dwarf::DW_FORM_data4, Value);
291 }
292
293 void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute, DIE &Entry) {
294   addDIEEntry(Die, Attribute, createDIEEntry(Entry));
295 }
296
297 void DwarfUnit::addDIETypeSignature(DIE &Die, const DwarfTypeUnit &Type) {
298   // Flag the type unit reference as a declaration so that if it contains
299   // members (implicit special members, static data member definitions, member
300   // declarations for definitions in this CU, etc) consumers don't get confused
301   // and think this is a full definition.
302   addFlag(Die, dwarf::DW_AT_declaration);
303
304   Die.addValue(dwarf::DW_AT_signature, dwarf::DW_FORM_ref_sig8,
305                new (DIEValueAllocator) DIETypeSignature(Type));
306 }
307
308 void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute,
309                             DIEEntry *Entry) {
310   const DIE *DieCU = Die.getUnitOrNull();
311   const DIE *EntryCU = Entry->getEntry().getUnitOrNull();
312   if (!DieCU)
313     // We assume that Die belongs to this CU, if it is not linked to any CU yet.
314     DieCU = &getUnitDie();
315   if (!EntryCU)
316     EntryCU = &getUnitDie();
317   Die.addValue(Attribute,
318                EntryCU == DieCU ? dwarf::DW_FORM_ref4 : dwarf::DW_FORM_ref_addr,
319                Entry);
320 }
321
322 DIE &DwarfUnit::createAndAddDIE(unsigned Tag, DIE &Parent, const DINode *N) {
323   assert(Tag != dwarf::DW_TAG_auto_variable &&
324          Tag != dwarf::DW_TAG_arg_variable);
325   Parent.addChild(make_unique<DIE>((dwarf::Tag)Tag));
326   DIE &Die = *Parent.getChildren().back();
327   if (N)
328     insertDIE(N, &Die);
329   return Die;
330 }
331
332 void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute, DIELoc *Loc) {
333   Loc->ComputeSize(Asm);
334   DIELocs.push_back(Loc); // Memoize so we can call the destructor later on.
335   Die.addValue(Attribute, Loc->BestForm(DD->getDwarfVersion()), Loc);
336 }
337
338 void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute,
339                          DIEBlock *Block) {
340   Block->ComputeSize(Asm);
341   DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
342   Die.addValue(Attribute, Block->BestForm(), Block);
343 }
344
345 void DwarfUnit::addSourceLine(DIE &Die, unsigned Line, StringRef File,
346                               StringRef Directory) {
347   if (Line == 0)
348     return;
349
350   unsigned FileID = getOrCreateSourceID(File, Directory);
351   assert(FileID && "Invalid file id");
352   addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
353   addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
354 }
355
356 void DwarfUnit::addSourceLine(DIE &Die, const DILocalVariable *V) {
357   assert(V);
358
359   addSourceLine(Die, V->getLine(), V->getScope()->getFilename(),
360                 V->getScope()->getDirectory());
361 }
362
363 void DwarfUnit::addSourceLine(DIE &Die, const DIGlobalVariable *G) {
364   assert(G);
365
366   addSourceLine(Die, G->getLine(), G->getFilename(), G->getDirectory());
367 }
368
369 void DwarfUnit::addSourceLine(DIE &Die, const DISubprogram *SP) {
370   assert(SP);
371
372   addSourceLine(Die, SP->getLine(), SP->getFilename(), SP->getDirectory());
373 }
374
375 void DwarfUnit::addSourceLine(DIE &Die, const DIType *Ty) {
376   assert(Ty);
377
378   addSourceLine(Die, Ty->getLine(), Ty->getFilename(), Ty->getDirectory());
379 }
380
381 void DwarfUnit::addSourceLine(DIE &Die, const DIObjCProperty *Ty) {
382   assert(Ty);
383
384   addSourceLine(Die, Ty->getLine(), Ty->getFilename(), Ty->getDirectory());
385 }
386
387 void DwarfUnit::addSourceLine(DIE &Die, const DINamespace *NS) {
388   addSourceLine(Die, NS->getLine(), NS->getFilename(), NS->getDirectory());
389 }
390
391 bool DwarfUnit::addRegisterOpPiece(DIELoc &TheDie, unsigned Reg,
392                                    unsigned SizeInBits, unsigned OffsetInBits) {
393   DIEDwarfExpression Expr(*Asm, *this, TheDie);
394   Expr.AddMachineRegPiece(Reg, SizeInBits, OffsetInBits);
395   return true;
396 }
397
398 bool DwarfUnit::addRegisterOffset(DIELoc &TheDie, unsigned Reg,
399                                   int64_t Offset) {
400   DIEDwarfExpression Expr(*Asm, *this, TheDie);
401   return Expr.AddMachineRegIndirect(Reg, Offset);
402 }
403
404 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
405    VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
406    gives the variable VarName either the struct, or a pointer to the struct, as
407    its type.  This is necessary for various behind-the-scenes things the
408    compiler needs to do with by-reference variables in Blocks.
409
410    However, as far as the original *programmer* is concerned, the variable
411    should still have type 'SomeType', as originally declared.
412
413    The function getBlockByrefType dives into the __Block_byref_x_VarName
414    struct to find the original type of the variable, which is then assigned to
415    the variable's Debug Information Entry as its real type.  So far, so good.
416    However now the debugger will expect the variable VarName to have the type
417    SomeType.  So we need the location attribute for the variable to be an
418    expression that explains to the debugger how to navigate through the
419    pointers and struct to find the actual variable of type SomeType.
420
421    The following function does just that.  We start by getting
422    the "normal" location for the variable. This will be the location
423    of either the struct __Block_byref_x_VarName or the pointer to the
424    struct __Block_byref_x_VarName.
425
426    The struct will look something like:
427
428    struct __Block_byref_x_VarName {
429      ... <various fields>
430      struct __Block_byref_x_VarName *forwarding;
431      ... <various other fields>
432      SomeType VarName;
433      ... <maybe more fields>
434    };
435
436    If we are given the struct directly (as our starting point) we
437    need to tell the debugger to:
438
439    1).  Add the offset of the forwarding field.
440
441    2).  Follow that pointer to get the real __Block_byref_x_VarName
442    struct to use (the real one may have been copied onto the heap).
443
444    3).  Add the offset for the field VarName, to find the actual variable.
445
446    If we started with a pointer to the struct, then we need to
447    dereference that pointer first, before the other steps.
448    Translating this into DWARF ops, we will need to append the following
449    to the current location description for the variable:
450
451    DW_OP_deref                    -- optional, if we start with a pointer
452    DW_OP_plus_uconst <forward_fld_offset>
453    DW_OP_deref
454    DW_OP_plus_uconst <varName_fld_offset>
455
456    That is what this function does.  */
457
458 void DwarfUnit::addBlockByrefAddress(const DbgVariable &DV, DIE &Die,
459                                      dwarf::Attribute Attribute,
460                                      const MachineLocation &Location) {
461   const DIType *Ty = DV.getType();
462   const DIType *TmpTy = Ty;
463   uint16_t Tag = Ty->getTag();
464   bool isPointer = false;
465
466   StringRef varName = DV.getName();
467
468   if (Tag == dwarf::DW_TAG_pointer_type) {
469     auto *DTy = cast<DIDerivedType>(Ty);
470     TmpTy = resolve(DTy->getBaseType());
471     isPointer = true;
472   }
473
474   // Find the __forwarding field and the variable field in the __Block_byref
475   // struct.
476   DINodeArray Fields = cast<DICompositeTypeBase>(TmpTy)->getElements();
477   const DIDerivedType *varField = nullptr;
478   const DIDerivedType *forwardingField = nullptr;
479
480   for (unsigned i = 0, N = Fields.size(); i < N; ++i) {
481     auto *DT = cast<DIDerivedType>(Fields[i]);
482     StringRef fieldName = DT->getName();
483     if (fieldName == "__forwarding")
484       forwardingField = DT;
485     else if (fieldName == varName)
486       varField = DT;
487   }
488
489   // Get the offsets for the forwarding field and the variable field.
490   unsigned forwardingFieldOffset = forwardingField->getOffsetInBits() >> 3;
491   unsigned varFieldOffset = varField->getOffsetInBits() >> 2;
492
493   // Decode the original location, and use that as the start of the byref
494   // variable's location.
495   DIELoc *Loc = new (DIEValueAllocator) DIELoc();
496
497   bool validReg;
498   if (Location.isReg())
499     validReg = addRegisterOpPiece(*Loc, Location.getReg());
500   else
501     validReg = addRegisterOffset(*Loc, Location.getReg(), Location.getOffset());
502
503   if (!validReg)
504     return;
505
506   // If we started with a pointer to the __Block_byref... struct, then
507   // the first thing we need to do is dereference the pointer (DW_OP_deref).
508   if (isPointer)
509     addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
510
511   // Next add the offset for the '__forwarding' field:
512   // DW_OP_plus_uconst ForwardingFieldOffset.  Note there's no point in
513   // adding the offset if it's 0.
514   if (forwardingFieldOffset > 0) {
515     addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
516     addUInt(*Loc, dwarf::DW_FORM_udata, forwardingFieldOffset);
517   }
518
519   // Now dereference the __forwarding field to get to the real __Block_byref
520   // struct:  DW_OP_deref.
521   addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
522
523   // Now that we've got the real __Block_byref... struct, add the offset
524   // for the variable's field to get to the location of the actual variable:
525   // DW_OP_plus_uconst varFieldOffset.  Again, don't add if it's 0.
526   if (varFieldOffset > 0) {
527     addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
528     addUInt(*Loc, dwarf::DW_FORM_udata, varFieldOffset);
529   }
530
531   // Now attach the location information to the DIE.
532   addBlock(Die, Attribute, Loc);
533 }
534
535 /// Return true if type encoding is unsigned.
536 static bool isUnsignedDIType(DwarfDebug *DD, const DIType *Ty) {
537   if (auto *DTy = dyn_cast<DIDerivedTypeBase>(Ty)) {
538     dwarf::Tag T = (dwarf::Tag)Ty->getTag();
539     // Encode pointer constants as unsigned bytes. This is used at least for
540     // null pointer constant emission.
541     // (Pieces of) aggregate types that get hacked apart by SROA may also be
542     // represented by a constant. Encode them as unsigned bytes.
543     // FIXME: reference and rvalue_reference /probably/ shouldn't be allowed
544     // here, but accept them for now due to a bug in SROA producing bogus
545     // dbg.values.
546     if (T == dwarf::DW_TAG_array_type ||
547         T == dwarf::DW_TAG_class_type ||
548         T == dwarf::DW_TAG_pointer_type ||
549         T == dwarf::DW_TAG_ptr_to_member_type ||
550         T == dwarf::DW_TAG_reference_type ||
551         T == dwarf::DW_TAG_rvalue_reference_type ||
552         T == dwarf::DW_TAG_structure_type ||
553         T == dwarf::DW_TAG_union_type)
554       return true;
555     assert(T == dwarf::DW_TAG_typedef || T == dwarf::DW_TAG_const_type ||
556            T == dwarf::DW_TAG_volatile_type ||
557            T == dwarf::DW_TAG_restrict_type ||
558            T == dwarf::DW_TAG_enumeration_type);
559     if (DITypeRef Deriv = DTy->getBaseType())
560       return isUnsignedDIType(DD, DD->resolve(Deriv));
561     // FIXME: Enums without a fixed underlying type have unknown signedness
562     // here, leading to incorrectly emitted constants.
563     assert(DTy->getTag() == dwarf::DW_TAG_enumeration_type);
564     return false;
565   }
566
567   auto *BTy = cast<DIBasicType>(Ty);
568   unsigned Encoding = BTy->getEncoding();
569   assert((Encoding == dwarf::DW_ATE_unsigned ||
570           Encoding == dwarf::DW_ATE_unsigned_char ||
571           Encoding == dwarf::DW_ATE_signed ||
572           Encoding == dwarf::DW_ATE_signed_char ||
573           Encoding == dwarf::DW_ATE_float || Encoding == dwarf::DW_ATE_UTF ||
574           Encoding == dwarf::DW_ATE_boolean ||
575           (Ty->getTag() == dwarf::DW_TAG_unspecified_type &&
576            Ty->getName() == "decltype(nullptr)")) &&
577          "Unsupported encoding");
578   return Encoding == dwarf::DW_ATE_unsigned ||
579          Encoding == dwarf::DW_ATE_unsigned_char ||
580          Encoding == dwarf::DW_ATE_UTF || Encoding == dwarf::DW_ATE_boolean ||
581          Ty->getTag() == dwarf::DW_TAG_unspecified_type;
582 }
583
584 /// If this type is derived from a base type then return base type size.
585 static uint64_t getBaseTypeSize(DwarfDebug *DD, const DIDerivedType *Ty) {
586   unsigned Tag = Ty->getTag();
587
588   if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef &&
589       Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type &&
590       Tag != dwarf::DW_TAG_restrict_type)
591     return Ty->getSizeInBits();
592
593   auto *BaseType = DD->resolve(Ty->getBaseType());
594
595   assert(BaseType && "Unexpected invalid base type");
596
597   // If this is a derived type, go ahead and get the base type, unless it's a
598   // reference then it's just the size of the field. Pointer types have no need
599   // of this since they're a different type of qualification on the type.
600   if (BaseType->getTag() == dwarf::DW_TAG_reference_type ||
601       BaseType->getTag() == dwarf::DW_TAG_rvalue_reference_type)
602     return Ty->getSizeInBits();
603
604   if (auto *DT = dyn_cast<DIDerivedType>(BaseType))
605     return getBaseTypeSize(DD, DT);
606
607   return BaseType->getSizeInBits();
608 }
609
610 void DwarfUnit::addConstantFPValue(DIE &Die, const MachineOperand &MO) {
611   assert(MO.isFPImm() && "Invalid machine operand!");
612   DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
613   APFloat FPImm = MO.getFPImm()->getValueAPF();
614
615   // Get the raw data form of the floating point.
616   const APInt FltVal = FPImm.bitcastToAPInt();
617   const char *FltPtr = (const char *)FltVal.getRawData();
618
619   int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
620   bool LittleEndian = Asm->getDataLayout().isLittleEndian();
621   int Incr = (LittleEndian ? 1 : -1);
622   int Start = (LittleEndian ? 0 : NumBytes - 1);
623   int Stop = (LittleEndian ? NumBytes : -1);
624
625   // Output the constant to DWARF one byte at a time.
626   for (; Start != Stop; Start += Incr)
627     addUInt(*Block, dwarf::DW_FORM_data1, (unsigned char)0xFF & FltPtr[Start]);
628
629   addBlock(Die, dwarf::DW_AT_const_value, Block);
630 }
631
632 void DwarfUnit::addConstantFPValue(DIE &Die, const ConstantFP *CFP) {
633   // Pass this down to addConstantValue as an unsigned bag of bits.
634   addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true);
635 }
636
637 void DwarfUnit::addConstantValue(DIE &Die, const ConstantInt *CI,
638                                  const DIType *Ty) {
639   addConstantValue(Die, CI->getValue(), Ty);
640 }
641
642 void DwarfUnit::addConstantValue(DIE &Die, const MachineOperand &MO,
643                                  const DIType *Ty) {
644   assert(MO.isImm() && "Invalid machine operand!");
645
646   addConstantValue(Die, isUnsignedDIType(DD, Ty), MO.getImm());
647 }
648
649 void DwarfUnit::addConstantValue(DIE &Die, bool Unsigned, uint64_t Val) {
650   // FIXME: This is a bit conservative/simple - it emits negative values always
651   // sign extended to 64 bits rather than minimizing the number of bytes.
652   addUInt(Die, dwarf::DW_AT_const_value,
653           Unsigned ? dwarf::DW_FORM_udata : dwarf::DW_FORM_sdata, Val);
654 }
655
656 void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, const DIType *Ty) {
657   addConstantValue(Die, Val, isUnsignedDIType(DD, Ty));
658 }
659
660 void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, bool Unsigned) {
661   unsigned CIBitWidth = Val.getBitWidth();
662   if (CIBitWidth <= 64) {
663     addConstantValue(Die, Unsigned,
664                      Unsigned ? Val.getZExtValue() : Val.getSExtValue());
665     return;
666   }
667
668   DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
669
670   // Get the raw data form of the large APInt.
671   const uint64_t *Ptr64 = Val.getRawData();
672
673   int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
674   bool LittleEndian = Asm->getDataLayout().isLittleEndian();
675
676   // Output the constant to DWARF one byte at a time.
677   for (int i = 0; i < NumBytes; i++) {
678     uint8_t c;
679     if (LittleEndian)
680       c = Ptr64[i / 8] >> (8 * (i & 7));
681     else
682       c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
683     addUInt(*Block, dwarf::DW_FORM_data1, c);
684   }
685
686   addBlock(Die, dwarf::DW_AT_const_value, Block);
687 }
688
689 void DwarfUnit::addLinkageName(DIE &Die, StringRef LinkageName) {
690   if (!LinkageName.empty())
691     addString(Die,
692               DD->getDwarfVersion() >= 4 ? dwarf::DW_AT_linkage_name
693                                          : dwarf::DW_AT_MIPS_linkage_name,
694               GlobalValue::getRealLinkageName(LinkageName));
695 }
696
697 void DwarfUnit::addTemplateParams(DIE &Buffer, DINodeArray TParams) {
698   // Add template parameters.
699   for (const auto *Element : TParams) {
700     if (auto *TTP = dyn_cast<DITemplateTypeParameter>(Element))
701       constructTemplateTypeParameterDIE(Buffer, TTP);
702     else if (auto *TVP = dyn_cast<DITemplateValueParameter>(Element))
703       constructTemplateValueParameterDIE(Buffer, TVP);
704   }
705 }
706
707 DIE *DwarfUnit::getOrCreateContextDIE(const DIScope *Context) {
708   if (!Context || isa<DIFile>(Context))
709     return &getUnitDie();
710   if (auto *T = dyn_cast<DIType>(Context))
711     return getOrCreateTypeDIE(T);
712   if (auto *NS = dyn_cast<DINamespace>(Context))
713     return getOrCreateNameSpace(NS);
714   if (auto *SP = dyn_cast<DISubprogram>(Context))
715     return getOrCreateSubprogramDIE(SP);
716   return getDIE(Context);
717 }
718
719 DIE *DwarfUnit::createTypeDIE(const DICompositeType *Ty) {
720   auto *Context = resolve(Ty->getScope());
721   DIE *ContextDIE = getOrCreateContextDIE(Context);
722
723   if (DIE *TyDIE = getDIE(Ty))
724     return TyDIE;
725
726   // Create new type.
727   DIE &TyDIE = createAndAddDIE(Ty->getTag(), *ContextDIE, Ty);
728
729   constructTypeDIE(TyDIE, cast<DICompositeType>(Ty));
730
731   updateAcceleratorTables(Context, Ty, TyDIE);
732   return &TyDIE;
733 }
734
735 DIE *DwarfUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
736   if (!TyNode)
737     return nullptr;
738
739   auto *Ty = cast<DIType>(TyNode);
740   assert(Ty == resolve(Ty->getRef()) &&
741          "type was not uniqued, possible ODR violation.");
742
743   // DW_TAG_restrict_type is not supported in DWARF2
744   if (Ty->getTag() == dwarf::DW_TAG_restrict_type && DD->getDwarfVersion() <= 2)
745     return getOrCreateTypeDIE(resolve(cast<DIDerivedType>(Ty)->getBaseType()));
746
747   // Construct the context before querying for the existence of the DIE in case
748   // such construction creates the DIE.
749   auto *Context = resolve(Ty->getScope());
750   DIE *ContextDIE = getOrCreateContextDIE(Context);
751   assert(ContextDIE);
752
753   if (DIE *TyDIE = getDIE(Ty))
754     return TyDIE;
755
756   // Create new type.
757   DIE &TyDIE = createAndAddDIE(Ty->getTag(), *ContextDIE, Ty);
758
759   updateAcceleratorTables(Context, Ty, TyDIE);
760
761   if (auto *BT = dyn_cast<DIBasicType>(Ty))
762     constructTypeDIE(TyDIE, BT);
763   else if (auto *STy = dyn_cast<DISubroutineType>(Ty))
764     constructTypeDIE(TyDIE, STy);
765   else if (auto *CTy = dyn_cast<DICompositeType>(Ty)) {
766     if (GenerateDwarfTypeUnits && !Ty->isForwardDecl())
767       if (MDString *TypeId = CTy->getRawIdentifier()) {
768         DD->addDwarfTypeUnitType(getCU(), TypeId->getString(), TyDIE, CTy);
769         // Skip updating the accelerator tables since this is not the full type.
770         return &TyDIE;
771       }
772     constructTypeDIE(TyDIE, CTy);
773   } else {
774     constructTypeDIE(TyDIE, cast<DIDerivedType>(Ty));
775   }
776
777   return &TyDIE;
778 }
779
780 void DwarfUnit::updateAcceleratorTables(const DIScope *Context,
781                                         const DIType *Ty, const DIE &TyDIE) {
782   if (!Ty->getName().empty() && !Ty->isForwardDecl()) {
783     bool IsImplementation = 0;
784     if (auto *CT = dyn_cast<DICompositeTypeBase>(Ty)) {
785       // A runtime language of 0 actually means C/C++ and that any
786       // non-negative value is some version of Objective-C/C++.
787       IsImplementation = CT->getRuntimeLang() == 0 || CT->isObjcClassComplete();
788     }
789     unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0;
790     DD->addAccelType(Ty->getName(), TyDIE, Flags);
791
792     if (!Context || isa<DICompileUnit>(Context) || isa<DIFile>(Context) ||
793         isa<DINamespace>(Context))
794       addGlobalType(Ty, TyDIE, Context);
795   }
796 }
797
798 void DwarfUnit::addType(DIE &Entity, const DIType *Ty,
799                         dwarf::Attribute Attribute) {
800   assert(Ty && "Trying to add a type that doesn't exist?");
801
802   // Check for pre-existence.
803   DIEEntry *Entry = getDIEEntry(Ty);
804   // If it exists then use the existing value.
805   if (Entry) {
806     addDIEEntry(Entity, Attribute, Entry);
807     return;
808   }
809
810   // Construct type.
811   DIE *Buffer = getOrCreateTypeDIE(Ty);
812
813   // Set up proxy.
814   Entry = createDIEEntry(*Buffer);
815   insertDIEEntry(Ty, Entry);
816   addDIEEntry(Entity, Attribute, Entry);
817 }
818
819 std::string DwarfUnit::getParentContextString(const DIScope *Context) const {
820   if (!Context)
821     return "";
822
823   // FIXME: Decide whether to implement this for non-C++ languages.
824   if (getLanguage() != dwarf::DW_LANG_C_plus_plus)
825     return "";
826
827   std::string CS;
828   SmallVector<const DIScope *, 1> Parents;
829   while (!isa<DICompileUnit>(Context)) {
830     Parents.push_back(Context);
831     if (Context->getScope())
832       Context = resolve(Context->getScope());
833     else
834       // Structure, etc types will have a NULL context if they're at the top
835       // level.
836       break;
837   }
838
839   // Reverse iterate over our list to go from the outermost construct to the
840   // innermost.
841   for (auto I = Parents.rbegin(), E = Parents.rend(); I != E; ++I) {
842     const DIScope *Ctx = *I;
843     StringRef Name = Ctx->getName();
844     if (Name.empty() && isa<DINamespace>(Ctx))
845       Name = "(anonymous namespace)";
846     if (!Name.empty()) {
847       CS += Name;
848       CS += "::";
849     }
850   }
851   return CS;
852 }
853
854 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DIBasicType *BTy) {
855   // Get core information.
856   StringRef Name = BTy->getName();
857   // Add name if not anonymous or intermediate type.
858   if (!Name.empty())
859     addString(Buffer, dwarf::DW_AT_name, Name);
860
861   // An unspecified type only has a name attribute.
862   if (BTy->getTag() == dwarf::DW_TAG_unspecified_type)
863     return;
864
865   addUInt(Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
866           BTy->getEncoding());
867
868   uint64_t Size = BTy->getSizeInBits() >> 3;
869   addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
870 }
871
872 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DIDerivedType *DTy) {
873   // Get core information.
874   StringRef Name = DTy->getName();
875   uint64_t Size = DTy->getSizeInBits() >> 3;
876   uint16_t Tag = Buffer.getTag();
877
878   // Map to main type, void will not have a type.
879   const DIType *FromTy = resolve(DTy->getBaseType());
880   if (FromTy)
881     addType(Buffer, FromTy);
882
883   // Add name if not anonymous or intermediate type.
884   if (!Name.empty())
885     addString(Buffer, dwarf::DW_AT_name, Name);
886
887   // Add size if non-zero (derived types might be zero-sized.)
888   if (Size && Tag != dwarf::DW_TAG_pointer_type
889            && Tag != dwarf::DW_TAG_ptr_to_member_type)
890     addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
891
892   if (Tag == dwarf::DW_TAG_ptr_to_member_type)
893     addDIEEntry(
894         Buffer, dwarf::DW_AT_containing_type,
895         *getOrCreateTypeDIE(resolve(cast<DIDerivedType>(DTy)->getClassType())));
896   // Add source line info if available and TyDesc is not a forward declaration.
897   if (!DTy->isForwardDecl())
898     addSourceLine(Buffer, DTy);
899 }
900
901 void DwarfUnit::constructSubprogramArguments(DIE &Buffer, DITypeRefArray Args) {
902   for (unsigned i = 1, N = Args.size(); i < N; ++i) {
903     const DIType *Ty = resolve(Args[i]);
904     if (!Ty) {
905       assert(i == N-1 && "Unspecified parameter must be the last argument");
906       createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
907     } else {
908       DIE &Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
909       addType(Arg, Ty);
910       if (Ty->isArtificial())
911         addFlag(Arg, dwarf::DW_AT_artificial);
912     }
913   }
914 }
915
916 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DISubroutineType *CTy) {
917   // Add return type.  A void return won't have a type.
918   auto Elements = cast<DISubroutineType>(CTy)->getTypeArray();
919   if (Elements.size())
920     if (auto RTy = resolve(Elements[0]))
921       addType(Buffer, RTy);
922
923   bool isPrototyped = true;
924   if (Elements.size() == 2 && !Elements[1])
925     isPrototyped = false;
926
927   constructSubprogramArguments(Buffer, Elements);
928
929   // Add prototype flag if we're dealing with a C language and the function has
930   // been prototyped.
931   uint16_t Language = getLanguage();
932   if (isPrototyped &&
933       (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
934        Language == dwarf::DW_LANG_ObjC))
935     addFlag(Buffer, dwarf::DW_AT_prototyped);
936
937   if (CTy->isLValueReference())
938     addFlag(Buffer, dwarf::DW_AT_reference);
939
940   if (CTy->isRValueReference())
941     addFlag(Buffer, dwarf::DW_AT_rvalue_reference);
942 }
943
944 void DwarfUnit::constructTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
945   // Add name if not anonymous or intermediate type.
946   StringRef Name = CTy->getName();
947
948   uint64_t Size = CTy->getSizeInBits() >> 3;
949   uint16_t Tag = Buffer.getTag();
950
951   switch (Tag) {
952   case dwarf::DW_TAG_array_type:
953     constructArrayTypeDIE(Buffer, CTy);
954     break;
955   case dwarf::DW_TAG_enumeration_type:
956     constructEnumTypeDIE(Buffer, CTy);
957     break;
958   case dwarf::DW_TAG_structure_type:
959   case dwarf::DW_TAG_union_type:
960   case dwarf::DW_TAG_class_type: {
961     // Add elements to structure type.
962     DINodeArray Elements = CTy->getElements();
963     for (const auto *Element : Elements) {
964       if (!Element)
965         continue;
966       if (auto *SP = dyn_cast<DISubprogram>(Element))
967         getOrCreateSubprogramDIE(SP);
968       else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
969         if (DDTy->getTag() == dwarf::DW_TAG_friend) {
970           DIE &ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
971           addType(ElemDie, resolve(DDTy->getBaseType()), dwarf::DW_AT_friend);
972         } else if (DDTy->isStaticMember()) {
973           getOrCreateStaticMemberDIE(DDTy);
974         } else {
975           constructMemberDIE(Buffer, DDTy);
976         }
977       } else if (auto *Property = dyn_cast<DIObjCProperty>(Element)) {
978         DIE &ElemDie = createAndAddDIE(Property->getTag(), Buffer);
979         StringRef PropertyName = Property->getName();
980         addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
981         if (Property->getType())
982           addType(ElemDie, Property->getType());
983         addSourceLine(ElemDie, Property);
984         StringRef GetterName = Property->getGetterName();
985         if (!GetterName.empty())
986           addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
987         StringRef SetterName = Property->getSetterName();
988         if (!SetterName.empty())
989           addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
990         if (unsigned PropertyAttributes = Property->getAttributes())
991           addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None,
992                   PropertyAttributes);
993
994         DIEEntry *Entry = getDIEEntry(Element);
995         if (!Entry) {
996           Entry = createDIEEntry(ElemDie);
997           insertDIEEntry(Element, Entry);
998         }
999       }
1000     }
1001
1002     if (CTy->isAppleBlockExtension())
1003       addFlag(Buffer, dwarf::DW_AT_APPLE_block);
1004
1005     // This is outside the DWARF spec, but GDB expects a DW_AT_containing_type
1006     // inside C++ composite types to point to the base class with the vtable.
1007     if (auto *ContainingType =
1008             dyn_cast_or_null<DICompositeType>(resolve(CTy->getVTableHolder())))
1009       addDIEEntry(Buffer, dwarf::DW_AT_containing_type,
1010                   *getOrCreateTypeDIE(ContainingType));
1011
1012     if (CTy->isObjcClassComplete())
1013       addFlag(Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
1014
1015     // Add template parameters to a class, structure or union types.
1016     // FIXME: The support isn't in the metadata for this yet.
1017     if (Tag == dwarf::DW_TAG_class_type ||
1018         Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
1019       addTemplateParams(Buffer, CTy->getTemplateParams());
1020
1021     break;
1022   }
1023   default:
1024     break;
1025   }
1026
1027   // Add name if not anonymous or intermediate type.
1028   if (!Name.empty())
1029     addString(Buffer, dwarf::DW_AT_name, Name);
1030
1031   if (Tag == dwarf::DW_TAG_enumeration_type ||
1032       Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
1033       Tag == dwarf::DW_TAG_union_type) {
1034     // Add size if non-zero (derived types might be zero-sized.)
1035     // TODO: Do we care about size for enum forward declarations?
1036     if (Size)
1037       addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
1038     else if (!CTy->isForwardDecl())
1039       // Add zero size if it is not a forward declaration.
1040       addUInt(Buffer, dwarf::DW_AT_byte_size, None, 0);
1041
1042     // If we're a forward decl, say so.
1043     if (CTy->isForwardDecl())
1044       addFlag(Buffer, dwarf::DW_AT_declaration);
1045
1046     // Add source line info if available.
1047     if (!CTy->isForwardDecl())
1048       addSourceLine(Buffer, CTy);
1049
1050     // No harm in adding the runtime language to the declaration.
1051     unsigned RLang = CTy->getRuntimeLang();
1052     if (RLang)
1053       addUInt(Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
1054               RLang);
1055   }
1056 }
1057
1058 void DwarfUnit::constructTemplateTypeParameterDIE(
1059     DIE &Buffer, const DITemplateTypeParameter *TP) {
1060   DIE &ParamDIE =
1061       createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
1062   // Add the type if it exists, it could be void and therefore no type.
1063   if (TP->getType())
1064     addType(ParamDIE, resolve(TP->getType()));
1065   if (!TP->getName().empty())
1066     addString(ParamDIE, dwarf::DW_AT_name, TP->getName());
1067 }
1068
1069 void DwarfUnit::constructTemplateValueParameterDIE(
1070     DIE &Buffer, const DITemplateValueParameter *VP) {
1071   DIE &ParamDIE = createAndAddDIE(VP->getTag(), Buffer);
1072
1073   // Add the type if there is one, template template and template parameter
1074   // packs will not have a type.
1075   if (VP->getTag() == dwarf::DW_TAG_template_value_parameter)
1076     addType(ParamDIE, resolve(VP->getType()));
1077   if (!VP->getName().empty())
1078     addString(ParamDIE, dwarf::DW_AT_name, VP->getName());
1079   if (Metadata *Val = VP->getValue()) {
1080     if (ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(Val))
1081       addConstantValue(ParamDIE, CI, resolve(VP->getType()));
1082     else if (GlobalValue *GV = mdconst::dyn_extract<GlobalValue>(Val)) {
1083       // For declaration non-type template parameters (such as global values and
1084       // functions)
1085       DIELoc *Loc = new (DIEValueAllocator) DIELoc();
1086       addOpAddress(*Loc, Asm->getSymbol(GV));
1087       // Emit DW_OP_stack_value to use the address as the immediate value of the
1088       // parameter, rather than a pointer to it.
1089       addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
1090       addBlock(ParamDIE, dwarf::DW_AT_location, Loc);
1091     } else if (VP->getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1092       assert(isa<MDString>(Val));
1093       addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
1094                 cast<MDString>(Val)->getString());
1095     } else if (VP->getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1096       addTemplateParams(ParamDIE, cast<MDTuple>(Val));
1097     }
1098   }
1099 }
1100
1101 DIE *DwarfUnit::getOrCreateNameSpace(const DINamespace *NS) {
1102   // Construct the context before querying for the existence of the DIE in case
1103   // such construction creates the DIE.
1104   DIE *ContextDIE = getOrCreateContextDIE(NS->getScope());
1105
1106   if (DIE *NDie = getDIE(NS))
1107     return NDie;
1108   DIE &NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS);
1109
1110   StringRef Name = NS->getName();
1111   if (!Name.empty())
1112     addString(NDie, dwarf::DW_AT_name, NS->getName());
1113   else
1114     Name = "(anonymous namespace)";
1115   DD->addAccelNamespace(Name, NDie);
1116   addGlobalName(Name, NDie, NS->getScope());
1117   addSourceLine(NDie, NS);
1118   return &NDie;
1119 }
1120
1121 DIE *DwarfUnit::getOrCreateSubprogramDIE(const DISubprogram *SP, bool Minimal) {
1122   // Construct the context before querying for the existence of the DIE in case
1123   // such construction creates the DIE (as is the case for member function
1124   // declarations).
1125   DIE *ContextDIE =
1126       Minimal ? &getUnitDie() : getOrCreateContextDIE(resolve(SP->getScope()));
1127
1128   if (DIE *SPDie = getDIE(SP))
1129     return SPDie;
1130
1131   if (auto *SPDecl = SP->getDeclaration()) {
1132     if (!Minimal) {
1133       // Add subprogram definitions to the CU die directly.
1134       ContextDIE = &getUnitDie();
1135       // Build the decl now to ensure it precedes the definition.
1136       getOrCreateSubprogramDIE(SPDecl);
1137     }
1138   }
1139
1140   // DW_TAG_inlined_subroutine may refer to this DIE.
1141   DIE &SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
1142
1143   // Stop here and fill this in later, depending on whether or not this
1144   // subprogram turns out to have inlined instances or not.
1145   if (SP->isDefinition())
1146     return &SPDie;
1147
1148   applySubprogramAttributes(SP, SPDie);
1149   return &SPDie;
1150 }
1151
1152 bool DwarfUnit::applySubprogramDefinitionAttributes(const DISubprogram *SP,
1153                                                     DIE &SPDie) {
1154   DIE *DeclDie = nullptr;
1155   StringRef DeclLinkageName;
1156   if (auto *SPDecl = SP->getDeclaration()) {
1157     DeclDie = getDIE(SPDecl);
1158     assert(DeclDie && "This DIE should've already been constructed when the "
1159                       "definition DIE was created in "
1160                       "getOrCreateSubprogramDIE");
1161     DeclLinkageName = SPDecl->getLinkageName();
1162   }
1163
1164   // Add function template parameters.
1165   addTemplateParams(SPDie, SP->getTemplateParams());
1166
1167   // Add the linkage name if we have one and it isn't in the Decl.
1168   StringRef LinkageName = SP->getLinkageName();
1169   assert(((LinkageName.empty() || DeclLinkageName.empty()) ||
1170           LinkageName == DeclLinkageName) &&
1171          "decl has a linkage name and it is different");
1172   if (DeclLinkageName.empty())
1173     addLinkageName(SPDie, LinkageName);
1174
1175   if (!DeclDie)
1176     return false;
1177
1178   // Refer to the function declaration where all the other attributes will be
1179   // found.
1180   addDIEEntry(SPDie, dwarf::DW_AT_specification, *DeclDie);
1181   return true;
1182 }
1183
1184 void DwarfUnit::applySubprogramAttributes(const DISubprogram *SP, DIE &SPDie,
1185                                           bool Minimal) {
1186   if (!Minimal)
1187     if (applySubprogramDefinitionAttributes(SP, SPDie))
1188       return;
1189
1190   // Constructors and operators for anonymous aggregates do not have names.
1191   if (!SP->getName().empty())
1192     addString(SPDie, dwarf::DW_AT_name, SP->getName());
1193
1194   // Skip the rest of the attributes under -gmlt to save space.
1195   if (Minimal)
1196     return;
1197
1198   addSourceLine(SPDie, SP);
1199
1200   // Add the prototype if we have a prototype and we have a C like
1201   // language.
1202   uint16_t Language = getLanguage();
1203   if (SP->isPrototyped() &&
1204       (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1205        Language == dwarf::DW_LANG_ObjC))
1206     addFlag(SPDie, dwarf::DW_AT_prototyped);
1207
1208   const DISubroutineType *SPTy = SP->getType();
1209   assert(SPTy->getTag() == dwarf::DW_TAG_subroutine_type &&
1210          "the type of a subprogram should be a subroutine");
1211
1212   auto Args = SPTy->getTypeArray();
1213   // Add a return type. If this is a type like a C/C++ void type we don't add a
1214   // return type.
1215   if (Args.size())
1216     if (auto Ty = resolve(Args[0]))
1217       addType(SPDie, Ty);
1218
1219   unsigned VK = SP->getVirtuality();
1220   if (VK) {
1221     addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1222     DIELoc *Block = getDIELoc();
1223     addUInt(*Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1224     addUInt(*Block, dwarf::DW_FORM_udata, SP->getVirtualIndex());
1225     addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
1226     ContainingTypeMap.insert(
1227         std::make_pair(&SPDie, resolve(SP->getContainingType())));
1228   }
1229
1230   if (!SP->isDefinition()) {
1231     addFlag(SPDie, dwarf::DW_AT_declaration);
1232
1233     // Add arguments. Do not add arguments for subprogram definition. They will
1234     // be handled while processing variables.
1235     constructSubprogramArguments(SPDie, Args);
1236   }
1237
1238   if (SP->isArtificial())
1239     addFlag(SPDie, dwarf::DW_AT_artificial);
1240
1241   if (!SP->isLocalToUnit())
1242     addFlag(SPDie, dwarf::DW_AT_external);
1243
1244   if (SP->isOptimized())
1245     addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1246
1247   if (unsigned isa = Asm->getISAEncoding())
1248     addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1249
1250   if (SP->isLValueReference())
1251     addFlag(SPDie, dwarf::DW_AT_reference);
1252
1253   if (SP->isRValueReference())
1254     addFlag(SPDie, dwarf::DW_AT_rvalue_reference);
1255
1256   if (SP->isProtected())
1257     addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1258             dwarf::DW_ACCESS_protected);
1259   else if (SP->isPrivate())
1260     addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1261             dwarf::DW_ACCESS_private);
1262   else if (SP->isPublic())
1263     addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1264             dwarf::DW_ACCESS_public);
1265
1266   if (SP->isExplicit())
1267     addFlag(SPDie, dwarf::DW_AT_explicit);
1268 }
1269
1270 void DwarfUnit::constructSubrangeDIE(DIE &Buffer, const DISubrange *SR,
1271                                      DIE *IndexTy) {
1272   DIE &DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
1273   addDIEEntry(DW_Subrange, dwarf::DW_AT_type, *IndexTy);
1274
1275   // The LowerBound value defines the lower bounds which is typically zero for
1276   // C/C++. The Count value is the number of elements.  Values are 64 bit. If
1277   // Count == -1 then the array is unbounded and we do not emit
1278   // DW_AT_lower_bound and DW_AT_count attributes.
1279   int64_t LowerBound = SR->getLowerBound();
1280   int64_t DefaultLowerBound = getDefaultLowerBound();
1281   int64_t Count = SR->getCount();
1282
1283   if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
1284     addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound);
1285
1286   if (Count != -1)
1287     // FIXME: An unbounded array should reference the expression that defines
1288     // the array.
1289     addUInt(DW_Subrange, dwarf::DW_AT_count, None, Count);
1290 }
1291
1292 DIE *DwarfUnit::getIndexTyDie() {
1293   if (IndexTyDie)
1294     return IndexTyDie;
1295   // Construct an integer type to use for indexes.
1296   IndexTyDie = &createAndAddDIE(dwarf::DW_TAG_base_type, UnitDie);
1297   addString(*IndexTyDie, dwarf::DW_AT_name, "sizetype");
1298   addUInt(*IndexTyDie, dwarf::DW_AT_byte_size, None, sizeof(int64_t));
1299   addUInt(*IndexTyDie, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1300           dwarf::DW_ATE_unsigned);
1301   return IndexTyDie;
1302 }
1303
1304 void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
1305   if (CTy->isVector())
1306     addFlag(Buffer, dwarf::DW_AT_GNU_vector);
1307
1308   // Emit the element type.
1309   addType(Buffer, resolve(CTy->getBaseType()));
1310
1311   // Get an anonymous type for index type.
1312   // FIXME: This type should be passed down from the front end
1313   // as different languages may have different sizes for indexes.
1314   DIE *IdxTy = getIndexTyDie();
1315
1316   // Add subranges to array type.
1317   DINodeArray Elements = CTy->getElements();
1318   for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
1319     // FIXME: Should this really be such a loose cast?
1320     if (auto *Element = dyn_cast_or_null<DINode>(Elements[i]))
1321       if (Element->getTag() == dwarf::DW_TAG_subrange_type)
1322         constructSubrangeDIE(Buffer, cast<DISubrange>(Element), IdxTy);
1323   }
1324 }
1325
1326 void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
1327   DINodeArray Elements = CTy->getElements();
1328
1329   // Add enumerators to enumeration type.
1330   for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
1331     auto *Enum = dyn_cast_or_null<DIEnumerator>(Elements[i]);
1332     if (Enum) {
1333       DIE &Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
1334       StringRef Name = Enum->getName();
1335       addString(Enumerator, dwarf::DW_AT_name, Name);
1336       int64_t Value = Enum->getValue();
1337       addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
1338               Value);
1339     }
1340   }
1341   const DIType *DTy = resolve(CTy->getBaseType());
1342   if (DTy) {
1343     addType(Buffer, DTy);
1344     addFlag(Buffer, dwarf::DW_AT_enum_class);
1345   }
1346 }
1347
1348 void DwarfUnit::constructContainingTypeDIEs() {
1349   for (auto CI = ContainingTypeMap.begin(), CE = ContainingTypeMap.end();
1350        CI != CE; ++CI) {
1351     DIE &SPDie = *CI->first;
1352     const DINode *D = CI->second;
1353     if (!D)
1354       continue;
1355     DIE *NDie = getDIE(D);
1356     if (!NDie)
1357       continue;
1358     addDIEEntry(SPDie, dwarf::DW_AT_containing_type, *NDie);
1359   }
1360 }
1361
1362 void DwarfUnit::constructMemberDIE(DIE &Buffer, const DIDerivedType *DT) {
1363   DIE &MemberDie = createAndAddDIE(DT->getTag(), Buffer);
1364   StringRef Name = DT->getName();
1365   if (!Name.empty())
1366     addString(MemberDie, dwarf::DW_AT_name, Name);
1367
1368   addType(MemberDie, resolve(DT->getBaseType()));
1369
1370   addSourceLine(MemberDie, DT);
1371
1372   if (DT->getTag() == dwarf::DW_TAG_inheritance && DT->isVirtual()) {
1373
1374     // For C++, virtual base classes are not at fixed offset. Use following
1375     // expression to extract appropriate offset from vtable.
1376     // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1377
1378     DIELoc *VBaseLocationDie = new (DIEValueAllocator) DIELoc();
1379     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1380     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1381     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1382     addUInt(*VBaseLocationDie, dwarf::DW_FORM_udata, DT->getOffsetInBits());
1383     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1384     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1385     addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1386
1387     addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
1388   } else {
1389     uint64_t Size = DT->getSizeInBits();
1390     uint64_t FieldSize = getBaseTypeSize(DD, DT);
1391     uint64_t OffsetInBytes;
1392
1393     if (FieldSize && Size != FieldSize) {
1394       // Handle bitfield, assume bytes are 8 bits.
1395       addUInt(MemberDie, dwarf::DW_AT_byte_size, None, FieldSize/8);
1396       addUInt(MemberDie, dwarf::DW_AT_bit_size, None, Size);
1397
1398       uint64_t Offset = DT->getOffsetInBits();
1399       uint64_t AlignMask = ~(DT->getAlignInBits() - 1);
1400       uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1401       uint64_t FieldOffset = (HiMark - FieldSize);
1402       Offset -= FieldOffset;
1403
1404       // Maybe we need to work from the other end.
1405       if (Asm->getDataLayout().isLittleEndian())
1406         Offset = FieldSize - (Offset + Size);
1407       addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset);
1408
1409       // Here DW_AT_data_member_location points to the anonymous
1410       // field that includes this bit field.
1411       OffsetInBytes = FieldOffset >> 3;
1412     } else
1413       // This is not a bitfield.
1414       OffsetInBytes = DT->getOffsetInBits() >> 3;
1415
1416     if (DD->getDwarfVersion() <= 2) {
1417       DIELoc *MemLocationDie = new (DIEValueAllocator) DIELoc();
1418       addUInt(*MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1419       addUInt(*MemLocationDie, dwarf::DW_FORM_udata, OffsetInBytes);
1420       addBlock(MemberDie, dwarf::DW_AT_data_member_location, MemLocationDie);
1421     } else
1422       addUInt(MemberDie, dwarf::DW_AT_data_member_location, None,
1423               OffsetInBytes);
1424   }
1425
1426   if (DT->isProtected())
1427     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1428             dwarf::DW_ACCESS_protected);
1429   else if (DT->isPrivate())
1430     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1431             dwarf::DW_ACCESS_private);
1432   // Otherwise C++ member and base classes are considered public.
1433   else if (DT->isPublic())
1434     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1435             dwarf::DW_ACCESS_public);
1436   if (DT->isVirtual())
1437     addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1438             dwarf::DW_VIRTUALITY_virtual);
1439
1440   // Objective-C properties.
1441   if (MDNode *PNode = DT->getObjCProperty())
1442     if (DIEEntry *PropertyDie = getDIEEntry(PNode))
1443       MemberDie.addValue(dwarf::DW_AT_APPLE_property, dwarf::DW_FORM_ref4,
1444                          PropertyDie);
1445
1446   if (DT->isArtificial())
1447     addFlag(MemberDie, dwarf::DW_AT_artificial);
1448 }
1449
1450 DIE *DwarfUnit::getOrCreateStaticMemberDIE(const DIDerivedType *DT) {
1451   if (!DT)
1452     return nullptr;
1453
1454   // Construct the context before querying for the existence of the DIE in case
1455   // such construction creates the DIE.
1456   DIE *ContextDIE = getOrCreateContextDIE(resolve(DT->getScope()));
1457   assert(dwarf::isType(ContextDIE->getTag()) &&
1458          "Static member should belong to a type.");
1459
1460   if (DIE *StaticMemberDIE = getDIE(DT))
1461     return StaticMemberDIE;
1462
1463   DIE &StaticMemberDIE = createAndAddDIE(DT->getTag(), *ContextDIE, DT);
1464
1465   const DIType *Ty = resolve(DT->getBaseType());
1466
1467   addString(StaticMemberDIE, dwarf::DW_AT_name, DT->getName());
1468   addType(StaticMemberDIE, Ty);
1469   addSourceLine(StaticMemberDIE, DT);
1470   addFlag(StaticMemberDIE, dwarf::DW_AT_external);
1471   addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
1472
1473   // FIXME: We could omit private if the parent is a class_type, and
1474   // public if the parent is something else.
1475   if (DT->isProtected())
1476     addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1477             dwarf::DW_ACCESS_protected);
1478   else if (DT->isPrivate())
1479     addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1480             dwarf::DW_ACCESS_private);
1481   else if (DT->isPublic())
1482     addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1483             dwarf::DW_ACCESS_public);
1484
1485   if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT->getConstant()))
1486     addConstantValue(StaticMemberDIE, CI, Ty);
1487   if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT->getConstant()))
1488     addConstantFPValue(StaticMemberDIE, CFP);
1489
1490   return &StaticMemberDIE;
1491 }
1492
1493 void DwarfUnit::emitHeader(bool UseOffsets) {
1494   // Emit size of content not including length itself
1495   Asm->OutStreamer->AddComment("Length of Unit");
1496   Asm->EmitInt32(getHeaderSize() + UnitDie.getSize());
1497
1498   Asm->OutStreamer->AddComment("DWARF version number");
1499   Asm->EmitInt16(DD->getDwarfVersion());
1500   Asm->OutStreamer->AddComment("Offset Into Abbrev. Section");
1501
1502   // We share one abbreviations table across all units so it's always at the
1503   // start of the section. Use a relocatable offset where needed to ensure
1504   // linking doesn't invalidate that offset.
1505   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1506   if (!UseOffsets)
1507     Asm->emitSectionOffset(TLOF.getDwarfAbbrevSection()->getBeginSymbol());
1508   else
1509     Asm->EmitInt32(0);
1510
1511   Asm->OutStreamer->AddComment("Address Size (in bytes)");
1512   Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
1513 }
1514
1515 void DwarfUnit::initSection(MCSection *Section) {
1516   assert(!this->Section);
1517   this->Section = Section;
1518 }
1519
1520 void DwarfTypeUnit::emitHeader(bool UseOffsets) {
1521   DwarfUnit::emitHeader(UseOffsets);
1522   Asm->OutStreamer->AddComment("Type Signature");
1523   Asm->OutStreamer->EmitIntValue(TypeSignature, sizeof(TypeSignature));
1524   Asm->OutStreamer->AddComment("Type DIE Offset");
1525   // In a skeleton type unit there is no type DIE so emit a zero offset.
1526   Asm->OutStreamer->EmitIntValue(Ty ? Ty->getOffset() : 0,
1527                                  sizeof(Ty->getOffset()));
1528 }
1529
1530 bool DwarfTypeUnit::isDwoUnit() const {
1531   // Since there are no skeleton type units, all type units are dwo type units
1532   // when split DWARF is being used.
1533   return DD->useSplitDwarf();
1534 }