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