Refactor code. Keep dwarf register operation selection logic at one place.
[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/Analysis/DIBuilder.h"
20 #include "llvm/Target/TargetData.h"
21 #include "llvm/Target/TargetFrameLowering.h"
22 #include "llvm/Target/TargetMachine.h"
23 #include "llvm/Target/TargetRegisterInfo.h"
24 #include "llvm/ADT/APFloat.h"
25 #include "llvm/Support/ErrorHandling.h"
26
27 using namespace llvm;
28
29 /// CompileUnit - Compile unit constructor.
30 CompileUnit::CompileUnit(unsigned I, DIE *D, AsmPrinter *A, DwarfDebug *DW)
31   : ID(I), CUDie(D), Asm(A), DD(DW), IndexTyDie(0) {
32   DIEIntegerOne = new (DIEValueAllocator) DIEInteger(1);
33 }
34
35 /// ~CompileUnit - Destructor for compile unit.
36 CompileUnit::~CompileUnit() {
37   for (unsigned j = 0, M = DIEBlocks.size(); j < M; ++j)
38     DIEBlocks[j]->~DIEBlock();
39 }
40
41 /// createDIEEntry - Creates a new DIEEntry to be a proxy for a debug
42 /// information entry.
43 DIEEntry *CompileUnit::createDIEEntry(DIE *Entry) {
44   DIEEntry *Value = new (DIEValueAllocator) DIEEntry(Entry);
45   return Value;
46 }
47
48 /// addUInt - Add an unsigned integer attribute data and value.
49 ///
50 void CompileUnit::addUInt(DIE *Die, unsigned Attribute,
51                           unsigned Form, uint64_t Integer) {
52   if (!Form) Form = DIEInteger::BestForm(false, Integer);
53   DIEValue *Value = Integer == 1 ?
54     DIEIntegerOne : new (DIEValueAllocator) DIEInteger(Integer);
55   Die->addValue(Attribute, Form, Value);
56 }
57
58 /// addSInt - Add an signed integer attribute data and value.
59 ///
60 void CompileUnit::addSInt(DIE *Die, unsigned Attribute,
61                           unsigned Form, int64_t Integer) {
62   if (!Form) Form = DIEInteger::BestForm(true, Integer);
63   DIEValue *Value = new (DIEValueAllocator) DIEInteger(Integer);
64   Die->addValue(Attribute, Form, Value);
65 }
66
67 /// addString - Add a string attribute data and value. DIEString only
68 /// keeps string reference.
69 void CompileUnit::addString(DIE *Die, unsigned Attribute, unsigned Form,
70                             StringRef String) {
71   DIEValue *Value = new (DIEValueAllocator) DIEString(String);
72   Die->addValue(Attribute, Form, Value);
73 }
74
75 /// addLabel - Add a Dwarf label attribute data and value.
76 ///
77 void CompileUnit::addLabel(DIE *Die, unsigned Attribute, unsigned Form,
78                            const MCSymbol *Label) {
79   DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
80   Die->addValue(Attribute, Form, Value);
81 }
82
83 /// addDelta - Add a label delta attribute data and value.
84 ///
85 void CompileUnit::addDelta(DIE *Die, unsigned Attribute, unsigned Form,
86                            const MCSymbol *Hi, const MCSymbol *Lo) {
87   DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
88   Die->addValue(Attribute, Form, Value);
89 }
90
91 /// addDIEEntry - Add a DIE attribute data and value.
92 ///
93 void CompileUnit::addDIEEntry(DIE *Die, unsigned Attribute, unsigned Form,
94                               DIE *Entry) {
95   Die->addValue(Attribute, Form, createDIEEntry(Entry));
96 }
97
98
99 /// addBlock - Add block data.
100 ///
101 void CompileUnit::addBlock(DIE *Die, unsigned Attribute, unsigned Form,
102                            DIEBlock *Block) {
103   Block->ComputeSize(Asm);
104   DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
105   Die->addValue(Attribute, Block->BestForm(), Block);
106 }
107
108 /// addSourceLine - Add location information to specified debug information
109 /// entry.
110 void CompileUnit::addSourceLine(DIE *Die, DIVariable V) {
111   // Verify variable.
112   if (!V.Verify())
113     return;
114   
115   unsigned Line = V.getLineNumber();
116   if (Line == 0)
117     return;
118   unsigned FileID = DD->GetOrCreateSourceID(V.getContext().getFilename(),
119                                             V.getContext().getDirectory());
120   assert(FileID && "Invalid file id");
121   addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
122   addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
123 }
124
125 /// addSourceLine - Add location information to specified debug information
126 /// entry.
127 void CompileUnit::addSourceLine(DIE *Die, DIGlobalVariable G) {
128   // Verify global variable.
129   if (!G.Verify())
130     return;
131
132   unsigned Line = G.getLineNumber();
133   if (Line == 0)
134     return;
135   unsigned FileID = DD->GetOrCreateSourceID(G.getContext().getFilename(),
136                                             G.getContext().getDirectory());
137   assert(FileID && "Invalid file id");
138   addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
139   addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
140 }
141
142 /// addSourceLine - Add location information to specified debug information
143 /// entry.
144 void CompileUnit::addSourceLine(DIE *Die, DISubprogram SP) {
145   // Verify subprogram.
146   if (!SP.Verify())
147     return;
148   // If the line number is 0, don't add it.
149   if (SP.getLineNumber() == 0)
150     return;
151
152   unsigned Line = SP.getLineNumber();
153   if (!SP.getContext().Verify())
154     return;
155   unsigned FileID = DD->GetOrCreateSourceID(SP.getFilename(), SP.getDirectory());
156   assert(FileID && "Invalid file id");
157   addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
158   addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
159 }
160
161 /// addSourceLine - Add location information to specified debug information
162 /// entry.
163 void CompileUnit::addSourceLine(DIE *Die, DIType Ty) {
164   // Verify type.
165   if (!Ty.Verify())
166     return;
167
168   unsigned Line = Ty.getLineNumber();
169   if (Line == 0 || !Ty.getContext().Verify())
170     return;
171   unsigned FileID = DD->GetOrCreateSourceID(Ty.getFilename(), Ty.getDirectory());
172   assert(FileID && "Invalid file id");
173   addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
174   addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
175 }
176
177 /// addSourceLine - Add location information to specified debug information
178 /// entry.
179 void CompileUnit::addSourceLine(DIE *Die, DINameSpace NS) {
180   // Verify namespace.
181   if (!NS.Verify())
182     return;
183
184   unsigned Line = NS.getLineNumber();
185   if (Line == 0)
186     return;
187   StringRef FN = NS.getFilename();
188
189   unsigned FileID = DD->GetOrCreateSourceID(FN, NS.getDirectory());
190   assert(FileID && "Invalid file id");
191   addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
192   addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
193 }
194
195 /// addFrameVariableAddress - Add DW_AT_location attribute for a 
196 /// DbgVariable based on provided frame index.
197 void CompileUnit::addFrameVariableAddress(DbgVariable *&DV, DIE *Die, 
198                                           int64_t FI) {
199   MachineLocation Location;
200   unsigned FrameReg;
201   const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
202   int Offset = TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
203   Location.set(FrameReg, Offset);
204
205   if (DV->variableHasComplexAddress())
206     addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
207   else if (DV->isBlockByrefVariable())
208     addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location);
209   else
210     addAddress(Die, dwarf::DW_AT_location, Location);
211 }
212
213 /// addRegisterOp - Add register operand.
214 void CompileUnit::addRegisterOp(DIE *TheDie, unsigned Reg) {
215   const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
216   unsigned DWReg = RI->getDwarfRegNum(Reg, false);
217   if (DWReg < 32)
218     addUInt(TheDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + DWReg);
219   else {
220     addUInt(TheDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
221     addUInt(TheDie, 0, dwarf::DW_FORM_udata, DWReg);
222   }
223 }
224
225 /// addRegisterOffset - Add register offset.
226 void CompileUnit::addRegisterOffset(DIE *TheDie, unsigned Reg,
227                                     int64_t Offset) {
228   const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
229   unsigned DWReg = RI->getDwarfRegNum(Reg, false);
230   const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
231   if (Reg == TRI->getFrameRegister(*Asm->MF))
232     // If variable offset is based in frame register then use fbreg.
233     addUInt(TheDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_fbreg);
234   else if (DWReg < 32)
235     addUInt(TheDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + DWReg);
236   else {
237     addUInt(TheDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
238     addUInt(TheDie, 0, dwarf::DW_FORM_udata, DWReg);
239   }
240   addSInt(TheDie, 0, dwarf::DW_FORM_sdata, Offset);
241 }
242
243 /// addAddress - Add an address attribute to a die based on the location
244 /// provided.
245 void CompileUnit::addAddress(DIE *Die, unsigned Attribute,
246                              const MachineLocation &Location) {
247   DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
248
249   if (Location.isReg())
250     addRegisterOp(Block, Location.getReg());
251   else
252     addRegisterOffset(Block, Location.getReg(), Location.getOffset());
253
254   // Now attach the location information to the DIE.
255   addBlock(Die, Attribute, 0, Block);
256 }
257
258 /// addRegisterAddress - Add register location entry in variable DIE.
259 bool CompileUnit::addRegisterAddress(DIE *Die, const MachineOperand &MO) {
260   assert (MO.isReg() && "Invalid machine operand!");
261   if (!MO.getReg())
262     return false;
263   MachineLocation Location;
264   Location.set(MO.getReg());
265   addAddress(Die, dwarf::DW_AT_location, Location);
266   return true;
267 }
268
269 /// addComplexAddress - Start with the address based on the location provided,
270 /// and generate the DWARF information necessary to find the actual variable
271 /// given the extra address information encoded in the DIVariable, starting from
272 /// the starting location.  Add the DWARF information to the die.
273 ///
274 void CompileUnit::addComplexAddress(DbgVariable *&DV, DIE *Die,
275                                     unsigned Attribute,
276                                     const MachineLocation &Location) {
277   DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
278
279   if (Location.isReg())
280     addRegisterOp(Block, Location.getReg());
281   else
282     addRegisterOffset(Block, Location.getReg(), Location.getOffset());
283
284   for (unsigned i = 0, N = DV->getNumAddrElements(); i < N; ++i) {
285     uint64_t Element = DV->getAddrElement(i);
286
287     if (Element == DIBuilder::OpPlus) {
288       addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
289       addUInt(Block, 0, dwarf::DW_FORM_udata, DV->getAddrElement(++i));
290     } else if (Element == DIBuilder::OpDeref) {
291       addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
292     } else llvm_unreachable("unknown DIBuilder Opcode");
293   }
294
295   // Now attach the location information to the DIE.
296   addBlock(Die, Attribute, 0, Block);
297 }
298
299 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
300    VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
301    gives the variable VarName either the struct, or a pointer to the struct, as
302    its type.  This is necessary for various behind-the-scenes things the
303    compiler needs to do with by-reference variables in Blocks.
304
305    However, as far as the original *programmer* is concerned, the variable
306    should still have type 'SomeType', as originally declared.
307
308    The function getBlockByrefType dives into the __Block_byref_x_VarName
309    struct to find the original type of the variable, which is then assigned to
310    the variable's Debug Information Entry as its real type.  So far, so good.
311    However now the debugger will expect the variable VarName to have the type
312    SomeType.  So we need the location attribute for the variable to be an
313    expression that explains to the debugger how to navigate through the
314    pointers and struct to find the actual variable of type SomeType.
315
316    The following function does just that.  We start by getting
317    the "normal" location for the variable. This will be the location
318    of either the struct __Block_byref_x_VarName or the pointer to the
319    struct __Block_byref_x_VarName.
320
321    The struct will look something like:
322
323    struct __Block_byref_x_VarName {
324      ... <various fields>
325      struct __Block_byref_x_VarName *forwarding;
326      ... <various other fields>
327      SomeType VarName;
328      ... <maybe more fields>
329    };
330
331    If we are given the struct directly (as our starting point) we
332    need to tell the debugger to:
333
334    1).  Add the offset of the forwarding field.
335
336    2).  Follow that pointer to get the real __Block_byref_x_VarName
337    struct to use (the real one may have been copied onto the heap).
338
339    3).  Add the offset for the field VarName, to find the actual variable.
340
341    If we started with a pointer to the struct, then we need to
342    dereference that pointer first, before the other steps.
343    Translating this into DWARF ops, we will need to append the following
344    to the current location description for the variable:
345
346    DW_OP_deref                    -- optional, if we start with a pointer
347    DW_OP_plus_uconst <forward_fld_offset>
348    DW_OP_deref
349    DW_OP_plus_uconst <varName_fld_offset>
350
351    That is what this function does.  */
352
353 /// addBlockByrefAddress - Start with the address based on the location
354 /// provided, and generate the DWARF information necessary to find the
355 /// actual Block variable (navigating the Block struct) based on the
356 /// starting location.  Add the DWARF information to the die.  For
357 /// more information, read large comment just above here.
358 ///
359 void CompileUnit::addBlockByrefAddress(DbgVariable *&DV, DIE *Die,
360                                        unsigned Attribute,
361                                        const MachineLocation &Location) {
362   DIType Ty = DV->getType();
363   DIType TmpTy = Ty;
364   unsigned Tag = Ty.getTag();
365   bool isPointer = false;
366
367   StringRef varName = DV->getName();
368
369   if (Tag == dwarf::DW_TAG_pointer_type) {
370     DIDerivedType DTy = DIDerivedType(Ty);
371     TmpTy = DTy.getTypeDerivedFrom();
372     isPointer = true;
373   }
374
375   DICompositeType blockStruct = DICompositeType(TmpTy);
376
377   // Find the __forwarding field and the variable field in the __Block_byref
378   // struct.
379   DIArray Fields = blockStruct.getTypeArray();
380   DIDescriptor varField = DIDescriptor();
381   DIDescriptor forwardingField = DIDescriptor();
382
383   for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
384     DIDescriptor Element = Fields.getElement(i);
385     DIDerivedType DT = DIDerivedType(Element);
386     StringRef fieldName = DT.getName();
387     if (fieldName == "__forwarding")
388       forwardingField = Element;
389     else if (fieldName == varName)
390       varField = Element;
391   }
392
393   // Get the offsets for the forwarding field and the variable field.
394   unsigned forwardingFieldOffset =
395     DIDerivedType(forwardingField).getOffsetInBits() >> 3;
396   unsigned varFieldOffset =
397     DIDerivedType(varField).getOffsetInBits() >> 3;
398
399   // Decode the original location, and use that as the start of the byref
400   // variable's location.
401   const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
402   unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
403   DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
404
405   if (Location.isReg()) {
406     if (Reg < 32)
407       addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
408     else {
409       addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
410       addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
411     }
412   } else {
413     if (Reg < 32)
414       addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
415     else {
416       addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
417       addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
418     }
419
420     addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
421   }
422
423   // If we started with a pointer to the __Block_byref... struct, then
424   // the first thing we need to do is dereference the pointer (DW_OP_deref).
425   if (isPointer)
426     addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
427
428   // Next add the offset for the '__forwarding' field:
429   // DW_OP_plus_uconst ForwardingFieldOffset.  Note there's no point in
430   // adding the offset if it's 0.
431   if (forwardingFieldOffset > 0) {
432     addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
433     addUInt(Block, 0, dwarf::DW_FORM_udata, forwardingFieldOffset);
434   }
435
436   // Now dereference the __forwarding field to get to the real __Block_byref
437   // struct:  DW_OP_deref.
438   addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
439
440   // Now that we've got the real __Block_byref... struct, add the offset
441   // for the variable's field to get to the location of the actual variable:
442   // DW_OP_plus_uconst varFieldOffset.  Again, don't add if it's 0.
443   if (varFieldOffset > 0) {
444     addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
445     addUInt(Block, 0, dwarf::DW_FORM_udata, varFieldOffset);
446   }
447
448   // Now attach the location information to the DIE.
449   addBlock(Die, Attribute, 0, Block);
450 }
451
452 /// addConstantValue - Add constant value entry in variable DIE.
453 bool CompileUnit::addConstantValue(DIE *Die, const MachineOperand &MO) {
454   assert (MO.isImm() && "Invalid machine operand!");
455   DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
456   unsigned Imm = MO.getImm();
457   addUInt(Block, 0, dwarf::DW_FORM_udata, Imm);
458   addBlock(Die, dwarf::DW_AT_const_value, 0, Block);
459   return true;
460 }
461
462 /// addConstantFPValue - Add constant value entry in variable DIE.
463 bool CompileUnit::addConstantFPValue(DIE *Die, const MachineOperand &MO) {
464   assert (MO.isFPImm() && "Invalid machine operand!");
465   DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
466   APFloat FPImm = MO.getFPImm()->getValueAPF();
467
468   // Get the raw data form of the floating point.
469   const APInt FltVal = FPImm.bitcastToAPInt();
470   const char *FltPtr = (const char*)FltVal.getRawData();
471
472   int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
473   bool LittleEndian = Asm->getTargetData().isLittleEndian();
474   int Incr = (LittleEndian ? 1 : -1);
475   int Start = (LittleEndian ? 0 : NumBytes - 1);
476   int Stop = (LittleEndian ? NumBytes : -1);
477
478   // Output the constant to DWARF one byte at a time.
479   for (; Start != Stop; Start += Incr)
480     addUInt(Block, 0, dwarf::DW_FORM_data1,
481             (unsigned char)0xFF & FltPtr[Start]);
482
483   addBlock(Die, dwarf::DW_AT_const_value, 0, Block);
484   return true;
485 }
486
487 /// addConstantValue - Add constant value entry in variable DIE.
488 bool CompileUnit::addConstantValue(DIE *Die, ConstantInt *CI,
489                                    bool Unsigned) {
490   if (CI->getBitWidth() <= 64) {
491     if (Unsigned)
492       addUInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_udata,
493               CI->getZExtValue());
494     else
495       addSInt(Die, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata,
496               CI->getSExtValue());
497     return true;
498   }
499
500   DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
501
502   // Get the raw data form of the large APInt.
503   const APInt Val = CI->getValue();
504   const char *Ptr = (const char*)Val.getRawData();
505
506   int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
507   bool LittleEndian = Asm->getTargetData().isLittleEndian();
508   int Incr = (LittleEndian ? 1 : -1);
509   int Start = (LittleEndian ? 0 : NumBytes - 1);
510   int Stop = (LittleEndian ? NumBytes : -1);
511
512   // Output the constant to DWARF one byte at a time.
513   for (; Start != Stop; Start += Incr)
514     addUInt(Block, 0, dwarf::DW_FORM_data1,
515             (unsigned char)0xFF & Ptr[Start]);
516
517   addBlock(Die, dwarf::DW_AT_const_value, 0, Block);
518   return true;
519 }
520
521 /// addTemplateParams - Add template parameters in buffer.
522 void CompileUnit::addTemplateParams(DIE &Buffer, DIArray TParams) {
523   // Add template parameters.
524   for (unsigned i = 0, e = TParams.getNumElements(); i != e; ++i) {
525     DIDescriptor Element = TParams.getElement(i);
526     if (Element.isTemplateTypeParameter())
527       Buffer.addChild(getOrCreateTemplateTypeParameterDIE(
528                         DITemplateTypeParameter(Element)));
529     else if (Element.isTemplateValueParameter())
530       Buffer.addChild(getOrCreateTemplateValueParameterDIE(
531                         DITemplateValueParameter(Element)));
532   }
533
534 }
535 /// addToContextOwner - Add Die into the list of its context owner's children.
536 void CompileUnit::addToContextOwner(DIE *Die, DIDescriptor Context) {
537   if (Context.isType()) {
538     DIE *ContextDIE = getOrCreateTypeDIE(DIType(Context));
539     ContextDIE->addChild(Die);
540   } else if (Context.isNameSpace()) {
541     DIE *ContextDIE = getOrCreateNameSpace(DINameSpace(Context));
542     ContextDIE->addChild(Die);
543   } else if (Context.isSubprogram()) {
544     DIE *ContextDIE = DD->createSubprogramDIE(DISubprogram(Context));
545     ContextDIE->addChild(Die);
546   } else if (DIE *ContextDIE = getDIE(Context))
547     ContextDIE->addChild(Die);
548   else
549     addDie(Die);
550 }
551
552 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
553 /// given DIType.
554 DIE *CompileUnit::getOrCreateTypeDIE(DIType Ty) {
555   DIE *TyDIE = getDIE(Ty);
556   if (TyDIE)
557     return TyDIE;
558
559   // Create new type.
560   TyDIE = new DIE(dwarf::DW_TAG_base_type);
561   insertDIE(Ty, TyDIE);
562   if (Ty.isBasicType())
563     constructTypeDIE(*TyDIE, DIBasicType(Ty));
564   else if (Ty.isCompositeType())
565     constructTypeDIE(*TyDIE, DICompositeType(Ty));
566   else {
567     assert(Ty.isDerivedType() && "Unknown kind of DIType");
568     constructTypeDIE(*TyDIE, DIDerivedType(Ty));
569   }
570
571   addToContextOwner(TyDIE, Ty.getContext());
572   return TyDIE;
573 }
574
575 /// addType - Add a new type attribute to the specified entity.
576 void CompileUnit::addType(DIE *Entity, DIType Ty) {
577   if (!Ty.Verify())
578     return;
579
580   // Check for pre-existence.
581   DIEEntry *Entry = getDIEEntry(Ty);
582   // If it exists then use the existing value.
583   if (Entry) {
584     Entity->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Entry);
585     return;
586   }
587
588   // Construct type.
589   DIE *Buffer = getOrCreateTypeDIE(Ty);
590
591   // Set up proxy.
592   Entry = createDIEEntry(Buffer);
593   insertDIEEntry(Ty, Entry);
594
595   Entity->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Entry);
596 }
597
598 /// constructTypeDIE - Construct basic type die from DIBasicType.
599 void CompileUnit::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
600   // Get core information.
601   StringRef Name = BTy.getName();
602   Buffer.setTag(dwarf::DW_TAG_base_type);
603   addUInt(&Buffer, dwarf::DW_AT_encoding,  dwarf::DW_FORM_data1,
604           BTy.getEncoding());
605
606   // Add name if not anonymous or intermediate type.
607   if (!Name.empty())
608     addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
609   uint64_t Size = BTy.getSizeInBits() >> 3;
610   addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
611 }
612
613 /// constructTypeDIE - Construct derived type die from DIDerivedType.
614 void CompileUnit::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
615   // Get core information.
616   StringRef Name = DTy.getName();
617   uint64_t Size = DTy.getSizeInBits() >> 3;
618   unsigned Tag = DTy.getTag();
619
620   // FIXME - Workaround for templates.
621   if (Tag == dwarf::DW_TAG_inheritance) Tag = dwarf::DW_TAG_reference_type;
622
623   Buffer.setTag(Tag);
624
625   // Map to main type, void will not have a type.
626   DIType FromTy = DTy.getTypeDerivedFrom();
627   addType(&Buffer, FromTy);
628
629   // Add name if not anonymous or intermediate type.
630   if (!Name.empty())
631     addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
632
633   // Add size if non-zero (derived types might be zero-sized.)
634   if (Size)
635     addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
636
637   // Add source line info if available and TyDesc is not a forward declaration.
638   if (!DTy.isForwardDecl())
639     addSourceLine(&Buffer, DTy);
640 }
641
642 /// constructTypeDIE - Construct type DIE from DICompositeType.
643 void CompileUnit::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
644   // Get core information.
645   StringRef Name = CTy.getName();
646
647   uint64_t Size = CTy.getSizeInBits() >> 3;
648   unsigned Tag = CTy.getTag();
649   Buffer.setTag(Tag);
650
651   switch (Tag) {
652   case dwarf::DW_TAG_vector_type:
653   case dwarf::DW_TAG_array_type:
654     constructArrayTypeDIE(Buffer, &CTy);
655     break;
656   case dwarf::DW_TAG_enumeration_type: {
657     DIArray Elements = CTy.getTypeArray();
658
659     // Add enumerators to enumeration type.
660     for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
661       DIE *ElemDie = NULL;
662       DIDescriptor Enum(Elements.getElement(i));
663       if (Enum.isEnumerator()) {
664         ElemDie = constructEnumTypeDIE(DIEnumerator(Enum));
665         Buffer.addChild(ElemDie);
666       }
667     }
668   }
669     break;
670   case dwarf::DW_TAG_subroutine_type: {
671     // Add return type.
672     DIArray Elements = CTy.getTypeArray();
673     DIDescriptor RTy = Elements.getElement(0);
674     addType(&Buffer, DIType(RTy));
675
676     bool isPrototyped = true;
677     // Add arguments.
678     for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
679       DIDescriptor Ty = Elements.getElement(i);
680       if (Ty.isUnspecifiedParameter()) {
681         DIE *Arg = new DIE(dwarf::DW_TAG_unspecified_parameters);
682         Buffer.addChild(Arg);
683         isPrototyped = false;
684       } else {
685         DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
686         addType(Arg, DIType(Ty));
687         Buffer.addChild(Arg);
688       }
689     }
690     // Add prototype flag.
691     if (isPrototyped)
692       addUInt(&Buffer, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
693   }
694     break;
695   case dwarf::DW_TAG_structure_type:
696   case dwarf::DW_TAG_union_type:
697   case dwarf::DW_TAG_class_type: {
698     // Add elements to structure type.
699     DIArray Elements = CTy.getTypeArray();
700
701     // A forward struct declared type may not have elements available.
702     unsigned N = Elements.getNumElements();
703     if (N == 0)
704       break;
705
706     // Add elements to structure type.
707     for (unsigned i = 0; i < N; ++i) {
708       DIDescriptor Element = Elements.getElement(i);
709       DIE *ElemDie = NULL;
710       if (Element.isSubprogram()) {
711         DISubprogram SP(Element);
712         ElemDie = DD->createSubprogramDIE(DISubprogram(Element));
713         if (SP.isProtected())
714           addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
715                   dwarf::DW_ACCESS_protected);
716         else if (SP.isPrivate())
717           addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
718                   dwarf::DW_ACCESS_private);
719         else 
720           addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
721             dwarf::DW_ACCESS_public);
722         if (SP.isExplicit())
723           addUInt(ElemDie, dwarf::DW_AT_explicit, dwarf::DW_FORM_flag, 1);
724       }
725       else if (Element.isVariable()) {
726         DIVariable DV(Element);
727         ElemDie = new DIE(dwarf::DW_TAG_variable);
728         addString(ElemDie, dwarf::DW_AT_name, dwarf::DW_FORM_string,
729                   DV.getName());
730         addType(ElemDie, DV.getType());
731         addUInt(ElemDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
732         addUInt(ElemDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
733         addSourceLine(ElemDie, DV);
734       } else if (Element.isDerivedType())
735         ElemDie = createMemberDIE(DIDerivedType(Element));
736       else
737         continue;
738       Buffer.addChild(ElemDie);
739     }
740
741     if (CTy.isAppleBlockExtension())
742       addUInt(&Buffer, dwarf::DW_AT_APPLE_block, dwarf::DW_FORM_flag, 1);
743
744     unsigned RLang = CTy.getRunTimeLang();
745     if (RLang)
746       addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class,
747               dwarf::DW_FORM_data1, RLang);
748
749     DICompositeType ContainingType = CTy.getContainingType();
750     if (DIDescriptor(ContainingType).isCompositeType())
751       addDIEEntry(&Buffer, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4,
752                   getOrCreateTypeDIE(DIType(ContainingType)));
753     else {
754       DIDescriptor Context = CTy.getContext();
755       addToContextOwner(&Buffer, Context);
756     }
757
758     if (Tag == dwarf::DW_TAG_class_type) 
759       addTemplateParams(Buffer, CTy.getTemplateParams());
760
761     break;
762   }
763   default:
764     break;
765   }
766
767   // Add name if not anonymous or intermediate type.
768   if (!Name.empty())
769     addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
770
771   if (Tag == dwarf::DW_TAG_enumeration_type || Tag == dwarf::DW_TAG_class_type
772       || Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
773     {
774     // Add size if non-zero (derived types might be zero-sized.)
775     if (Size)
776       addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
777     else {
778       // Add zero size if it is not a forward declaration.
779       if (CTy.isForwardDecl())
780         addUInt(&Buffer, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
781       else
782         addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, 0);
783     }
784
785     // Add source line info if available.
786     if (!CTy.isForwardDecl())
787       addSourceLine(&Buffer, CTy);
788   }
789 }
790
791 /// getOrCreateTemplateTypeParameterDIE - Find existing DIE or create new DIE 
792 /// for the given DITemplateTypeParameter.
793 DIE *
794 CompileUnit::getOrCreateTemplateTypeParameterDIE(DITemplateTypeParameter TP) {
795   DIE *ParamDIE = getDIE(TP);
796   if (ParamDIE)
797     return ParamDIE;
798
799   ParamDIE = new DIE(dwarf::DW_TAG_template_type_parameter);
800   addType(ParamDIE, TP.getType());
801   addString(ParamDIE, dwarf::DW_AT_name, dwarf::DW_FORM_string, TP.getName());
802   return ParamDIE;
803 }
804
805 /// getOrCreateTemplateValueParameterDIE - Find existing DIE or create new DIE 
806 /// for the given DITemplateValueParameter.
807 DIE *
808 CompileUnit::getOrCreateTemplateValueParameterDIE(DITemplateValueParameter TPV) {
809   DIE *ParamDIE = getDIE(TPV);
810   if (ParamDIE)
811     return ParamDIE;
812
813   ParamDIE = new DIE(dwarf::DW_TAG_template_value_parameter);
814   addType(ParamDIE, TPV.getType());
815   if (!TPV.getName().empty())
816     addString(ParamDIE, dwarf::DW_AT_name, dwarf::DW_FORM_string, TPV.getName());
817   addUInt(ParamDIE, dwarf::DW_AT_const_value, dwarf::DW_FORM_udata, 
818           TPV.getValue());
819   return ParamDIE;
820 }
821
822 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
823 void CompileUnit::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy){
824   DIE *DW_Subrange = new DIE(dwarf::DW_TAG_subrange_type);
825   addDIEEntry(DW_Subrange, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, IndexTy);
826   int64_t L = SR.getLo();
827   int64_t H = SR.getHi();
828
829   // The L value defines the lower bounds which is typically zero for C/C++. The
830   // H value is the upper bounds.  Values are 64 bit.  H - L + 1 is the size
831   // of the array. If L > H then do not emit DW_AT_lower_bound and 
832   // DW_AT_upper_bound attributes. If L is zero and H is also zero then the
833   // array has one element and in such case do not emit lower bound.
834
835   if (L > H) {
836     Buffer.addChild(DW_Subrange);
837     return;
838   }
839   if (L)
840     addSInt(DW_Subrange, dwarf::DW_AT_lower_bound, 0, L);
841   addSInt(DW_Subrange, dwarf::DW_AT_upper_bound, 0, H);
842   Buffer.addChild(DW_Subrange);
843 }
844
845 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
846 void CompileUnit::constructArrayTypeDIE(DIE &Buffer,
847                                         DICompositeType *CTy) {
848   Buffer.setTag(dwarf::DW_TAG_array_type);
849   if (CTy->getTag() == dwarf::DW_TAG_vector_type)
850     addUInt(&Buffer, dwarf::DW_AT_GNU_vector, dwarf::DW_FORM_flag, 1);
851
852   // Emit derived type.
853   addType(&Buffer, CTy->getTypeDerivedFrom());
854   DIArray Elements = CTy->getTypeArray();
855
856   // Get an anonymous type for index type.
857   DIE *IdxTy = getIndexTyDie();
858   if (!IdxTy) {
859     // Construct an anonymous type for index type.
860     IdxTy = new DIE(dwarf::DW_TAG_base_type);
861     addUInt(IdxTy, dwarf::DW_AT_byte_size, 0, sizeof(int32_t));
862     addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
863             dwarf::DW_ATE_signed);
864     addDie(IdxTy);
865     setIndexTyDie(IdxTy);
866   }
867
868   // Add subranges to array type.
869   for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
870     DIDescriptor Element = Elements.getElement(i);
871     if (Element.getTag() == dwarf::DW_TAG_subrange_type)
872       constructSubrangeDIE(Buffer, DISubrange(Element), IdxTy);
873   }
874 }
875
876 /// constructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
877 DIE *CompileUnit::constructEnumTypeDIE(DIEnumerator ETy) {
878   DIE *Enumerator = new DIE(dwarf::DW_TAG_enumerator);
879   StringRef Name = ETy.getName();
880   addString(Enumerator, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
881   int64_t Value = ETy.getEnumValue();
882   addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, Value);
883   return Enumerator;
884 }
885
886 /// createMemberDIE - Create new member DIE.
887 DIE *CompileUnit::createMemberDIE(DIDerivedType DT) {
888   DIE *MemberDie = new DIE(DT.getTag());
889   StringRef Name = DT.getName();
890   if (!Name.empty())
891     addString(MemberDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
892
893   addType(MemberDie, DT.getTypeDerivedFrom());
894
895   addSourceLine(MemberDie, DT);
896
897   DIEBlock *MemLocationDie = new (DIEValueAllocator) DIEBlock();
898   addUInt(MemLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
899
900   uint64_t Size = DT.getSizeInBits();
901   uint64_t FieldSize = DT.getOriginalTypeSize();
902
903   if (Size != FieldSize) {
904     // Handle bitfield.
905     addUInt(MemberDie, dwarf::DW_AT_byte_size, 0, DT.getOriginalTypeSize()>>3);
906     addUInt(MemberDie, dwarf::DW_AT_bit_size, 0, DT.getSizeInBits());
907
908     uint64_t Offset = DT.getOffsetInBits();
909     uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
910     uint64_t HiMark = (Offset + FieldSize) & AlignMask;
911     uint64_t FieldOffset = (HiMark - FieldSize);
912     Offset -= FieldOffset;
913
914     // Maybe we need to work from the other end.
915     if (Asm->getTargetData().isLittleEndian())
916       Offset = FieldSize - (Offset + Size);
917     addUInt(MemberDie, dwarf::DW_AT_bit_offset, 0, Offset);
918
919     // Here WD_AT_data_member_location points to the anonymous
920     // field that includes this bit field.
921     addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, FieldOffset >> 3);
922
923   } else
924     // This is not a bitfield.
925     addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits() >> 3);
926
927   if (DT.getTag() == dwarf::DW_TAG_inheritance
928       && DT.isVirtual()) {
929
930     // For C++, virtual base classes are not at fixed offset. Use following
931     // expression to extract appropriate offset from vtable.
932     // BaseAddr = ObAddr + *((*ObAddr) - Offset)
933
934     DIEBlock *VBaseLocationDie = new (DIEValueAllocator) DIEBlock();
935     addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
936     addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
937     addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
938     addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits());
939     addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
940     addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
941     addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
942
943     addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0,
944              VBaseLocationDie);
945   } else
946     addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0, MemLocationDie);
947
948   if (DT.isProtected())
949     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
950             dwarf::DW_ACCESS_protected);
951   else if (DT.isPrivate())
952     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
953             dwarf::DW_ACCESS_private);
954   // Otherwise C++ member and base classes are considered public.
955   else if (DT.getCompileUnit().getLanguage() == dwarf::DW_LANG_C_plus_plus)
956     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
957             dwarf::DW_ACCESS_public);
958   if (DT.isVirtual())
959     addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_flag,
960             dwarf::DW_VIRTUALITY_virtual);
961
962   // Objective-C properties.
963   StringRef PropertyName = DT.getObjCPropertyName();
964   if (!PropertyName.empty()) {
965     addString(MemberDie, dwarf::DW_AT_APPLE_property_name, dwarf::DW_FORM_string,
966               PropertyName);
967     StringRef GetterName = DT.getObjCPropertyGetterName();
968     if (!GetterName.empty())
969       addString(MemberDie, dwarf::DW_AT_APPLE_property_getter,
970                 dwarf::DW_FORM_string, GetterName);
971     StringRef SetterName = DT.getObjCPropertySetterName();
972     if (!SetterName.empty())
973       addString(MemberDie, dwarf::DW_AT_APPLE_property_setter,
974                 dwarf::DW_FORM_string, SetterName);
975     unsigned PropertyAttributes = 0;
976     if (DT.isReadOnlyObjCProperty())
977       PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readonly;
978     if (DT.isReadWriteObjCProperty())
979       PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readwrite;
980     if (DT.isAssignObjCProperty())
981       PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_assign;
982     if (DT.isRetainObjCProperty())
983       PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_retain;
984     if (DT.isCopyObjCProperty())
985       PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_copy;
986     if (DT.isNonAtomicObjCProperty())
987       PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_nonatomic;
988     if (PropertyAttributes)
989       addUInt(MemberDie, dwarf::DW_AT_APPLE_property_attribute, 0, 
990               PropertyAttributes);
991   }
992   return MemberDie;
993 }