LLVM API Documentation

DwarfCompileUnit.cpp
Go to the documentation of this file.
00001 //===-- llvm/CodeGen/DwarfCompileUnit.cpp - Dwarf Compile Unit ------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file contains support for constructing a dwarf compile unit.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #define DEBUG_TYPE "dwarfdebug"
00015 
00016 #include "DwarfCompileUnit.h"
00017 #include "DwarfAccelTable.h"
00018 #include "DwarfDebug.h"
00019 #include "llvm/ADT/APFloat.h"
00020 #include "llvm/DIBuilder.h"
00021 #include "llvm/IR/Constants.h"
00022 #include "llvm/IR/DataLayout.h"
00023 #include "llvm/IR/GlobalVariable.h"
00024 #include "llvm/IR/Instructions.h"
00025 #include "llvm/Support/Debug.h"
00026 #include "llvm/Support/ErrorHandling.h"
00027 #include "llvm/Target/Mangler.h"
00028 #include "llvm/Target/TargetFrameLowering.h"
00029 #include "llvm/Target/TargetMachine.h"
00030 #include "llvm/Target/TargetRegisterInfo.h"
00031 
00032 using namespace llvm;
00033 
00034 /// CompileUnit - Compile unit constructor.
00035 CompileUnit::CompileUnit(unsigned UID, unsigned L, DIE *D, const MDNode *N,
00036                          AsmPrinter *A, DwarfDebug *DW, DwarfUnits *DWU)
00037   : UniqueID(UID), Language(L), CUDie(D), Asm(A), DD(DW), DU(DWU),
00038     IndexTyDie(0), DebugInfoOffset(0) {
00039   DIEIntegerOne = new (DIEValueAllocator) DIEInteger(1);
00040   insertDIE(N, D);
00041 }
00042 
00043 /// ~CompileUnit - Destructor for compile unit.
00044 CompileUnit::~CompileUnit() {
00045   for (unsigned j = 0, M = DIEBlocks.size(); j < M; ++j)
00046     DIEBlocks[j]->~DIEBlock();
00047 }
00048 
00049 /// createDIEEntry - Creates a new DIEEntry to be a proxy for a debug
00050 /// information entry.
00051 DIEEntry *CompileUnit::createDIEEntry(DIE *Entry) {
00052   DIEEntry *Value = new (DIEValueAllocator) DIEEntry(Entry);
00053   return Value;
00054 }
00055 
00056 /// getDefaultLowerBound - Return the default lower bound for an array. If the
00057 /// DWARF version doesn't handle the language, return -1.
00058 int64_t CompileUnit::getDefaultLowerBound() const {
00059   switch (Language) {
00060   default:
00061     break;
00062 
00063   case dwarf::DW_LANG_C89:
00064   case dwarf::DW_LANG_C99:
00065   case dwarf::DW_LANG_C:
00066   case dwarf::DW_LANG_C_plus_plus:
00067   case dwarf::DW_LANG_ObjC:
00068   case dwarf::DW_LANG_ObjC_plus_plus:
00069     return 0;
00070 
00071   case dwarf::DW_LANG_Fortran77:
00072   case dwarf::DW_LANG_Fortran90:
00073   case dwarf::DW_LANG_Fortran95:
00074     return 1;
00075 
00076   // The languages below have valid values only if the DWARF version >= 4.
00077   case dwarf::DW_LANG_Java:
00078   case dwarf::DW_LANG_Python:
00079   case dwarf::DW_LANG_UPC:
00080   case dwarf::DW_LANG_D:
00081     if (dwarf::DWARF_VERSION >= 4)
00082       return 0;
00083     break;
00084 
00085   case dwarf::DW_LANG_Ada83:
00086   case dwarf::DW_LANG_Ada95:
00087   case dwarf::DW_LANG_Cobol74:
00088   case dwarf::DW_LANG_Cobol85:
00089   case dwarf::DW_LANG_Modula2:
00090   case dwarf::DW_LANG_Pascal83:
00091   case dwarf::DW_LANG_PLI:
00092     if (dwarf::DWARF_VERSION >= 4)
00093       return 1;
00094     break;
00095   }
00096 
00097   return -1;
00098 }
00099 
00100 /// addFlag - Add a flag that is true.
00101 void CompileUnit::addFlag(DIE *Die, unsigned Attribute) {
00102   if (!DD->useDarwinGDBCompat())
00103     Die->addValue(Attribute, dwarf::DW_FORM_flag_present,
00104                   DIEIntegerOne);
00105   else
00106     addUInt(Die, Attribute, dwarf::DW_FORM_flag, 1);
00107 }
00108 
00109 /// addUInt - Add an unsigned integer attribute data and value.
00110 ///
00111 void CompileUnit::addUInt(DIE *Die, unsigned Attribute,
00112                           unsigned Form, uint64_t Integer) {
00113   if (!Form) Form = DIEInteger::BestForm(false, Integer);
00114   DIEValue *Value = Integer == 1 ?
00115     DIEIntegerOne : new (DIEValueAllocator) DIEInteger(Integer);
00116   Die->addValue(Attribute, Form, Value);
00117 }
00118 
00119 /// addSInt - Add an signed integer attribute data and value.
00120 ///
00121 void CompileUnit::addSInt(DIE *Die, unsigned Attribute,
00122                           unsigned Form, int64_t Integer) {
00123   if (!Form) Form = DIEInteger::BestForm(true, Integer);
00124   DIEValue *Value = new (DIEValueAllocator) DIEInteger(Integer);
00125   Die->addValue(Attribute, Form, Value);
00126 }
00127 
00128 /// addString - Add a string attribute data and value. We always emit a
00129 /// reference to the string pool instead of immediate strings so that DIEs have
00130 /// more predictable sizes. In the case of split dwarf we emit an index
00131 /// into another table which gets us the static offset into the string
00132 /// table.
00133 void CompileUnit::addString(DIE *Die, unsigned Attribute, StringRef String) {
00134   if (!DD->useSplitDwarf()) {
00135     MCSymbol *Symb = DU->getStringPoolEntry(String);
00136     DIEValue *Value;
00137     if (Asm->needsRelocationsForDwarfStringPool())
00138       Value = new (DIEValueAllocator) DIELabel(Symb);
00139     else {
00140       MCSymbol *StringPool = DU->getStringPoolSym();
00141       Value = new (DIEValueAllocator) DIEDelta(Symb, StringPool);
00142     }
00143     Die->addValue(Attribute, dwarf::DW_FORM_strp, Value);
00144   } else {
00145     unsigned idx = DU->getStringPoolIndex(String);
00146     DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
00147     Die->addValue(Attribute, dwarf::DW_FORM_GNU_str_index, Value);
00148   }
00149 }
00150 
00151 /// addLocalString - Add a string attribute data and value. This is guaranteed
00152 /// to be in the local string pool instead of indirected.
00153 void CompileUnit::addLocalString(DIE *Die, unsigned Attribute,
00154                                  StringRef String) {
00155   MCSymbol *Symb = DU->getStringPoolEntry(String);
00156   DIEValue *Value;
00157   if (Asm->needsRelocationsForDwarfStringPool())
00158     Value = new (DIEValueAllocator) DIELabel(Symb);
00159   else {
00160     MCSymbol *StringPool = DU->getStringPoolSym();
00161     Value = new (DIEValueAllocator) DIEDelta(Symb, StringPool);
00162   }
00163   Die->addValue(Attribute, dwarf::DW_FORM_strp, Value);
00164 }
00165 
00166 /// addLabel - Add a Dwarf label attribute data and value.
00167 ///
00168 void CompileUnit::addLabel(DIE *Die, unsigned Attribute, unsigned Form,
00169                            const MCSymbol *Label) {
00170   DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
00171   Die->addValue(Attribute, Form, Value);
00172 }
00173 
00174 /// addLabelAddress - Add a dwarf label attribute data and value using
00175 /// DW_FORM_addr or DW_FORM_GNU_addr_index.
00176 ///
00177 void CompileUnit::addLabelAddress(DIE *Die, unsigned Attribute,
00178                                   MCSymbol *Label) {
00179   if (!DD->useSplitDwarf()) {
00180     if (Label != NULL) {
00181       DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
00182       Die->addValue(Attribute, dwarf::DW_FORM_addr, Value);
00183     } else {
00184       DIEValue *Value = new (DIEValueAllocator) DIEInteger(0);
00185       Die->addValue(Attribute, dwarf::DW_FORM_addr, Value);
00186     }
00187   } else {
00188     unsigned idx = DU->getAddrPoolIndex(Label);
00189     DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
00190     Die->addValue(Attribute, dwarf::DW_FORM_GNU_addr_index, Value);
00191   }
00192 }
00193 
00194 /// addOpAddress - Add a dwarf op address data and value using the
00195 /// form given and an op of either DW_FORM_addr or DW_FORM_GNU_addr_index.
00196 ///
00197 void CompileUnit::addOpAddress(DIE *Die, MCSymbol *Sym) {
00198 
00199   if (!DD->useSplitDwarf()) {
00200     addUInt(Die, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
00201     addLabel(Die, 0, dwarf::DW_FORM_udata, Sym);
00202   } else {
00203     unsigned idx = DU->getAddrPoolIndex(Sym);
00204     DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
00205     addUInt(Die, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index);
00206     Die->addValue(0, dwarf::DW_FORM_GNU_addr_index, Value);
00207   }
00208 }
00209 
00210 /// addDelta - Add a label delta attribute data and value.
00211 ///
00212 void CompileUnit::addDelta(DIE *Die, unsigned Attribute, unsigned Form,
00213                            const MCSymbol *Hi, const MCSymbol *Lo) {
00214   DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
00215   Die->addValue(Attribute, Form, Value);
00216 }
00217 
00218 /// addDIEEntry - Add a DIE attribute data and value.
00219 ///
00220 void CompileUnit::addDIEEntry(DIE *Die, unsigned Attribute, unsigned Form,
00221                               DIE *Entry) {
00222   Die->addValue(Attribute, Form, createDIEEntry(Entry));
00223 }
00224 
00225 /// addBlock - Add block data.
00226 ///
00227 void CompileUnit::addBlock(DIE *Die, unsigned Attribute, unsigned Form,
00228                            DIEBlock *Block) {
00229   Block->ComputeSize(Asm);
00230   DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
00231   Die->addValue(Attribute, Block->BestForm(), Block);
00232 }
00233 
00234 /// addSourceLine - Add location information to specified debug information
00235 /// entry.
00236 void CompileUnit::addSourceLine(DIE *Die, DIVariable V) {
00237   // Verify variable.
00238   if (!V.Verify())
00239     return;
00240 
00241   unsigned Line = V.getLineNumber();
00242   if (Line == 0)
00243     return;
00244   unsigned FileID = DD->getOrCreateSourceID(V.getContext().getFilename(),
00245                                             V.getContext().getDirectory(),
00246                                             getUniqueID());
00247   assert(FileID && "Invalid file id");
00248   addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
00249   addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
00250 }
00251 
00252 /// addSourceLine - Add location information to specified debug information
00253 /// entry.
00254 void CompileUnit::addSourceLine(DIE *Die, DIGlobalVariable G) {
00255   // Verify global variable.
00256   if (!G.Verify())
00257     return;
00258 
00259   unsigned Line = G.getLineNumber();
00260   if (Line == 0)
00261     return;
00262   unsigned FileID = DD->getOrCreateSourceID(G.getFilename(), G.getDirectory(),
00263                                             getUniqueID());
00264   assert(FileID && "Invalid file id");
00265   addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
00266   addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
00267 }
00268 
00269 /// addSourceLine - Add location information to specified debug information
00270 /// entry.
00271 void CompileUnit::addSourceLine(DIE *Die, DISubprogram SP) {
00272   // Verify subprogram.
00273   if (!SP.Verify())
00274     return;
00275 
00276   // If the line number is 0, don't add it.
00277   unsigned Line = SP.getLineNumber();
00278   if (Line == 0)
00279     return;
00280 
00281   unsigned FileID = DD->getOrCreateSourceID(SP.getFilename(),
00282                                             SP.getDirectory(), getUniqueID());
00283   assert(FileID && "Invalid file id");
00284   addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
00285   addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
00286 }
00287 
00288 /// addSourceLine - Add location information to specified debug information
00289 /// entry.
00290 void CompileUnit::addSourceLine(DIE *Die, DIType Ty) {
00291   // Verify type.
00292   if (!Ty.Verify())
00293     return;
00294 
00295   unsigned Line = Ty.getLineNumber();
00296   if (Line == 0)
00297     return;
00298   unsigned FileID = DD->getOrCreateSourceID(Ty.getFilename(),
00299                                             Ty.getDirectory(), getUniqueID());
00300   assert(FileID && "Invalid file id");
00301   addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
00302   addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
00303 }
00304 
00305 /// addSourceLine - Add location information to specified debug information
00306 /// entry.
00307 void CompileUnit::addSourceLine(DIE *Die, DIObjCProperty Ty) {
00308   // Verify type.
00309   if (!Ty.Verify())
00310     return;
00311 
00312   unsigned Line = Ty.getLineNumber();
00313   if (Line == 0)
00314     return;
00315   DIFile File = Ty.getFile();
00316   unsigned FileID = DD->getOrCreateSourceID(File.getFilename(),
00317                                             File.getDirectory(), getUniqueID());
00318   assert(FileID && "Invalid file id");
00319   addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
00320   addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
00321 }
00322 
00323 /// addSourceLine - Add location information to specified debug information
00324 /// entry.
00325 void CompileUnit::addSourceLine(DIE *Die, DINameSpace NS) {
00326   // Verify namespace.
00327   if (!NS.Verify())
00328     return;
00329 
00330   unsigned Line = NS.getLineNumber();
00331   if (Line == 0)
00332     return;
00333   StringRef FN = NS.getFilename();
00334 
00335   unsigned FileID = DD->getOrCreateSourceID(FN, NS.getDirectory(),
00336                                             getUniqueID());
00337   assert(FileID && "Invalid file id");
00338   addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
00339   addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
00340 }
00341 
00342 /// addVariableAddress - Add DW_AT_location attribute for a
00343 /// DbgVariable based on provided MachineLocation.
00344 void CompileUnit::addVariableAddress(DbgVariable *&DV, DIE *Die,
00345                                      MachineLocation Location) {
00346   if (DV->variableHasComplexAddress())
00347     addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
00348   else if (DV->isBlockByrefVariable())
00349     addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location);
00350   else
00351     addAddress(Die, dwarf::DW_AT_location, Location);
00352 }
00353 
00354 /// addRegisterOp - Add register operand.
00355 void CompileUnit::addRegisterOp(DIE *TheDie, unsigned Reg) {
00356   const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
00357   unsigned DWReg = RI->getDwarfRegNum(Reg, false);
00358   if (DWReg < 32)
00359     addUInt(TheDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + DWReg);
00360   else {
00361     addUInt(TheDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
00362     addUInt(TheDie, 0, dwarf::DW_FORM_udata, DWReg);
00363   }
00364 }
00365 
00366 /// addRegisterOffset - Add register offset.
00367 void CompileUnit::addRegisterOffset(DIE *TheDie, unsigned Reg,
00368                                     int64_t Offset) {
00369   const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
00370   unsigned DWReg = RI->getDwarfRegNum(Reg, false);
00371   const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
00372   if (Reg == TRI->getFrameRegister(*Asm->MF))
00373     // If variable offset is based in frame register then use fbreg.
00374     addUInt(TheDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_fbreg);
00375   else if (DWReg < 32)
00376     addUInt(TheDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + DWReg);
00377   else {
00378     addUInt(TheDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
00379     addUInt(TheDie, 0, dwarf::DW_FORM_udata, DWReg);
00380   }
00381   addSInt(TheDie, 0, dwarf::DW_FORM_sdata, Offset);
00382 }
00383 
00384 /// addAddress - Add an address attribute to a die based on the location
00385 /// provided.
00386 void CompileUnit::addAddress(DIE *Die, unsigned Attribute,
00387                              const MachineLocation &Location) {
00388   DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
00389 
00390   if (Location.isReg())
00391     addRegisterOp(Block, Location.getReg());
00392   else
00393     addRegisterOffset(Block, Location.getReg(), Location.getOffset());
00394 
00395   // Now attach the location information to the DIE.
00396   addBlock(Die, Attribute, 0, Block);
00397 }
00398 
00399 /// addComplexAddress - Start with the address based on the location provided,
00400 /// and generate the DWARF information necessary to find the actual variable
00401 /// given the extra address information encoded in the DIVariable, starting from
00402 /// the starting location.  Add the DWARF information to the die.
00403 ///
00404 void CompileUnit::addComplexAddress(DbgVariable *&DV, DIE *Die,
00405                                     unsigned Attribute,
00406                                     const MachineLocation &Location) {
00407   DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
00408   unsigned N = DV->getNumAddrElements();
00409   unsigned i = 0;
00410   if (Location.isReg()) {
00411     if (N >= 2 && DV->getAddrElement(0) == DIBuilder::OpPlus) {
00412       // If first address element is OpPlus then emit
00413       // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
00414       addRegisterOffset(Block, Location.getReg(), DV->getAddrElement(1));
00415       i = 2;
00416     } else
00417       addRegisterOp(Block, Location.getReg());
00418   }
00419   else
00420     addRegisterOffset(Block, Location.getReg(), Location.getOffset());
00421 
00422   for (;i < N; ++i) {
00423     uint64_t Element = DV->getAddrElement(i);
00424     if (Element == DIBuilder::OpPlus) {
00425       addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
00426       addUInt(Block, 0, dwarf::DW_FORM_udata, DV->getAddrElement(++i));
00427     } else if (Element == DIBuilder::OpDeref) {
00428       if (!Location.isReg())
00429         addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
00430     } else llvm_unreachable("unknown DIBuilder Opcode");
00431   }
00432 
00433   // Now attach the location information to the DIE.
00434   addBlock(Die, Attribute, 0, Block);
00435 }
00436 
00437 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
00438    VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
00439    gives the variable VarName either the struct, or a pointer to the struct, as
00440    its type.  This is necessary for various behind-the-scenes things the
00441    compiler needs to do with by-reference variables in Blocks.
00442 
00443    However, as far as the original *programmer* is concerned, the variable
00444    should still have type 'SomeType', as originally declared.
00445 
00446    The function getBlockByrefType dives into the __Block_byref_x_VarName
00447    struct to find the original type of the variable, which is then assigned to
00448    the variable's Debug Information Entry as its real type.  So far, so good.
00449    However now the debugger will expect the variable VarName to have the type
00450    SomeType.  So we need the location attribute for the variable to be an
00451    expression that explains to the debugger how to navigate through the
00452    pointers and struct to find the actual variable of type SomeType.
00453 
00454    The following function does just that.  We start by getting
00455    the "normal" location for the variable. This will be the location
00456    of either the struct __Block_byref_x_VarName or the pointer to the
00457    struct __Block_byref_x_VarName.
00458 
00459    The struct will look something like:
00460 
00461    struct __Block_byref_x_VarName {
00462      ... <various fields>
00463      struct __Block_byref_x_VarName *forwarding;
00464      ... <various other fields>
00465      SomeType VarName;
00466      ... <maybe more fields>
00467    };
00468 
00469    If we are given the struct directly (as our starting point) we
00470    need to tell the debugger to:
00471 
00472    1).  Add the offset of the forwarding field.
00473 
00474    2).  Follow that pointer to get the real __Block_byref_x_VarName
00475    struct to use (the real one may have been copied onto the heap).
00476 
00477    3).  Add the offset for the field VarName, to find the actual variable.
00478 
00479    If we started with a pointer to the struct, then we need to
00480    dereference that pointer first, before the other steps.
00481    Translating this into DWARF ops, we will need to append the following
00482    to the current location description for the variable:
00483 
00484    DW_OP_deref                    -- optional, if we start with a pointer
00485    DW_OP_plus_uconst <forward_fld_offset>
00486    DW_OP_deref
00487    DW_OP_plus_uconst <varName_fld_offset>
00488 
00489    That is what this function does.  */
00490 
00491 /// addBlockByrefAddress - Start with the address based on the location
00492 /// provided, and generate the DWARF information necessary to find the
00493 /// actual Block variable (navigating the Block struct) based on the
00494 /// starting location.  Add the DWARF information to the die.  For
00495 /// more information, read large comment just above here.
00496 ///
00497 void CompileUnit::addBlockByrefAddress(DbgVariable *&DV, DIE *Die,
00498                                        unsigned Attribute,
00499                                        const MachineLocation &Location) {
00500   DIType Ty = DV->getType();
00501   DIType TmpTy = Ty;
00502   unsigned Tag = Ty.getTag();
00503   bool isPointer = false;
00504 
00505   StringRef varName = DV->getName();
00506 
00507   if (Tag == dwarf::DW_TAG_pointer_type) {
00508     DIDerivedType DTy = DIDerivedType(Ty);
00509     TmpTy = DTy.getTypeDerivedFrom();
00510     isPointer = true;
00511   }
00512 
00513   DICompositeType blockStruct = DICompositeType(TmpTy);
00514 
00515   // Find the __forwarding field and the variable field in the __Block_byref
00516   // struct.
00517   DIArray Fields = blockStruct.getTypeArray();
00518   DIDescriptor varField = DIDescriptor();
00519   DIDescriptor forwardingField = DIDescriptor();
00520 
00521   for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
00522     DIDescriptor Element = Fields.getElement(i);
00523     DIDerivedType DT = DIDerivedType(Element);
00524     StringRef fieldName = DT.getName();
00525     if (fieldName == "__forwarding")
00526       forwardingField = Element;
00527     else if (fieldName == varName)
00528       varField = Element;
00529   }
00530 
00531   // Get the offsets for the forwarding field and the variable field.
00532   unsigned forwardingFieldOffset =
00533     DIDerivedType(forwardingField).getOffsetInBits() >> 3;
00534   unsigned varFieldOffset =
00535     DIDerivedType(varField).getOffsetInBits() >> 3;
00536 
00537   // Decode the original location, and use that as the start of the byref
00538   // variable's location.
00539   DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
00540 
00541   if (Location.isReg())
00542     addRegisterOp(Block, Location.getReg());
00543   else
00544     addRegisterOffset(Block, Location.getReg(), Location.getOffset());
00545 
00546   // If we started with a pointer to the __Block_byref... struct, then
00547   // the first thing we need to do is dereference the pointer (DW_OP_deref).
00548   if (isPointer)
00549     addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
00550 
00551   // Next add the offset for the '__forwarding' field:
00552   // DW_OP_plus_uconst ForwardingFieldOffset.  Note there's no point in
00553   // adding the offset if it's 0.
00554   if (forwardingFieldOffset > 0) {
00555     addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
00556     addUInt(Block, 0, dwarf::DW_FORM_udata, forwardingFieldOffset);
00557   }
00558 
00559   // Now dereference the __forwarding field to get to the real __Block_byref
00560   // struct:  DW_OP_deref.
00561   addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
00562 
00563   // Now that we've got the real __Block_byref... struct, add the offset
00564   // for the variable's field to get to the location of the actual variable:
00565   // DW_OP_plus_uconst varFieldOffset.  Again, don't add if it's 0.
00566   if (varFieldOffset > 0) {
00567     addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
00568     addUInt(Block, 0, dwarf::DW_FORM_udata, varFieldOffset);
00569   }
00570 
00571   // Now attach the location information to the DIE.
00572   addBlock(Die, Attribute, 0, Block);
00573 }
00574 
00575 /// isTypeSigned - Return true if the type is signed.
00576 static bool isTypeSigned(DIType Ty, int *SizeInBits) {
00577   if (Ty.isDerivedType())
00578     return isTypeSigned(DIDerivedType(Ty).getTypeDerivedFrom(), SizeInBits);
00579   if (Ty.isBasicType())
00580     if (DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed
00581         || DIBasicType(Ty).getEncoding() == dwarf::DW_ATE_signed_char) {
00582       *SizeInBits = Ty.getSizeInBits();
00583       return true;
00584     }
00585   return false;
00586 }
00587 
00588 /// addConstantValue - Add constant value entry in variable DIE.
00589 bool CompileUnit::addConstantValue(DIE *Die, const MachineOperand &MO,
00590                                    DIType Ty) {
00591   // FIXME: This is a bit conservative/simple - it emits negative values at
00592   // their maximum bit width which is a bit unfortunate (& doesn't prefer
00593   // udata/sdata over dataN as suggested by the DWARF spec)
00594   assert(MO.isImm() && "Invalid machine operand!");
00595   DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
00596   int SizeInBits = -1;
00597   bool SignedConstant = isTypeSigned(Ty, &SizeInBits);
00598   unsigned Form = SignedConstant ? dwarf::DW_FORM_sdata : dwarf::DW_FORM_udata;
00599   switch (SizeInBits) {
00600     case 8:  Form = dwarf::DW_FORM_data1; break;
00601     case 16: Form = dwarf::DW_FORM_data2; break;
00602     case 32: Form = dwarf::DW_FORM_data4; break;
00603     case 64: Form = dwarf::DW_FORM_data8; break;
00604     default: break;
00605   }
00606   SignedConstant ? addSInt(Block, 0, Form, MO.getImm())
00607     : addUInt(Block, 0, Form, MO.getImm());
00608 
00609   addBlock(Die, dwarf::DW_AT_const_value, 0, Block);
00610   return true;
00611 }
00612 
00613 /// addConstantFPValue - Add constant value entry in variable DIE.
00614 bool CompileUnit::addConstantFPValue(DIE *Die, const MachineOperand &MO) {
00615   assert (MO.isFPImm() && "Invalid machine operand!");
00616   DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
00617   APFloat FPImm = MO.getFPImm()->getValueAPF();
00618 
00619   // Get the raw data form of the floating point.
00620   const APInt FltVal = FPImm.bitcastToAPInt();
00621   const char *FltPtr = (const char*)FltVal.getRawData();
00622 
00623   int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
00624   bool LittleEndian = Asm->getDataLayout().isLittleEndian();
00625   int Incr = (LittleEndian ? 1 : -1);
00626   int Start = (LittleEndian ? 0 : NumBytes - 1);
00627   int Stop = (LittleEndian ? NumBytes : -1);
00628 
00629   // Output the constant to DWARF one byte at a time.
00630   for (; Start != Stop; Start += Incr)
00631     addUInt(Block, 0, dwarf::DW_FORM_data1,
00632             (unsigned char)0xFF & FltPtr[Start]);
00633 
00634   addBlock(Die, dwarf::DW_AT_const_value, 0, Block);
00635   return true;
00636 }
00637 
00638 /// addConstantFPValue - Add constant value entry in variable DIE.
00639 bool CompileUnit::addConstantFPValue(DIE *Die, const ConstantFP *CFP) {
00640   return addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), false);
00641 }
00642 
00643 /// addConstantValue - Add constant value entry in variable DIE.
00644 bool CompileUnit::addConstantValue(DIE *Die, const ConstantInt *CI,
00645                                    bool Unsigned) {
00646   return addConstantValue(Die, CI->getValue(), Unsigned);
00647 }
00648 
00649 // addConstantValue - Add constant value entry in variable DIE.
00650 bool CompileUnit::addConstantValue(DIE *Die, const APInt &Val,
00651                                    bool Unsigned) {
00652   unsigned CIBitWidth = Val.getBitWidth();
00653   if (CIBitWidth <= 64) {
00654     unsigned form = 0;
00655     switch (CIBitWidth) {
00656     case 8: form = dwarf::DW_FORM_data1; break;
00657     case 16: form = dwarf::DW_FORM_data2; break;
00658     case 32: form = dwarf::DW_FORM_data4; break;
00659     case 64: form = dwarf::DW_FORM_data8; break;
00660     default:
00661       form = Unsigned ? dwarf::DW_FORM_udata : dwarf::DW_FORM_sdata;
00662     }
00663     if (Unsigned)
00664       addUInt(Die, dwarf::DW_AT_const_value, form, Val.getZExtValue());
00665     else
00666       addSInt(Die, dwarf::DW_AT_const_value, form, Val.getSExtValue());
00667     return true;
00668   }
00669 
00670   DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
00671 
00672   // Get the raw data form of the large APInt.
00673   const uint64_t *Ptr64 = Val.getRawData();
00674 
00675   int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
00676   bool LittleEndian = Asm->getDataLayout().isLittleEndian();
00677 
00678   // Output the constant to DWARF one byte at a time.
00679   for (int i = 0; i < NumBytes; i++) {
00680     uint8_t c;
00681     if (LittleEndian)
00682       c = Ptr64[i / 8] >> (8 * (i & 7));
00683     else
00684       c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
00685     addUInt(Block, 0, dwarf::DW_FORM_data1, c);
00686   }
00687 
00688   addBlock(Die, dwarf::DW_AT_const_value, 0, Block);
00689   return true;
00690 }
00691 
00692 /// addTemplateParams - Add template parameters into buffer.
00693 void CompileUnit::addTemplateParams(DIE &Buffer, DIArray TParams) {
00694   // Add template parameters.
00695   for (unsigned i = 0, e = TParams.getNumElements(); i != e; ++i) {
00696     DIDescriptor Element = TParams.getElement(i);
00697     if (Element.isTemplateTypeParameter())
00698       Buffer.addChild(getOrCreateTemplateTypeParameterDIE(
00699                         DITemplateTypeParameter(Element)));
00700     else if (Element.isTemplateValueParameter())
00701       Buffer.addChild(getOrCreateTemplateValueParameterDIE(
00702                         DITemplateValueParameter(Element)));
00703   }
00704 }
00705 
00706 /// getOrCreateContextDIE - Get context owner's DIE.
00707 DIE *CompileUnit::getOrCreateContextDIE(DIDescriptor Context) {
00708   if (Context.isType())
00709     return getOrCreateTypeDIE(DIType(Context));
00710   else if (Context.isNameSpace())
00711     return getOrCreateNameSpace(DINameSpace(Context));
00712   else if (Context.isSubprogram())
00713     return getOrCreateSubprogramDIE(DISubprogram(Context));
00714   else
00715     return getDIE(Context);
00716 }
00717 
00718 /// addToContextOwner - Add Die into the list of its context owner's children.
00719 void CompileUnit::addToContextOwner(DIE *Die, DIDescriptor Context) {
00720   if (DIE *ContextDIE = getOrCreateContextDIE(Context))
00721     ContextDIE->addChild(Die);
00722   else
00723     addDie(Die);
00724 }
00725 
00726 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
00727 /// given DIType.
00728 DIE *CompileUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
00729   DIType Ty(TyNode);
00730   if (!Ty.Verify())
00731     return NULL;
00732   DIE *TyDIE = getDIE(Ty);
00733   if (TyDIE)
00734     return TyDIE;
00735 
00736   // Create new type.
00737   TyDIE = new DIE(dwarf::DW_TAG_base_type);
00738   insertDIE(Ty, TyDIE);
00739   if (Ty.isBasicType())
00740     constructTypeDIE(*TyDIE, DIBasicType(Ty));
00741   else if (Ty.isCompositeType())
00742     constructTypeDIE(*TyDIE, DICompositeType(Ty));
00743   else {
00744     assert(Ty.isDerivedType() && "Unknown kind of DIType");
00745     constructTypeDIE(*TyDIE, DIDerivedType(Ty));
00746   }
00747   // If this is a named finished type then include it in the list of types
00748   // for the accelerator tables.
00749   if (!Ty.getName().empty() && !Ty.isForwardDecl()) {
00750     bool IsImplementation = 0;
00751     if (Ty.isCompositeType()) {
00752       DICompositeType CT(Ty);
00753       // A runtime language of 0 actually means C/C++ and that any
00754       // non-negative value is some version of Objective-C/C++.
00755       IsImplementation = (CT.getRunTimeLang() == 0) ||
00756         CT.isObjcClassComplete();
00757     }
00758     unsigned Flags = IsImplementation ?
00759                      DwarfAccelTable::eTypeFlagClassIsImplementation : 0;
00760     addAccelType(Ty.getName(), std::make_pair(TyDIE, Flags));
00761   }
00762 
00763   addToContextOwner(TyDIE, Ty.getContext());
00764   return TyDIE;
00765 }
00766 
00767 /// addType - Add a new type attribute to the specified entity.
00768 void CompileUnit::addType(DIE *Entity, DIType Ty, unsigned Attribute) {
00769   if (!Ty.Verify())
00770     return;
00771 
00772   // Check for pre-existence.
00773   DIEEntry *Entry = getDIEEntry(Ty);
00774   // If it exists then use the existing value.
00775   if (Entry) {
00776     Entity->addValue(Attribute, dwarf::DW_FORM_ref4, Entry);
00777     return;
00778   }
00779 
00780   // Construct type.
00781   DIE *Buffer = getOrCreateTypeDIE(Ty);
00782 
00783   // Set up proxy.
00784   Entry = createDIEEntry(Buffer);
00785   insertDIEEntry(Ty, Entry);
00786   Entity->addValue(Attribute, dwarf::DW_FORM_ref4, Entry);
00787 
00788   // If this is a complete composite type then include it in the
00789   // list of global types.
00790   addGlobalType(Ty);
00791 }
00792 
00793 /// addGlobalType - Add a new global type to the compile unit.
00794 ///
00795 void CompileUnit::addGlobalType(DIType Ty) {
00796   DIDescriptor Context = Ty.getContext();
00797   if (Ty.isCompositeType() && !Ty.getName().empty() && !Ty.isForwardDecl()
00798       && (!Context || Context.isCompileUnit() || Context.isFile()
00799           || Context.isNameSpace()))
00800     if (DIEEntry *Entry = getDIEEntry(Ty))
00801       GlobalTypes[Ty.getName()] = Entry->getEntry();
00802 }
00803 
00804 /// addPubTypes - Add type for pubtypes section.
00805 void CompileUnit::addPubTypes(DISubprogram SP) {
00806   DICompositeType SPTy = SP.getType();
00807   unsigned SPTag = SPTy.getTag();
00808   if (SPTag != dwarf::DW_TAG_subroutine_type)
00809     return;
00810 
00811   DIArray Args = SPTy.getTypeArray();
00812   for (unsigned i = 0, e = Args.getNumElements(); i != e; ++i) {
00813     DIType ATy(Args.getElement(i));
00814     if (!ATy.Verify())
00815       continue;
00816     addGlobalType(ATy);
00817   }
00818 }
00819 
00820 /// constructTypeDIE - Construct basic type die from DIBasicType.
00821 void CompileUnit::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
00822   // Get core information.
00823   StringRef Name = BTy.getName();
00824   // Add name if not anonymous or intermediate type.
00825   if (!Name.empty())
00826     addString(&Buffer, dwarf::DW_AT_name, Name);
00827 
00828   if (BTy.getTag() == dwarf::DW_TAG_unspecified_type) {
00829     Buffer.setTag(dwarf::DW_TAG_unspecified_type);
00830     // Unspecified types has only name, nothing else.
00831     return;
00832   }
00833 
00834   Buffer.setTag(dwarf::DW_TAG_base_type);
00835   addUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
00836           BTy.getEncoding());
00837 
00838   uint64_t Size = BTy.getSizeInBits() >> 3;
00839   addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
00840 }
00841 
00842 /// constructTypeDIE - Construct derived type die from DIDerivedType.
00843 void CompileUnit::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
00844   // Get core information.
00845   StringRef Name = DTy.getName();
00846   uint64_t Size = DTy.getSizeInBits() >> 3;
00847   unsigned Tag = DTy.getTag();
00848 
00849   // FIXME - Workaround for templates.
00850   if (Tag == dwarf::DW_TAG_inheritance) Tag = dwarf::DW_TAG_reference_type;
00851 
00852   Buffer.setTag(Tag);
00853 
00854   // Map to main type, void will not have a type.
00855   DIType FromTy = DTy.getTypeDerivedFrom();
00856   addType(&Buffer, FromTy);
00857 
00858   // Add name if not anonymous or intermediate type.
00859   if (!Name.empty())
00860     addString(&Buffer, dwarf::DW_AT_name, Name);
00861 
00862   // Add size if non-zero (derived types might be zero-sized.)
00863   if (Size && Tag != dwarf::DW_TAG_pointer_type)
00864     addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
00865 
00866   if (Tag == dwarf::DW_TAG_ptr_to_member_type)
00867       addDIEEntry(&Buffer, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4,
00868                   getOrCreateTypeDIE(DTy.getClassType()));
00869   // Add source line info if available and TyDesc is not a forward declaration.
00870   if (!DTy.isForwardDecl())
00871     addSourceLine(&Buffer, DTy);
00872 }
00873 
00874 /// constructTypeDIE - Construct type DIE from DICompositeType.
00875 void CompileUnit::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
00876   // Get core information.
00877   StringRef Name = CTy.getName();
00878 
00879   uint64_t Size = CTy.getSizeInBits() >> 3;
00880   unsigned Tag = CTy.getTag();
00881   Buffer.setTag(Tag);
00882 
00883   switch (Tag) {
00884   case dwarf::DW_TAG_array_type:
00885     constructArrayTypeDIE(Buffer, &CTy);
00886     break;
00887   case dwarf::DW_TAG_enumeration_type: {
00888     DIArray Elements = CTy.getTypeArray();
00889 
00890     // Add enumerators to enumeration type.
00891     for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
00892       DIE *ElemDie = NULL;
00893       DIDescriptor Enum(Elements.getElement(i));
00894       if (Enum.isEnumerator()) {
00895         ElemDie = constructEnumTypeDIE(DIEnumerator(Enum));
00896         Buffer.addChild(ElemDie);
00897       }
00898     }
00899     DIType DTy = CTy.getTypeDerivedFrom();
00900     if (DTy.Verify()) {
00901       addType(&Buffer, DTy);
00902       addUInt(&Buffer, dwarf::DW_AT_enum_class, dwarf::DW_FORM_flag, 1);
00903     }
00904   }
00905     break;
00906   case dwarf::DW_TAG_subroutine_type: {
00907     // Add return type.
00908     DIArray Elements = CTy.getTypeArray();
00909     DIDescriptor RTy = Elements.getElement(0);
00910     addType(&Buffer, DIType(RTy));
00911 
00912     bool isPrototyped = true;
00913     // Add arguments.
00914     for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
00915       DIDescriptor Ty = Elements.getElement(i);
00916       if (Ty.isUnspecifiedParameter()) {
00917         DIE *Arg = new DIE(dwarf::DW_TAG_unspecified_parameters);
00918         Buffer.addChild(Arg);
00919         isPrototyped = false;
00920       } else {
00921         DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
00922         addType(Arg, DIType(Ty));
00923         if (DIType(Ty).isArtificial())
00924           addFlag(Arg, dwarf::DW_AT_artificial);
00925         Buffer.addChild(Arg);
00926       }
00927     }
00928     // Add prototype flag if we're dealing with a C language and the
00929     // function has been prototyped.
00930     if (isPrototyped &&
00931         (Language == dwarf::DW_LANG_C89 ||
00932          Language == dwarf::DW_LANG_C99 ||
00933          Language == dwarf::DW_LANG_ObjC))
00934       addFlag(&Buffer, dwarf::DW_AT_prototyped);
00935   }
00936     break;
00937   case dwarf::DW_TAG_structure_type:
00938   case dwarf::DW_TAG_union_type:
00939   case dwarf::DW_TAG_class_type: {
00940     // Add elements to structure type.
00941     DIArray Elements = CTy.getTypeArray();
00942 
00943     // A forward struct declared type may not have elements available.
00944     unsigned N = Elements.getNumElements();
00945     if (N == 0)
00946       break;
00947 
00948     // Add elements to structure type.
00949     for (unsigned i = 0; i < N; ++i) {
00950       DIDescriptor Element = Elements.getElement(i);
00951       DIE *ElemDie = NULL;
00952       if (Element.isSubprogram()) {
00953         DISubprogram SP(Element);
00954         ElemDie = getOrCreateSubprogramDIE(DISubprogram(Element));
00955         if (SP.isProtected())
00956           addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
00957                   dwarf::DW_ACCESS_protected);
00958         else if (SP.isPrivate())
00959           addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
00960                   dwarf::DW_ACCESS_private);
00961         else
00962           addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
00963             dwarf::DW_ACCESS_public);
00964         if (SP.isExplicit())
00965           addFlag(ElemDie, dwarf::DW_AT_explicit);
00966       } else if (Element.isDerivedType()) {
00967         DIDerivedType DDTy(Element);
00968         if (DDTy.getTag() == dwarf::DW_TAG_friend) {
00969           ElemDie = new DIE(dwarf::DW_TAG_friend);
00970           addType(ElemDie, DDTy.getTypeDerivedFrom(), dwarf::DW_AT_friend);
00971         } else if (DDTy.isStaticMember())
00972           ElemDie = createStaticMemberDIE(DDTy);
00973         else
00974           ElemDie = createMemberDIE(DDTy);
00975       } else if (Element.isObjCProperty()) {
00976         DIObjCProperty Property(Element);
00977         ElemDie = new DIE(Property.getTag());
00978         StringRef PropertyName = Property.getObjCPropertyName();
00979         addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
00980         addType(ElemDie, Property.getType());
00981         addSourceLine(ElemDie, Property);
00982         StringRef GetterName = Property.getObjCPropertyGetterName();
00983         if (!GetterName.empty())
00984           addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
00985         StringRef SetterName = Property.getObjCPropertySetterName();
00986         if (!SetterName.empty())
00987           addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
00988         unsigned PropertyAttributes = 0;
00989         if (Property.isReadOnlyObjCProperty())
00990           PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readonly;
00991         if (Property.isReadWriteObjCProperty())
00992           PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_readwrite;
00993         if (Property.isAssignObjCProperty())
00994           PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_assign;
00995         if (Property.isRetainObjCProperty())
00996           PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_retain;
00997         if (Property.isCopyObjCProperty())
00998           PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_copy;
00999         if (Property.isNonAtomicObjCProperty())
01000           PropertyAttributes |= dwarf::DW_APPLE_PROPERTY_nonatomic;
01001         if (PropertyAttributes)
01002           addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, 0,
01003                  PropertyAttributes);
01004 
01005         DIEEntry *Entry = getDIEEntry(Element);
01006         if (!Entry) {
01007           Entry = createDIEEntry(ElemDie);
01008           insertDIEEntry(Element, Entry);
01009         }
01010       } else
01011         continue;
01012       Buffer.addChild(ElemDie);
01013     }
01014 
01015     if (CTy.isAppleBlockExtension())
01016       addFlag(&Buffer, dwarf::DW_AT_APPLE_block);
01017 
01018     DICompositeType ContainingType = CTy.getContainingType();
01019     if (DIDescriptor(ContainingType).isCompositeType())
01020       addDIEEntry(&Buffer, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4,
01021                   getOrCreateTypeDIE(DIType(ContainingType)));
01022     else {
01023       DIDescriptor Context = CTy.getContext();
01024       addToContextOwner(&Buffer, Context);
01025     }
01026 
01027     if (CTy.isObjcClassComplete())
01028       addFlag(&Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
01029 
01030     // Add template parameters to a class, structure or union types.
01031     // FIXME: The support isn't in the metadata for this yet.
01032     if (Tag == dwarf::DW_TAG_class_type ||
01033         Tag == dwarf::DW_TAG_structure_type ||
01034         Tag == dwarf::DW_TAG_union_type)
01035       addTemplateParams(Buffer, CTy.getTemplateParams());
01036 
01037     break;
01038   }
01039   default:
01040     break;
01041   }
01042 
01043   // Add name if not anonymous or intermediate type.
01044   if (!Name.empty())
01045     addString(&Buffer, dwarf::DW_AT_name, Name);
01046 
01047   if (Tag == dwarf::DW_TAG_enumeration_type ||
01048       Tag == dwarf::DW_TAG_class_type ||
01049       Tag == dwarf::DW_TAG_structure_type ||
01050       Tag == dwarf::DW_TAG_union_type) {
01051     // Add size if non-zero (derived types might be zero-sized.)
01052     // TODO: Do we care about size for enum forward declarations?
01053     if (Size)
01054       addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
01055     else if (!CTy.isForwardDecl())
01056       // Add zero size if it is not a forward declaration.
01057       addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, 0);
01058 
01059     // If we're a forward decl, say so.
01060     if (CTy.isForwardDecl())
01061       addFlag(&Buffer, dwarf::DW_AT_declaration);
01062 
01063     // Add source line info if available.
01064     if (!CTy.isForwardDecl())
01065       addSourceLine(&Buffer, CTy);
01066 
01067     // No harm in adding the runtime language to the declaration.
01068     unsigned RLang = CTy.getRunTimeLang();
01069     if (RLang)
01070       addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class,
01071               dwarf::DW_FORM_data1, RLang);
01072   }
01073 }
01074 
01075 /// getOrCreateTemplateTypeParameterDIE - Find existing DIE or create new DIE
01076 /// for the given DITemplateTypeParameter.
01077 DIE *
01078 CompileUnit::getOrCreateTemplateTypeParameterDIE(DITemplateTypeParameter TP) {
01079   DIE *ParamDIE = getDIE(TP);
01080   if (ParamDIE)
01081     return ParamDIE;
01082 
01083   ParamDIE = new DIE(dwarf::DW_TAG_template_type_parameter);
01084   addType(ParamDIE, TP.getType());
01085   addString(ParamDIE, dwarf::DW_AT_name, TP.getName());
01086   return ParamDIE;
01087 }
01088 
01089 /// getOrCreateTemplateValueParameterDIE - Find existing DIE or create new DIE
01090 /// for the given DITemplateValueParameter.
01091 DIE *
01092 CompileUnit::getOrCreateTemplateValueParameterDIE(DITemplateValueParameter TPV){
01093   DIE *ParamDIE = getDIE(TPV);
01094   if (ParamDIE)
01095     return ParamDIE;
01096 
01097   ParamDIE = new DIE(dwarf::DW_TAG_template_value_parameter);
01098   addType(ParamDIE, TPV.getType());
01099   if (!TPV.getName().empty())
01100     addString(ParamDIE, dwarf::DW_AT_name, TPV.getName());
01101   if (Value *Val = TPV.getValue()) {
01102     if (ConstantInt *CI = dyn_cast<ConstantInt>(Val))
01103       addConstantValue(ParamDIE, CI, TPV.getType().isUnsignedDIType());
01104     else if (GlobalValue *GV = dyn_cast<GlobalValue>(Val)) {
01105       // For declaration non-type template parameters (such as global values and
01106       // functions)
01107       DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
01108       addOpAddress(Block, Asm->Mang->getSymbol(GV));
01109       // Emit DW_OP_stack_value to use the address as the immediate value of the
01110       // parameter, rather than a pointer to it.
01111       addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
01112       addBlock(ParamDIE, dwarf::DW_AT_location, 0, Block);
01113     }
01114   }
01115 
01116   return ParamDIE;
01117 }
01118 
01119 /// getOrCreateNameSpace - Create a DIE for DINameSpace.
01120 DIE *CompileUnit::getOrCreateNameSpace(DINameSpace NS) {
01121   DIE *NDie = getDIE(NS);
01122   if (NDie)
01123     return NDie;
01124   NDie = new DIE(dwarf::DW_TAG_namespace);
01125   insertDIE(NS, NDie);
01126   if (!NS.getName().empty()) {
01127     addString(NDie, dwarf::DW_AT_name, NS.getName());
01128     addAccelNamespace(NS.getName(), NDie);
01129   } else
01130     addAccelNamespace("(anonymous namespace)", NDie);
01131   addSourceLine(NDie, NS);
01132   addToContextOwner(NDie, NS.getContext());
01133   return NDie;
01134 }
01135 
01136 /// getOrCreateSubprogramDIE - Create new DIE using SP.
01137 DIE *CompileUnit::getOrCreateSubprogramDIE(DISubprogram SP) {
01138   DIE *SPDie = getDIE(SP);
01139   if (SPDie)
01140     return SPDie;
01141 
01142   SPDie = new DIE(dwarf::DW_TAG_subprogram);
01143 
01144   // DW_TAG_inlined_subroutine may refer to this DIE.
01145   insertDIE(SP, SPDie);
01146 
01147   DISubprogram SPDecl = SP.getFunctionDeclaration();
01148   DIE *DeclDie = NULL;
01149   if (SPDecl.isSubprogram()) {
01150     DeclDie = getOrCreateSubprogramDIE(SPDecl);
01151   }
01152 
01153   // Add to context owner.
01154   addToContextOwner(SPDie, SP.getContext());
01155 
01156   // Add function template parameters.
01157   addTemplateParams(*SPDie, SP.getTemplateParams());
01158 
01159   // Unfortunately this code needs to stay here instead of below the
01160   // AT_specification code in order to work around a bug in older
01161   // gdbs that requires the linkage name to resolve multiple template
01162   // functions.
01163   // TODO: Remove this set of code when we get rid of the old gdb
01164   // compatibility.
01165   StringRef LinkageName = SP.getLinkageName();
01166   if (!LinkageName.empty() && DD->useDarwinGDBCompat())
01167     addString(SPDie, dwarf::DW_AT_MIPS_linkage_name,
01168               GlobalValue::getRealLinkageName(LinkageName));
01169 
01170   // If this DIE is going to refer declaration info using AT_specification
01171   // then there is no need to add other attributes.
01172   if (DeclDie) {
01173     // Refer function declaration directly.
01174     addDIEEntry(SPDie, dwarf::DW_AT_specification, dwarf::DW_FORM_ref4,
01175                 DeclDie);
01176 
01177     return SPDie;
01178   }
01179 
01180   // Add the linkage name if we have one.
01181   if (!LinkageName.empty() && !DD->useDarwinGDBCompat())
01182     addString(SPDie, dwarf::DW_AT_MIPS_linkage_name,
01183               GlobalValue::getRealLinkageName(LinkageName));
01184 
01185   // Constructors and operators for anonymous aggregates do not have names.
01186   if (!SP.getName().empty())
01187     addString(SPDie, dwarf::DW_AT_name, SP.getName());
01188 
01189   addSourceLine(SPDie, SP);
01190 
01191   // Add the prototype if we have a prototype and we have a C like
01192   // language.
01193   if (SP.isPrototyped() &&
01194       (Language == dwarf::DW_LANG_C89 ||
01195        Language == dwarf::DW_LANG_C99 ||
01196        Language == dwarf::DW_LANG_ObjC))
01197     addFlag(SPDie, dwarf::DW_AT_prototyped);
01198 
01199   // Add Return Type.
01200   DICompositeType SPTy = SP.getType();
01201   assert(SPTy.getTag() == dwarf::DW_TAG_subroutine_type &&
01202          "the type of a subprogram should be a subroutine");
01203 
01204   DIArray Args = SPTy.getTypeArray();
01205   addType(SPDie, DIType(Args.getElement(0)));
01206 
01207   unsigned VK = SP.getVirtuality();
01208   if (VK) {
01209     addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
01210     DIEBlock *Block = getDIEBlock();
01211     addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
01212     addUInt(Block, 0, dwarf::DW_FORM_udata, SP.getVirtualIndex());
01213     addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, 0, Block);
01214     ContainingTypeMap.insert(std::make_pair(SPDie,
01215                                             SP.getContainingType()));
01216   }
01217 
01218   if (!SP.isDefinition()) {
01219     addFlag(SPDie, dwarf::DW_AT_declaration);
01220 
01221     // Add arguments. Do not add arguments for subprogram definition. They will
01222     // be handled while processing variables.
01223     for (unsigned i = 1, N =  Args.getNumElements(); i < N; ++i) {
01224       DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
01225       DIType ATy = DIType(Args.getElement(i));
01226       addType(Arg, ATy);
01227       if (ATy.isArtificial())
01228         addFlag(Arg, dwarf::DW_AT_artificial);
01229       SPDie->addChild(Arg);
01230     }
01231   }
01232 
01233   if (SP.isArtificial())
01234     addFlag(SPDie, dwarf::DW_AT_artificial);
01235 
01236   if (!SP.isLocalToUnit())
01237     addFlag(SPDie, dwarf::DW_AT_external);
01238 
01239   if (SP.isOptimized())
01240     addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
01241 
01242   if (unsigned isa = Asm->getISAEncoding()) {
01243     addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
01244   }
01245 
01246   return SPDie;
01247 }
01248 
01249 // Return const expression if value is a GEP to access merged global
01250 // constant. e.g.
01251 // i8* getelementptr ({ i8, i8, i8, i8 }* @_MergedGlobals, i32 0, i32 0)
01252 static const ConstantExpr *getMergedGlobalExpr(const Value *V) {
01253   const ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(V);
01254   if (!CE || CE->getNumOperands() != 3 ||
01255       CE->getOpcode() != Instruction::GetElementPtr)
01256     return NULL;
01257 
01258   // First operand points to a global struct.
01259   Value *Ptr = CE->getOperand(0);
01260   if (!isa<GlobalValue>(Ptr) ||
01261       !isa<StructType>(cast<PointerType>(Ptr->getType())->getElementType()))
01262     return NULL;
01263 
01264   // Second operand is zero.
01265   const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(CE->getOperand(1));
01266   if (!CI || !CI->isZero())
01267     return NULL;
01268 
01269   // Third operand is offset.
01270   if (!isa<ConstantInt>(CE->getOperand(2)))
01271     return NULL;
01272 
01273   return CE;
01274 }
01275 
01276 /// createGlobalVariableDIE - create global variable DIE.
01277 void CompileUnit::createGlobalVariableDIE(const MDNode *N) {
01278   // Check for pre-existence.
01279   if (getDIE(N))
01280     return;
01281 
01282   DIGlobalVariable GV(N);
01283   if (!GV.Verify())
01284     return;
01285 
01286   DIDescriptor GVContext = GV.getContext();
01287   DIType GTy = GV.getType();
01288 
01289   // If this is a static data member definition, some attributes belong
01290   // to the declaration DIE.
01291   DIE *VariableDIE = NULL;
01292   bool IsStaticMember = false;
01293   DIDerivedType SDMDecl = GV.getStaticDataMemberDeclaration();
01294   if (SDMDecl.Verify()) {
01295     assert(SDMDecl.isStaticMember() && "Expected static member decl");
01296     // We need the declaration DIE that is in the static member's class.
01297     // But that class might not exist in the DWARF yet.
01298     // Creating the class will create the static member decl DIE.
01299     getOrCreateContextDIE(SDMDecl.getContext());
01300     VariableDIE = getDIE(SDMDecl);
01301     assert(VariableDIE && "Static member decl has no context?");
01302     IsStaticMember = true;
01303   }
01304 
01305   // If this is not a static data member definition, create the variable
01306   // DIE and add the initial set of attributes to it.
01307   if (!VariableDIE) {
01308     VariableDIE = new DIE(GV.getTag());
01309     // Add to map.
01310     insertDIE(N, VariableDIE);
01311 
01312     // Add name and type.
01313     addString(VariableDIE, dwarf::DW_AT_name, GV.getDisplayName());
01314     addType(VariableDIE, GTy);
01315 
01316     // Add scoping info.
01317     if (!GV.isLocalToUnit()) {
01318       addFlag(VariableDIE, dwarf::DW_AT_external);
01319       addGlobalName(GV.getName(), VariableDIE);
01320     }
01321 
01322     // Add line number info.
01323     addSourceLine(VariableDIE, GV);
01324     // Add to context owner.
01325     addToContextOwner(VariableDIE, GVContext);
01326   }
01327 
01328   // Add location.
01329   bool addToAccelTable = false;
01330   DIE *VariableSpecDIE = NULL;
01331   bool isGlobalVariable = GV.getGlobal() != NULL;
01332   if (isGlobalVariable) {
01333     addToAccelTable = true;
01334     DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
01335     addOpAddress(Block, Asm->Mang->getSymbol(GV.getGlobal()));
01336     // Do not create specification DIE if context is either compile unit
01337     // or a subprogram.
01338     if (GVContext && GV.isDefinition() && !GVContext.isCompileUnit() &&
01339         !GVContext.isFile() && !isSubprogramContext(GVContext)) {
01340       // Create specification DIE.
01341       VariableSpecDIE = new DIE(dwarf::DW_TAG_variable);
01342       addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification,
01343                   dwarf::DW_FORM_ref4, VariableDIE);
01344       addBlock(VariableSpecDIE, dwarf::DW_AT_location, 0, Block);
01345       // A static member's declaration is already flagged as such.
01346       if (!SDMDecl.Verify())
01347         addFlag(VariableDIE, dwarf::DW_AT_declaration);
01348       addDie(VariableSpecDIE);
01349     } else {
01350       addBlock(VariableDIE, dwarf::DW_AT_location, 0, Block);
01351     }
01352     // Add linkage name.
01353     StringRef LinkageName = GV.getLinkageName();
01354     if (!LinkageName.empty()) {
01355       // From DWARF4: DIEs to which DW_AT_linkage_name may apply include:
01356       // TAG_common_block, TAG_constant, TAG_entry_point, TAG_subprogram and
01357       // TAG_variable.
01358       addString(IsStaticMember && VariableSpecDIE ?
01359                 VariableSpecDIE : VariableDIE, dwarf::DW_AT_MIPS_linkage_name,
01360                 GlobalValue::getRealLinkageName(LinkageName));
01361       // In compatibility mode with older gdbs we put the linkage name on both
01362       // the TAG_variable DIE and on the TAG_member DIE.
01363       if (IsStaticMember && VariableSpecDIE && DD->useDarwinGDBCompat())
01364         addString(VariableDIE, dwarf::DW_AT_MIPS_linkage_name,
01365                   GlobalValue::getRealLinkageName(LinkageName));
01366     }
01367   } else if (const ConstantInt *CI =
01368              dyn_cast_or_null<ConstantInt>(GV.getConstant())) {
01369     // AT_const_value was added when the static member was created. To avoid
01370     // emitting AT_const_value multiple times, we only add AT_const_value when
01371     // it is not a static member.
01372     if (!IsStaticMember)
01373       addConstantValue(VariableDIE, CI, GTy.isUnsignedDIType());
01374   } else if (const ConstantExpr *CE = getMergedGlobalExpr(N->getOperand(11))) {
01375     addToAccelTable = true;
01376     // GV is a merged global.
01377     DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
01378     Value *Ptr = CE->getOperand(0);
01379     addOpAddress(Block, Asm->Mang->getSymbol(cast<GlobalValue>(Ptr)));
01380     addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
01381     SmallVector<Value*, 3> Idx(CE->op_begin()+1, CE->op_end());
01382     addUInt(Block, 0, dwarf::DW_FORM_udata,
01383                    Asm->getDataLayout().getIndexedOffset(Ptr->getType(), Idx));
01384     addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
01385     addBlock(VariableDIE, dwarf::DW_AT_location, 0, Block);
01386   }
01387 
01388   if (addToAccelTable) {
01389     DIE *AddrDIE = VariableSpecDIE ? VariableSpecDIE : VariableDIE;
01390     addAccelName(GV.getName(), AddrDIE);
01391 
01392     // If the linkage name is different than the name, go ahead and output
01393     // that as well into the name table.
01394     if (GV.getLinkageName() != "" && GV.getName() != GV.getLinkageName())
01395       addAccelName(GV.getLinkageName(), AddrDIE);
01396   }
01397 
01398   return;
01399 }
01400 
01401 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
01402 void CompileUnit::constructSubrangeDIE(DIE &Buffer, DISubrange SR,
01403                                        DIE *IndexTy) {
01404   DIE *DW_Subrange = new DIE(dwarf::DW_TAG_subrange_type);
01405   addDIEEntry(DW_Subrange, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, IndexTy);
01406 
01407   // The LowerBound value defines the lower bounds which is typically zero for
01408   // C/C++. The Count value is the number of elements.  Values are 64 bit. If
01409   // Count == -1 then the array is unbounded and we do not emit
01410   // DW_AT_lower_bound and DW_AT_upper_bound attributes. If LowerBound == 0 and
01411   // Count == 0, then the array has zero elements in which case we do not emit
01412   // an upper bound.
01413   int64_t LowerBound = SR.getLo();
01414   int64_t DefaultLowerBound = getDefaultLowerBound();
01415   int64_t Count = SR.getCount();
01416 
01417   if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound)
01418     addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, 0, LowerBound);
01419 
01420   if (Count != -1 && Count != 0)
01421     // FIXME: An unbounded array should reference the expression that defines
01422     // the array.
01423     addUInt(DW_Subrange, dwarf::DW_AT_upper_bound, 0, LowerBound + Count - 1);
01424 
01425   Buffer.addChild(DW_Subrange);
01426 }
01427 
01428 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
01429 void CompileUnit::constructArrayTypeDIE(DIE &Buffer,
01430                                         DICompositeType *CTy) {
01431   Buffer.setTag(dwarf::DW_TAG_array_type);
01432   if (CTy->isVector())
01433     addFlag(&Buffer, dwarf::DW_AT_GNU_vector);
01434 
01435   // Emit derived type.
01436   addType(&Buffer, CTy->getTypeDerivedFrom());
01437   DIArray Elements = CTy->getTypeArray();
01438 
01439   // Get an anonymous type for index type.
01440   // FIXME: This type should be passed down from the front end
01441   // as different languages may have different sizes for indexes.
01442   DIE *IdxTy = getIndexTyDie();
01443   if (!IdxTy) {
01444     // Construct an anonymous type for index type.
01445     IdxTy = new DIE(dwarf::DW_TAG_base_type);
01446     addString(IdxTy, dwarf::DW_AT_name, "int");
01447     addUInt(IdxTy, dwarf::DW_AT_byte_size, 0, sizeof(int32_t));
01448     addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
01449             dwarf::DW_ATE_signed);
01450     addDie(IdxTy);
01451     setIndexTyDie(IdxTy);
01452   }
01453 
01454   // Add subranges to array type.
01455   for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
01456     DIDescriptor Element = Elements.getElement(i);
01457     if (Element.getTag() == dwarf::DW_TAG_subrange_type)
01458       constructSubrangeDIE(Buffer, DISubrange(Element), IdxTy);
01459   }
01460 }
01461 
01462 /// constructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
01463 DIE *CompileUnit::constructEnumTypeDIE(DIEnumerator ETy) {
01464   DIE *Enumerator = new DIE(dwarf::DW_TAG_enumerator);
01465   StringRef Name = ETy.getName();
01466   addString(Enumerator, dwarf::DW_AT_name, Name);
01467   int64_t Value = ETy.getEnumValue();
01468   addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, Value);
01469   return Enumerator;
01470 }
01471 
01472 /// constructContainingTypeDIEs - Construct DIEs for types that contain
01473 /// vtables.
01474 void CompileUnit::constructContainingTypeDIEs() {
01475   for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(),
01476          CE = ContainingTypeMap.end(); CI != CE; ++CI) {
01477     DIE *SPDie = CI->first;
01478     const MDNode *N = CI->second;
01479     if (!N) continue;
01480     DIE *NDie = getDIE(N);
01481     if (!NDie) continue;
01482     addDIEEntry(SPDie, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4, NDie);
01483   }
01484 }
01485 
01486 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
01487 DIE *CompileUnit::constructVariableDIE(DbgVariable *DV, bool isScopeAbstract) {
01488   StringRef Name = DV->getName();
01489 
01490   // Translate tag to proper Dwarf tag.
01491   unsigned Tag = DV->getTag();
01492 
01493   // Define variable debug information entry.
01494   DIE *VariableDie = new DIE(Tag);
01495   DbgVariable *AbsVar = DV->getAbstractVariable();
01496   DIE *AbsDIE = AbsVar ? AbsVar->getDIE() : NULL;
01497   if (AbsDIE)
01498     addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin,
01499                             dwarf::DW_FORM_ref4, AbsDIE);
01500   else {
01501     addString(VariableDie, dwarf::DW_AT_name, Name);
01502     addSourceLine(VariableDie, DV->getVariable());
01503     addType(VariableDie, DV->getType());
01504   }
01505 
01506   if (DV->isArtificial())
01507     addFlag(VariableDie, dwarf::DW_AT_artificial);
01508 
01509   if (isScopeAbstract) {
01510     DV->setDIE(VariableDie);
01511     return VariableDie;
01512   }
01513 
01514   // Add variable address.
01515 
01516   unsigned Offset = DV->getDotDebugLocOffset();
01517   if (Offset != ~0U) {
01518     addLabel(VariableDie, dwarf::DW_AT_location,
01519                          dwarf::DW_FORM_data4,
01520                          Asm->GetTempSymbol("debug_loc", Offset));
01521     DV->setDIE(VariableDie);
01522     return VariableDie;
01523   }
01524 
01525   // Check if variable is described by a DBG_VALUE instruction.
01526   if (const MachineInstr *DVInsn = DV->getMInsn()) {
01527     bool updated = false;
01528     assert(DVInsn->getNumOperands() == 3);
01529     if (DVInsn->getOperand(0).isReg()) {
01530       const MachineOperand RegOp = DVInsn->getOperand(0);
01531       if (int64_t Offset = DVInsn->getOperand(1).getImm()) {
01532         MachineLocation Location(RegOp.getReg(), Offset);
01533         addVariableAddress(DV, VariableDie, Location);
01534       } else if (RegOp.getReg())
01535         addVariableAddress(DV, VariableDie, MachineLocation(RegOp.getReg()));
01536       updated = true;
01537     } else if (DVInsn->getOperand(0).isImm())
01538       updated =
01539           addConstantValue(VariableDie, DVInsn->getOperand(0), DV->getType());
01540     else if (DVInsn->getOperand(0).isFPImm())
01541       updated = addConstantFPValue(VariableDie, DVInsn->getOperand(0));
01542     else if (DVInsn->getOperand(0).isCImm())
01543       updated = addConstantValue(VariableDie, DVInsn->getOperand(0).getCImm(),
01544                                  DV->getType().isUnsignedDIType());
01545     if (!updated) {
01546       // If variableDie is not updated then DBG_VALUE instruction does not
01547       // have valid variable info.
01548       delete VariableDie;
01549       return NULL;
01550     }
01551     DV->setDIE(VariableDie);
01552     return VariableDie;
01553   } else {
01554     // .. else use frame index.
01555     int FI = DV->getFrameIndex();
01556     if (FI != ~0) {
01557       unsigned FrameReg = 0;
01558       const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
01559       int Offset =
01560         TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
01561       MachineLocation Location(FrameReg, Offset);
01562       addVariableAddress(DV, VariableDie, Location);
01563     }
01564   }
01565 
01566   DV->setDIE(VariableDie);
01567   return VariableDie;
01568 }
01569 
01570 /// createMemberDIE - Create new member DIE.
01571 DIE *CompileUnit::createMemberDIE(DIDerivedType DT) {
01572   DIE *MemberDie = new DIE(DT.getTag());
01573   StringRef Name = DT.getName();
01574   if (!Name.empty())
01575     addString(MemberDie, dwarf::DW_AT_name, Name);
01576 
01577   addType(MemberDie, DT.getTypeDerivedFrom());
01578 
01579   addSourceLine(MemberDie, DT);
01580 
01581   DIEBlock *MemLocationDie = new (DIEValueAllocator) DIEBlock();
01582   addUInt(MemLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
01583 
01584   uint64_t Size = DT.getSizeInBits();
01585   uint64_t FieldSize = DT.getOriginalTypeSize();
01586 
01587   if (Size != FieldSize) {
01588     // Handle bitfield.
01589     addUInt(MemberDie, dwarf::DW_AT_byte_size, 0, DT.getOriginalTypeSize()>>3);
01590     addUInt(MemberDie, dwarf::DW_AT_bit_size, 0, DT.getSizeInBits());
01591 
01592     uint64_t Offset = DT.getOffsetInBits();
01593     uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
01594     uint64_t HiMark = (Offset + FieldSize) & AlignMask;
01595     uint64_t FieldOffset = (HiMark - FieldSize);
01596     Offset -= FieldOffset;
01597 
01598     // Maybe we need to work from the other end.
01599     if (Asm->getDataLayout().isLittleEndian())
01600       Offset = FieldSize - (Offset + Size);
01601     addUInt(MemberDie, dwarf::DW_AT_bit_offset, 0, Offset);
01602 
01603     // Here WD_AT_data_member_location points to the anonymous
01604     // field that includes this bit field.
01605     addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, FieldOffset >> 3);
01606 
01607   } else
01608     // This is not a bitfield.
01609     addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits() >> 3);
01610 
01611   if (DT.getTag() == dwarf::DW_TAG_inheritance
01612       && DT.isVirtual()) {
01613 
01614     // For C++, virtual base classes are not at fixed offset. Use following
01615     // expression to extract appropriate offset from vtable.
01616     // BaseAddr = ObAddr + *((*ObAddr) - Offset)
01617 
01618     DIEBlock *VBaseLocationDie = new (DIEValueAllocator) DIEBlock();
01619     addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
01620     addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
01621     addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
01622     addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits());
01623     addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
01624     addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
01625     addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
01626 
01627     addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0,
01628              VBaseLocationDie);
01629   } else
01630     addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0, MemLocationDie);
01631 
01632   if (DT.isProtected())
01633     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
01634             dwarf::DW_ACCESS_protected);
01635   else if (DT.isPrivate())
01636     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
01637             dwarf::DW_ACCESS_private);
01638   // Otherwise C++ member and base classes are considered public.
01639   else
01640     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
01641             dwarf::DW_ACCESS_public);
01642   if (DT.isVirtual())
01643     addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
01644             dwarf::DW_VIRTUALITY_virtual);
01645 
01646   // Objective-C properties.
01647   if (MDNode *PNode = DT.getObjCProperty())
01648     if (DIEEntry *PropertyDie = getDIEEntry(PNode))
01649       MemberDie->addValue(dwarf::DW_AT_APPLE_property, dwarf::DW_FORM_ref4,
01650                           PropertyDie);
01651 
01652   if (DT.isArtificial())
01653     addFlag(MemberDie, dwarf::DW_AT_artificial);
01654 
01655   return MemberDie;
01656 }
01657 
01658 /// createStaticMemberDIE - Create new DIE for C++ static member.
01659 DIE *CompileUnit::createStaticMemberDIE(const DIDerivedType DT) {
01660   if (!DT.Verify())
01661     return NULL;
01662 
01663   DIE *StaticMemberDIE = new DIE(DT.getTag());
01664   DIType Ty = DT.getTypeDerivedFrom();
01665 
01666   addString(StaticMemberDIE, dwarf::DW_AT_name, DT.getName());
01667   addType(StaticMemberDIE, Ty);
01668   addSourceLine(StaticMemberDIE, DT);
01669   addFlag(StaticMemberDIE, dwarf::DW_AT_external);
01670   addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
01671 
01672   // FIXME: We could omit private if the parent is a class_type, and
01673   // public if the parent is something else.
01674   if (DT.isProtected())
01675     addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
01676             dwarf::DW_ACCESS_protected);
01677   else if (DT.isPrivate())
01678     addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
01679             dwarf::DW_ACCESS_private);
01680   else
01681     addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
01682             dwarf::DW_ACCESS_public);
01683 
01684   if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT.getConstant()))
01685     addConstantValue(StaticMemberDIE, CI, Ty.isUnsignedDIType());
01686   if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT.getConstant()))
01687     addConstantFPValue(StaticMemberDIE, CFP);
01688 
01689   insertDIE(DT, StaticMemberDIE);
01690   return StaticMemberDIE;
01691 }