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