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