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