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