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