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