DwarfCompileUnit.cpp revision 14268416720155d63f190a6143ee40b3b850e409
1//===-- llvm/CodeGen/DwarfCompileUnit.cpp - Dwarf Compile Unit ------------===//
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#define DEBUG_TYPE "dwarfdebug"
15
16#include "DwarfCompileUnit.h"
17#include "DwarfAccelTable.h"
18#include "DwarfDebug.h"
19#include "llvm/ADT/APFloat.h"
20#include "llvm/DIBuilder.h"
21#include "llvm/IR/Constants.h"
22#include "llvm/IR/DataLayout.h"
23#include "llvm/IR/GlobalVariable.h"
24#include "llvm/IR/Instructions.h"
25#include "llvm/Support/Debug.h"
26#include "llvm/Support/ErrorHandling.h"
27#include "llvm/Target/Mangler.h"
28#include "llvm/Target/TargetFrameLowering.h"
29#include "llvm/Target/TargetMachine.h"
30#include "llvm/Target/TargetRegisterInfo.h"
31
32using namespace llvm;
33
34/// CompileUnit - Compile unit constructor.
35CompileUnit::CompileUnit(unsigned UID, unsigned L, DIE *D, AsmPrinter *A,
36                         DwarfDebug *DW, DwarfUnits *DWU)
37  : UniqueID(UID), Language(L), CUDie(D), Asm(A), DD(DW), DU(DWU),
38    IndexTyDie(0) {
39  DIEIntegerOne = new (DIEValueAllocator) DIEInteger(1);
40}
41
42/// ~CompileUnit - Destructor for compile unit.
43CompileUnit::~CompileUnit() {
44  for (unsigned j = 0, M = DIEBlocks.size(); j < M; ++j)
45    DIEBlocks[j]->~DIEBlock();
46}
47
48/// createDIEEntry - Creates a new DIEEntry to be a proxy for a debug
49/// information entry.
50DIEEntry *CompileUnit::createDIEEntry(DIE *Entry) {
51  DIEEntry *Value = new (DIEValueAllocator) DIEEntry(Entry);
52  return Value;
53}
54
55/// getDefaultLowerBound - Return the default lower bound for an array. If the
56/// DWARF version doesn't handle the language, return -1.
57int64_t CompileUnit::getDefaultLowerBound() const {
58  switch (Language) {
59  default:
60    break;
61
62  case dwarf::DW_LANG_C89:
63  case dwarf::DW_LANG_C99:
64  case dwarf::DW_LANG_C:
65  case dwarf::DW_LANG_C_plus_plus:
66  case dwarf::DW_LANG_ObjC:
67  case dwarf::DW_LANG_ObjC_plus_plus:
68    return 0;
69
70  case dwarf::DW_LANG_Fortran77:
71  case dwarf::DW_LANG_Fortran90:
72  case dwarf::DW_LANG_Fortran95:
73    return 1;
74
75  // The languages below have valid values only if the DWARF version >= 4.
76  case dwarf::DW_LANG_Java:
77  case dwarf::DW_LANG_Python:
78  case dwarf::DW_LANG_UPC:
79  case dwarf::DW_LANG_D:
80    if (dwarf::DWARF_VERSION >= 4)
81      return 0;
82    break;
83
84  case dwarf::DW_LANG_Ada83:
85  case dwarf::DW_LANG_Ada95:
86  case dwarf::DW_LANG_Cobol74:
87  case dwarf::DW_LANG_Cobol85:
88  case dwarf::DW_LANG_Modula2:
89  case dwarf::DW_LANG_Pascal83:
90  case dwarf::DW_LANG_PLI:
91    if (dwarf::DWARF_VERSION >= 4)
92      return 1;
93    break;
94  }
95
96  return -1;
97}
98
99/// addFlag - Add a flag that is true.
100void CompileUnit::addFlag(DIE *Die, unsigned Attribute) {
101  if (!DD->useDarwinGDBCompat())
102    Die->addValue(Attribute, dwarf::DW_FORM_flag_present,
103                  DIEIntegerOne);
104  else
105    addUInt(Die, Attribute, dwarf::DW_FORM_flag, 1);
106}
107
108/// addUInt - Add an unsigned integer attribute data and value.
109///
110void CompileUnit::addUInt(DIE *Die, unsigned Attribute,
111                          unsigned Form, uint64_t Integer) {
112  if (!Form) Form = DIEInteger::BestForm(false, Integer);
113  DIEValue *Value = Integer == 1 ?
114    DIEIntegerOne : new (DIEValueAllocator) DIEInteger(Integer);
115  Die->addValue(Attribute, Form, Value);
116}
117
118/// addSInt - Add an signed integer attribute data and value.
119///
120void CompileUnit::addSInt(DIE *Die, unsigned Attribute,
121                          unsigned Form, int64_t Integer) {
122  if (!Form) Form = DIEInteger::BestForm(true, Integer);
123  DIEValue *Value = new (DIEValueAllocator) DIEInteger(Integer);
124  Die->addValue(Attribute, Form, Value);
125}
126
127/// addString - Add a string attribute data and value. We always emit a
128/// reference to the string pool instead of immediate strings so that DIEs have
129/// more predictable sizes. In the case of split dwarf we emit an index
130/// into another table which gets us the static offset into the string
131/// table.
132void CompileUnit::addString(DIE *Die, unsigned Attribute, StringRef String) {
133  if (!DD->useSplitDwarf()) {
134    MCSymbol *Symb = DU->getStringPoolEntry(String);
135    DIEValue *Value;
136    if (Asm->needsRelocationsForDwarfStringPool())
137      Value = new (DIEValueAllocator) DIELabel(Symb);
138    else {
139      MCSymbol *StringPool = DU->getStringPoolSym();
140      Value = new (DIEValueAllocator) DIEDelta(Symb, StringPool);
141    }
142    Die->addValue(Attribute, dwarf::DW_FORM_strp, Value);
143  } else {
144    unsigned idx = DU->getStringPoolIndex(String);
145    DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
146    Die->addValue(Attribute, dwarf::DW_FORM_GNU_str_index, Value);
147  }
148}
149
150/// addLocalString - Add a string attribute data and value. This is guaranteed
151/// to be in the local string pool instead of indirected.
152void CompileUnit::addLocalString(DIE *Die, unsigned Attribute,
153                                 StringRef String) {
154  MCSymbol *Symb = DU->getStringPoolEntry(String);
155  DIEValue *Value;
156  if (Asm->needsRelocationsForDwarfStringPool())
157    Value = new (DIEValueAllocator) DIELabel(Symb);
158  else {
159    MCSymbol *StringPool = DU->getStringPoolSym();
160    Value = new (DIEValueAllocator) DIEDelta(Symb, StringPool);
161  }
162  Die->addValue(Attribute, dwarf::DW_FORM_strp, Value);
163}
164
165/// addLabel - Add a Dwarf label attribute data and value.
166///
167void CompileUnit::addLabel(DIE *Die, unsigned Attribute, unsigned Form,
168                           const MCSymbol *Label) {
169  DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
170  Die->addValue(Attribute, Form, Value);
171}
172
173/// addLabelAddress - Add a dwarf label attribute data and value using
174/// DW_FORM_addr or DW_FORM_GNU_addr_index.
175///
176void CompileUnit::addLabelAddress(DIE *Die, unsigned Attribute,
177                                  MCSymbol *Label) {
178  if (!DD->useSplitDwarf()) {
179    if (Label != NULL) {
180      DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
181      Die->addValue(Attribute, dwarf::DW_FORM_addr, Value);
182    } else {
183      DIEValue *Value = new (DIEValueAllocator) DIEInteger(0);
184      Die->addValue(Attribute, dwarf::DW_FORM_addr, Value);
185    }
186  } else {
187    unsigned idx = DU->getAddrPoolIndex(Label);
188    DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
189    Die->addValue(Attribute, dwarf::DW_FORM_GNU_addr_index, Value);
190  }
191}
192
193/// addOpAddress - Add a dwarf op address data and value using the
194/// form given and an op of either DW_FORM_addr or DW_FORM_GNU_addr_index.
195///
196void CompileUnit::addOpAddress(DIE *Die, MCSymbol *Sym) {
197
198  if (!DD->useSplitDwarf()) {
199    addUInt(Die, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
200    addLabel(Die, 0, dwarf::DW_FORM_udata, Sym);
201  } else {
202    unsigned idx = DU->getAddrPoolIndex(Sym);
203    DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
204    addUInt(Die, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index);
205    Die->addValue(0, dwarf::DW_FORM_GNU_addr_index, Value);
206  }
207}
208
209/// addDelta - Add a label delta attribute data and value.
210///
211void CompileUnit::addDelta(DIE *Die, unsigned Attribute, unsigned Form,
212                           const MCSymbol *Hi, const MCSymbol *Lo) {
213  DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
214  Die->addValue(Attribute, Form, Value);
215}
216
217/// addDIEEntry - Add a DIE attribute data and value.
218///
219void CompileUnit::addDIEEntry(DIE *Die, unsigned Attribute, unsigned Form,
220                              DIE *Entry) {
221  Die->addValue(Attribute, Form, createDIEEntry(Entry));
222}
223
224/// addBlock - Add block data.
225///
226void CompileUnit::addBlock(DIE *Die, unsigned Attribute, unsigned Form,
227                           DIEBlock *Block) {
228  Block->ComputeSize(Asm);
229  DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
230  Die->addValue(Attribute, Block->BestForm(), Block);
231}
232
233/// addSourceLine - Add location information to specified debug information
234/// entry.
235void CompileUnit::addSourceLine(DIE *Die, DIVariable V) {
236  // Verify variable.
237  if (!V.Verify())
238    return;
239
240  unsigned Line = V.getLineNumber();
241  if (Line == 0)
242    return;
243  unsigned FileID = DD->getOrCreateSourceID(V.getContext().getFilename(),
244                                            V.getContext().getDirectory());
245  assert(FileID && "Invalid file id");
246  addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
247  addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
248}
249
250/// addSourceLine - Add location information to specified debug information
251/// entry.
252void CompileUnit::addSourceLine(DIE *Die, DIGlobalVariable G) {
253  // Verify global variable.
254  if (!G.Verify())
255    return;
256
257  unsigned Line = G.getLineNumber();
258  if (Line == 0)
259    return;
260  unsigned FileID = DD->getOrCreateSourceID(G.getFilename(), G.getDirectory());
261  assert(FileID && "Invalid file id");
262  addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
263  addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
264}
265
266/// addSourceLine - Add location information to specified debug information
267/// entry.
268void CompileUnit::addSourceLine(DIE *Die, DISubprogram SP) {
269  // Verify subprogram.
270  if (!SP.Verify())
271    return;
272
273  // If the line number is 0, don't add it.
274  unsigned Line = SP.getLineNumber();
275  if (Line == 0)
276    return;
277
278  unsigned FileID = DD->getOrCreateSourceID(SP.getFilename(),
279                                            SP.getDirectory());
280  assert(FileID && "Invalid file id");
281  addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
282  addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
283}
284
285/// addSourceLine - Add location information to specified debug information
286/// entry.
287void CompileUnit::addSourceLine(DIE *Die, DIType Ty) {
288  // Verify type.
289  if (!Ty.Verify())
290    return;
291
292  unsigned Line = Ty.getLineNumber();
293  if (Line == 0)
294    return;
295  unsigned FileID = DD->getOrCreateSourceID(Ty.getFilename(),
296                                            Ty.getDirectory());
297  assert(FileID && "Invalid file id");
298  addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
299  addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
300}
301
302/// addSourceLine - Add location information to specified debug information
303/// entry.
304void CompileUnit::addSourceLine(DIE *Die, DIObjCProperty Ty) {
305  // Verify type.
306  if (!Ty.Verify())
307    return;
308
309  unsigned Line = Ty.getLineNumber();
310  if (Line == 0)
311    return;
312  DIFile File = Ty.getFile();
313  unsigned FileID = DD->getOrCreateSourceID(File.getFilename(),
314                                            File.getDirectory());
315  assert(FileID && "Invalid file id");
316  addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
317  addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
318}
319
320/// addSourceLine - Add location information to specified debug information
321/// entry.
322void CompileUnit::addSourceLine(DIE *Die, DINameSpace NS) {
323  // Verify namespace.
324  if (!NS.Verify())
325    return;
326
327  unsigned Line = NS.getLineNumber();
328  if (Line == 0)
329    return;
330  StringRef FN = NS.getFilename();
331
332  unsigned FileID = DD->getOrCreateSourceID(FN, NS.getDirectory());
333  assert(FileID && "Invalid file id");
334  addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
335  addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
336}
337
338/// addVariableAddress - Add DW_AT_location attribute for a
339/// DbgVariable based on provided MachineLocation.
340void CompileUnit::addVariableAddress(DbgVariable *&DV, DIE *Die,
341                                     MachineLocation Location) {
342  if (DV->variableHasComplexAddress())
343    addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
344  else if (DV->isBlockByrefVariable())
345    addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location);
346  else
347    addAddress(Die, dwarf::DW_AT_location, Location);
348}
349
350/// addRegisterOp - Add register operand.
351void CompileUnit::addRegisterOp(DIE *TheDie, unsigned Reg) {
352  const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
353  unsigned DWReg = RI->getDwarfRegNum(Reg, false);
354  if (DWReg < 32)
355    addUInt(TheDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + DWReg);
356  else {
357    addUInt(TheDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
358    addUInt(TheDie, 0, dwarf::DW_FORM_udata, DWReg);
359  }
360}
361
362/// addRegisterOffset - Add register offset.
363void CompileUnit::addRegisterOffset(DIE *TheDie, unsigned Reg,
364                                    int64_t Offset) {
365  const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
366  unsigned DWReg = RI->getDwarfRegNum(Reg, false);
367  const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
368  if (Reg == TRI->getFrameRegister(*Asm->MF))
369    // If variable offset is based in frame register then use fbreg.
370    addUInt(TheDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_fbreg);
371  else if (DWReg < 32)
372    addUInt(TheDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + DWReg);
373  else {
374    addUInt(TheDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
375    addUInt(TheDie, 0, dwarf::DW_FORM_udata, DWReg);
376  }
377  addSInt(TheDie, 0, dwarf::DW_FORM_sdata, Offset);
378}
379
380/// addAddress - Add an address attribute to a die based on the location
381/// provided.
382void CompileUnit::addAddress(DIE *Die, unsigned Attribute,
383                             const MachineLocation &Location) {
384  DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
385
386  if (Location.isReg())
387    addRegisterOp(Block, Location.getReg());
388  else
389    addRegisterOffset(Block, Location.getReg(), Location.getOffset());
390
391  // Now attach the location information to the DIE.
392  addBlock(Die, Attribute, 0, Block);
393}
394
395/// addComplexAddress - Start with the address based on the location provided,
396/// and generate the DWARF information necessary to find the actual variable
397/// given the extra address information encoded in the DIVariable, starting from
398/// the starting location.  Add the DWARF information to the die.
399///
400void CompileUnit::addComplexAddress(DbgVariable *&DV, DIE *Die,
401                                    unsigned Attribute,
402                                    const MachineLocation &Location) {
403  DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
404  unsigned N = DV->getNumAddrElements();
405  unsigned i = 0;
406  if (Location.isReg()) {
407    if (N >= 2 && DV->getAddrElement(0) == DIBuilder::OpPlus) {
408      // If first address element is OpPlus then emit
409      // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
410      addRegisterOffset(Block, Location.getReg(), DV->getAddrElement(1));
411      i = 2;
412    } else
413      addRegisterOp(Block, Location.getReg());
414  }
415  else
416    addRegisterOffset(Block, Location.getReg(), Location.getOffset());
417
418  for (;i < N; ++i) {
419    uint64_t Element = DV->getAddrElement(i);
420    if (Element == DIBuilder::OpPlus) {
421      addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
422      addUInt(Block, 0, dwarf::DW_FORM_udata, DV->getAddrElement(++i));
423    } else if (Element == DIBuilder::OpDeref) {
424      if (!Location.isReg())
425        addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
426    } else llvm_unreachable("unknown DIBuilder Opcode");
427  }
428
429  // Now attach the location information to the DIE.
430  addBlock(Die, Attribute, 0, Block);
431}
432
433/* Byref variables, in Blocks, are declared by the programmer as "SomeType
434   VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
435   gives the variable VarName either the struct, or a pointer to the struct, as
436   its type.  This is necessary for various behind-the-scenes things the
437   compiler needs to do with by-reference variables in Blocks.
438
439   However, as far as the original *programmer* is concerned, the variable
440   should still have type 'SomeType', as originally declared.
441
442   The function getBlockByrefType dives into the __Block_byref_x_VarName
443   struct to find the original type of the variable, which is then assigned to
444   the variable's Debug Information Entry as its real type.  So far, so good.
445   However now the debugger will expect the variable VarName to have the type
446   SomeType.  So we need the location attribute for the variable to be an
447   expression that explains to the debugger how to navigate through the
448   pointers and struct to find the actual variable of type SomeType.
449
450   The following function does just that.  We start by getting
451   the "normal" location for the variable. This will be the location
452   of either the struct __Block_byref_x_VarName or the pointer to the
453   struct __Block_byref_x_VarName.
454
455   The struct will look something like:
456
457   struct __Block_byref_x_VarName {
458     ... <various fields>
459     struct __Block_byref_x_VarName *forwarding;
460     ... <various other fields>
461     SomeType VarName;
462     ... <maybe more fields>
463   };
464
465   If we are given the struct directly (as our starting point) we
466   need to tell the debugger to:
467
468   1).  Add the offset of the forwarding field.
469
470   2).  Follow that pointer to get the real __Block_byref_x_VarName
471   struct to use (the real one may have been copied onto the heap).
472
473   3).  Add the offset for the field VarName, to find the actual variable.
474
475   If we started with a pointer to the struct, then we need to
476   dereference that pointer first, before the other steps.
477   Translating this into DWARF ops, we will need to append the following
478   to the current location description for the variable:
479
480   DW_OP_deref                    -- optional, if we start with a pointer
481   DW_OP_plus_uconst <forward_fld_offset>
482   DW_OP_deref
483   DW_OP_plus_uconst <varName_fld_offset>
484
485   That is what this function does.  */
486
487/// addBlockByrefAddress - Start with the address based on the location
488/// provided, and generate the DWARF information necessary to find the
489/// actual Block variable (navigating the Block struct) based on the
490/// starting location.  Add the DWARF information to the die.  For
491/// more information, read large comment just above here.
492///
493void CompileUnit::addBlockByrefAddress(DbgVariable *&DV, DIE *Die,
494                                       unsigned Attribute,
495                                       const MachineLocation &Location) {
496  DIType Ty = DV->getType();
497  DIType TmpTy = Ty;
498  unsigned Tag = Ty.getTag();
499  bool isPointer = false;
500
501  StringRef varName = DV->getName();
502
503  if (Tag == dwarf::DW_TAG_pointer_type) {
504    DIDerivedType DTy = DIDerivedType(Ty);
505    TmpTy = DTy.getTypeDerivedFrom();
506    isPointer = true;
507  }
508
509  DICompositeType blockStruct = DICompositeType(TmpTy);
510
511  // Find the __forwarding field and the variable field in the __Block_byref
512  // struct.
513  DIArray Fields = blockStruct.getTypeArray();
514  DIDescriptor varField = DIDescriptor();
515  DIDescriptor forwardingField = DIDescriptor();
516
517  for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
518    DIDescriptor Element = Fields.getElement(i);
519    DIDerivedType DT = DIDerivedType(Element);
520    StringRef fieldName = DT.getName();
521    if (fieldName == "__forwarding")
522      forwardingField = Element;
523    else if (fieldName == varName)
524      varField = Element;
525  }
526
527  // Get the offsets for the forwarding field and the variable field.
528  unsigned forwardingFieldOffset =
529    DIDerivedType(forwardingField).getOffsetInBits() >> 3;
530  unsigned varFieldOffset =
531    DIDerivedType(varField).getOffsetInBits() >> 3;
532
533  // Decode the original location, and use that as the start of the byref
534  // variable's location.
535  DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
536
537  if (Location.isReg())
538    addRegisterOp(Block, Location.getReg());
539  else
540    addRegisterOffset(Block, Location.getReg(), Location.getOffset());
541
542  // If we started with a pointer to the __Block_byref... struct, then
543  // the first thing we need to do is dereference the pointer (DW_OP_deref).
544  if (isPointer)
545    addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
546
547  // Next add the offset for the '__forwarding' field:
548  // DW_OP_plus_uconst ForwardingFieldOffset.  Note there's no point in
549  // adding the offset if it's 0.
550  if (forwardingFieldOffset > 0) {
551    addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
552    addUInt(Block, 0, dwarf::DW_FORM_udata, forwardingFieldOffset);
553  }
554
555  // Now dereference the __forwarding field to get to the real __Block_byref
556  // struct:  DW_OP_deref.
557  addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
558
559  // Now that we've got the real __Block_byref... struct, add the offset
560  // for the variable's field to get to the location of the actual variable:
561  // DW_OP_plus_uconst varFieldOffset.  Again, don't add if it's 0.
562  if (varFieldOffset > 0) {
563    addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
564    addUInt(Block, 0, dwarf::DW_FORM_udata, varFieldOffset);
565  }
566
567  // Now attach the location information to the DIE.
568  addBlock(Die, Attribute, 0, Block);
569}
570
571/// isTypeSigned - Return true if the type is signed.
572static bool isTypeSigned(DIType Ty, int *SizeInBits) {
573  if (Ty.isDerivedType())
574    return isTypeSigned(DIDerivedType(Ty).getTypeDerivedFrom(), SizeInBits);
575  if (Ty.isBasicType())
576    if (DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed
577        || DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed_char) {
578      *SizeInBits = Ty.getSizeInBits();
579      return true;
580    }
581  return false;
582}
583
584/// addConstantValue - Add constant value entry in variable DIE.
585bool CompileUnit::addConstantValue(DIE *Die, const MachineOperand &MO,
586                                   DIType Ty) {
587  assert(MO.isImm() && "Invalid machine operand!");
588  DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
589  int SizeInBits = -1;
590  bool SignedConstant = isTypeSigned(Ty, &SizeInBits);
591  unsigned Form = SignedConstant ? dwarf::DW_FORM_sdata : dwarf::DW_FORM_udata;
592  switch (SizeInBits) {
593    case 8:  Form = dwarf::DW_FORM_data1; break;
594    case 16: Form = dwarf::DW_FORM_data2; break;
595    case 32: Form = dwarf::DW_FORM_data4; break;
596    case 64: Form = dwarf::DW_FORM_data8; break;
597    default: break;
598  }
599  SignedConstant ? addSInt(Block, 0, Form, MO.getImm())
600    : addUInt(Block, 0, Form, MO.getImm());
601
602  addBlock(Die, dwarf::DW_AT_const_value, 0, Block);
603  return true;
604}
605
606/// addConstantFPValue - Add constant value entry in variable DIE.
607bool CompileUnit::addConstantFPValue(DIE *Die, const MachineOperand &MO) {
608  assert (MO.isFPImm() && "Invalid machine operand!");
609  DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
610  APFloat FPImm = MO.getFPImm()->getValueAPF();
611
612  // Get the raw data form of the floating point.
613  const APInt FltVal = FPImm.bitcastToAPInt();
614  const char *FltPtr = (const char*)FltVal.getRawData();
615
616  int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
617  bool LittleEndian = Asm->getDataLayout().isLittleEndian();
618  int Incr = (LittleEndian ? 1 : -1);
619  int Start = (LittleEndian ? 0 : NumBytes - 1);
620  int Stop = (LittleEndian ? NumBytes : -1);
621
622  // Output the constant to DWARF one byte at a time.
623  for (; Start != Stop; Start += Incr)
624    addUInt(Block, 0, dwarf::DW_FORM_data1,
625            (unsigned char)0xFF & FltPtr[Start]);
626
627  addBlock(Die, dwarf::DW_AT_const_value, 0, Block);
628  return true;
629}
630
631/// addConstantFPValue - Add constant value entry in variable DIE.
632bool CompileUnit::addConstantFPValue(DIE *Die, const ConstantFP *CFP) {
633  return addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), false);
634}
635
636/// addConstantValue - Add constant value entry in variable DIE.
637bool CompileUnit::addConstantValue(DIE *Die, const ConstantInt *CI,
638                                   bool Unsigned) {
639  return addConstantValue(Die, CI->getValue(), Unsigned);
640}
641
642// addConstantValue - Add constant value entry in variable DIE.
643bool CompileUnit::addConstantValue(DIE *Die, const APInt &Val,
644                                   bool Unsigned) {
645  unsigned CIBitWidth = Val.getBitWidth();
646  if (CIBitWidth <= 64) {
647    unsigned form = 0;
648    switch (CIBitWidth) {
649    case 8: form = dwarf::DW_FORM_data1; break;
650    case 16: form = dwarf::DW_FORM_data2; break;
651    case 32: form = dwarf::DW_FORM_data4; break;
652    case 64: form = dwarf::DW_FORM_data8; break;
653    default:
654      form = Unsigned ? dwarf::DW_FORM_udata : dwarf::DW_FORM_sdata;
655    }
656    if (Unsigned)
657      addUInt(Die, dwarf::DW_AT_const_value, form, Val.getZExtValue());
658    else
659      addSInt(Die, dwarf::DW_AT_const_value, form, Val.getSExtValue());
660    return true;
661  }
662
663  DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
664
665  // Get the raw data form of the large APInt.
666  const uint64_t *Ptr64 = Val.getRawData();
667
668  int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
669  bool LittleEndian = Asm->getDataLayout().isLittleEndian();
670
671  // Output the constant to DWARF one byte at a time.
672  for (int i = 0; i < NumBytes; i++) {
673    uint8_t c;
674    if (LittleEndian)
675      c = Ptr64[i / 8] >> (8 * (i & 7));
676    else
677      c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
678    addUInt(Block, 0, dwarf::DW_FORM_data1, c);
679  }
680
681  addBlock(Die, dwarf::DW_AT_const_value, 0, Block);
682  return true;
683}
684
685/// addTemplateParams - Add template parameters in buffer.
686void CompileUnit::addTemplateParams(DIE &Buffer, DIArray TParams) {
687  // Add template parameters.
688  for (unsigned i = 0, e = TParams.getNumElements(); i != e; ++i) {
689    DIDescriptor Element = TParams.getElement(i);
690    if (Element.isTemplateTypeParameter())
691      Buffer.addChild(getOrCreateTemplateTypeParameterDIE(
692                        DITemplateTypeParameter(Element)));
693    else if (Element.isTemplateValueParameter())
694      Buffer.addChild(getOrCreateTemplateValueParameterDIE(
695                        DITemplateValueParameter(Element)));
696  }
697}
698
699/// getOrCreateContextDIE - Get context owner's DIE.
700DIE *CompileUnit::getOrCreateContextDIE(DIDescriptor Context) {
701  if (Context.isType())
702    return getOrCreateTypeDIE(DIType(Context));
703  else if (Context.isNameSpace())
704    return getOrCreateNameSpace(DINameSpace(Context));
705  else if (Context.isSubprogram())
706    return getOrCreateSubprogramDIE(DISubprogram(Context));
707  else
708    return getDIE(Context);
709}
710
711/// addToContextOwner - Add Die into the list of its context owner's children.
712void CompileUnit::addToContextOwner(DIE *Die, DIDescriptor Context) {
713  if (DIE *ContextDIE = getOrCreateContextDIE(Context))
714    ContextDIE->addChild(Die);
715  else
716    addDie(Die);
717}
718
719/// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
720/// given DIType.
721DIE *CompileUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
722  DIType Ty(TyNode);
723  if (!Ty.Verify())
724    return NULL;
725  DIE *TyDIE = getDIE(Ty);
726  if (TyDIE)
727    return TyDIE;
728
729  // Create new type.
730  TyDIE = new DIE(dwarf::DW_TAG_base_type);
731  insertDIE(Ty, TyDIE);
732  if (Ty.isBasicType())
733    constructTypeDIE(*TyDIE, DIBasicType(Ty));
734  else if (Ty.isCompositeType())
735    constructTypeDIE(*TyDIE, DICompositeType(Ty));
736  else {
737    assert(Ty.isDerivedType() && "Unknown kind of DIType");
738    constructTypeDIE(*TyDIE, DIDerivedType(Ty));
739  }
740  // If this is a named finished type then include it in the list of types
741  // for the accelerator tables.
742  if (!Ty.getName().empty() && !Ty.isForwardDecl()) {
743    bool IsImplementation = 0;
744    if (Ty.isCompositeType()) {
745      DICompositeType CT(Ty);
746      // A runtime language of 0 actually means C/C++ and that any
747      // non-negative value is some version of Objective-C/C++.
748      IsImplementation = (CT.getRunTimeLang() == 0) ||
749        CT.isObjcClassComplete();
750    }
751    unsigned Flags = IsImplementation ?
752                     DwarfAccelTable::eTypeFlagClassIsImplementation : 0;
753    addAccelType(Ty.getName(), std::make_pair(TyDIE, Flags));
754  }
755
756  addToContextOwner(TyDIE, Ty.getContext());
757  return TyDIE;
758}
759
760/// addType - Add a new type attribute to the specified entity.
761void CompileUnit::addType(DIE *Entity, DIType Ty, unsigned Attribute) {
762  if (!Ty.Verify())
763    return;
764
765  // Check for pre-existence.
766  DIEEntry *Entry = getDIEEntry(Ty);
767  // If it exists then use the existing value.
768  if (Entry) {
769    Entity->addValue(Attribute, dwarf::DW_FORM_ref4, Entry);
770    return;
771  }
772
773  // Construct type.
774  DIE *Buffer = getOrCreateTypeDIE(Ty);
775
776  // Set up proxy.
777  Entry = createDIEEntry(Buffer);
778  insertDIEEntry(Ty, Entry);
779  Entity->addValue(Attribute, dwarf::DW_FORM_ref4, Entry);
780
781  // If this is a complete composite type then include it in the
782  // list of global types.
783  addGlobalType(Ty);
784}
785
786/// addGlobalType - Add a new global type to the compile unit.
787///
788void CompileUnit::addGlobalType(DIType Ty) {
789  DIDescriptor Context = Ty.getContext();
790  if (Ty.isCompositeType() && !Ty.getName().empty() && !Ty.isForwardDecl()
791      && (!Context || Context.isCompileUnit() || Context.isFile()
792          || Context.isNameSpace()))
793    if (DIEEntry *Entry = getDIEEntry(Ty))
794      GlobalTypes[Ty.getName()] = Entry->getEntry();
795}
796
797/// addPubTypes - Add type for pubtypes section.
798void CompileUnit::addPubTypes(DISubprogram SP) {
799  DICompositeType SPTy = SP.getType();
800  unsigned SPTag = SPTy.getTag();
801  if (SPTag != dwarf::DW_TAG_subroutine_type)
802    return;
803
804  DIArray Args = SPTy.getTypeArray();
805  for (unsigned i = 0, e = Args.getNumElements(); i != e; ++i) {
806    DIType ATy(Args.getElement(i));
807    if (!ATy.Verify())
808      continue;
809    addGlobalType(ATy);
810  }
811}
812
813/// constructTypeDIE - Construct basic type die from DIBasicType.
814void CompileUnit::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
815  // Get core information.
816  StringRef Name = BTy.getName();
817  // Add name if not anonymous or intermediate type.
818  if (!Name.empty())
819    addString(&Buffer, dwarf::DW_AT_name, Name);
820
821  if (BTy.getTag() == dwarf::DW_TAG_unspecified_type) {
822    Buffer.setTag(dwarf::DW_TAG_unspecified_type);
823    // Unspecified types has only name, nothing else.
824    return;
825  }
826
827  Buffer.setTag(dwarf::DW_TAG_base_type);
828  addUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
829          BTy.getEncoding());
830
831  uint64_t Size = BTy.getSizeInBits() >> 3;
832  addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
833}
834
835/// constructTypeDIE - Construct derived type die from DIDerivedType.
836void CompileUnit::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
837  // Get core information.
838  StringRef Name = DTy.getName();
839  uint64_t Size = DTy.getSizeInBits() >> 3;
840  unsigned Tag = DTy.getTag();
841
842  // FIXME - Workaround for templates.
843  if (Tag == dwarf::DW_TAG_inheritance) Tag = dwarf::DW_TAG_reference_type;
844
845  Buffer.setTag(Tag);
846
847  // Map to main type, void will not have a type.
848  DIType FromTy = DTy.getTypeDerivedFrom();
849  addType(&Buffer, FromTy);
850
851  // Add name if not anonymous or intermediate type.
852  if (!Name.empty())
853    addString(&Buffer, dwarf::DW_AT_name, Name);
854
855  // Add size if non-zero (derived types might be zero-sized.)
856  if (Size && Tag != dwarf::DW_TAG_pointer_type)
857    addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
858
859  if (Tag == dwarf::DW_TAG_ptr_to_member_type)
860      addDIEEntry(&Buffer, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4,
861                  getOrCreateTypeDIE(DTy.getClassType()));
862  // Add source line info if available and TyDesc is not a forward declaration.
863  if (!DTy.isForwardDecl())
864    addSourceLine(&Buffer, DTy);
865}
866
867/// constructTypeDIE - Construct type DIE from DICompositeType.
868void CompileUnit::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
869  // Get core information.
870  StringRef Name = CTy.getName();
871
872  uint64_t Size = CTy.getSizeInBits() >> 3;
873  unsigned Tag = CTy.getTag();
874  Buffer.setTag(Tag);
875
876  switch (Tag) {
877  case dwarf::DW_TAG_array_type:
878    constructArrayTypeDIE(Buffer, &CTy);
879    break;
880  case dwarf::DW_TAG_enumeration_type: {
881    DIArray Elements = CTy.getTypeArray();
882
883    // Add enumerators to enumeration type.
884    for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
885      DIE *ElemDie = NULL;
886      DIDescriptor Enum(Elements.getElement(i));
887      if (Enum.isEnumerator()) {
888        ElemDie = constructEnumTypeDIE(DIEnumerator(Enum));
889        Buffer.addChild(ElemDie);
890      }
891    }
892    DIType DTy = CTy.getTypeDerivedFrom();
893    if (DTy.Verify()) {
894      addType(&Buffer, DTy);
895      addUInt(&Buffer, dwarf::DW_AT_enum_class, dwarf::DW_FORM_flag, 1);
896    }
897  }
898    break;
899  case dwarf::DW_TAG_subroutine_type: {
900    // Add return type.
901    DIArray Elements = CTy.getTypeArray();
902    DIDescriptor RTy = Elements.getElement(0);
903    addType(&Buffer, DIType(RTy));
904
905    bool isPrototyped = true;
906    // Add arguments.
907    for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
908      DIDescriptor Ty = Elements.getElement(i);
909      if (Ty.isUnspecifiedParameter()) {
910        DIE *Arg = new DIE(dwarf::DW_TAG_unspecified_parameters);
911        Buffer.addChild(Arg);
912        isPrototyped = false;
913      } else {
914        DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
915        addType(Arg, DIType(Ty));
916        Buffer.addChild(Arg);
917      }
918    }
919    // Add prototype flag if we're dealing with a C language and the
920    // function has been prototyped.
921    if (isPrototyped &&
922        (Language == dwarf::DW_LANG_C89 ||
923         Language == dwarf::DW_LANG_C99 ||
924         Language == dwarf::DW_LANG_ObjC))
925      addFlag(&Buffer, dwarf::DW_AT_prototyped);
926  }
927    break;
928  case dwarf::DW_TAG_structure_type:
929  case dwarf::DW_TAG_union_type:
930  case dwarf::DW_TAG_class_type: {
931    // Add elements to structure type.
932    DIArray Elements = CTy.getTypeArray();
933
934    // A forward struct declared type may not have elements available.
935    unsigned N = Elements.getNumElements();
936    if (N == 0)
937      break;
938
939    // Add elements to structure type.
940    for (unsigned i = 0; i < N; ++i) {
941      DIDescriptor Element = Elements.getElement(i);
942      DIE *ElemDie = NULL;
943      if (Element.isSubprogram()) {
944        DISubprogram SP(Element);
945        ElemDie = getOrCreateSubprogramDIE(DISubprogram(Element));
946        if (SP.isProtected())
947          addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
948                  dwarf::DW_ACCESS_protected);
949        else if (SP.isPrivate())
950          addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
951                  dwarf::DW_ACCESS_private);
952        else
953          addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
954            dwarf::DW_ACCESS_public);
955        if (SP.isExplicit())
956          addFlag(ElemDie, dwarf::DW_AT_explicit);
957      } else if (Element.isDerivedType()) {
958        DIDerivedType DDTy(Element);
959        if (DDTy.getTag() == dwarf::DW_TAG_friend) {
960          ElemDie = new DIE(dwarf::DW_TAG_friend);
961          addType(ElemDie, DDTy.getTypeDerivedFrom(), dwarf::DW_AT_friend);
962        } else if (DDTy.isStaticMember())
963          ElemDie = createStaticMemberDIE(DDTy);
964        else
965          ElemDie = createMemberDIE(DDTy);
966      } else if (Element.isObjCProperty()) {
967        DIObjCProperty Property(Element);
968        ElemDie = new DIE(Property.getTag());
969        StringRef PropertyName = Property.getObjCPropertyName();
970        addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
971        addType(ElemDie, Property.getType());
972        addSourceLine(ElemDie, Property);
973        StringRef GetterName = Property.getObjCPropertyGetterName();
974        if (!GetterName.empty())
975          addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
976        StringRef SetterName = Property.getObjCPropertySetterName();
977        if (!SetterName.empty())
978          addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
979        unsigned PropertyAttributes = 0;
980        if (Property.isReadOnlyObjCProperty())
981          PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readonly;
982        if (Property.isReadWriteObjCProperty())
983          PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readwrite;
984        if (Property.isAssignObjCProperty())
985          PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_assign;
986        if (Property.isRetainObjCProperty())
987          PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_retain;
988        if (Property.isCopyObjCProperty())
989          PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_copy;
990        if (Property.isNonAtomicObjCProperty())
991          PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_nonatomic;
992        if (PropertyAttributes)
993          addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, 0,
994                 PropertyAttributes);
995
996        DIEEntry *Entry = getDIEEntry(Element);
997        if (!Entry) {
998          Entry = createDIEEntry(ElemDie);
999          insertDIEEntry(Element, Entry);
1000        }
1001      } else
1002        continue;
1003      Buffer.addChild(ElemDie);
1004    }
1005
1006    if (CTy.isAppleBlockExtension())
1007      addFlag(&Buffer, dwarf::DW_AT_APPLE_block);
1008
1009    DICompositeType ContainingType = CTy.getContainingType();
1010    if (DIDescriptor(ContainingType).isCompositeType())
1011      addDIEEntry(&Buffer, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4,
1012                  getOrCreateTypeDIE(DIType(ContainingType)));
1013    else {
1014      DIDescriptor Context = CTy.getContext();
1015      addToContextOwner(&Buffer, Context);
1016    }
1017
1018    if (CTy.isObjcClassComplete())
1019      addFlag(&Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
1020
1021    // Add template parameters to a class, structure or union types.
1022    // FIXME: The support isn't in the metadata for this yet.
1023    if (Tag == dwarf::DW_TAG_class_type ||
1024        Tag == dwarf::DW_TAG_structure_type ||
1025        Tag == dwarf::DW_TAG_union_type)
1026      addTemplateParams(Buffer, CTy.getTemplateParams());
1027
1028    break;
1029  }
1030  default:
1031    break;
1032  }
1033
1034  // Add name if not anonymous or intermediate type.
1035  if (!Name.empty())
1036    addString(&Buffer, dwarf::DW_AT_name, Name);
1037
1038  if (Tag == dwarf::DW_TAG_enumeration_type ||
1039      Tag == dwarf::DW_TAG_class_type ||
1040      Tag == dwarf::DW_TAG_structure_type ||
1041      Tag == dwarf::DW_TAG_union_type) {
1042    // Add size if non-zero (derived types might be zero-sized.)
1043    // TODO: Do we care about size for enum forward declarations?
1044    if (Size)
1045      addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
1046    else if (!CTy.isForwardDecl())
1047      // Add zero size if it is not a forward declaration.
1048      addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, 0);
1049
1050    // If we're a forward decl, say so.
1051    if (CTy.isForwardDecl())
1052      addFlag(&Buffer, dwarf::DW_AT_declaration);
1053
1054    // Add source line info if available.
1055    if (!CTy.isForwardDecl())
1056      addSourceLine(&Buffer, CTy);
1057
1058    // No harm in adding the runtime language to the declaration.
1059    unsigned RLang = CTy.getRunTimeLang();
1060    if (RLang)
1061      addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class,
1062              dwarf::DW_FORM_data1, RLang);
1063  }
1064}
1065
1066/// getOrCreateTemplateTypeParameterDIE - Find existing DIE or create new DIE
1067/// for the given DITemplateTypeParameter.
1068DIE *
1069CompileUnit::getOrCreateTemplateTypeParameterDIE(DITemplateTypeParameter TP) {
1070  DIE *ParamDIE = getDIE(TP);
1071  if (ParamDIE)
1072    return ParamDIE;
1073
1074  ParamDIE = new DIE(dwarf::DW_TAG_template_type_parameter);
1075  addType(ParamDIE, TP.getType());
1076  addString(ParamDIE, dwarf::DW_AT_name, TP.getName());
1077  return ParamDIE;
1078}
1079
1080/// getOrCreateTemplateValueParameterDIE - Find existing DIE or create new DIE
1081/// for the given DITemplateValueParameter.
1082DIE *
1083CompileUnit::getOrCreateTemplateValueParameterDIE(DITemplateValueParameter TPV){
1084  DIE *ParamDIE = getDIE(TPV);
1085  if (ParamDIE)
1086    return ParamDIE;
1087
1088  ParamDIE = new DIE(dwarf::DW_TAG_template_value_parameter);
1089  addType(ParamDIE, TPV.getType());
1090  if (!TPV.getName().empty())
1091    addString(ParamDIE, dwarf::DW_AT_name, TPV.getName());
1092  addUInt(ParamDIE, dwarf::DW_AT_const_value, dwarf::DW_FORM_udata,
1093          TPV.getValue());
1094  return ParamDIE;
1095}
1096
1097/// getOrCreateNameSpace - Create a DIE for DINameSpace.
1098DIE *CompileUnit::getOrCreateNameSpace(DINameSpace NS) {
1099  DIE *NDie = getDIE(NS);
1100  if (NDie)
1101    return NDie;
1102  NDie = new DIE(dwarf::DW_TAG_namespace);
1103  insertDIE(NS, NDie);
1104  if (!NS.getName().empty()) {
1105    addString(NDie, dwarf::DW_AT_name, NS.getName());
1106    addAccelNamespace(NS.getName(), NDie);
1107  } else
1108    addAccelNamespace("(anonymous namespace)", NDie);
1109  addSourceLine(NDie, NS);
1110  addToContextOwner(NDie, NS.getContext());
1111  return NDie;
1112}
1113
1114/// getRealLinkageName - If special LLVM prefix that is used to inform the asm
1115/// printer to not emit usual symbol prefix before the symbol name is used then
1116/// return linkage name after skipping this special LLVM prefix.
1117static StringRef getRealLinkageName(StringRef LinkageName) {
1118  char One = '\1';
1119  if (LinkageName.startswith(StringRef(&One, 1)))
1120    return LinkageName.substr(1);
1121  return LinkageName;
1122}
1123
1124/// getOrCreateSubprogramDIE - Create new DIE using SP.
1125DIE *CompileUnit::getOrCreateSubprogramDIE(DISubprogram SP) {
1126  DIE *SPDie = getDIE(SP);
1127  if (SPDie)
1128    return SPDie;
1129
1130  SPDie = new DIE(dwarf::DW_TAG_subprogram);
1131
1132  // DW_TAG_inlined_subroutine may refer to this DIE.
1133  insertDIE(SP, SPDie);
1134
1135  DISubprogram SPDecl = SP.getFunctionDeclaration();
1136  DIE *DeclDie = NULL;
1137  if (SPDecl.isSubprogram()) {
1138    DeclDie = getOrCreateSubprogramDIE(SPDecl);
1139  }
1140
1141  // Add to context owner.
1142  addToContextOwner(SPDie, SP.getContext());
1143
1144  // Add function template parameters.
1145  addTemplateParams(*SPDie, SP.getTemplateParams());
1146
1147  // Unfortunately this code needs to stay here instead of below the
1148  // AT_specification code in order to work around a bug in older
1149  // gdbs that requires the linkage name to resolve multiple template
1150  // functions.
1151  // TODO: Remove this set of code when we get rid of the old gdb
1152  // compatibility.
1153  StringRef LinkageName = SP.getLinkageName();
1154  if (!LinkageName.empty() && DD->useDarwinGDBCompat())
1155    addString(SPDie, dwarf::DW_AT_MIPS_linkage_name,
1156              getRealLinkageName(LinkageName));
1157
1158  // If this DIE is going to refer declaration info using AT_specification
1159  // then there is no need to add other attributes.
1160  if (DeclDie) {
1161    // Refer function declaration directly.
1162    addDIEEntry(SPDie, dwarf::DW_AT_specification, dwarf::DW_FORM_ref4,
1163                DeclDie);
1164
1165    return SPDie;
1166  }
1167
1168  // Add the linkage name if we have one.
1169  if (!LinkageName.empty() && !DD->useDarwinGDBCompat())
1170    addString(SPDie, dwarf::DW_AT_MIPS_linkage_name,
1171              getRealLinkageName(LinkageName));
1172
1173  // Constructors and operators for anonymous aggregates do not have names.
1174  if (!SP.getName().empty())
1175    addString(SPDie, dwarf::DW_AT_name, SP.getName());
1176
1177  addSourceLine(SPDie, SP);
1178
1179  // Add the prototype if we have a prototype and we have a C like
1180  // language.
1181  if (SP.isPrototyped() &&
1182      (Language == dwarf::DW_LANG_C89 ||
1183       Language == dwarf::DW_LANG_C99 ||
1184       Language == dwarf::DW_LANG_ObjC))
1185    addFlag(SPDie, dwarf::DW_AT_prototyped);
1186
1187  // Add Return Type.
1188  DICompositeType SPTy = SP.getType();
1189  DIArray Args = SPTy.getTypeArray();
1190  unsigned SPTag = SPTy.getTag();
1191
1192  if (Args.getNumElements() == 0 || SPTag != dwarf::DW_TAG_subroutine_type)
1193    addType(SPDie, SPTy);
1194  else
1195    addType(SPDie, DIType(Args.getElement(0)));
1196
1197  unsigned VK = SP.getVirtuality();
1198  if (VK) {
1199    addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1200    DIEBlock *Block = getDIEBlock();
1201    addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1202    addUInt(Block, 0, dwarf::DW_FORM_udata, SP.getVirtualIndex());
1203    addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, 0, Block);
1204    ContainingTypeMap.insert(std::make_pair(SPDie,
1205                                            SP.getContainingType()));
1206  }
1207
1208  if (!SP.isDefinition()) {
1209    addFlag(SPDie, dwarf::DW_AT_declaration);
1210
1211    // Add arguments. Do not add arguments for subprogram definition. They will
1212    // be handled while processing variables.
1213    DICompositeType SPTy = SP.getType();
1214    DIArray Args = SPTy.getTypeArray();
1215    unsigned SPTag = SPTy.getTag();
1216
1217    if (SPTag == dwarf::DW_TAG_subroutine_type)
1218      for (unsigned i = 1, N =  Args.getNumElements(); i < N; ++i) {
1219        DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1220        DIType ATy = DIType(Args.getElement(i));
1221        addType(Arg, ATy);
1222        if (ATy.isArtificial())
1223          addFlag(Arg, dwarf::DW_AT_artificial);
1224        SPDie->addChild(Arg);
1225      }
1226  }
1227
1228  if (SP.isArtificial())
1229    addFlag(SPDie, dwarf::DW_AT_artificial);
1230
1231  if (!SP.isLocalToUnit())
1232    addFlag(SPDie, dwarf::DW_AT_external);
1233
1234  if (SP.isOptimized())
1235    addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1236
1237  if (unsigned isa = Asm->getISAEncoding()) {
1238    addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1239  }
1240
1241  return SPDie;
1242}
1243
1244// Return const expression if value is a GEP to access merged global
1245// constant. e.g.
1246// i8* getelementptr ({ i8, i8, i8, i8 }* @_MergedGlobals, i32 0, i32 0)
1247static const ConstantExpr *getMergedGlobalExpr(const Value *V) {
1248  const ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(V);
1249  if (!CE || CE->getNumOperands() != 3 ||
1250      CE->getOpcode() != Instruction::GetElementPtr)
1251    return NULL;
1252
1253  // First operand points to a global struct.
1254  Value *Ptr = CE->getOperand(0);
1255  if (!isa<GlobalValue>(Ptr) ||
1256      !isa<StructType>(cast<PointerType>(Ptr->getType())->getElementType()))
1257    return NULL;
1258
1259  // Second operand is zero.
1260  const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(CE->getOperand(1));
1261  if (!CI || !CI->isZero())
1262    return NULL;
1263
1264  // Third operand is offset.
1265  if (!isa<ConstantInt>(CE->getOperand(2)))
1266    return NULL;
1267
1268  return CE;
1269}
1270
1271/// createGlobalVariableDIE - create global variable DIE.
1272void CompileUnit::createGlobalVariableDIE(const MDNode *N) {
1273  // Check for pre-existence.
1274  if (getDIE(N))
1275    return;
1276
1277  DIGlobalVariable GV(N);
1278  if (!GV.Verify())
1279    return;
1280
1281  DIDescriptor GVContext = GV.getContext();
1282  DIType GTy = GV.getType();
1283
1284  // If this is a static data member definition, some attributes belong
1285  // to the declaration DIE.
1286  DIE *VariableDIE = NULL;
1287  DIDerivedType SDMDecl = GV.getStaticDataMemberDeclaration();
1288  if (SDMDecl.Verify()) {
1289    assert(SDMDecl.isStaticMember() && "Expected static member decl");
1290    // We need the declaration DIE that is in the static member's class.
1291    // But that class might not exist in the DWARF yet.
1292    // Creating the class will create the static member decl DIE.
1293    getOrCreateContextDIE(SDMDecl.getContext());
1294    VariableDIE = getDIE(SDMDecl);
1295    assert(VariableDIE && "Static member decl has no context?");
1296  }
1297
1298  // If this is not a static data member definition, create the variable
1299  // DIE and add the initial set of attributes to it.
1300  if (!VariableDIE) {
1301    VariableDIE = new DIE(GV.getTag());
1302    // Add to map.
1303    insertDIE(N, VariableDIE);
1304
1305    // Add name and type.
1306    addString(VariableDIE, dwarf::DW_AT_name, GV.getDisplayName());
1307    addType(VariableDIE, GTy);
1308
1309    // Add scoping info.
1310    if (!GV.isLocalToUnit())
1311      addFlag(VariableDIE, dwarf::DW_AT_external);
1312
1313    // Add line number info.
1314    addSourceLine(VariableDIE, GV);
1315    // Add to context owner.
1316    addToContextOwner(VariableDIE, GVContext);
1317  }
1318
1319  // Add location.
1320  bool addToAccelTable = false;
1321  DIE *VariableSpecDIE = NULL;
1322  bool isGlobalVariable = GV.getGlobal() != NULL;
1323  if (isGlobalVariable) {
1324    addToAccelTable = true;
1325    DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1326    addOpAddress(Block, Asm->Mang->getSymbol(GV.getGlobal()));
1327    // Do not create specification DIE if context is either compile unit
1328    // or a subprogram.
1329    if (GVContext && GV.isDefinition() && !GVContext.isCompileUnit() &&
1330        !GVContext.isFile() && !isSubprogramContext(GVContext)) {
1331      // Create specification DIE.
1332      VariableSpecDIE = new DIE(dwarf::DW_TAG_variable);
1333      addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification,
1334                  dwarf::DW_FORM_ref4, VariableDIE);
1335      addBlock(VariableSpecDIE, dwarf::DW_AT_location, 0, Block);
1336      // A static member's declaration is already flagged as such.
1337      if (!SDMDecl.Verify())
1338        addFlag(VariableDIE, dwarf::DW_AT_declaration);
1339      addDie(VariableSpecDIE);
1340    } else {
1341      addBlock(VariableDIE, dwarf::DW_AT_location, 0, Block);
1342    }
1343    // Add linkage name.
1344    StringRef LinkageName = GV.getLinkageName();
1345    if (!LinkageName.empty() && isGlobalVariable)
1346      addString(VariableDIE, dwarf::DW_AT_MIPS_linkage_name,
1347                getRealLinkageName(LinkageName));
1348  } else if (const ConstantInt *CI =
1349             dyn_cast_or_null<ConstantInt>(GV.getConstant()))
1350    addConstantValue(VariableDIE, CI, GTy.isUnsignedDIType());
1351  else if (const ConstantExpr *CE = getMergedGlobalExpr(N->getOperand(11))) {
1352    addToAccelTable = true;
1353    // GV is a merged global.
1354    DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1355    Value *Ptr = CE->getOperand(0);
1356    addOpAddress(Block, Asm->Mang->getSymbol(cast<GlobalValue>(Ptr)));
1357    addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1358    SmallVector<Value*, 3> Idx(CE->op_begin()+1, CE->op_end());
1359    addUInt(Block, 0, dwarf::DW_FORM_udata,
1360                   Asm->getDataLayout().getIndexedOffset(Ptr->getType(), Idx));
1361    addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1362    addBlock(VariableDIE, dwarf::DW_AT_location, 0, Block);
1363  }
1364
1365  if (addToAccelTable) {
1366    DIE *AddrDIE = VariableSpecDIE ? VariableSpecDIE : VariableDIE;
1367    addAccelName(GV.getName(), AddrDIE);
1368
1369    // If the linkage name is different than the name, go ahead and output
1370    // that as well into the name table.
1371    if (GV.getLinkageName() != "" && GV.getName() != GV.getLinkageName())
1372      addAccelName(GV.getLinkageName(), AddrDIE);
1373  }
1374
1375  return;
1376}
1377
1378/// constructSubrangeDIE - Construct subrange DIE from DISubrange.
1379void CompileUnit::constructSubrangeDIE(DIE &Buffer, DISubrange SR,
1380                                       DIE *IndexTy) {
1381  DIE *DW_Subrange = new DIE(dwarf::DW_TAG_subrange_type);
1382  addDIEEntry(DW_Subrange, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, IndexTy);
1383
1384  // The LowerBound value defines the lower bounds which is typically zero for
1385  // C/C++. The Count value is the number of elements.  Values are 64 bit. If
1386  // Count == -1 then the array is unbounded and we do not emit
1387  // DW_AT_lower_bound and DW_AT_upper_bound attributes. If LowerBound == 0 and
1388  // Count == 0, then the array has zero elements in which case we do not emit
1389  // an upper bound.
1390  int64_t LowerBound = SR.getLo();
1391  int64_t DefaultLowerBound = getDefaultLowerBound();
1392  int64_t Count = SR.getCount();
1393
1394  if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
1395    addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, 0, LowerBound);
1396
1397  if (Count != -1 && Count != 0)
1398    // FIXME: An unbounded array should reference the expression that defines
1399    // the array.
1400    addUInt(DW_Subrange, dwarf::DW_AT_upper_bound, 0, LowerBound + Count - 1);
1401
1402  Buffer.addChild(DW_Subrange);
1403}
1404
1405/// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
1406void CompileUnit::constructArrayTypeDIE(DIE &Buffer,
1407                                        DICompositeType *CTy) {
1408  Buffer.setTag(dwarf::DW_TAG_array_type);
1409  if (CTy->isVector())
1410    addFlag(&Buffer, dwarf::DW_AT_GNU_vector);
1411
1412  // Emit derived type.
1413  addType(&Buffer, CTy->getTypeDerivedFrom());
1414  DIArray Elements = CTy->getTypeArray();
1415
1416  // Get an anonymous type for index type.
1417  // FIXME: This type should be passed down from the front end
1418  // as different languages may have different sizes for indexes.
1419  DIE *IdxTy = getIndexTyDie();
1420  if (!IdxTy) {
1421    // Construct an anonymous type for index type.
1422    IdxTy = new DIE(dwarf::DW_TAG_base_type);
1423    addString(IdxTy, dwarf::DW_AT_name, "int");
1424    addUInt(IdxTy, dwarf::DW_AT_byte_size, 0, sizeof(int32_t));
1425    addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1426            dwarf::DW_ATE_signed);
1427    addDie(IdxTy);
1428    setIndexTyDie(IdxTy);
1429  }
1430
1431  // Add subranges to array type.
1432  for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1433    DIDescriptor Element = Elements.getElement(i);
1434    if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1435      constructSubrangeDIE(Buffer, DISubrange(Element), IdxTy);
1436  }
1437}
1438
1439/// constructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
1440DIE *CompileUnit::constructEnumTypeDIE(DIEnumerator ETy) {
1441  DIE *Enumerator = new DIE(dwarf::DW_TAG_enumerator);
1442  StringRef Name = ETy.getName();
1443  addString(Enumerator, dwarf::DW_AT_name, Name);
1444  int64_t Value = ETy.getEnumValue();
1445  addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, Value);
1446  return Enumerator;
1447}
1448
1449/// constructContainingTypeDIEs - Construct DIEs for types that contain
1450/// vtables.
1451void CompileUnit::constructContainingTypeDIEs() {
1452  for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(),
1453         CE = ContainingTypeMap.end(); CI != CE; ++CI) {
1454    DIE *SPDie = CI->first;
1455    const MDNode *N = CI->second;
1456    if (!N) continue;
1457    DIE *NDie = getDIE(N);
1458    if (!NDie) continue;
1459    addDIEEntry(SPDie, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4, NDie);
1460  }
1461}
1462
1463/// constructVariableDIE - Construct a DIE for the given DbgVariable.
1464DIE *CompileUnit::constructVariableDIE(DbgVariable *DV, bool isScopeAbstract) {
1465  StringRef Name = DV->getName();
1466
1467  // Translate tag to proper Dwarf tag.
1468  unsigned Tag = DV->getTag();
1469
1470  // Define variable debug information entry.
1471  DIE *VariableDie = new DIE(Tag);
1472  DbgVariable *AbsVar = DV->getAbstractVariable();
1473  DIE *AbsDIE = AbsVar ? AbsVar->getDIE() : NULL;
1474  if (AbsDIE)
1475    addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin,
1476                            dwarf::DW_FORM_ref4, AbsDIE);
1477  else {
1478    addString(VariableDie, dwarf::DW_AT_name, Name);
1479    addSourceLine(VariableDie, DV->getVariable());
1480    addType(VariableDie, DV->getType());
1481  }
1482
1483  if (DV->isArtificial())
1484    addFlag(VariableDie, dwarf::DW_AT_artificial);
1485
1486  if (isScopeAbstract) {
1487    DV->setDIE(VariableDie);
1488    return VariableDie;
1489  }
1490
1491  // Add variable address.
1492
1493  unsigned Offset = DV->getDotDebugLocOffset();
1494  if (Offset != ~0U) {
1495    addLabel(VariableDie, dwarf::DW_AT_location,
1496                         dwarf::DW_FORM_data4,
1497                         Asm->GetTempSymbol("debug_loc", Offset));
1498    DV->setDIE(VariableDie);
1499    return VariableDie;
1500  }
1501
1502  // Check if variable is described by a DBG_VALUE instruction.
1503  if (const MachineInstr *DVInsn = DV->getMInsn()) {
1504    bool updated = false;
1505    if (DVInsn->getNumOperands() == 3) {
1506      if (DVInsn->getOperand(0).isReg()) {
1507        const MachineOperand RegOp = DVInsn->getOperand(0);
1508        const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1509        if (DVInsn->getOperand(1).isImm() &&
1510            TRI->getFrameRegister(*Asm->MF) == RegOp.getReg()) {
1511          unsigned FrameReg = 0;
1512          const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
1513          int Offset =
1514            TFI->getFrameIndexReference(*Asm->MF,
1515                                        DVInsn->getOperand(1).getImm(),
1516                                        FrameReg);
1517          MachineLocation Location(FrameReg, Offset);
1518          addVariableAddress(DV, VariableDie, Location);
1519
1520        } else if (RegOp.getReg())
1521          addVariableAddress(DV, VariableDie,
1522                                         MachineLocation(RegOp.getReg()));
1523        updated = true;
1524      }
1525      else if (DVInsn->getOperand(0).isImm())
1526        updated =
1527          addConstantValue(VariableDie, DVInsn->getOperand(0),
1528                                       DV->getType());
1529      else if (DVInsn->getOperand(0).isFPImm())
1530        updated =
1531          addConstantFPValue(VariableDie, DVInsn->getOperand(0));
1532      else if (DVInsn->getOperand(0).isCImm())
1533        updated =
1534          addConstantValue(VariableDie,
1535                                       DVInsn->getOperand(0).getCImm(),
1536                                       DV->getType().isUnsignedDIType());
1537    } else {
1538      addVariableAddress(DV, VariableDie,
1539                                     Asm->getDebugValueLocation(DVInsn));
1540      updated = true;
1541    }
1542    if (!updated) {
1543      // If variableDie is not updated then DBG_VALUE instruction does not
1544      // have valid variable info.
1545      delete VariableDie;
1546      return NULL;
1547    }
1548    DV->setDIE(VariableDie);
1549    return VariableDie;
1550  } else {
1551    // .. else use frame index.
1552    int FI = DV->getFrameIndex();
1553    if (FI != ~0) {
1554      unsigned FrameReg = 0;
1555      const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
1556      int Offset =
1557        TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
1558      MachineLocation Location(FrameReg, Offset);
1559      addVariableAddress(DV, VariableDie, Location);
1560    }
1561  }
1562
1563  DV->setDIE(VariableDie);
1564  return VariableDie;
1565}
1566
1567/// createMemberDIE - Create new member DIE.
1568DIE *CompileUnit::createMemberDIE(DIDerivedType DT) {
1569  DIE *MemberDie = new DIE(DT.getTag());
1570  StringRef Name = DT.getName();
1571  if (!Name.empty())
1572    addString(MemberDie, dwarf::DW_AT_name, Name);
1573
1574  addType(MemberDie, DT.getTypeDerivedFrom());
1575
1576  addSourceLine(MemberDie, DT);
1577
1578  DIEBlock *MemLocationDie = new (DIEValueAllocator) DIEBlock();
1579  addUInt(MemLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1580
1581  uint64_t Size = DT.getSizeInBits();
1582  uint64_t FieldSize = DT.getOriginalTypeSize();
1583
1584  if (Size != FieldSize) {
1585    // Handle bitfield.
1586    addUInt(MemberDie, dwarf::DW_AT_byte_size, 0, DT.getOriginalTypeSize()>>3);
1587    addUInt(MemberDie, dwarf::DW_AT_bit_size, 0, DT.getSizeInBits());
1588
1589    uint64_t Offset = DT.getOffsetInBits();
1590    uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1591    uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1592    uint64_t FieldOffset = (HiMark - FieldSize);
1593    Offset -= FieldOffset;
1594
1595    // Maybe we need to work from the other end.
1596    if (Asm->getDataLayout().isLittleEndian())
1597      Offset = FieldSize - (Offset + Size);
1598    addUInt(MemberDie, dwarf::DW_AT_bit_offset, 0, Offset);
1599
1600    // Here WD_AT_data_member_location points to the anonymous
1601    // field that includes this bit field.
1602    addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, FieldOffset >> 3);
1603
1604  } else
1605    // This is not a bitfield.
1606    addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits() >> 3);
1607
1608  if (DT.getTag() == dwarf::DW_TAG_inheritance
1609      && DT.isVirtual()) {
1610
1611    // For C++, virtual base classes are not at fixed offset. Use following
1612    // expression to extract appropriate offset from vtable.
1613    // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1614
1615    DIEBlock *VBaseLocationDie = new (DIEValueAllocator) DIEBlock();
1616    addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1617    addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1618    addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1619    addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1620    addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1621    addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1622    addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1623
1624    addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0,
1625             VBaseLocationDie);
1626  } else
1627    addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0, MemLocationDie);
1628
1629  if (DT.isProtected())
1630    addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1631            dwarf::DW_ACCESS_protected);
1632  else if (DT.isPrivate())
1633    addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1634            dwarf::DW_ACCESS_private);
1635  // Otherwise C++ member and base classes are considered public.
1636  else
1637    addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1638            dwarf::DW_ACCESS_public);
1639  if (DT.isVirtual())
1640    addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1641            dwarf::DW_VIRTUALITY_virtual);
1642
1643  // Objective-C properties.
1644  if (MDNode *PNode = DT.getObjCProperty())
1645    if (DIEEntry *PropertyDie = getDIEEntry(PNode))
1646      MemberDie->addValue(dwarf::DW_AT_APPLE_property, dwarf::DW_FORM_ref4,
1647                          PropertyDie);
1648
1649  if (DT.isArtificial())
1650    addFlag(MemberDie, dwarf::DW_AT_artificial);
1651
1652  // This is only for backward compatibility.
1653  StringRef PropertyName = DT.getObjCPropertyName();
1654  if (!PropertyName.empty()) {
1655    addString(MemberDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
1656    StringRef GetterName = DT.getObjCPropertyGetterName();
1657    if (!GetterName.empty())
1658      addString(MemberDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
1659    StringRef SetterName = DT.getObjCPropertySetterName();
1660    if (!SetterName.empty())
1661      addString(MemberDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
1662    unsigned PropertyAttributes = 0;
1663    if (DT.isReadOnlyObjCProperty())
1664      PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readonly;
1665    if (DT.isReadWriteObjCProperty())
1666      PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readwrite;
1667    if (DT.isAssignObjCProperty())
1668      PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_assign;
1669    if (DT.isRetainObjCProperty())
1670      PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_retain;
1671    if (DT.isCopyObjCProperty())
1672      PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_copy;
1673    if (DT.isNonAtomicObjCProperty())
1674      PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_nonatomic;
1675    if (PropertyAttributes)
1676      addUInt(MemberDie, dwarf::DW_AT_APPLE_property_attribute, 0,
1677              PropertyAttributes);
1678  }
1679  return MemberDie;
1680}
1681
1682/// createStaticMemberDIE - Create new DIE for C++ static member.
1683DIE *CompileUnit::createStaticMemberDIE(const DIDerivedType DT) {
1684  if (!DT.Verify())
1685    return NULL;
1686
1687  DIE *StaticMemberDIE = new DIE(DT.getTag());
1688  DIType Ty = DT.getTypeDerivedFrom();
1689
1690  addString(StaticMemberDIE, dwarf::DW_AT_name, DT.getName());
1691  addType(StaticMemberDIE, Ty);
1692  addSourceLine(StaticMemberDIE, DT);
1693  addFlag(StaticMemberDIE, dwarf::DW_AT_external);
1694  addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
1695
1696  // FIXME: We could omit private if the parent is a class_type, and
1697  // public if the parent is something else.
1698  if (DT.isProtected())
1699    addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1700            dwarf::DW_ACCESS_protected);
1701  else if (DT.isPrivate())
1702    addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1703            dwarf::DW_ACCESS_private);
1704  else
1705    addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1706            dwarf::DW_ACCESS_public);
1707
1708  if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT.getConstant()))
1709    addConstantValue(StaticMemberDIE, CI, Ty.isUnsignedDIType());
1710  if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT.getConstant()))
1711    addConstantFPValue(StaticMemberDIE, CFP);
1712
1713  insertDIE(DT, StaticMemberDIE);
1714  return StaticMemberDIE;
1715}
1716