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