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