CGDebugInfo.cpp revision 22fe585bd689c2ff64af193e207901aba14cadd5
1//===--- CGDebugInfo.cpp - Emit Debug Information for a Module ------------===//
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 coordinates the debug information generation while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGDebugInfo.h"
15#include "CodeGenFunction.h"
16#include "CodeGenModule.h"
17#include "clang/AST/ASTContext.h"
18#include "clang/AST/DeclObjC.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/RecordLayout.h"
21#include "clang/Basic/SourceManager.h"
22#include "clang/Basic/FileManager.h"
23#include "clang/Basic/Version.h"
24#include "clang/CodeGen/CodeGenOptions.h"
25#include "llvm/Constants.h"
26#include "llvm/DerivedTypes.h"
27#include "llvm/Instructions.h"
28#include "llvm/Intrinsics.h"
29#include "llvm/Module.h"
30#include "llvm/ADT/StringExtras.h"
31#include "llvm/ADT/SmallVector.h"
32#include "llvm/Support/Dwarf.h"
33#include "llvm/System/Path.h"
34#include "llvm/Target/TargetMachine.h"
35using namespace clang;
36using namespace clang::CodeGen;
37
38CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
39  : CGM(CGM), DebugFactory(CGM.getModule()),
40    FwdDeclCount(0), BlockLiteralGenericSet(false) {
41  CreateCompileUnit();
42}
43
44CGDebugInfo::~CGDebugInfo() {
45  assert(RegionStack.empty() && "Region stack mismatch, stack not empty!");
46}
47
48void CGDebugInfo::setLocation(SourceLocation Loc) {
49  if (Loc.isValid())
50    CurLoc = CGM.getContext().getSourceManager().getInstantiationLoc(Loc);
51}
52
53/// getContextDescriptor - Get context info for the decl.
54llvm::DIDescriptor CGDebugInfo::getContextDescriptor(const Decl *Context,
55                                              llvm::DIDescriptor &CompileUnit) {
56  if (!Context)
57    return CompileUnit;
58
59  llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
60    I = RegionMap.find(Context);
61  if (I != RegionMap.end())
62    return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(I->second));
63
64  // Check namespace.
65  if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
66    return llvm::DIDescriptor(getOrCreateNameSpace(NSDecl, CompileUnit));
67
68  return CompileUnit;
69}
70
71/// getFunctionName - Get function name for the given FunctionDecl. If the
72/// name is constructred on demand (e.g. C++ destructor) then the name
73/// is stored on the side.
74llvm::StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
75  assert (FD && "Invalid FunctionDecl!");
76  IdentifierInfo *FII = FD->getIdentifier();
77  if (FII)
78    return FII->getName();
79
80  // Otherwise construct human readable name for debug info.
81  std::string NS = FD->getNameAsString();
82
83  // Copy this name on the side and use its reference.
84  char *StrPtr = DebugInfoNames.Allocate<char>(NS.length());
85  memcpy(StrPtr, NS.data(), NS.length());
86  return llvm::StringRef(StrPtr, NS.length());
87}
88
89/// getOrCreateFile - Get the file debug info descriptor for the input location.
90llvm::DIFile CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
91  if (!Loc.isValid())
92    // If Location is not valid then use main input file.
93    return DebugFactory.CreateFile(TheCU.getFilename(), TheCU.getDirectory(),
94                                   TheCU);
95  SourceManager &SM = CGM.getContext().getSourceManager();
96  PresumedLoc PLoc = SM.getPresumedLoc(Loc);
97  llvm::sys::Path AbsFileName(PLoc.getFilename());
98  AbsFileName.makeAbsolute();
99
100  return DebugFactory.CreateFile(AbsFileName.getLast(),
101                                 AbsFileName.getDirname(), TheCU);
102}
103/// CreateCompileUnit - Create new compile unit.
104void CGDebugInfo::CreateCompileUnit() {
105
106  // Get absolute path name.
107  std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
108  if (MainFileName.empty())
109    MainFileName = "<unknown>";
110  llvm::sys::Path AbsFileName(MainFileName);
111  AbsFileName.makeAbsolute();
112
113  unsigned LangTag;
114  const LangOptions &LO = CGM.getLangOptions();
115  if (LO.CPlusPlus) {
116    if (LO.ObjC1)
117      LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
118    else
119      LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
120  } else if (LO.ObjC1) {
121    LangTag = llvm::dwarf::DW_LANG_ObjC;
122  } else if (LO.C99) {
123    LangTag = llvm::dwarf::DW_LANG_C99;
124  } else {
125    LangTag = llvm::dwarf::DW_LANG_C89;
126  }
127
128  const char *Producer =
129#ifdef CLANG_VENDOR
130    CLANG_VENDOR
131#endif
132    "clang " CLANG_VERSION_STRING;
133
134  // Figure out which version of the ObjC runtime we have.
135  unsigned RuntimeVers = 0;
136  if (LO.ObjC1)
137    RuntimeVers = LO.ObjCNonFragileABI ? 2 : 1;
138
139  // Create new compile unit.
140  TheCU = DebugFactory.CreateCompileUnit(
141    LangTag, AbsFileName.getLast(), AbsFileName.getDirname(), Producer, true,
142    LO.Optimize, CGM.getCodeGenOpts().DwarfDebugFlags, RuntimeVers);
143}
144
145/// CreateType - Get the Basic type from the cache or create a new
146/// one if necessary.
147llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT,
148                                     llvm::DIFile Unit) {
149  unsigned Encoding = 0;
150  switch (BT->getKind()) {
151  default:
152  case BuiltinType::Void:
153    return llvm::DIType();
154  case BuiltinType::UChar:
155  case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break;
156  case BuiltinType::Char_S:
157  case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break;
158  case BuiltinType::UShort:
159  case BuiltinType::UInt:
160  case BuiltinType::ULong:
161  case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break;
162  case BuiltinType::Short:
163  case BuiltinType::Int:
164  case BuiltinType::Long:
165  case BuiltinType::LongLong:  Encoding = llvm::dwarf::DW_ATE_signed; break;
166  case BuiltinType::Bool:      Encoding = llvm::dwarf::DW_ATE_boolean; break;
167  case BuiltinType::Float:
168  case BuiltinType::LongDouble:
169  case BuiltinType::Double:    Encoding = llvm::dwarf::DW_ATE_float; break;
170  }
171  // Bit size, align and offset of the type.
172  uint64_t Size = CGM.getContext().getTypeSize(BT);
173  uint64_t Align = CGM.getContext().getTypeAlign(BT);
174  uint64_t Offset = 0;
175
176  llvm::DIType DbgTy =
177    DebugFactory.CreateBasicType(Unit,
178                                 BT->getName(CGM.getContext().getLangOptions()),
179                                 Unit, 0, Size, Align,
180                                 Offset, /*flags*/ 0, Encoding);
181  return DbgTy;
182}
183
184llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty,
185                                     llvm::DIFile Unit) {
186  // Bit size, align and offset of the type.
187  unsigned Encoding = llvm::dwarf::DW_ATE_complex_float;
188  if (Ty->isComplexIntegerType())
189    Encoding = llvm::dwarf::DW_ATE_lo_user;
190
191  uint64_t Size = CGM.getContext().getTypeSize(Ty);
192  uint64_t Align = CGM.getContext().getTypeAlign(Ty);
193  uint64_t Offset = 0;
194
195  llvm::DIType DbgTy =
196    DebugFactory.CreateBasicType(Unit, "complex",
197                                 Unit, 0, Size, Align,
198                                 Offset, /*flags*/ 0, Encoding);
199  return DbgTy;
200}
201
202/// CreateCVRType - Get the qualified type from the cache or create
203/// a new one if necessary.
204llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit) {
205  QualifierCollector Qc;
206  const Type *T = Qc.strip(Ty);
207
208  // Ignore these qualifiers for now.
209  Qc.removeObjCGCAttr();
210  Qc.removeAddressSpace();
211
212  // We will create one Derived type for one qualifier and recurse to handle any
213  // additional ones.
214  unsigned Tag;
215  if (Qc.hasConst()) {
216    Tag = llvm::dwarf::DW_TAG_const_type;
217    Qc.removeConst();
218  } else if (Qc.hasVolatile()) {
219    Tag = llvm::dwarf::DW_TAG_volatile_type;
220    Qc.removeVolatile();
221  } else if (Qc.hasRestrict()) {
222    Tag = llvm::dwarf::DW_TAG_restrict_type;
223    Qc.removeRestrict();
224  } else {
225    assert(Qc.empty() && "Unknown type qualifier for debug info");
226    return getOrCreateType(QualType(T, 0), Unit);
227  }
228
229  llvm::DIType FromTy = getOrCreateType(Qc.apply(T), Unit);
230
231  // No need to fill in the Name, Line, Size, Alignment, Offset in case of
232  // CVR derived types.
233  llvm::DIType DbgTy =
234    DebugFactory.CreateDerivedType(Tag, Unit, "", Unit,
235                                   0, 0, 0, 0, 0, FromTy);
236  return DbgTy;
237}
238
239llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
240                                     llvm::DIFile Unit) {
241  llvm::DIType DbgTy =
242    CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
243                          Ty->getPointeeType(), Unit);
244  return DbgTy;
245}
246
247llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
248                                     llvm::DIFile Unit) {
249  return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
250                               Ty->getPointeeType(), Unit);
251}
252
253llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag,
254                                                const Type *Ty,
255                                                QualType PointeeTy,
256                                                llvm::DIFile Unit) {
257  llvm::DIType EltTy = getOrCreateType(PointeeTy, Unit);
258
259  // Bit size, align and offset of the type.
260
261  // Size is always the size of a pointer. We can't use getTypeSize here
262  // because that does not return the correct value for references.
263  uint64_t Size =
264    CGM.getContext().Target.getPointerWidth(PointeeTy.getAddressSpace());
265  uint64_t Align = CGM.getContext().getTypeAlign(Ty);
266
267  return
268    DebugFactory.CreateDerivedType(Tag, Unit, "", Unit,
269                                   0, Size, Align, 0, 0, EltTy);
270
271}
272
273llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
274                                     llvm::DIFile Unit) {
275  if (BlockLiteralGenericSet)
276    return BlockLiteralGeneric;
277
278  unsigned Tag = llvm::dwarf::DW_TAG_structure_type;
279
280  llvm::SmallVector<llvm::DIDescriptor, 5> EltTys;
281
282  llvm::DIType FieldTy;
283
284  QualType FType;
285  uint64_t FieldSize, FieldOffset;
286  unsigned FieldAlign;
287
288  llvm::DIArray Elements;
289  llvm::DIType EltTy, DescTy;
290
291  FieldOffset = 0;
292  FType = CGM.getContext().UnsignedLongTy;
293  FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
294  FieldSize = CGM.getContext().getTypeSize(FType);
295  FieldAlign = CGM.getContext().getTypeAlign(FType);
296  FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
297                                           "reserved", Unit,
298                                           0, FieldSize, FieldAlign,
299                                           FieldOffset, 0, FieldTy);
300  EltTys.push_back(FieldTy);
301
302  FieldOffset += FieldSize;
303  FType = CGM.getContext().UnsignedLongTy;
304  FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
305  FieldSize = CGM.getContext().getTypeSize(FType);
306  FieldAlign = CGM.getContext().getTypeAlign(FType);
307  FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
308                                           "Size", Unit,
309                                           0, FieldSize, FieldAlign,
310                                           FieldOffset, 0, FieldTy);
311  EltTys.push_back(FieldTy);
312
313  FieldOffset += FieldSize;
314  Elements = DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
315  EltTys.clear();
316
317  unsigned Flags = llvm::DIType::FlagAppleBlock;
318
319  EltTy = DebugFactory.CreateCompositeType(Tag, Unit, "__block_descriptor",
320                                           Unit, 0, FieldOffset, 0, 0, Flags,
321                                           llvm::DIType(), Elements);
322
323  // Bit size, align and offset of the type.
324  uint64_t Size = CGM.getContext().getTypeSize(Ty);
325  uint64_t Align = CGM.getContext().getTypeAlign(Ty);
326
327  DescTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type,
328                                          Unit, "", Unit,
329                                          0, Size, Align, 0, 0, EltTy);
330
331  FieldOffset = 0;
332  FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
333  FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
334  FieldSize = CGM.getContext().getTypeSize(FType);
335  FieldAlign = CGM.getContext().getTypeAlign(FType);
336  FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
337                                           "__isa", Unit,
338                                           0, FieldSize, FieldAlign,
339                                           FieldOffset, 0, FieldTy);
340  EltTys.push_back(FieldTy);
341
342  FieldOffset += FieldSize;
343  FType = CGM.getContext().IntTy;
344  FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
345  FieldSize = CGM.getContext().getTypeSize(FType);
346  FieldAlign = CGM.getContext().getTypeAlign(FType);
347  FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
348                                           "__flags", Unit,
349                                           0, FieldSize, FieldAlign,
350                                           FieldOffset, 0, FieldTy);
351  EltTys.push_back(FieldTy);
352
353  FieldOffset += FieldSize;
354  FType = CGM.getContext().IntTy;
355  FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
356  FieldSize = CGM.getContext().getTypeSize(FType);
357  FieldAlign = CGM.getContext().getTypeAlign(FType);
358  FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
359                                           "__reserved", Unit,
360                                           0, FieldSize, FieldAlign,
361                                           FieldOffset, 0, FieldTy);
362  EltTys.push_back(FieldTy);
363
364  FieldOffset += FieldSize;
365  FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
366  FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
367  FieldSize = CGM.getContext().getTypeSize(FType);
368  FieldAlign = CGM.getContext().getTypeAlign(FType);
369  FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
370                                           "__FuncPtr", Unit,
371                                           0, FieldSize, FieldAlign,
372                                           FieldOffset, 0, FieldTy);
373  EltTys.push_back(FieldTy);
374
375  FieldOffset += FieldSize;
376  FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
377  FieldTy = DescTy;
378  FieldSize = CGM.getContext().getTypeSize(Ty);
379  FieldAlign = CGM.getContext().getTypeAlign(Ty);
380  FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
381                                           "__descriptor", Unit,
382                                           0, FieldSize, FieldAlign,
383                                           FieldOffset, 0, FieldTy);
384  EltTys.push_back(FieldTy);
385
386  FieldOffset += FieldSize;
387  Elements = DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
388
389  EltTy = DebugFactory.CreateCompositeType(Tag, Unit, "__block_literal_generic",
390                                           Unit, 0, FieldOffset, 0, 0, Flags,
391                                           llvm::DIType(), Elements);
392
393  BlockLiteralGenericSet = true;
394  BlockLiteralGeneric
395    = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type, Unit,
396                                     "", Unit,
397                                     0, Size, Align, 0, 0, EltTy);
398  return BlockLiteralGeneric;
399}
400
401llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty,
402                                     llvm::DIFile Unit) {
403  // Typedefs are derived from some other type.  If we have a typedef of a
404  // typedef, make sure to emit the whole chain.
405  llvm::DIType Src = getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
406
407  // We don't set size information, but do specify where the typedef was
408  // declared.
409  SourceManager &SM = CGM.getContext().getSourceManager();
410  PresumedLoc PLoc = SM.getPresumedLoc(Ty->getDecl()->getLocation());
411  unsigned Line = PLoc.isInvalid() ? 0 : PLoc.getLine();
412
413  llvm::DIDescriptor TyContext
414    = getContextDescriptor(dyn_cast<Decl>(Ty->getDecl()->getDeclContext()),
415                           Unit);
416  llvm::DIType DbgTy =
417    DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_typedef,
418                                   TyContext,
419                                   Ty->getDecl()->getName(), Unit,
420                                   Line, 0, 0, 0, 0, Src);
421  return DbgTy;
422}
423
424llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
425                                     llvm::DIFile Unit) {
426  llvm::SmallVector<llvm::DIDescriptor, 16> EltTys;
427
428  // Add the result type at least.
429  EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit));
430
431  // Set up remainder of arguments if there is a prototype.
432  // FIXME: IF NOT, HOW IS THIS REPRESENTED?  llvm-gcc doesn't represent '...'!
433  if (const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(Ty)) {
434    for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i)
435      EltTys.push_back(getOrCreateType(FTP->getArgType(i), Unit));
436  } else {
437    // FIXME: Handle () case in C.  llvm-gcc doesn't do it either.
438  }
439
440  llvm::DIArray EltTypeArray =
441    DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
442
443  llvm::DIType DbgTy =
444    DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_subroutine_type,
445                                     Unit, "", Unit,
446                                     0, 0, 0, 0, 0,
447                                     llvm::DIType(), EltTypeArray);
448  return DbgTy;
449}
450
451/// CollectRecordFields - A helper function to collect debug info for
452/// record fields. This is used while creating debug info entry for a Record.
453void CGDebugInfo::
454CollectRecordFields(const RecordDecl *RD, llvm::DIFile Unit,
455                    llvm::SmallVectorImpl<llvm::DIDescriptor> &EltTys) {
456  unsigned FieldNo = 0;
457  SourceManager &SM = CGM.getContext().getSourceManager();
458  const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
459  for (RecordDecl::field_iterator I = RD->field_begin(),
460                                  E = RD->field_end();
461       I != E; ++I, ++FieldNo) {
462    FieldDecl *Field = *I;
463    llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
464
465    llvm::StringRef FieldName = Field->getName();
466
467    // Ignore unnamed fields. Do not ignore unnamed records.
468    if (FieldName.empty() && !isa<RecordType>(Field->getType()))
469      continue;
470
471    // Get the location for the field.
472    SourceLocation FieldDefLoc = Field->getLocation();
473    PresumedLoc PLoc = SM.getPresumedLoc(FieldDefLoc);
474    llvm::DIFile FieldDefUnit;
475    unsigned FieldLine = 0;
476
477    if (!PLoc.isInvalid()) {
478      FieldDefUnit = getOrCreateFile(FieldDefLoc);
479      FieldLine = PLoc.getLine();
480    }
481
482    QualType FType = Field->getType();
483    uint64_t FieldSize = 0;
484    unsigned FieldAlign = 0;
485    if (!FType->isIncompleteArrayType()) {
486
487      // Bit size, align and offset of the type.
488      FieldSize = CGM.getContext().getTypeSize(FType);
489      Expr *BitWidth = Field->getBitWidth();
490      if (BitWidth)
491        FieldSize = BitWidth->EvaluateAsInt(CGM.getContext()).getZExtValue();
492
493      FieldAlign =  CGM.getContext().getTypeAlign(FType);
494    }
495
496    uint64_t FieldOffset = RL.getFieldOffset(FieldNo);
497
498    // Create a DW_TAG_member node to remember the offset of this field in the
499    // struct.  FIXME: This is an absolutely insane way to capture this
500    // information.  When we gut debug info, this should be fixed.
501    FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
502                                             FieldName, FieldDefUnit,
503                                             FieldLine, FieldSize, FieldAlign,
504                                             FieldOffset, 0, FieldTy);
505    EltTys.push_back(FieldTy);
506  }
507}
508
509/// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
510/// function type is not updated to include implicit "this" pointer. Use this
511/// routine to get a method type which includes "this" pointer.
512llvm::DIType
513CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
514                                   llvm::DIFile Unit) {
515  llvm::DIType FnTy = getOrCreateType(Method->getType(), Unit);
516
517  // Static methods do not need "this" pointer argument.
518  if (Method->isStatic())
519    return FnTy;
520
521  // Add "this" pointer.
522
523  llvm::DIArray Args = llvm::DICompositeType(FnTy.getNode()).getTypeArray();
524  assert (Args.getNumElements() && "Invalid number of arguments!");
525
526  llvm::SmallVector<llvm::DIDescriptor, 16> Elts;
527
528  // First element is always return type. For 'void' functions it is NULL.
529  Elts.push_back(Args.getElement(0));
530
531  // "this" pointer is always first argument.
532  ASTContext &Context = CGM.getContext();
533  QualType ThisPtr =
534    Context.getPointerType(Context.getTagDeclType(Method->getParent()));
535  llvm::DIType ThisPtrType =
536    DebugFactory.CreateArtificialType(getOrCreateType(ThisPtr, Unit));
537  TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType.getNode();
538  Elts.push_back(ThisPtrType);
539
540  // Copy rest of the arguments.
541  for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
542    Elts.push_back(Args.getElement(i));
543
544  llvm::DIArray EltTypeArray =
545    DebugFactory.GetOrCreateArray(Elts.data(), Elts.size());
546
547  return
548    DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_subroutine_type,
549                                     Unit, "", Unit,
550                                     0, 0, 0, 0, 0,
551                                     llvm::DIType(), EltTypeArray);
552}
553
554/// CreateCXXMemberFunction - A helper function to create a DISubprogram for
555/// a single member function GlobalDecl.
556llvm::DISubprogram
557CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
558                                     llvm::DIFile Unit,
559                                     llvm::DICompositeType &RecordTy) {
560  bool IsCtorOrDtor =
561    isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
562
563  llvm::StringRef MethodName = getFunctionName(Method);
564  llvm::StringRef MethodLinkageName;
565  llvm::DIType MethodTy = getOrCreateMethodType(Method, Unit);
566
567  // Since a single ctor/dtor corresponds to multiple functions, it doesn't
568  // make sense to give a single ctor/dtor a linkage name.
569  if (!IsCtorOrDtor)
570    MethodLinkageName = CGM.getMangledName(Method);
571
572  SourceManager &SM = CGM.getContext().getSourceManager();
573
574  // Get the location for the method.
575  SourceLocation MethodDefLoc = Method->getLocation();
576  PresumedLoc PLoc = SM.getPresumedLoc(MethodDefLoc);
577  llvm::DIFile MethodDefUnit;
578  unsigned MethodLine = 0;
579
580  if (!PLoc.isInvalid()) {
581    MethodDefUnit = getOrCreateFile(MethodDefLoc);
582    MethodLine = PLoc.getLine();
583  }
584
585  // Collect virtual method info.
586  llvm::DIType ContainingType;
587  unsigned Virtuality = 0;
588  unsigned VIndex = 0;
589
590  if (Method->isVirtual()) {
591    if (Method->isPure())
592      Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
593    else
594      Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
595
596    // It doesn't make sense to give a virtual destructor a vtable index,
597    // since a single destructor has two entries in the vtable.
598    if (!isa<CXXDestructorDecl>(Method))
599      VIndex = CGM.getVtableInfo().getMethodVtableIndex(Method);
600    ContainingType = RecordTy;
601  }
602
603  llvm::DISubprogram SP =
604    DebugFactory.CreateSubprogram(RecordTy , MethodName, MethodName,
605                                  MethodLinkageName,
606                                  MethodDefUnit, MethodLine,
607                                  MethodTy, /*isLocalToUnit=*/false,
608                                  Method->isThisDeclarationADefinition(),
609                                  Virtuality, VIndex, ContainingType);
610
611  // Don't cache ctors or dtors since we have to emit multiple functions for
612  // a single ctor or dtor.
613  if (!IsCtorOrDtor && Method->isThisDeclarationADefinition())
614    SPCache[Method] = llvm::WeakVH(SP.getNode());
615
616  return SP;
617}
618
619/// CollectCXXMemberFunctions - A helper function to collect debug info for
620/// C++ member functions.This is used while creating debug info entry for
621/// a Record.
622void CGDebugInfo::
623CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
624                          llvm::SmallVectorImpl<llvm::DIDescriptor> &EltTys,
625                          llvm::DICompositeType &RecordTy) {
626  for(CXXRecordDecl::method_iterator I = RD->method_begin(),
627        E = RD->method_end(); I != E; ++I) {
628    const CXXMethodDecl *Method = *I;
629
630    if (Method->isImplicit() && !Method->isUsed())
631      continue;
632
633    EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
634  }
635}
636
637/// CollectCXXBases - A helper function to collect debug info for
638/// C++ base classes. This is used while creating debug info entry for
639/// a Record.
640void CGDebugInfo::
641CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
642                llvm::SmallVectorImpl<llvm::DIDescriptor> &EltTys,
643                llvm::DICompositeType &RecordTy) {
644
645  const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
646  for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
647         BE = RD->bases_end(); BI != BE; ++BI) {
648    unsigned BFlags = 0;
649    uint64_t BaseOffset;
650
651    const CXXRecordDecl *Base =
652      cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl());
653
654    if (BI->isVirtual()) {
655      // virtual base offset offset is -ve. The code generator emits dwarf
656      // expression where it expects +ve number.
657      BaseOffset = 0 - CGM.getVtableInfo().getVirtualBaseOffsetOffset(RD, Base);
658      BFlags = llvm::DIType::FlagVirtual;
659    } else
660      BaseOffset = RL.getBaseClassOffset(Base);
661
662    AccessSpecifier Access = BI->getAccessSpecifier();
663    if (Access == clang::AS_private)
664      BFlags |= llvm::DIType::FlagPrivate;
665    else if (Access == clang::AS_protected)
666      BFlags |= llvm::DIType::FlagProtected;
667
668    llvm::DIType DTy =
669      DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_inheritance,
670                                     RecordTy, llvm::StringRef(),
671                                     Unit, 0, 0, 0,
672                                     BaseOffset, BFlags,
673                                     getOrCreateType(BI->getType(),
674                                                     Unit));
675    EltTys.push_back(DTy);
676  }
677}
678
679/// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
680llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
681  if (VTablePtrType.isValid())
682    return VTablePtrType;
683
684  ASTContext &Context = CGM.getContext();
685
686  /* Function type */
687  llvm::SmallVector<llvm::DIDescriptor, 16> STys;
688  STys.push_back(getOrCreateType(Context.IntTy, Unit));
689  llvm::DIArray SElements =
690    DebugFactory.GetOrCreateArray(STys.data(), STys.size());
691  llvm::DIType SubTy =
692    DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_subroutine_type,
693                                     Unit, "", Unit,
694                                     0, 0, 0, 0, 0, llvm::DIType(), SElements);
695
696  unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
697  llvm::DIType vtbl_ptr_type
698    = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type,
699                                     Unit, "__vtbl_ptr_type", Unit,
700                                     0, Size, 0, 0, 0, SubTy);
701
702  VTablePtrType =
703    DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type,
704                                   Unit, "", Unit,
705                                   0, Size, 0, 0, 0, vtbl_ptr_type);
706  return VTablePtrType;
707}
708
709/// getVtableName - Get vtable name for the given Class.
710llvm::StringRef CGDebugInfo::getVtableName(const CXXRecordDecl *RD) {
711  // Otherwise construct gdb compatible name name.
712  std::string Name = "_vptr$" + RD->getNameAsString();
713
714  // Copy this name on the side and use its reference.
715  char *StrPtr = DebugInfoNames.Allocate<char>(Name.length());
716  memcpy(StrPtr, Name.data(), Name.length());
717  return llvm::StringRef(StrPtr, Name.length());
718}
719
720
721/// CollectVtableInfo - If the C++ class has vtable info then insert appropriate
722/// debug info entry in EltTys vector.
723void CGDebugInfo::
724CollectVtableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
725                  llvm::SmallVectorImpl<llvm::DIDescriptor> &EltTys) {
726  const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
727
728  // If there is a primary base then it will hold vtable info.
729  if (RL.getPrimaryBase())
730    return;
731
732  // If this class is not dynamic then there is not any vtable info to collect.
733  if (!RD->isDynamicClass())
734    return;
735
736  unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
737  llvm::DIType VPTR
738    = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
739                                     getVtableName(RD), Unit,
740                                     0, Size, 0, 0, 0,
741                                     getOrCreateVTablePtrType(Unit));
742  EltTys.push_back(VPTR);
743}
744
745/// CreateType - get structure or union type.
746llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty,
747                                     llvm::DIFile Unit) {
748  RecordDecl *RD = Ty->getDecl();
749
750  unsigned Tag;
751  if (RD->isStruct())
752    Tag = llvm::dwarf::DW_TAG_structure_type;
753  else if (RD->isUnion())
754    Tag = llvm::dwarf::DW_TAG_union_type;
755  else {
756    assert(RD->isClass() && "Unknown RecordType!");
757    Tag = llvm::dwarf::DW_TAG_class_type;
758  }
759
760  SourceManager &SM = CGM.getContext().getSourceManager();
761
762  // Get overall information about the record type for the debug info.
763  PresumedLoc PLoc = SM.getPresumedLoc(RD->getLocation());
764  llvm::DIFile DefUnit;
765  unsigned Line = 0;
766  if (!PLoc.isInvalid()) {
767    DefUnit = getOrCreateFile(RD->getLocation());
768    Line = PLoc.getLine();
769  }
770
771  // Records and classes and unions can all be recursive.  To handle them, we
772  // first generate a debug descriptor for the struct as a forward declaration.
773  // Then (if it is a definition) we go through and get debug info for all of
774  // its members.  Finally, we create a descriptor for the complete type (which
775  // may refer to the forward decl if the struct is recursive) and replace all
776  // uses of the forward declaration with the final definition.
777
778  // A RD->getName() is not unique. However, the debug info descriptors
779  // are uniqued so use type name to ensure uniquness.
780  llvm::SmallString<256> FwdDeclName;
781  FwdDeclName.resize(256);
782  sprintf(&FwdDeclName[0], "fwd.type.%d", FwdDeclCount++);
783  llvm::DIDescriptor FDContext =
784    getContextDescriptor(dyn_cast<Decl>(RD->getDeclContext()), Unit);
785  llvm::DICompositeType FwdDecl =
786    DebugFactory.CreateCompositeType(Tag, FDContext, FwdDeclName,
787                                     DefUnit, Line, 0, 0, 0, 0,
788                                     llvm::DIType(), llvm::DIArray());
789
790  // If this is just a forward declaration, return it.
791  if (!RD->getDefinition())
792    return FwdDecl;
793
794  llvm::TrackingVH<llvm::MDNode> FwdDeclNode = FwdDecl.getNode();
795  // Otherwise, insert it into the TypeCache so that recursive uses will find
796  // it.
797  TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl.getNode();
798  // Push the struct on region stack.
799  RegionStack.push_back(FwdDecl.getNode());
800  RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl.getNode());
801
802  // Convert all the elements.
803  llvm::SmallVector<llvm::DIDescriptor, 16> EltTys;
804
805  const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
806  if (CXXDecl) {
807    CollectCXXBases(CXXDecl, Unit, EltTys, FwdDecl);
808    CollectVtableInfo(CXXDecl, Unit, EltTys);
809  }
810  CollectRecordFields(RD, Unit, EltTys);
811  llvm::MDNode *ContainingType = NULL;
812  if (CXXDecl) {
813    CollectCXXMemberFunctions(CXXDecl, Unit, EltTys, FwdDecl);
814
815    // A class's primary base or the class itself contains the vtable.
816    const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
817    if (const CXXRecordDecl *PBase = RL.getPrimaryBase())
818      ContainingType =
819        getOrCreateType(QualType(PBase->getTypeForDecl(), 0), Unit).getNode();
820    else if (CXXDecl->isDynamicClass())
821      ContainingType = FwdDecl.getNode();
822  }
823
824  llvm::DIArray Elements =
825    DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
826
827  // Bit size, align and offset of the type.
828  uint64_t Size = CGM.getContext().getTypeSize(Ty);
829  uint64_t Align = CGM.getContext().getTypeAlign(Ty);
830
831  RegionStack.pop_back();
832  llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator RI =
833    RegionMap.find(Ty->getDecl());
834  if (RI != RegionMap.end())
835    RegionMap.erase(RI);
836
837  llvm::DIDescriptor RDContext =
838    getContextDescriptor(dyn_cast<Decl>(RD->getDeclContext()), Unit);
839  llvm::DICompositeType RealDecl =
840    DebugFactory.CreateCompositeType(Tag, RDContext,
841                                     RD->getName(),
842                                     DefUnit, Line, Size, Align, 0, 0,
843                                     llvm::DIType(), Elements,
844                                     0, ContainingType);
845
846  // Now that we have a real decl for the struct, replace anything using the
847  // old decl with the new one.  This will recursively update the debug info.
848  llvm::DIDerivedType(FwdDeclNode).replaceAllUsesWith(RealDecl);
849  RegionMap[RD] = llvm::WeakVH(RealDecl.getNode());
850  return RealDecl;
851}
852
853/// CreateType - get objective-c interface type.
854llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
855                                     llvm::DIFile Unit) {
856  ObjCInterfaceDecl *ID = Ty->getDecl();
857
858  unsigned Tag = llvm::dwarf::DW_TAG_structure_type;
859  SourceManager &SM = CGM.getContext().getSourceManager();
860
861  // Get overall information about the record type for the debug info.
862  llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
863  PresumedLoc PLoc = SM.getPresumedLoc(ID->getLocation());
864  unsigned Line = PLoc.isInvalid() ? 0 : PLoc.getLine();
865
866
867  unsigned RuntimeLang = TheCU.getLanguage();
868
869  // To handle recursive interface, we
870  // first generate a debug descriptor for the struct as a forward declaration.
871  // Then (if it is a definition) we go through and get debug info for all of
872  // its members.  Finally, we create a descriptor for the complete type (which
873  // may refer to the forward decl if the struct is recursive) and replace all
874  // uses of the forward declaration with the final definition.
875  llvm::DICompositeType FwdDecl =
876    DebugFactory.CreateCompositeType(Tag, Unit, ID->getName(),
877                                     DefUnit, Line, 0, 0, 0, 0,
878                                     llvm::DIType(), llvm::DIArray(),
879                                     RuntimeLang);
880
881  // If this is just a forward declaration, return it.
882  if (ID->isForwardDecl())
883    return FwdDecl;
884
885  llvm::TrackingVH<llvm::MDNode> FwdDeclNode = FwdDecl.getNode();
886  // Otherwise, insert it into the TypeCache so that recursive uses will find
887  // it.
888  TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl.getNode();
889  // Push the struct on region stack.
890  RegionStack.push_back(FwdDecl.getNode());
891  RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl.getNode());
892
893  // Convert all the elements.
894  llvm::SmallVector<llvm::DIDescriptor, 16> EltTys;
895
896  ObjCInterfaceDecl *SClass = ID->getSuperClass();
897  if (SClass) {
898    llvm::DIType SClassTy =
899      getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
900    llvm::DIType InhTag =
901      DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_inheritance,
902                                     Unit, "", Unit, 0, 0, 0,
903                                     0 /* offset */, 0, SClassTy);
904    EltTys.push_back(InhTag);
905  }
906
907  const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
908
909  unsigned FieldNo = 0;
910  for (ObjCInterfaceDecl::ivar_iterator I = ID->ivar_begin(),
911         E = ID->ivar_end();  I != E; ++I, ++FieldNo) {
912    ObjCIvarDecl *Field = *I;
913    llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
914
915    llvm::StringRef FieldName = Field->getName();
916
917    // Ignore unnamed fields.
918    if (FieldName.empty())
919      continue;
920
921    // Get the location for the field.
922    SourceLocation FieldDefLoc = Field->getLocation();
923    llvm::DIFile FieldDefUnit = getOrCreateFile(FieldDefLoc);
924    PresumedLoc PLoc = SM.getPresumedLoc(FieldDefLoc);
925    unsigned FieldLine = PLoc.isInvalid() ? 0 : PLoc.getLine();
926
927
928    QualType FType = Field->getType();
929    uint64_t FieldSize = 0;
930    unsigned FieldAlign = 0;
931
932    if (!FType->isIncompleteArrayType()) {
933
934      // Bit size, align and offset of the type.
935      FieldSize = CGM.getContext().getTypeSize(FType);
936      Expr *BitWidth = Field->getBitWidth();
937      if (BitWidth)
938        FieldSize = BitWidth->EvaluateAsInt(CGM.getContext()).getZExtValue();
939
940      FieldAlign =  CGM.getContext().getTypeAlign(FType);
941    }
942
943    uint64_t FieldOffset = RL.getFieldOffset(FieldNo);
944
945    unsigned Flags = 0;
946    if (Field->getAccessControl() == ObjCIvarDecl::Protected)
947      Flags = llvm::DIType::FlagProtected;
948    else if (Field->getAccessControl() == ObjCIvarDecl::Private)
949      Flags = llvm::DIType::FlagPrivate;
950
951    // Create a DW_TAG_member node to remember the offset of this field in the
952    // struct.  FIXME: This is an absolutely insane way to capture this
953    // information.  When we gut debug info, this should be fixed.
954    FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
955                                             FieldName, FieldDefUnit,
956                                             FieldLine, FieldSize, FieldAlign,
957                                             FieldOffset, Flags, FieldTy);
958    EltTys.push_back(FieldTy);
959  }
960
961  llvm::DIArray Elements =
962    DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
963
964  RegionStack.pop_back();
965  llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator RI =
966    RegionMap.find(Ty->getDecl());
967  if (RI != RegionMap.end())
968    RegionMap.erase(RI);
969
970  // Bit size, align and offset of the type.
971  uint64_t Size = CGM.getContext().getTypeSize(Ty);
972  uint64_t Align = CGM.getContext().getTypeAlign(Ty);
973
974  llvm::DICompositeType RealDecl =
975    DebugFactory.CreateCompositeType(Tag, Unit, ID->getName(), DefUnit,
976                                     Line, Size, Align, 0, 0, llvm::DIType(),
977                                     Elements, RuntimeLang);
978
979  // Now that we have a real decl for the struct, replace anything using the
980  // old decl with the new one.  This will recursively update the debug info.
981  llvm::DIDerivedType(FwdDeclNode).replaceAllUsesWith(RealDecl);
982  RegionMap[ID] = llvm::WeakVH(RealDecl.getNode());
983
984  return RealDecl;
985}
986
987llvm::DIType CGDebugInfo::CreateType(const EnumType *Ty,
988                                     llvm::DIFile Unit) {
989  EnumDecl *ED = Ty->getDecl();
990
991  llvm::SmallVector<llvm::DIDescriptor, 32> Enumerators;
992
993  // Create DIEnumerator elements for each enumerator.
994  for (EnumDecl::enumerator_iterator
995         Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
996       Enum != EnumEnd; ++Enum) {
997    Enumerators.push_back(DebugFactory.CreateEnumerator(Enum->getName(),
998                                            Enum->getInitVal().getZExtValue()));
999  }
1000
1001  // Return a CompositeType for the enum itself.
1002  llvm::DIArray EltArray =
1003    DebugFactory.GetOrCreateArray(Enumerators.data(), Enumerators.size());
1004
1005  SourceLocation DefLoc = ED->getLocation();
1006  llvm::DIFile DefUnit = getOrCreateFile(DefLoc);
1007  SourceManager &SM = CGM.getContext().getSourceManager();
1008  PresumedLoc PLoc = SM.getPresumedLoc(DefLoc);
1009  unsigned Line = PLoc.isInvalid() ? 0 : PLoc.getLine();
1010
1011
1012  // Size and align of the type.
1013  uint64_t Size = 0;
1014  unsigned Align = 0;
1015  if (!Ty->isIncompleteType()) {
1016    Size = CGM.getContext().getTypeSize(Ty);
1017    Align = CGM.getContext().getTypeAlign(Ty);
1018  }
1019
1020  llvm::DIType DbgTy =
1021    DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_enumeration_type,
1022                                     Unit, ED->getName(), DefUnit, Line,
1023                                     Size, Align, 0, 0,
1024                                     llvm::DIType(), EltArray);
1025  return DbgTy;
1026}
1027
1028llvm::DIType CGDebugInfo::CreateType(const TagType *Ty,
1029                                     llvm::DIFile Unit) {
1030  if (const RecordType *RT = dyn_cast<RecordType>(Ty))
1031    return CreateType(RT, Unit);
1032  else if (const EnumType *ET = dyn_cast<EnumType>(Ty))
1033    return CreateType(ET, Unit);
1034
1035  return llvm::DIType();
1036}
1037
1038llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty,
1039				     llvm::DIFile Unit) {
1040  llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1041  uint64_t NumElems = Ty->getNumElements();
1042  if (NumElems > 0)
1043    --NumElems;
1044  llvm::SmallVector<llvm::DIDescriptor, 8> Subscripts;
1045  Subscripts.push_back(DebugFactory.GetOrCreateSubrange(0, NumElems));
1046
1047  llvm::DIArray SubscriptArray =
1048    DebugFactory.GetOrCreateArray(Subscripts.data(), Subscripts.size());
1049
1050  uint64_t Size = CGM.getContext().getTypeSize(Ty);
1051  uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1052
1053  return
1054    DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_vector_type,
1055                                     Unit, "", Unit,
1056                                     0, Size, Align, 0, 0,
1057				     ElementTy,  SubscriptArray);
1058}
1059
1060llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1061                                     llvm::DIFile Unit) {
1062  uint64_t Size;
1063  uint64_t Align;
1064
1065
1066  // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1067  if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1068    Size = 0;
1069    Align =
1070      CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1071  } else if (Ty->isIncompleteArrayType()) {
1072    Size = 0;
1073    Align = CGM.getContext().getTypeAlign(Ty->getElementType());
1074  } else {
1075    // Size and align of the whole array, not the element type.
1076    Size = CGM.getContext().getTypeSize(Ty);
1077    Align = CGM.getContext().getTypeAlign(Ty);
1078  }
1079
1080  // Add the dimensions of the array.  FIXME: This loses CV qualifiers from
1081  // interior arrays, do we care?  Why aren't nested arrays represented the
1082  // obvious/recursive way?
1083  llvm::SmallVector<llvm::DIDescriptor, 8> Subscripts;
1084  QualType EltTy(Ty, 0);
1085  while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1086    uint64_t Upper = 0;
1087    if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1088      if (CAT->getSize().getZExtValue())
1089        Upper = CAT->getSize().getZExtValue() - 1;
1090    // FIXME: Verify this is right for VLAs.
1091    Subscripts.push_back(DebugFactory.GetOrCreateSubrange(0, Upper));
1092    EltTy = Ty->getElementType();
1093  }
1094
1095  llvm::DIArray SubscriptArray =
1096    DebugFactory.GetOrCreateArray(Subscripts.data(), Subscripts.size());
1097
1098  llvm::DIType DbgTy =
1099    DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_array_type,
1100                                     Unit, "", Unit,
1101                                     0, Size, Align, 0, 0,
1102                                     getOrCreateType(EltTy, Unit),
1103                                     SubscriptArray);
1104  return DbgTy;
1105}
1106
1107llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
1108                                     llvm::DIFile Unit) {
1109  return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
1110                               Ty, Ty->getPointeeType(), Unit);
1111}
1112
1113llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
1114                                     llvm::DIFile U) {
1115  QualType PointerDiffTy = CGM.getContext().getPointerDiffType();
1116  llvm::DIType PointerDiffDITy = getOrCreateType(PointerDiffTy, U);
1117
1118  if (!Ty->getPointeeType()->isFunctionType()) {
1119    // We have a data member pointer type.
1120    return PointerDiffDITy;
1121  }
1122
1123  // We have a member function pointer type. Treat it as a struct with two
1124  // ptrdiff_t members.
1125  std::pair<uint64_t, unsigned> Info = CGM.getContext().getTypeInfo(Ty);
1126
1127  uint64_t FieldOffset = 0;
1128  llvm::DIDescriptor ElementTypes[2];
1129
1130  // FIXME: This should probably be a function type instead.
1131  ElementTypes[0] =
1132    DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, U,
1133                                   "ptr", U, 0,
1134                                   Info.first, Info.second, FieldOffset, 0,
1135                                   PointerDiffDITy);
1136  FieldOffset += Info.first;
1137
1138  ElementTypes[1] =
1139    DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, U,
1140                                   "ptr", U, 0,
1141                                   Info.first, Info.second, FieldOffset, 0,
1142                                   PointerDiffDITy);
1143
1144  llvm::DIArray Elements =
1145    DebugFactory.GetOrCreateArray(&ElementTypes[0],
1146                                  llvm::array_lengthof(ElementTypes));
1147
1148  return DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_structure_type,
1149                                          U, llvm::StringRef("test"),
1150                                          U, 0, FieldOffset,
1151                                          0, 0, 0, llvm::DIType(), Elements);
1152}
1153
1154static QualType UnwrapTypeForDebugInfo(QualType T) {
1155  do {
1156    QualType LastT = T;
1157    switch (T->getTypeClass()) {
1158    default:
1159      return T;
1160    case Type::TemplateSpecialization:
1161      T = cast<TemplateSpecializationType>(T)->desugar();
1162      break;
1163    case Type::TypeOfExpr: {
1164      TypeOfExprType *Ty = cast<TypeOfExprType>(T);
1165      T = Ty->getUnderlyingExpr()->getType();
1166      break;
1167    }
1168    case Type::TypeOf:
1169      T = cast<TypeOfType>(T)->getUnderlyingType();
1170      break;
1171    case Type::Decltype:
1172      T = cast<DecltypeType>(T)->getUnderlyingType();
1173      break;
1174    case Type::QualifiedName:
1175      T = cast<QualifiedNameType>(T)->getNamedType();
1176      break;
1177    case Type::SubstTemplateTypeParm:
1178      T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
1179      break;
1180    case Type::Elaborated:
1181      T = cast<ElaboratedType>(T)->getUnderlyingType();
1182      break;
1183    }
1184
1185    assert(T != LastT && "Type unwrapping failed to unwrap!");
1186    if (T == LastT)
1187      return T;
1188  } while (true);
1189
1190  return T;
1191}
1192
1193/// getOrCreateType - Get the type from the cache or create a new
1194/// one if necessary.
1195llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty,
1196                                          llvm::DIFile Unit) {
1197  if (Ty.isNull())
1198    return llvm::DIType();
1199
1200  // Unwrap the type as needed for debug information.
1201  Ty = UnwrapTypeForDebugInfo(Ty);
1202
1203  // Check for existing entry.
1204  std::map<void *, llvm::WeakVH>::iterator it =
1205    TypeCache.find(Ty.getAsOpaquePtr());
1206  if (it != TypeCache.end()) {
1207    // Verify that the debug info still exists.
1208    if (&*it->second)
1209      return llvm::DIType(cast<llvm::MDNode>(it->second));
1210  }
1211
1212  // Otherwise create the type.
1213  llvm::DIType Res = CreateTypeNode(Ty, Unit);
1214
1215  // And update the type cache.
1216  TypeCache[Ty.getAsOpaquePtr()] = Res.getNode();
1217  return Res;
1218}
1219
1220/// CreateTypeNode - Create a new debug type node.
1221llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty,
1222                                         llvm::DIFile Unit) {
1223  // Handle qualifiers, which recursively handles what they refer to.
1224  if (Ty.hasLocalQualifiers())
1225    return CreateQualifiedType(Ty, Unit);
1226
1227  const char *Diag = 0;
1228
1229  // Work out details of type.
1230  switch (Ty->getTypeClass()) {
1231#define TYPE(Class, Base)
1232#define ABSTRACT_TYPE(Class, Base)
1233#define NON_CANONICAL_TYPE(Class, Base)
1234#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1235#include "clang/AST/TypeNodes.def"
1236    assert(false && "Dependent types cannot show up in debug information");
1237
1238  // FIXME: Handle these.
1239  case Type::ExtVector:
1240    return llvm::DIType();
1241
1242  case Type::Vector:
1243    return CreateType(cast<VectorType>(Ty), Unit);
1244  case Type::ObjCObjectPointer:
1245    return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
1246  case Type::ObjCInterface:
1247    return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
1248  case Type::Builtin: return CreateType(cast<BuiltinType>(Ty), Unit);
1249  case Type::Complex: return CreateType(cast<ComplexType>(Ty), Unit);
1250  case Type::Pointer: return CreateType(cast<PointerType>(Ty), Unit);
1251  case Type::BlockPointer:
1252    return CreateType(cast<BlockPointerType>(Ty), Unit);
1253  case Type::Typedef: return CreateType(cast<TypedefType>(Ty), Unit);
1254  case Type::Record:
1255  case Type::Enum:
1256    return CreateType(cast<TagType>(Ty), Unit);
1257  case Type::FunctionProto:
1258  case Type::FunctionNoProto:
1259    return CreateType(cast<FunctionType>(Ty), Unit);
1260  case Type::ConstantArray:
1261  case Type::VariableArray:
1262  case Type::IncompleteArray:
1263    return CreateType(cast<ArrayType>(Ty), Unit);
1264
1265  case Type::LValueReference:
1266    return CreateType(cast<LValueReferenceType>(Ty), Unit);
1267
1268  case Type::MemberPointer:
1269    return CreateType(cast<MemberPointerType>(Ty), Unit);
1270
1271  case Type::InjectedClassName:
1272  case Type::TemplateSpecialization:
1273  case Type::Elaborated:
1274  case Type::QualifiedName:
1275  case Type::SubstTemplateTypeParm:
1276  case Type::TypeOfExpr:
1277  case Type::TypeOf:
1278  case Type::Decltype:
1279    llvm_unreachable("type should have been unwrapped!");
1280    return llvm::DIType();
1281
1282  case Type::RValueReference:
1283    // FIXME: Implement!
1284    Diag = "rvalue references";
1285    break;
1286  }
1287
1288  assert(Diag && "Fall through without a diagnostic?");
1289  unsigned DiagID = CGM.getDiags().getCustomDiagID(Diagnostic::Error,
1290                               "debug information for %0 is not yet supported");
1291  CGM.getDiags().Report(FullSourceLoc(), DiagID)
1292    << Diag;
1293  return llvm::DIType();
1294}
1295
1296/// EmitFunctionStart - Constructs the debug code for entering a function -
1297/// "llvm.dbg.func.start.".
1298void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
1299                                    llvm::Function *Fn,
1300                                    CGBuilderTy &Builder) {
1301
1302  llvm::StringRef Name;
1303  llvm::StringRef LinkageName;
1304
1305  const Decl *D = GD.getDecl();
1306  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1307    // If there is a DISubprogram for  this function available then use it.
1308    llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
1309      FI = SPCache.find(FD);
1310    if (FI != SPCache.end()) {
1311      llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(FI->second));
1312      if (SP.isSubprogram() && llvm::DISubprogram(SP.getNode()).isDefinition()) {
1313        RegionStack.push_back(SP.getNode());
1314        RegionMap[D] = llvm::WeakVH(SP.getNode());
1315        return;
1316      }
1317    }
1318    Name = getFunctionName(FD);
1319    if (!Name.empty() && Name[0] == '\01')
1320      Name = Name.substr(1);
1321    // Use mangled name as linkage name for c/c++ functions.
1322    LinkageName = CGM.getMangledName(GD);
1323  } else {
1324    // Use llvm function name as linkage name.
1325    Name = Fn->getName();
1326    LinkageName = Name;
1327    if (!Name.empty() && Name[0] == '\01')
1328      Name = Name.substr(1);
1329  }
1330
1331  // It is expected that CurLoc is set before using EmitFunctionStart.
1332  // Usually, CurLoc points to the left bracket location of compound
1333  // statement representing function body.
1334  llvm::DIFile Unit = getOrCreateFile(CurLoc);
1335  SourceManager &SM = CGM.getContext().getSourceManager();
1336  unsigned LineNo = SM.getPresumedLoc(CurLoc).getLine();
1337
1338  llvm::DISubprogram SP =
1339    DebugFactory.CreateSubprogram(Unit, Name, Name, LinkageName, Unit, LineNo,
1340                                  getOrCreateType(FnType, Unit),
1341                                  Fn->hasInternalLinkage(), true/*definition*/);
1342
1343  // Push function on region stack.
1344  RegionStack.push_back(SP.getNode());
1345  RegionMap[D] = llvm::WeakVH(SP.getNode());
1346}
1347
1348
1349void CGDebugInfo::EmitStopPoint(llvm::Function *Fn, CGBuilderTy &Builder) {
1350  if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
1351
1352  // Don't bother if things are the same as last time.
1353  SourceManager &SM = CGM.getContext().getSourceManager();
1354  if (CurLoc == PrevLoc
1355       || (SM.getInstantiationLineNumber(CurLoc) ==
1356           SM.getInstantiationLineNumber(PrevLoc)
1357           && SM.isFromSameFile(CurLoc, PrevLoc)))
1358    return;
1359
1360  // Update last state.
1361  PrevLoc = CurLoc;
1362
1363  // Get the appropriate compile unit.
1364  llvm::DIFile Unit = getOrCreateFile(CurLoc);
1365  PresumedLoc PLoc = SM.getPresumedLoc(CurLoc);
1366
1367  llvm::DIDescriptor DR(RegionStack.back());
1368  llvm::DIScope DS = llvm::DIScope(DR.getNode());
1369  llvm::DILocation DO(NULL);
1370  llvm::DILocation DL =
1371    DebugFactory.CreateLocation(PLoc.getLine(), PLoc.getColumn(),
1372                                DS, DO);
1373  Builder.SetCurrentDebugLocation(DL.getNode());
1374}
1375
1376/// EmitRegionStart- Constructs the debug code for entering a declarative
1377/// region - "llvm.dbg.region.start.".
1378void CGDebugInfo::EmitRegionStart(llvm::Function *Fn, CGBuilderTy &Builder) {
1379  SourceManager &SM = CGM.getContext().getSourceManager();
1380  PresumedLoc PLoc = SM.getPresumedLoc(CurLoc);
1381  llvm::DIDescriptor D =
1382    DebugFactory.CreateLexicalBlock(RegionStack.empty() ?
1383                                    llvm::DIDescriptor() :
1384                                    llvm::DIDescriptor(RegionStack.back()),
1385                                    PLoc.getLine(), PLoc.getColumn());
1386  RegionStack.push_back(D.getNode());
1387}
1388
1389/// EmitRegionEnd - Constructs the debug code for exiting a declarative
1390/// region - "llvm.dbg.region.end."
1391void CGDebugInfo::EmitRegionEnd(llvm::Function *Fn, CGBuilderTy &Builder) {
1392  assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
1393
1394  // Provide an region stop point.
1395  EmitStopPoint(Fn, Builder);
1396
1397  RegionStack.pop_back();
1398}
1399
1400// EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
1401// See BuildByRefType.
1402llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const ValueDecl *VD,
1403                                                       uint64_t *XOffset) {
1404
1405  llvm::SmallVector<llvm::DIDescriptor, 5> EltTys;
1406
1407  QualType FType;
1408  uint64_t FieldSize, FieldOffset;
1409  unsigned FieldAlign;
1410
1411  llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
1412  QualType Type = VD->getType();
1413
1414  FieldOffset = 0;
1415  FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1416  llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1417  FieldSize = CGM.getContext().getTypeSize(FType);
1418  FieldAlign = CGM.getContext().getTypeAlign(FType);
1419  FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1420                                           "__isa", Unit,
1421                                           0, FieldSize, FieldAlign,
1422                                           FieldOffset, 0, FieldTy);
1423  EltTys.push_back(FieldTy);
1424  FieldOffset += FieldSize;
1425
1426  FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1427  FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1428  FieldSize = CGM.getContext().getTypeSize(FType);
1429  FieldAlign = CGM.getContext().getTypeAlign(FType);
1430  FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1431                                           "__forwarding", Unit,
1432                                           0, FieldSize, FieldAlign,
1433                                           FieldOffset, 0, FieldTy);
1434  EltTys.push_back(FieldTy);
1435  FieldOffset += FieldSize;
1436
1437  FType = CGM.getContext().IntTy;
1438  FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1439  FieldSize = CGM.getContext().getTypeSize(FType);
1440  FieldAlign = CGM.getContext().getTypeAlign(FType);
1441  FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1442                                           "__flags", Unit,
1443                                           0, FieldSize, FieldAlign,
1444                                           FieldOffset, 0, FieldTy);
1445  EltTys.push_back(FieldTy);
1446  FieldOffset += FieldSize;
1447
1448  FType = CGM.getContext().IntTy;
1449  FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1450  FieldSize = CGM.getContext().getTypeSize(FType);
1451  FieldAlign = CGM.getContext().getTypeAlign(FType);
1452  FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1453                                           "__size", Unit,
1454                                           0, FieldSize, FieldAlign,
1455                                           FieldOffset, 0, FieldTy);
1456  EltTys.push_back(FieldTy);
1457  FieldOffset += FieldSize;
1458
1459  bool HasCopyAndDispose = CGM.BlockRequiresCopying(Type);
1460  if (HasCopyAndDispose) {
1461    FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1462    FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1463    FieldSize = CGM.getContext().getTypeSize(FType);
1464    FieldAlign = CGM.getContext().getTypeAlign(FType);
1465    FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1466                                             "__copy_helper", Unit,
1467                                             0, FieldSize, FieldAlign,
1468                                             FieldOffset, 0, FieldTy);
1469    EltTys.push_back(FieldTy);
1470    FieldOffset += FieldSize;
1471
1472    FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1473    FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1474    FieldSize = CGM.getContext().getTypeSize(FType);
1475    FieldAlign = CGM.getContext().getTypeAlign(FType);
1476    FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1477                                             "__destroy_helper", Unit,
1478                                             0, FieldSize, FieldAlign,
1479                                             FieldOffset, 0, FieldTy);
1480    EltTys.push_back(FieldTy);
1481    FieldOffset += FieldSize;
1482  }
1483
1484  CharUnits Align = CGM.getContext().getDeclAlign(VD);
1485  if (Align > CharUnits::fromQuantity(
1486        CGM.getContext().Target.getPointerAlign(0) / 8)) {
1487    unsigned AlignedOffsetInBytes
1488      = llvm::RoundUpToAlignment(FieldOffset/8, Align.getQuantity());
1489    unsigned NumPaddingBytes
1490      = AlignedOffsetInBytes - FieldOffset/8;
1491
1492    if (NumPaddingBytes > 0) {
1493      llvm::APInt pad(32, NumPaddingBytes);
1494      FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
1495                                                    pad, ArrayType::Normal, 0);
1496      FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1497      FieldSize = CGM.getContext().getTypeSize(FType);
1498      FieldAlign = CGM.getContext().getTypeAlign(FType);
1499      FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member,
1500                                               Unit, "", Unit,
1501                                               0, FieldSize, FieldAlign,
1502                                               FieldOffset, 0, FieldTy);
1503      EltTys.push_back(FieldTy);
1504      FieldOffset += FieldSize;
1505    }
1506  }
1507
1508  FType = Type;
1509  FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1510  FieldSize = CGM.getContext().getTypeSize(FType);
1511  FieldAlign = Align.getQuantity()*8;
1512
1513  *XOffset = FieldOffset;
1514  FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1515                                           VD->getName(), Unit,
1516                                           0, FieldSize, FieldAlign,
1517                                           FieldOffset, 0, FieldTy);
1518  EltTys.push_back(FieldTy);
1519  FieldOffset += FieldSize;
1520
1521  llvm::DIArray Elements =
1522    DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
1523
1524  unsigned Flags = llvm::DIType::FlagBlockByrefStruct;
1525
1526  return DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_structure_type,
1527                                          Unit, "", Unit,
1528                                          0, FieldOffset, 0, 0, Flags,
1529                                          llvm::DIType(), Elements);
1530
1531}
1532/// EmitDeclare - Emit local variable declaration debug info.
1533void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
1534                              llvm::Value *Storage, CGBuilderTy &Builder) {
1535  assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
1536
1537  // Do not emit variable debug information while generating optimized code.
1538  // The llvm optimizer and code generator are not yet ready to support
1539  // optimized code debugging.
1540  const CodeGenOptions &CGO = CGM.getCodeGenOpts();
1541  if (CGO.OptimizationLevel)
1542    return;
1543
1544  llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
1545  llvm::DIType Ty;
1546  uint64_t XOffset = 0;
1547  if (VD->hasAttr<BlocksAttr>())
1548    Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
1549  else
1550    Ty = getOrCreateType(VD->getType(), Unit);
1551
1552  // Get location information.
1553  SourceManager &SM = CGM.getContext().getSourceManager();
1554  PresumedLoc PLoc = SM.getPresumedLoc(VD->getLocation());
1555  unsigned Line = 0;
1556  unsigned Column = 0;
1557  if (PLoc.isInvalid())
1558    PLoc = SM.getPresumedLoc(CurLoc);
1559  if (PLoc.isValid()) {
1560    Line = PLoc.getLine();
1561    Column = PLoc.getColumn();
1562    Unit = getOrCreateFile(CurLoc);
1563  } else {
1564    Unit = llvm::DIFile();
1565  }
1566
1567  // Create the descriptor for the variable.
1568  llvm::DIVariable D =
1569    DebugFactory.CreateVariable(Tag, llvm::DIDescriptor(RegionStack.back()),
1570                                VD->getName(),
1571                                Unit, Line, Ty);
1572  // Insert an llvm.dbg.declare into the current block.
1573  llvm::Instruction *Call =
1574    DebugFactory.InsertDeclare(Storage, D, Builder.GetInsertBlock());
1575
1576  llvm::DIScope DS(RegionStack.back());
1577  llvm::DILocation DO(NULL);
1578  llvm::DILocation DL = DebugFactory.CreateLocation(Line, Column, DS, DO);
1579
1580  Call->setMetadata("dbg", DL.getNode());
1581}
1582
1583/// EmitDeclare - Emit local variable declaration debug info.
1584void CGDebugInfo::EmitDeclare(const BlockDeclRefExpr *BDRE, unsigned Tag,
1585                              llvm::Value *Storage, CGBuilderTy &Builder,
1586                              CodeGenFunction *CGF) {
1587  const ValueDecl *VD = BDRE->getDecl();
1588  assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
1589
1590  // Do not emit variable debug information while generating optimized code.
1591  // The llvm optimizer and code generator are not yet ready to support
1592  // optimized code debugging.
1593  const CodeGenOptions &CGO = CGM.getCodeGenOpts();
1594  if (CGO.OptimizationLevel || Builder.GetInsertBlock() == 0)
1595    return;
1596
1597  uint64_t XOffset = 0;
1598  llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
1599  llvm::DIType Ty;
1600  if (VD->hasAttr<BlocksAttr>())
1601    Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
1602  else
1603    Ty = getOrCreateType(VD->getType(), Unit);
1604
1605  // Get location information.
1606  SourceManager &SM = CGM.getContext().getSourceManager();
1607  PresumedLoc PLoc = SM.getPresumedLoc(VD->getLocation());
1608  unsigned Line = 0;
1609  if (!PLoc.isInvalid())
1610    Line = PLoc.getLine();
1611  else
1612    Unit = llvm::DIFile();
1613
1614  CharUnits offset = CGF->BlockDecls[VD];
1615  llvm::SmallVector<llvm::Value *, 9> addr;
1616  const llvm::Type *Int64Ty = llvm::Type::getInt64Ty(CGM.getLLVMContext());
1617  addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpDeref));
1618  addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpPlus));
1619  addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
1620  if (BDRE->isByRef()) {
1621    addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpDeref));
1622    addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpPlus));
1623    // offset of __forwarding field
1624    offset = CharUnits::fromQuantity(CGF->LLVMPointerWidth/8);
1625    addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
1626    addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpDeref));
1627    addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpPlus));
1628    // offset of x field
1629    offset = CharUnits::fromQuantity(XOffset/8);
1630    addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
1631  }
1632
1633  // Create the descriptor for the variable.
1634  llvm::DIVariable D =
1635    DebugFactory.CreateComplexVariable(Tag,
1636                                       llvm::DIDescriptor(RegionStack.back()),
1637                                       VD->getName(), Unit, Line, Ty,
1638                                       addr);
1639  // Insert an llvm.dbg.declare into the current block.
1640  llvm::Instruction *Call =
1641    DebugFactory.InsertDeclare(Storage, D, Builder.GetInsertBlock());
1642
1643  llvm::DIScope DS(RegionStack.back());
1644  llvm::DILocation DO(NULL);
1645  llvm::DILocation DL =
1646    DebugFactory.CreateLocation(Line, PLoc.getColumn(), DS, DO);
1647
1648  Call->setMetadata("dbg", DL.getNode());
1649}
1650
1651void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
1652                                            llvm::Value *Storage,
1653                                            CGBuilderTy &Builder) {
1654  EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, Builder);
1655}
1656
1657void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(
1658  const BlockDeclRefExpr *BDRE, llvm::Value *Storage, CGBuilderTy &Builder,
1659  CodeGenFunction *CGF) {
1660  EmitDeclare(BDRE, llvm::dwarf::DW_TAG_auto_variable, Storage, Builder, CGF);
1661}
1662
1663/// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
1664/// variable declaration.
1665void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
1666                                           CGBuilderTy &Builder) {
1667  EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, Builder);
1668}
1669
1670
1671
1672/// EmitGlobalVariable - Emit information about a global variable.
1673void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
1674                                     const VarDecl *D) {
1675
1676  // Create global variable debug descriptor.
1677  llvm::DIFile Unit = getOrCreateFile(D->getLocation());
1678  SourceManager &SM = CGM.getContext().getSourceManager();
1679  PresumedLoc PLoc = SM.getPresumedLoc(D->getLocation());
1680  unsigned LineNo = PLoc.isInvalid() ? 0 : PLoc.getLine();
1681
1682  QualType T = D->getType();
1683  if (T->isIncompleteArrayType()) {
1684
1685    // CodeGen turns int[] into int[1] so we'll do the same here.
1686    llvm::APSInt ConstVal(32);
1687
1688    ConstVal = 1;
1689    QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
1690
1691    T = CGM.getContext().getConstantArrayType(ET, ConstVal,
1692                                           ArrayType::Normal, 0);
1693  }
1694  llvm::StringRef DeclName = Var->getName();
1695  llvm::DIDescriptor DContext =
1696    getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()), Unit);
1697  DebugFactory.CreateGlobalVariable(DContext, DeclName,
1698                                    DeclName, llvm::StringRef(), Unit, LineNo,
1699                                    getOrCreateType(T, Unit),
1700                                    Var->hasInternalLinkage(),
1701                                    true/*definition*/, Var);
1702}
1703
1704/// EmitGlobalVariable - Emit information about an objective-c interface.
1705void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
1706                                     ObjCInterfaceDecl *ID) {
1707  // Create global variable debug descriptor.
1708  llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
1709  SourceManager &SM = CGM.getContext().getSourceManager();
1710  PresumedLoc PLoc = SM.getPresumedLoc(ID->getLocation());
1711  unsigned LineNo = PLoc.isInvalid() ? 0 : PLoc.getLine();
1712
1713  llvm::StringRef Name = ID->getName();
1714
1715  QualType T = CGM.getContext().getObjCInterfaceType(ID);
1716  if (T->isIncompleteArrayType()) {
1717
1718    // CodeGen turns int[] into int[1] so we'll do the same here.
1719    llvm::APSInt ConstVal(32);
1720
1721    ConstVal = 1;
1722    QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
1723
1724    T = CGM.getContext().getConstantArrayType(ET, ConstVal,
1725                                           ArrayType::Normal, 0);
1726  }
1727
1728  DebugFactory.CreateGlobalVariable(Unit, Name, Name, Name, Unit, LineNo,
1729                                    getOrCreateType(T, Unit),
1730                                    Var->hasInternalLinkage(),
1731                                    true/*definition*/, Var);
1732}
1733
1734/// getOrCreateNamesSpace - Return namespace descriptor for the given
1735/// namespace decl.
1736llvm::DINameSpace
1737CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl,
1738                                  llvm::DIDescriptor Unit) {
1739  llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
1740    NameSpaceCache.find(NSDecl);
1741  if (I != NameSpaceCache.end())
1742    return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
1743
1744  SourceManager &SM = CGM.getContext().getSourceManager();
1745  PresumedLoc PLoc = SM.getPresumedLoc(NSDecl->getLocation());
1746  unsigned LineNo = PLoc.isInvalid() ? 0 : PLoc.getLine();
1747
1748  llvm::DIDescriptor Context =
1749    getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()), Unit);
1750  llvm::DINameSpace NS =
1751    DebugFactory.CreateNameSpace(Context, NSDecl->getName(),
1752	llvm::DIFile(Unit.getNode()), LineNo);
1753  NameSpaceCache[NSDecl] = llvm::WeakVH(NS.getNode());
1754  return NS;
1755}
1756