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