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