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