CGDebugInfo.cpp revision 36b8ee6325b709dd301681fb281b6cf102a5e51a
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  if (CXXDecl) {
957    CollectCXXMemberFunctions(CXXDecl, Unit, EltTys, FwdDecl);
958    CollectCXXFriends(CXXDecl, Unit, EltTys, FwdDecl);
959  }
960
961  RegionStack.pop_back();
962  llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator RI =
963    RegionMap.find(Ty->getDecl());
964  if (RI != RegionMap.end())
965    RegionMap.erase(RI);
966
967  llvm::DIDescriptor RDContext =
968    getContextDescriptor(dyn_cast<Decl>(RD->getDeclContext()));
969  llvm::StringRef RDName = RD->getName();
970  uint64_t Size = CGM.getContext().getTypeSize(Ty);
971  uint64_t Align = CGM.getContext().getTypeAlign(Ty);
972  llvm::DIArray Elements =
973    DBuilder.GetOrCreateArray(EltTys.data(), EltTys.size());
974  llvm::MDNode *RealDecl = NULL;
975
976  if (RD->isStruct())
977    RealDecl = DBuilder.CreateStructType(RDContext, RDName, DefUnit, Line,
978                                         Size, Align, 0, Elements);
979  else if (RD->isUnion())
980    RealDecl = DBuilder.CreateUnionType(RDContext, RDName, DefUnit, Line,
981                                         Size, Align, 0, Elements);
982  else {
983    assert(RD->isClass() && "Unknown RecordType!");
984    RDName = getClassName(RD);
985     // A class's primary base or the class itself contains the vtable.
986    llvm::MDNode *ContainingType = NULL;
987    const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
988    if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
989      // Seek non virtual primary base root.
990      while (1) {
991        const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
992        const CXXRecordDecl *PBT = BRL.getPrimaryBase();
993        if (PBT && !BRL.isPrimaryBaseVirtual())
994          PBase = PBT;
995        else
996          break;
997      }
998      ContainingType =
999        getOrCreateType(QualType(PBase->getTypeForDecl(), 0), Unit);
1000    }
1001    else if (CXXDecl->isDynamicClass())
1002      ContainingType = FwdDecl;
1003   RealDecl = DBuilder.CreateClassType(RDContext, RDName, DefUnit, Line,
1004                                       Size, Align, 0, 0, llvm::DIType(),
1005                                       Elements, ContainingType);
1006  }
1007
1008  // Now that we have a real decl for the struct, replace anything using the
1009  // old decl with the new one.  This will recursively update the debug info.
1010  llvm::DIType(FwdDeclNode).replaceAllUsesWith(RealDecl);
1011  RegionMap[RD] = llvm::WeakVH(RealDecl);
1012  return llvm::DIType(RealDecl);
1013}
1014
1015/// CreateType - get objective-c object type.
1016llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1017                                     llvm::DIFile Unit) {
1018  // Ignore protocols.
1019  return getOrCreateType(Ty->getBaseType(), Unit);
1020}
1021
1022/// CreateType - get objective-c interface type.
1023llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1024                                     llvm::DIFile Unit) {
1025  ObjCInterfaceDecl *ID = Ty->getDecl();
1026  if (!ID)
1027    return llvm::DIType();
1028
1029  // Get overall information about the record type for the debug info.
1030  llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1031  unsigned Line = getLineNumber(ID->getLocation());
1032  unsigned RuntimeLang = TheCU.getLanguage();
1033
1034  // If this is just a forward declaration, return a special forward-declaration
1035  // debug type.
1036  if (ID->isForwardDecl()) {
1037    llvm::DIType FwdDecl =
1038      DBuilder.CreateStructType(Unit, ID->getName(),
1039                                DefUnit, Line, 0, 0, 0,
1040                                llvm::DIArray(), RuntimeLang);
1041    return FwdDecl;
1042  }
1043
1044  // To handle recursive interface, we
1045  // first generate a debug descriptor for the struct as a forward declaration.
1046  // Then (if it is a definition) we go through and get debug info for all of
1047  // its members.  Finally, we create a descriptor for the complete type (which
1048  // may refer to the forward decl if the struct is recursive) and replace all
1049  // uses of the forward declaration with the final definition.
1050  llvm::DIType FwdDecl = DBuilder.CreateTemporaryType(DefUnit);
1051
1052  llvm::MDNode *MN = FwdDecl;
1053  llvm::TrackingVH<llvm::MDNode> FwdDeclNode = MN;
1054  // Otherwise, insert it into the TypeCache so that recursive uses will find
1055  // it.
1056  TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1057  // Push the struct on region stack.
1058  RegionStack.push_back(FwdDeclNode);
1059  RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1060
1061  // Convert all the elements.
1062  llvm::SmallVector<llvm::Value *, 16> EltTys;
1063
1064  ObjCInterfaceDecl *SClass = ID->getSuperClass();
1065  if (SClass) {
1066    llvm::DIType SClassTy =
1067      getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1068    if (!SClassTy.isValid())
1069      return llvm::DIType();
1070
1071    llvm::DIType InhTag =
1072      DBuilder.CreateInheritance(FwdDecl, SClassTy, 0, 0);
1073    EltTys.push_back(InhTag);
1074  }
1075
1076  const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1077
1078  unsigned FieldNo = 0;
1079  for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1080       Field = Field->getNextIvar(), ++FieldNo) {
1081    llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1082    if (!FieldTy.isValid())
1083      return llvm::DIType();
1084
1085    llvm::StringRef FieldName = Field->getName();
1086
1087    // Ignore unnamed fields.
1088    if (FieldName.empty())
1089      continue;
1090
1091    // Get the location for the field.
1092    llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1093    unsigned FieldLine = getLineNumber(Field->getLocation());
1094    QualType FType = Field->getType();
1095    uint64_t FieldSize = 0;
1096    unsigned FieldAlign = 0;
1097
1098    if (!FType->isIncompleteArrayType()) {
1099
1100      // Bit size, align and offset of the type.
1101      FieldSize = CGM.getContext().getTypeSize(FType);
1102      Expr *BitWidth = Field->getBitWidth();
1103      if (BitWidth)
1104        FieldSize = BitWidth->EvaluateAsInt(CGM.getContext()).getZExtValue();
1105
1106      FieldAlign =  CGM.getContext().getTypeAlign(FType);
1107    }
1108
1109    uint64_t FieldOffset = RL.getFieldOffset(FieldNo);
1110
1111    unsigned Flags = 0;
1112    if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1113      Flags = llvm::DIDescriptor::FlagProtected;
1114    else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1115      Flags = llvm::DIDescriptor::FlagPrivate;
1116
1117    FieldTy = DBuilder.CreateMemberType(FieldName, FieldDefUnit,
1118                                        FieldLine, FieldSize, FieldAlign,
1119                                        FieldOffset, Flags, FieldTy);
1120    EltTys.push_back(FieldTy);
1121  }
1122
1123  llvm::DIArray Elements =
1124    DBuilder.GetOrCreateArray(EltTys.data(), EltTys.size());
1125
1126  RegionStack.pop_back();
1127  llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator RI =
1128    RegionMap.find(Ty->getDecl());
1129  if (RI != RegionMap.end())
1130    RegionMap.erase(RI);
1131
1132  // Bit size, align and offset of the type.
1133  uint64_t Size = CGM.getContext().getTypeSize(Ty);
1134  uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1135
1136  llvm::DIType RealDecl =
1137    DBuilder.CreateStructType(Unit, ID->getName(), DefUnit,
1138                                  Line, Size, Align, 0,
1139                                  Elements, RuntimeLang);
1140
1141  // Now that we have a real decl for the struct, replace anything using the
1142  // old decl with the new one.  This will recursively update the debug info.
1143  llvm::DIType(FwdDeclNode).replaceAllUsesWith(RealDecl);
1144  RegionMap[ID] = llvm::WeakVH(RealDecl);
1145
1146  return RealDecl;
1147}
1148
1149llvm::DIType CGDebugInfo::CreateType(const TagType *Ty) {
1150  if (const RecordType *RT = dyn_cast<RecordType>(Ty))
1151    return CreateType(RT);
1152  else if (const EnumType *ET = dyn_cast<EnumType>(Ty))
1153    return CreateEnumType(ET->getDecl());
1154
1155  return llvm::DIType();
1156}
1157
1158llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty,
1159                                     llvm::DIFile Unit) {
1160  llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1161  uint64_t NumElems = Ty->getNumElements();
1162  if (NumElems > 0)
1163    --NumElems;
1164
1165  llvm::Value *Subscript = DBuilder.GetOrCreateSubrange(0, NumElems);
1166  llvm::DIArray SubscriptArray = DBuilder.GetOrCreateArray(&Subscript, 1);
1167
1168  uint64_t Size = CGM.getContext().getTypeSize(Ty);
1169  uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1170
1171  return
1172    DBuilder.CreateVectorType(Size, Align, ElementTy, SubscriptArray);
1173}
1174
1175llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1176                                     llvm::DIFile Unit) {
1177  uint64_t Size;
1178  uint64_t Align;
1179
1180
1181  // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1182  if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1183    Size = 0;
1184    Align =
1185      CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1186  } else if (Ty->isIncompleteArrayType()) {
1187    Size = 0;
1188    Align = CGM.getContext().getTypeAlign(Ty->getElementType());
1189  } else {
1190    // Size and align of the whole array, not the element type.
1191    Size = CGM.getContext().getTypeSize(Ty);
1192    Align = CGM.getContext().getTypeAlign(Ty);
1193  }
1194
1195  // Add the dimensions of the array.  FIXME: This loses CV qualifiers from
1196  // interior arrays, do we care?  Why aren't nested arrays represented the
1197  // obvious/recursive way?
1198  llvm::SmallVector<llvm::Value *, 8> Subscripts;
1199  QualType EltTy(Ty, 0);
1200  if (Ty->isIncompleteArrayType())
1201    EltTy = Ty->getElementType();
1202  else {
1203    while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1204      uint64_t Upper = 0;
1205      if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1206        if (CAT->getSize().getZExtValue())
1207          Upper = CAT->getSize().getZExtValue() - 1;
1208      // FIXME: Verify this is right for VLAs.
1209      Subscripts.push_back(DBuilder.GetOrCreateSubrange(0, Upper));
1210      EltTy = Ty->getElementType();
1211    }
1212  }
1213
1214  llvm::DIArray SubscriptArray =
1215    DBuilder.GetOrCreateArray(Subscripts.data(), Subscripts.size());
1216
1217  llvm::DIType DbgTy =
1218    DBuilder.CreateArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1219                             SubscriptArray);
1220  return DbgTy;
1221}
1222
1223llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
1224                                     llvm::DIFile Unit) {
1225  return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
1226                               Ty, Ty->getPointeeType(), Unit);
1227}
1228
1229llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
1230                                     llvm::DIFile Unit) {
1231  return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type,
1232                               Ty, Ty->getPointeeType(), Unit);
1233}
1234
1235llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
1236                                     llvm::DIFile U) {
1237  QualType PointerDiffTy = CGM.getContext().getPointerDiffType();
1238  llvm::DIType PointerDiffDITy = getOrCreateType(PointerDiffTy, U);
1239
1240  if (!Ty->getPointeeType()->isFunctionType()) {
1241    // We have a data member pointer type.
1242    return PointerDiffDITy;
1243  }
1244
1245  // We have a member function pointer type. Treat it as a struct with two
1246  // ptrdiff_t members.
1247  std::pair<uint64_t, unsigned> Info = CGM.getContext().getTypeInfo(Ty);
1248
1249  uint64_t FieldOffset = 0;
1250  llvm::Value *ElementTypes[2];
1251
1252  // FIXME: This should probably be a function type instead.
1253  ElementTypes[0] =
1254    DBuilder.CreateMemberType("ptr", U, 0,
1255                              Info.first, Info.second, FieldOffset, 0,
1256                              PointerDiffDITy);
1257  FieldOffset += Info.first;
1258
1259  ElementTypes[1] =
1260    DBuilder.CreateMemberType("ptr", U, 0,
1261                              Info.first, Info.second, FieldOffset, 0,
1262                              PointerDiffDITy);
1263
1264  llvm::DIArray Elements =
1265    DBuilder.GetOrCreateArray(&ElementTypes[0],
1266                              llvm::array_lengthof(ElementTypes));
1267
1268  return DBuilder.CreateStructType(U, llvm::StringRef("test"),
1269                                   U, 0, FieldOffset,
1270                                   0, 0, Elements);
1271}
1272
1273/// CreateEnumType - get enumeration type.
1274llvm::DIType CGDebugInfo::CreateEnumType(const EnumDecl *ED) {
1275  llvm::DIFile Unit = getOrCreateFile(ED->getLocation());
1276  llvm::SmallVector<llvm::Value *, 16> Enumerators;
1277
1278  // Create DIEnumerator elements for each enumerator.
1279  for (EnumDecl::enumerator_iterator
1280         Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
1281       Enum != EnumEnd; ++Enum) {
1282    Enumerators.push_back(
1283      DBuilder.CreateEnumerator(Enum->getName(),
1284                                Enum->getInitVal().getZExtValue()));
1285  }
1286
1287  // Return a CompositeType for the enum itself.
1288  llvm::DIArray EltArray =
1289    DBuilder.GetOrCreateArray(Enumerators.data(), Enumerators.size());
1290
1291  llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1292  unsigned Line = getLineNumber(ED->getLocation());
1293  uint64_t Size = 0;
1294  uint64_t Align = 0;
1295  if (!ED->getTypeForDecl()->isIncompleteType()) {
1296    Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1297    Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1298  }
1299  llvm::DIDescriptor EnumContext =
1300    getContextDescriptor(dyn_cast<Decl>(ED->getDeclContext()));
1301  llvm::DIType DbgTy =
1302    DBuilder.CreateEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1303                                   Size, Align, EltArray);
1304  return DbgTy;
1305}
1306
1307static QualType UnwrapTypeForDebugInfo(QualType T) {
1308  do {
1309    QualType LastT = T;
1310    switch (T->getTypeClass()) {
1311    default:
1312      return T;
1313    case Type::TemplateSpecialization:
1314      T = cast<TemplateSpecializationType>(T)->desugar();
1315      break;
1316    case Type::TypeOfExpr:
1317      T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1318      break;
1319    case Type::TypeOf:
1320      T = cast<TypeOfType>(T)->getUnderlyingType();
1321      break;
1322    case Type::Decltype:
1323      T = cast<DecltypeType>(T)->getUnderlyingType();
1324      break;
1325    case Type::Attributed:
1326      T = cast<AttributedType>(T)->getEquivalentType();
1327    case Type::Elaborated:
1328      T = cast<ElaboratedType>(T)->getNamedType();
1329      break;
1330    case Type::Paren:
1331      T = cast<ParenType>(T)->getInnerType();
1332      break;
1333    case Type::SubstTemplateTypeParm:
1334      T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
1335      break;
1336    }
1337
1338    assert(T != LastT && "Type unwrapping failed to unwrap!");
1339    if (T == LastT)
1340      return T;
1341  } while (true);
1342
1343  return T;
1344}
1345
1346/// getOrCreateType - Get the type from the cache or create a new
1347/// one if necessary.
1348llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty,
1349                                          llvm::DIFile Unit) {
1350  if (Ty.isNull())
1351    return llvm::DIType();
1352
1353  // Unwrap the type as needed for debug information.
1354  Ty = UnwrapTypeForDebugInfo(Ty);
1355
1356  // Check for existing entry.
1357  llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1358    TypeCache.find(Ty.getAsOpaquePtr());
1359  if (it != TypeCache.end()) {
1360    // Verify that the debug info still exists.
1361    if (&*it->second)
1362      return llvm::DIType(cast<llvm::MDNode>(it->second));
1363  }
1364
1365  // Otherwise create the type.
1366  llvm::DIType Res = CreateTypeNode(Ty, Unit);
1367
1368  // And update the type cache.
1369  TypeCache[Ty.getAsOpaquePtr()] = Res;
1370  return Res;
1371}
1372
1373/// CreateTypeNode - Create a new debug type node.
1374llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty,
1375                                         llvm::DIFile Unit) {
1376  // Handle qualifiers, which recursively handles what they refer to.
1377  if (Ty.hasLocalQualifiers())
1378    return CreateQualifiedType(Ty, Unit);
1379
1380  const char *Diag = 0;
1381
1382  // Work out details of type.
1383  switch (Ty->getTypeClass()) {
1384#define TYPE(Class, Base)
1385#define ABSTRACT_TYPE(Class, Base)
1386#define NON_CANONICAL_TYPE(Class, Base)
1387#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1388#include "clang/AST/TypeNodes.def"
1389    assert(false && "Dependent types cannot show up in debug information");
1390
1391  // FIXME: Handle these.
1392  case Type::ExtVector:
1393    return llvm::DIType();
1394
1395  case Type::Vector:
1396    return CreateType(cast<VectorType>(Ty), Unit);
1397  case Type::ObjCObjectPointer:
1398    return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
1399  case Type::ObjCObject:
1400    return CreateType(cast<ObjCObjectType>(Ty), Unit);
1401  case Type::ObjCInterface:
1402    return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
1403  case Type::Builtin: return CreateType(cast<BuiltinType>(Ty));
1404  case Type::Complex: return CreateType(cast<ComplexType>(Ty));
1405  case Type::Pointer: return CreateType(cast<PointerType>(Ty), Unit);
1406  case Type::BlockPointer:
1407    return CreateType(cast<BlockPointerType>(Ty), Unit);
1408  case Type::Typedef: return CreateType(cast<TypedefType>(Ty), Unit);
1409  case Type::Record:
1410  case Type::Enum:
1411    return CreateType(cast<TagType>(Ty));
1412  case Type::FunctionProto:
1413  case Type::FunctionNoProto:
1414    return CreateType(cast<FunctionType>(Ty), Unit);
1415  case Type::ConstantArray:
1416  case Type::VariableArray:
1417  case Type::IncompleteArray:
1418    return CreateType(cast<ArrayType>(Ty), Unit);
1419
1420  case Type::LValueReference:
1421    return CreateType(cast<LValueReferenceType>(Ty), Unit);
1422  case Type::RValueReference:
1423    return CreateType(cast<RValueReferenceType>(Ty), Unit);
1424
1425  case Type::MemberPointer:
1426    return CreateType(cast<MemberPointerType>(Ty), Unit);
1427
1428  case Type::Attributed:
1429  case Type::TemplateSpecialization:
1430  case Type::Elaborated:
1431  case Type::Paren:
1432  case Type::SubstTemplateTypeParm:
1433  case Type::TypeOfExpr:
1434  case Type::TypeOf:
1435  case Type::Decltype:
1436    llvm_unreachable("type should have been unwrapped!");
1437    return llvm::DIType();
1438  }
1439
1440  assert(Diag && "Fall through without a diagnostic?");
1441  unsigned DiagID = CGM.getDiags().getCustomDiagID(Diagnostic::Error,
1442                               "debug information for %0 is not yet supported");
1443  CGM.getDiags().Report(DiagID)
1444    << Diag;
1445  return llvm::DIType();
1446}
1447
1448/// CreateMemberType - Create new member and increase Offset by FType's size.
1449llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
1450                                           llvm::StringRef Name,
1451                                           uint64_t *Offset) {
1452  llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1453  uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
1454  unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
1455  llvm::DIType Ty = DBuilder.CreateMemberType(Name, Unit, 0,
1456                                              FieldSize, FieldAlign,
1457                                              *Offset, 0, FieldTy);
1458  *Offset += FieldSize;
1459  return Ty;
1460}
1461
1462/// EmitFunctionStart - Constructs the debug code for entering a function -
1463/// "llvm.dbg.func.start.".
1464void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
1465                                    llvm::Function *Fn,
1466                                    CGBuilderTy &Builder) {
1467
1468  llvm::StringRef Name;
1469  llvm::StringRef LinkageName;
1470
1471  FnBeginRegionCount.push_back(RegionStack.size());
1472
1473  const Decl *D = GD.getDecl();
1474  unsigned Flags = 0;
1475  llvm::DIFile Unit = getOrCreateFile(CurLoc);
1476  llvm::DIDescriptor FDContext(Unit);
1477  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1478    // If there is a DISubprogram for  this function available then use it.
1479    llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
1480      FI = SPCache.find(FD);
1481    if (FI != SPCache.end()) {
1482      llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(&*FI->second));
1483      if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
1484        llvm::MDNode *SPN = SP;
1485        RegionStack.push_back(SPN);
1486        RegionMap[D] = llvm::WeakVH(SP);
1487        return;
1488      }
1489    }
1490    Name = getFunctionName(FD);
1491    // Use mangled name as linkage name for c/c++ functions.
1492    LinkageName = CGM.getMangledName(GD);
1493    if (LinkageName == Name)
1494      LinkageName = llvm::StringRef();
1495    if (FD->hasPrototype())
1496      Flags |= llvm::DIDescriptor::FlagPrototyped;
1497    if (const NamespaceDecl *NSDecl =
1498        dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
1499      FDContext = getOrCreateNameSpace(NSDecl);
1500  } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
1501    Name = getObjCMethodName(OMD);
1502    Flags |= llvm::DIDescriptor::FlagPrototyped;
1503  } else {
1504    // Use llvm function name.
1505    Name = Fn->getName();
1506    Flags |= llvm::DIDescriptor::FlagPrototyped;
1507  }
1508  if (!Name.empty() && Name[0] == '\01')
1509    Name = Name.substr(1);
1510
1511  // It is expected that CurLoc is set before using EmitFunctionStart.
1512  // Usually, CurLoc points to the left bracket location of compound
1513  // statement representing function body.
1514  unsigned LineNo = getLineNumber(CurLoc);
1515  if (D->isImplicit())
1516    Flags |= llvm::DIDescriptor::FlagArtificial;
1517  llvm::DISubprogram SP =
1518    DBuilder.CreateFunction(FDContext, Name, LinkageName, Unit,
1519                            LineNo, getOrCreateType(FnType, Unit),
1520                            Fn->hasInternalLinkage(), true/*definition*/,
1521                            Flags, CGM.getLangOptions().Optimize, Fn);
1522
1523  // Push function on region stack.
1524  llvm::MDNode *SPN = SP;
1525  RegionStack.push_back(SPN);
1526  RegionMap[D] = llvm::WeakVH(SP);
1527
1528  // Clear stack used to keep track of #line directives.
1529  LineDirectiveFiles.clear();
1530}
1531
1532
1533void CGDebugInfo::EmitStopPoint(CGBuilderTy &Builder) {
1534  if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
1535
1536  // Don't bother if things are the same as last time.
1537  SourceManager &SM = CGM.getContext().getSourceManager();
1538  if (CurLoc == PrevLoc
1539       || (SM.getInstantiationLineNumber(CurLoc) ==
1540           SM.getInstantiationLineNumber(PrevLoc)
1541           && SM.isFromSameFile(CurLoc, PrevLoc)))
1542    // New Builder may not be in sync with CGDebugInfo.
1543    if (!Builder.getCurrentDebugLocation().isUnknown())
1544      return;
1545
1546  // Update last state.
1547  PrevLoc = CurLoc;
1548
1549  llvm::MDNode *Scope = RegionStack.back();
1550  Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(CurLoc),
1551                                                      getColumnNumber(CurLoc),
1552                                                      Scope));
1553}
1554
1555/// UpdateLineDirectiveRegion - Update region stack only if #line directive
1556/// has introduced scope change.
1557void CGDebugInfo::UpdateLineDirectiveRegion(CGBuilderTy &Builder) {
1558  if (CurLoc.isInvalid() || CurLoc.isMacroID() ||
1559      PrevLoc.isInvalid() || PrevLoc.isMacroID())
1560    return;
1561  SourceManager &SM = CGM.getContext().getSourceManager();
1562  PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
1563  PresumedLoc PPLoc = SM.getPresumedLoc(PrevLoc);
1564
1565  if (PCLoc.isInvalid() || PPLoc.isInvalid() ||
1566      !strcmp(PPLoc.getFilename(), PCLoc.getFilename()))
1567    return;
1568
1569  // If #line directive stack is empty then we are entering a new scope.
1570  if (LineDirectiveFiles.empty()) {
1571    EmitRegionStart(Builder);
1572    LineDirectiveFiles.push_back(PCLoc.getFilename());
1573    return;
1574  }
1575
1576  assert (RegionStack.size() >= LineDirectiveFiles.size()
1577          && "error handling  #line regions!");
1578
1579  bool SeenThisFile = false;
1580  // Chek if current file is already seen earlier.
1581  for(std::vector<const char *>::iterator I = LineDirectiveFiles.begin(),
1582        E = LineDirectiveFiles.end(); I != E; ++I)
1583    if (!strcmp(PCLoc.getFilename(), *I)) {
1584      SeenThisFile = true;
1585      break;
1586    }
1587
1588  // If #line for this file is seen earlier then pop out #line regions.
1589  if (SeenThisFile) {
1590    while (!LineDirectiveFiles.empty()) {
1591      const char *LastFile = LineDirectiveFiles.back();
1592      RegionStack.pop_back();
1593      LineDirectiveFiles.pop_back();
1594      if (!strcmp(PPLoc.getFilename(), LastFile))
1595        break;
1596    }
1597    return;
1598  }
1599
1600  // .. otherwise insert new #line region.
1601  EmitRegionStart(Builder);
1602  LineDirectiveFiles.push_back(PCLoc.getFilename());
1603
1604  return;
1605}
1606/// EmitRegionStart- Constructs the debug code for entering a declarative
1607/// region - "llvm.dbg.region.start.".
1608void CGDebugInfo::EmitRegionStart(CGBuilderTy &Builder) {
1609  llvm::DIDescriptor D =
1610    DBuilder.CreateLexicalBlock(RegionStack.empty() ?
1611                                llvm::DIDescriptor() :
1612                                llvm::DIDescriptor(RegionStack.back()),
1613                                getOrCreateFile(CurLoc),
1614                                getLineNumber(CurLoc),
1615                                getColumnNumber(CurLoc));
1616  llvm::MDNode *DN = D;
1617  RegionStack.push_back(DN);
1618}
1619
1620/// EmitRegionEnd - Constructs the debug code for exiting a declarative
1621/// region - "llvm.dbg.region.end."
1622void CGDebugInfo::EmitRegionEnd(CGBuilderTy &Builder) {
1623  assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
1624
1625  // Provide an region stop point.
1626  EmitStopPoint(Builder);
1627
1628  RegionStack.pop_back();
1629}
1630
1631/// EmitFunctionEnd - Constructs the debug code for exiting a function.
1632void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
1633  assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
1634  unsigned RCount = FnBeginRegionCount.back();
1635  assert(RCount <= RegionStack.size() && "Region stack mismatch");
1636
1637  // Pop all regions for this function.
1638  while (RegionStack.size() != RCount)
1639    EmitRegionEnd(Builder);
1640  FnBeginRegionCount.pop_back();
1641}
1642
1643// EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
1644// See BuildByRefType.
1645llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const ValueDecl *VD,
1646                                                       uint64_t *XOffset) {
1647
1648  llvm::SmallVector<llvm::Value *, 5> EltTys;
1649  QualType FType;
1650  uint64_t FieldSize, FieldOffset;
1651  unsigned FieldAlign;
1652
1653  llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
1654  QualType Type = VD->getType();
1655
1656  FieldOffset = 0;
1657  FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1658  EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
1659  EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
1660  FType = CGM.getContext().IntTy;
1661  EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
1662  EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
1663
1664  bool HasCopyAndDispose = CGM.BlockRequiresCopying(Type);
1665  if (HasCopyAndDispose) {
1666    FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1667    EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
1668                                      &FieldOffset));
1669    EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
1670                                      &FieldOffset));
1671  }
1672
1673  CharUnits Align = CGM.getContext().getDeclAlign(VD);
1674  if (Align > CharUnits::fromQuantity(
1675        CGM.getContext().Target.getPointerAlign(0) / 8)) {
1676    unsigned AlignedOffsetInBytes
1677      = llvm::RoundUpToAlignment(FieldOffset/8, Align.getQuantity());
1678    unsigned NumPaddingBytes
1679      = AlignedOffsetInBytes - FieldOffset/8;
1680
1681    if (NumPaddingBytes > 0) {
1682      llvm::APInt pad(32, NumPaddingBytes);
1683      FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
1684                                                    pad, ArrayType::Normal, 0);
1685      EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
1686    }
1687  }
1688
1689  FType = Type;
1690  llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1691  FieldSize = CGM.getContext().getTypeSize(FType);
1692  FieldAlign = Align.getQuantity()*8;
1693
1694  *XOffset = FieldOffset;
1695  FieldTy = DBuilder.CreateMemberType(VD->getName(), Unit,
1696                                      0, FieldSize, FieldAlign,
1697                                      FieldOffset, 0, FieldTy);
1698  EltTys.push_back(FieldTy);
1699  FieldOffset += FieldSize;
1700
1701  llvm::DIArray Elements =
1702    DBuilder.GetOrCreateArray(EltTys.data(), EltTys.size());
1703
1704  unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
1705
1706  return DBuilder.CreateStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
1707                                   Elements);
1708}
1709
1710/// EmitDeclare - Emit local variable declaration debug info.
1711void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
1712                              llvm::Value *Storage, CGBuilderTy &Builder) {
1713  assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
1714
1715  llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
1716  llvm::DIType Ty;
1717  uint64_t XOffset = 0;
1718  if (VD->hasAttr<BlocksAttr>())
1719    Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
1720  else
1721    Ty = getOrCreateType(VD->getType(), Unit);
1722
1723  // If there is not any debug info for type then do not emit debug info
1724  // for this variable.
1725  if (!Ty)
1726    return;
1727
1728  // Get location information.
1729  unsigned Line = getLineNumber(VD->getLocation());
1730  unsigned Column = getColumnNumber(VD->getLocation());
1731  unsigned Flags = 0;
1732  if (VD->isImplicit())
1733    Flags |= llvm::DIDescriptor::FlagArtificial;
1734  llvm::MDNode *Scope = RegionStack.back();
1735
1736  llvm::StringRef Name = VD->getName();
1737  if (!Name.empty()) {
1738    if (VD->hasAttr<BlocksAttr>()) {
1739      CharUnits offset = CharUnits::fromQuantity(32);
1740      llvm::SmallVector<llvm::Value *, 9> addr;
1741      const llvm::Type *Int64Ty = llvm::Type::getInt64Ty(CGM.getLLVMContext());
1742      addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpPlus));
1743      // offset of __forwarding field
1744      offset =
1745        CharUnits::fromQuantity(CGM.getContext().Target.getPointerWidth(0)/8);
1746      addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
1747      addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpDeref));
1748      addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpPlus));
1749      // offset of x field
1750      offset = CharUnits::fromQuantity(XOffset/8);
1751      addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
1752
1753      // Create the descriptor for the variable.
1754      llvm::DIVariable D =
1755        DBuilder.CreateComplexVariable(Tag,
1756                                       llvm::DIDescriptor(RegionStack.back()),
1757                                       VD->getName(), Unit, Line, Ty,
1758                                       addr.data(), addr.size());
1759
1760      // Insert an llvm.dbg.declare into the current block.
1761      llvm::Instruction *Call =
1762        DBuilder.InsertDeclare(Storage, D, Builder.GetInsertBlock());
1763
1764      Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
1765      return;
1766    }
1767      // Create the descriptor for the variable.
1768    llvm::DIVariable D =
1769      DBuilder.CreateLocalVariable(Tag, llvm::DIDescriptor(Scope),
1770                                   Name, Unit, Line, Ty,
1771                                   CGM.getLangOptions().Optimize, Flags);
1772
1773    // Insert an llvm.dbg.declare into the current block.
1774    llvm::Instruction *Call =
1775      DBuilder.InsertDeclare(Storage, D, Builder.GetInsertBlock());
1776
1777    Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
1778    return;
1779  }
1780
1781  // If VD is an anonymous union then Storage represents value for
1782  // all union fields.
1783  if (const RecordType *RT = dyn_cast<RecordType>(VD->getType()))
1784    if (const RecordDecl *RD = dyn_cast<RecordDecl>(RT->getDecl()))
1785      if (RD->isUnion()) {
1786        for (RecordDecl::field_iterator I = RD->field_begin(),
1787               E = RD->field_end();
1788             I != E; ++I) {
1789          FieldDecl *Field = *I;
1790          llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1791          llvm::StringRef FieldName = Field->getName();
1792
1793          // Ignore unnamed fields. Do not ignore unnamed records.
1794          if (FieldName.empty() && !isa<RecordType>(Field->getType()))
1795            continue;
1796
1797          // Use VarDecl's Tag, Scope and Line number.
1798          llvm::DIVariable D =
1799            DBuilder.CreateLocalVariable(Tag, llvm::DIDescriptor(Scope),
1800                                         FieldName, Unit, Line, FieldTy,
1801                                         CGM.getLangOptions().Optimize, Flags);
1802
1803          // Insert an llvm.dbg.declare into the current block.
1804          llvm::Instruction *Call =
1805            DBuilder.InsertDeclare(Storage, D, Builder.GetInsertBlock());
1806
1807          Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
1808        }
1809      }
1810}
1811
1812/// EmitDeclare - Emit local variable declaration debug info.
1813void CGDebugInfo::EmitDeclare(const BlockDeclRefExpr *BDRE, unsigned Tag,
1814                              llvm::Value *Storage, CGBuilderTy &Builder,
1815                              CodeGenFunction *CGF) {
1816  const ValueDecl *VD = BDRE->getDecl();
1817  assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
1818
1819  if (Builder.GetInsertBlock() == 0)
1820    return;
1821
1822  uint64_t XOffset = 0;
1823  llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
1824  llvm::DIType Ty;
1825  if (VD->hasAttr<BlocksAttr>())
1826    Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
1827  else
1828    Ty = getOrCreateType(VD->getType(), Unit);
1829
1830  // Get location information.
1831  unsigned Line = getLineNumber(VD->getLocation());
1832  unsigned Column = getColumnNumber(VD->getLocation());
1833
1834  CharUnits offset = CGF->BlockDecls[VD];
1835  llvm::SmallVector<llvm::Value *, 9> addr;
1836  const llvm::Type *Int64Ty = llvm::Type::getInt64Ty(CGM.getLLVMContext());
1837  addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpDeref));
1838  addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpPlus));
1839  addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
1840  if (BDRE->isByRef()) {
1841    addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpDeref));
1842    addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpPlus));
1843    // offset of __forwarding field
1844    offset = CharUnits::fromQuantity(CGF->LLVMPointerWidth/8);
1845    addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
1846    addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpDeref));
1847    addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpPlus));
1848    // offset of x field
1849    offset = CharUnits::fromQuantity(XOffset/8);
1850    addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
1851  }
1852
1853  // Create the descriptor for the variable.
1854  llvm::DIVariable D =
1855    DBuilder.CreateComplexVariable(Tag, llvm::DIDescriptor(RegionStack.back()),
1856                                   VD->getName(), Unit, Line, Ty,
1857                                   addr.data(), addr.size());
1858  // Insert an llvm.dbg.declare into the current block.
1859  llvm::Instruction *Call =
1860    DBuilder.InsertDeclare(Storage, D, Builder.GetInsertBlock());
1861
1862  llvm::MDNode *Scope = RegionStack.back();
1863  Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
1864}
1865
1866void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
1867                                            llvm::Value *Storage,
1868                                            CGBuilderTy &Builder) {
1869  EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, Builder);
1870}
1871
1872void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(
1873  const BlockDeclRefExpr *BDRE, llvm::Value *Storage, CGBuilderTy &Builder,
1874  CodeGenFunction *CGF) {
1875  EmitDeclare(BDRE, llvm::dwarf::DW_TAG_auto_variable, Storage, Builder, CGF);
1876}
1877
1878/// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
1879/// variable declaration.
1880void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
1881                                           CGBuilderTy &Builder) {
1882  EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, Builder);
1883}
1884
1885
1886
1887/// EmitGlobalVariable - Emit information about a global variable.
1888void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
1889                                     const VarDecl *D) {
1890
1891  // Create global variable debug descriptor.
1892  llvm::DIFile Unit = getOrCreateFile(D->getLocation());
1893  unsigned LineNo = getLineNumber(D->getLocation());
1894
1895  QualType T = D->getType();
1896  if (T->isIncompleteArrayType()) {
1897
1898    // CodeGen turns int[] into int[1] so we'll do the same here.
1899    llvm::APSInt ConstVal(32);
1900
1901    ConstVal = 1;
1902    QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
1903
1904    T = CGM.getContext().getConstantArrayType(ET, ConstVal,
1905                                           ArrayType::Normal, 0);
1906  }
1907  llvm::StringRef DeclName = D->getName();
1908  llvm::StringRef LinkageName;
1909  if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext()))
1910    LinkageName = Var->getName();
1911  if (LinkageName == DeclName)
1912    LinkageName = llvm::StringRef();
1913  llvm::DIDescriptor DContext =
1914    getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
1915  DBuilder.CreateStaticVariable(DContext, DeclName, LinkageName,
1916                                Unit, LineNo, getOrCreateType(T, Unit),
1917                                Var->hasInternalLinkage(), Var);
1918}
1919
1920/// EmitGlobalVariable - Emit information about an objective-c interface.
1921void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
1922                                     ObjCInterfaceDecl *ID) {
1923  // Create global variable debug descriptor.
1924  llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
1925  unsigned LineNo = getLineNumber(ID->getLocation());
1926
1927  llvm::StringRef Name = ID->getName();
1928
1929  QualType T = CGM.getContext().getObjCInterfaceType(ID);
1930  if (T->isIncompleteArrayType()) {
1931
1932    // CodeGen turns int[] into int[1] so we'll do the same here.
1933    llvm::APSInt ConstVal(32);
1934
1935    ConstVal = 1;
1936    QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
1937
1938    T = CGM.getContext().getConstantArrayType(ET, ConstVal,
1939                                           ArrayType::Normal, 0);
1940  }
1941
1942  DBuilder.CreateGlobalVariable(Name, Unit, LineNo,
1943                                getOrCreateType(T, Unit),
1944                                Var->hasInternalLinkage(), Var);
1945}
1946
1947/// EmitGlobalVariable - Emit global variable's debug info.
1948void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
1949                                     llvm::Constant *Init) {
1950  // Create the descriptor for the variable.
1951  llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
1952  llvm::StringRef Name = VD->getName();
1953  llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
1954  if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
1955    if (const EnumDecl *ED = dyn_cast<EnumDecl>(ECD->getDeclContext()))
1956      Ty = CreateEnumType(ED);
1957  }
1958  // Do not use DIGlobalVariable for enums.
1959  if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
1960    return;
1961  DBuilder.CreateStaticVariable(Unit, Name, Name, Unit,
1962                                getLineNumber(VD->getLocation()),
1963                                Ty, true, Init);
1964}
1965
1966/// getOrCreateNamesSpace - Return namespace descriptor for the given
1967/// namespace decl.
1968llvm::DINameSpace
1969CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
1970  llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
1971    NameSpaceCache.find(NSDecl);
1972  if (I != NameSpaceCache.end())
1973    return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
1974
1975  unsigned LineNo = getLineNumber(NSDecl->getLocation());
1976  llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
1977  llvm::DIDescriptor Context =
1978    getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
1979  llvm::DINameSpace NS =
1980    DBuilder.CreateNameSpace(Context, NSDecl->getName(), FileD, LineNo);
1981  NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
1982  return NS;
1983}
1984