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