CGDebugInfo.cpp revision 9d156a7b1b2771e191f2f5a45a7b7a694129463b
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                                     llvm::DIFile Unit) {
884  RecordDecl *RD = Ty->getDecl();
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 EnumType *Ty,
1150                                     llvm::DIFile Unit) {
1151  return CreateEnumType(Ty->getDecl(), Unit);
1152
1153}
1154
1155llvm::DIType CGDebugInfo::CreateType(const TagType *Ty,
1156                                     llvm::DIFile Unit) {
1157  if (const RecordType *RT = dyn_cast<RecordType>(Ty))
1158    return CreateType(RT, Unit);
1159  else if (const EnumType *ET = dyn_cast<EnumType>(Ty))
1160    return CreateType(ET, Unit);
1161
1162  return llvm::DIType();
1163}
1164
1165llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty,
1166                                     llvm::DIFile Unit) {
1167  llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1168  uint64_t NumElems = Ty->getNumElements();
1169  if (NumElems > 0)
1170    --NumElems;
1171
1172  llvm::Value *Subscript = DBuilder.GetOrCreateSubrange(0, NumElems);
1173  llvm::DIArray SubscriptArray = DBuilder.GetOrCreateArray(&Subscript, 1);
1174
1175  uint64_t Size = CGM.getContext().getTypeSize(Ty);
1176  uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1177
1178  return
1179    DBuilder.CreateVectorType(Size, Align, ElementTy, SubscriptArray);
1180}
1181
1182llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1183                                     llvm::DIFile Unit) {
1184  uint64_t Size;
1185  uint64_t Align;
1186
1187
1188  // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1189  if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1190    Size = 0;
1191    Align =
1192      CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1193  } else if (Ty->isIncompleteArrayType()) {
1194    Size = 0;
1195    Align = CGM.getContext().getTypeAlign(Ty->getElementType());
1196  } else {
1197    // Size and align of the whole array, not the element type.
1198    Size = CGM.getContext().getTypeSize(Ty);
1199    Align = CGM.getContext().getTypeAlign(Ty);
1200  }
1201
1202  // Add the dimensions of the array.  FIXME: This loses CV qualifiers from
1203  // interior arrays, do we care?  Why aren't nested arrays represented the
1204  // obvious/recursive way?
1205  llvm::SmallVector<llvm::Value *, 8> Subscripts;
1206  QualType EltTy(Ty, 0);
1207  if (Ty->isIncompleteArrayType())
1208    EltTy = Ty->getElementType();
1209  else {
1210    while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1211      uint64_t Upper = 0;
1212      if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1213        if (CAT->getSize().getZExtValue())
1214          Upper = CAT->getSize().getZExtValue() - 1;
1215      // FIXME: Verify this is right for VLAs.
1216      Subscripts.push_back(DBuilder.GetOrCreateSubrange(0, Upper));
1217      EltTy = Ty->getElementType();
1218    }
1219  }
1220
1221  llvm::DIArray SubscriptArray =
1222    DBuilder.GetOrCreateArray(Subscripts.data(), Subscripts.size());
1223
1224  llvm::DIType DbgTy =
1225    DBuilder.CreateArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1226                             SubscriptArray);
1227  return DbgTy;
1228}
1229
1230llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
1231                                     llvm::DIFile Unit) {
1232  return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
1233                               Ty, Ty->getPointeeType(), Unit);
1234}
1235
1236llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
1237                                     llvm::DIFile U) {
1238  QualType PointerDiffTy = CGM.getContext().getPointerDiffType();
1239  llvm::DIType PointerDiffDITy = getOrCreateType(PointerDiffTy, U);
1240
1241  if (!Ty->getPointeeType()->isFunctionType()) {
1242    // We have a data member pointer type.
1243    return PointerDiffDITy;
1244  }
1245
1246  // We have a member function pointer type. Treat it as a struct with two
1247  // ptrdiff_t members.
1248  std::pair<uint64_t, unsigned> Info = CGM.getContext().getTypeInfo(Ty);
1249
1250  uint64_t FieldOffset = 0;
1251  llvm::Value *ElementTypes[2];
1252
1253  // FIXME: This should probably be a function type instead.
1254  ElementTypes[0] =
1255    DBuilder.CreateMemberType("ptr", U, 0,
1256                              Info.first, Info.second, FieldOffset, 0,
1257                              PointerDiffDITy);
1258  FieldOffset += Info.first;
1259
1260  ElementTypes[1] =
1261    DBuilder.CreateMemberType("ptr", U, 0,
1262                              Info.first, Info.second, FieldOffset, 0,
1263                              PointerDiffDITy);
1264
1265  llvm::DIArray Elements =
1266    DBuilder.GetOrCreateArray(&ElementTypes[0],
1267                              llvm::array_lengthof(ElementTypes));
1268
1269  return DBuilder.CreateStructType(U, llvm::StringRef("test"),
1270                                   U, 0, FieldOffset,
1271                                   0, 0, Elements);
1272}
1273
1274/// CreateEnumType - get enumeration type.
1275llvm::DIType CGDebugInfo::CreateEnumType(const EnumDecl *ED, llvm::DIFile Unit){
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      TypeOfExprType *Ty = cast<TypeOfExprType>(T);
1318      T = Ty->getUnderlyingExpr()->getType();
1319      break;
1320    }
1321    case Type::TypeOf:
1322      T = cast<TypeOfType>(T)->getUnderlyingType();
1323      break;
1324    case Type::Decltype:
1325      T = cast<DecltypeType>(T)->getUnderlyingType();
1326      break;
1327    case Type::Attributed:
1328      T = cast<AttributedType>(T)->getEquivalentType();
1329    case Type::Elaborated:
1330      T = cast<ElaboratedType>(T)->getNamedType();
1331      break;
1332    case Type::Paren:
1333      T = cast<ParenType>(T)->getInnerType();
1334      break;
1335    case Type::SubstTemplateTypeParm:
1336      T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
1337      break;
1338    }
1339
1340    assert(T != LastT && "Type unwrapping failed to unwrap!");
1341    if (T == LastT)
1342      return T;
1343  } while (true);
1344
1345  return T;
1346}
1347
1348/// getOrCreateType - Get the type from the cache or create a new
1349/// one if necessary.
1350llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty,
1351                                          llvm::DIFile Unit) {
1352  if (Ty.isNull())
1353    return llvm::DIType();
1354
1355  // Unwrap the type as needed for debug information.
1356  Ty = UnwrapTypeForDebugInfo(Ty);
1357
1358  // Check for existing entry.
1359  llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1360    TypeCache.find(Ty.getAsOpaquePtr());
1361  if (it != TypeCache.end()) {
1362    // Verify that the debug info still exists.
1363    if (&*it->second)
1364      return llvm::DIType(cast<llvm::MDNode>(it->second));
1365  }
1366
1367  // Otherwise create the type.
1368  llvm::DIType Res = CreateTypeNode(Ty, Unit);
1369
1370  // And update the type cache.
1371  TypeCache[Ty.getAsOpaquePtr()] = Res;
1372  return Res;
1373}
1374
1375/// CreateTypeNode - Create a new debug type node.
1376llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty,
1377                                         llvm::DIFile Unit) {
1378  // Handle qualifiers, which recursively handles what they refer to.
1379  if (Ty.hasLocalQualifiers())
1380    return CreateQualifiedType(Ty, Unit);
1381
1382  const char *Diag = 0;
1383
1384  // Work out details of type.
1385  switch (Ty->getTypeClass()) {
1386#define TYPE(Class, Base)
1387#define ABSTRACT_TYPE(Class, Base)
1388#define NON_CANONICAL_TYPE(Class, Base)
1389#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1390#include "clang/AST/TypeNodes.def"
1391    assert(false && "Dependent types cannot show up in debug information");
1392
1393  // FIXME: Handle these.
1394  case Type::ExtVector:
1395    return llvm::DIType();
1396
1397  case Type::Vector:
1398    return CreateType(cast<VectorType>(Ty), Unit);
1399  case Type::ObjCObjectPointer:
1400    return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
1401  case Type::ObjCObject:
1402    return CreateType(cast<ObjCObjectType>(Ty), Unit);
1403  case Type::ObjCInterface:
1404    return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
1405  case Type::Builtin: return CreateType(cast<BuiltinType>(Ty));
1406  case Type::Complex: return CreateType(cast<ComplexType>(Ty));
1407  case Type::Pointer: return CreateType(cast<PointerType>(Ty), Unit);
1408  case Type::BlockPointer:
1409    return CreateType(cast<BlockPointerType>(Ty), Unit);
1410  case Type::Typedef: return CreateType(cast<TypedefType>(Ty), Unit);
1411  case Type::Record:
1412  case Type::Enum:
1413    return CreateType(cast<TagType>(Ty), Unit);
1414  case Type::FunctionProto:
1415  case Type::FunctionNoProto:
1416    return CreateType(cast<FunctionType>(Ty), Unit);
1417  case Type::ConstantArray:
1418  case Type::VariableArray:
1419  case Type::IncompleteArray:
1420    return CreateType(cast<ArrayType>(Ty), Unit);
1421
1422  case Type::LValueReference:
1423    return CreateType(cast<LValueReferenceType>(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  case Type::RValueReference:
1440    // FIXME: Implement!
1441    Diag = "rvalue references";
1442    break;
1443  }
1444
1445  assert(Diag && "Fall through without a diagnostic?");
1446  unsigned DiagID = CGM.getDiags().getCustomDiagID(Diagnostic::Error,
1447                               "debug information for %0 is not yet supported");
1448  CGM.getDiags().Report(DiagID)
1449    << Diag;
1450  return llvm::DIType();
1451}
1452
1453/// CreateMemberType - Create new member and increase Offset by FType's size.
1454llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
1455                                           llvm::StringRef Name,
1456                                           uint64_t *Offset) {
1457  llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1458  uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
1459  unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
1460  llvm::DIType Ty = DBuilder.CreateMemberType(Name, Unit, 0,
1461                                              FieldSize, FieldAlign,
1462                                              *Offset, 0, FieldTy);
1463  *Offset += FieldSize;
1464  return Ty;
1465}
1466
1467/// EmitFunctionStart - Constructs the debug code for entering a function -
1468/// "llvm.dbg.func.start.".
1469void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
1470                                    llvm::Function *Fn,
1471                                    CGBuilderTy &Builder) {
1472
1473  llvm::StringRef Name;
1474  llvm::StringRef LinkageName;
1475
1476  FnBeginRegionCount.push_back(RegionStack.size());
1477
1478  const Decl *D = GD.getDecl();
1479  unsigned Flags = 0;
1480  llvm::DIFile Unit = getOrCreateFile(CurLoc);
1481  llvm::DIDescriptor FDContext(Unit);
1482  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1483    // If there is a DISubprogram for  this function available then use it.
1484    llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
1485      FI = SPCache.find(FD);
1486    if (FI != SPCache.end()) {
1487      llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(&*FI->second));
1488      if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
1489        llvm::MDNode *SPN = SP;
1490        RegionStack.push_back(SPN);
1491        RegionMap[D] = llvm::WeakVH(SP);
1492        return;
1493      }
1494    }
1495    Name = getFunctionName(FD);
1496    // Use mangled name as linkage name for c/c++ functions.
1497    LinkageName = CGM.getMangledName(GD);
1498    if (LinkageName == Name)
1499      LinkageName = llvm::StringRef();
1500    if (FD->hasPrototype())
1501      Flags |= llvm::DIDescriptor::FlagPrototyped;
1502    if (const NamespaceDecl *NSDecl =
1503        dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
1504      FDContext = getOrCreateNameSpace(NSDecl);
1505  } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
1506    Name = getObjCMethodName(OMD);
1507    Flags |= llvm::DIDescriptor::FlagPrototyped;
1508  } else {
1509    // Use llvm function name.
1510    Name = Fn->getName();
1511    Flags |= llvm::DIDescriptor::FlagPrototyped;
1512  }
1513  if (!Name.empty() && Name[0] == '\01')
1514    Name = Name.substr(1);
1515
1516  // It is expected that CurLoc is set before using EmitFunctionStart.
1517  // Usually, CurLoc points to the left bracket location of compound
1518  // statement representing function body.
1519  unsigned LineNo = getLineNumber(CurLoc);
1520  if (D->isImplicit())
1521    Flags |= llvm::DIDescriptor::FlagArtificial;
1522  llvm::DISubprogram SP =
1523    DBuilder.CreateFunction(FDContext, Name, LinkageName, Unit,
1524                            LineNo, getOrCreateType(FnType, Unit),
1525                            Fn->hasInternalLinkage(), true/*definition*/,
1526                            Flags, CGM.getLangOptions().Optimize, Fn);
1527
1528  // Push function on region stack.
1529  llvm::MDNode *SPN = SP;
1530  RegionStack.push_back(SPN);
1531  RegionMap[D] = llvm::WeakVH(SP);
1532
1533  // Clear stack used to keep track of #line directives.
1534  LineDirectiveFiles.clear();
1535}
1536
1537
1538void CGDebugInfo::EmitStopPoint(CGBuilderTy &Builder) {
1539  if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
1540
1541  // Don't bother if things are the same as last time.
1542  SourceManager &SM = CGM.getContext().getSourceManager();
1543  if (CurLoc == PrevLoc
1544       || (SM.getInstantiationLineNumber(CurLoc) ==
1545           SM.getInstantiationLineNumber(PrevLoc)
1546           && SM.isFromSameFile(CurLoc, PrevLoc)))
1547    // New Builder may not be in sync with CGDebugInfo.
1548    if (!Builder.getCurrentDebugLocation().isUnknown())
1549      return;
1550
1551  // Update last state.
1552  PrevLoc = CurLoc;
1553
1554  llvm::MDNode *Scope = RegionStack.back();
1555  Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(CurLoc),
1556                                                      getColumnNumber(CurLoc),
1557                                                      Scope));
1558}
1559
1560/// UpdateLineDirectiveRegion - Update region stack only if #line directive
1561/// has introduced scope change.
1562void CGDebugInfo::UpdateLineDirectiveRegion(CGBuilderTy &Builder) {
1563  if (CurLoc.isInvalid() || CurLoc.isMacroID() ||
1564      PrevLoc.isInvalid() || PrevLoc.isMacroID())
1565    return;
1566  SourceManager &SM = CGM.getContext().getSourceManager();
1567  PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
1568  PresumedLoc PPLoc = SM.getPresumedLoc(PrevLoc);
1569
1570  if (PCLoc.isInvalid() || PPLoc.isInvalid() ||
1571      !strcmp(PPLoc.getFilename(), PCLoc.getFilename()))
1572    return;
1573
1574  // If #line directive stack is empty then we are entering a new scope.
1575  if (LineDirectiveFiles.empty()) {
1576    EmitRegionStart(Builder);
1577    LineDirectiveFiles.push_back(PCLoc.getFilename());
1578    return;
1579  }
1580
1581  assert (RegionStack.size() >= LineDirectiveFiles.size()
1582          && "error handling  #line regions!");
1583
1584  bool SeenThisFile = false;
1585  // Chek if current file is already seen earlier.
1586  for(std::vector<const char *>::iterator I = LineDirectiveFiles.begin(),
1587        E = LineDirectiveFiles.end(); I != E; ++I)
1588    if (!strcmp(PCLoc.getFilename(), *I)) {
1589      SeenThisFile = true;
1590      break;
1591    }
1592
1593  // If #line for this file is seen earlier then pop out #line regions.
1594  if (SeenThisFile) {
1595    while (!LineDirectiveFiles.empty()) {
1596      const char *LastFile = LineDirectiveFiles.back();
1597      RegionStack.pop_back();
1598      LineDirectiveFiles.pop_back();
1599      if (!strcmp(PPLoc.getFilename(), LastFile))
1600        break;
1601    }
1602    return;
1603  }
1604
1605  // .. otherwise insert new #line region.
1606  EmitRegionStart(Builder);
1607  LineDirectiveFiles.push_back(PCLoc.getFilename());
1608
1609  return;
1610}
1611/// EmitRegionStart- Constructs the debug code for entering a declarative
1612/// region - "llvm.dbg.region.start.".
1613void CGDebugInfo::EmitRegionStart(CGBuilderTy &Builder) {
1614  llvm::DIDescriptor D =
1615    DBuilder.CreateLexicalBlock(RegionStack.empty() ?
1616                                llvm::DIDescriptor() :
1617                                llvm::DIDescriptor(RegionStack.back()),
1618                                getOrCreateFile(CurLoc),
1619                                getLineNumber(CurLoc),
1620                                getColumnNumber(CurLoc));
1621  llvm::MDNode *DN = D;
1622  RegionStack.push_back(DN);
1623}
1624
1625/// EmitRegionEnd - Constructs the debug code for exiting a declarative
1626/// region - "llvm.dbg.region.end."
1627void CGDebugInfo::EmitRegionEnd(CGBuilderTy &Builder) {
1628  assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
1629
1630  // Provide an region stop point.
1631  EmitStopPoint(Builder);
1632
1633  RegionStack.pop_back();
1634}
1635
1636/// EmitFunctionEnd - Constructs the debug code for exiting a function.
1637void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
1638  assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
1639  unsigned RCount = FnBeginRegionCount.back();
1640  assert(RCount <= RegionStack.size() && "Region stack mismatch");
1641
1642  // Pop all regions for this function.
1643  while (RegionStack.size() != RCount)
1644    EmitRegionEnd(Builder);
1645  FnBeginRegionCount.pop_back();
1646}
1647
1648// EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
1649// See BuildByRefType.
1650llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const ValueDecl *VD,
1651                                                       uint64_t *XOffset) {
1652
1653  llvm::SmallVector<llvm::Value *, 5> EltTys;
1654  QualType FType;
1655  uint64_t FieldSize, FieldOffset;
1656  unsigned FieldAlign;
1657
1658  llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
1659  QualType Type = VD->getType();
1660
1661  FieldOffset = 0;
1662  FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1663  EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
1664  EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
1665  FType = CGM.getContext().IntTy;
1666  EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
1667  EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
1668
1669  bool HasCopyAndDispose = CGM.BlockRequiresCopying(Type);
1670  if (HasCopyAndDispose) {
1671    FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1672    EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
1673                                      &FieldOffset));
1674    EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
1675                                      &FieldOffset));
1676  }
1677
1678  CharUnits Align = CGM.getContext().getDeclAlign(VD);
1679  if (Align > CharUnits::fromQuantity(
1680        CGM.getContext().Target.getPointerAlign(0) / 8)) {
1681    unsigned AlignedOffsetInBytes
1682      = llvm::RoundUpToAlignment(FieldOffset/8, Align.getQuantity());
1683    unsigned NumPaddingBytes
1684      = AlignedOffsetInBytes - FieldOffset/8;
1685
1686    if (NumPaddingBytes > 0) {
1687      llvm::APInt pad(32, NumPaddingBytes);
1688      FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
1689                                                    pad, ArrayType::Normal, 0);
1690      EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
1691    }
1692  }
1693
1694  FType = Type;
1695  llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1696  FieldSize = CGM.getContext().getTypeSize(FType);
1697  FieldAlign = Align.getQuantity()*8;
1698
1699  *XOffset = FieldOffset;
1700  FieldTy = DBuilder.CreateMemberType(VD->getName(), Unit,
1701                                      0, FieldSize, FieldAlign,
1702                                      FieldOffset, 0, FieldTy);
1703  EltTys.push_back(FieldTy);
1704  FieldOffset += FieldSize;
1705
1706  llvm::DIArray Elements =
1707    DBuilder.GetOrCreateArray(EltTys.data(), EltTys.size());
1708
1709  unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
1710
1711  return DBuilder.CreateStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
1712                                   Elements);
1713}
1714
1715/// EmitDeclare - Emit local variable declaration debug info.
1716void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
1717                              llvm::Value *Storage, CGBuilderTy &Builder) {
1718  assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
1719
1720  llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
1721  llvm::DIType Ty;
1722  uint64_t XOffset = 0;
1723  if (VD->hasAttr<BlocksAttr>())
1724    Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
1725  else
1726    Ty = getOrCreateType(VD->getType(), Unit);
1727
1728  // If there is not any debug info for type then do not emit debug info
1729  // for this variable.
1730  if (!Ty)
1731    return;
1732
1733  // Get location information.
1734  unsigned Line = getLineNumber(VD->getLocation());
1735  unsigned Column = getColumnNumber(VD->getLocation());
1736  unsigned Flags = 0;
1737  if (VD->isImplicit())
1738    Flags |= llvm::DIDescriptor::FlagArtificial;
1739  llvm::MDNode *Scope = RegionStack.back();
1740
1741  llvm::StringRef Name = VD->getName();
1742  if (!Name.empty()) {
1743    // Create the descriptor for the variable.
1744    llvm::DIVariable D =
1745      DBuilder.CreateLocalVariable(Tag, llvm::DIDescriptor(Scope),
1746                                   Name, Unit, Line, Ty,
1747                                   CGM.getLangOptions().Optimize, Flags);
1748
1749    // Insert an llvm.dbg.declare into the current block.
1750    llvm::Instruction *Call =
1751      DBuilder.InsertDeclare(Storage, D, Builder.GetInsertBlock());
1752
1753    Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
1754    return;
1755  }
1756
1757  // If VD is an anonymous union then Storage represents value for
1758  // all union fields.
1759  if (const RecordType *RT = dyn_cast<RecordType>(VD->getType()))
1760    if (const RecordDecl *RD = dyn_cast<RecordDecl>(RT->getDecl()))
1761      if (RD->isUnion()) {
1762        for (RecordDecl::field_iterator I = RD->field_begin(),
1763               E = RD->field_end();
1764             I != E; ++I) {
1765          FieldDecl *Field = *I;
1766          llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1767          llvm::StringRef FieldName = Field->getName();
1768
1769          // Ignore unnamed fields. Do not ignore unnamed records.
1770          if (FieldName.empty() && !isa<RecordType>(Field->getType()))
1771            continue;
1772
1773          // Use VarDecl's Tag, Scope and Line number.
1774          llvm::DIVariable D =
1775            DBuilder.CreateLocalVariable(Tag, llvm::DIDescriptor(Scope),
1776                                         FieldName, Unit, Line, FieldTy,
1777                                         CGM.getLangOptions().Optimize, Flags);
1778
1779          // Insert an llvm.dbg.declare into the current block.
1780          llvm::Instruction *Call =
1781            DBuilder.InsertDeclare(Storage, D, Builder.GetInsertBlock());
1782
1783          Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
1784        }
1785      }
1786}
1787
1788/// EmitDeclare - Emit local variable declaration debug info.
1789void CGDebugInfo::EmitDeclare(const BlockDeclRefExpr *BDRE, unsigned Tag,
1790                              llvm::Value *Storage, CGBuilderTy &Builder,
1791                              CodeGenFunction *CGF) {
1792  const ValueDecl *VD = BDRE->getDecl();
1793  assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
1794
1795  if (Builder.GetInsertBlock() == 0)
1796    return;
1797
1798  uint64_t XOffset = 0;
1799  llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
1800  llvm::DIType Ty;
1801  if (VD->hasAttr<BlocksAttr>())
1802    Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
1803  else
1804    Ty = getOrCreateType(VD->getType(), Unit);
1805
1806  // Get location information.
1807  unsigned Line = getLineNumber(VD->getLocation());
1808  unsigned Column = getColumnNumber(VD->getLocation());
1809
1810  CharUnits offset = CGF->BlockDecls[VD];
1811  llvm::SmallVector<llvm::Value *, 9> addr;
1812  const llvm::Type *Int64Ty = llvm::Type::getInt64Ty(CGM.getLLVMContext());
1813  addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpDeref));
1814  addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpPlus));
1815  addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
1816  if (BDRE->isByRef()) {
1817    addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpDeref));
1818    addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpPlus));
1819    // offset of __forwarding field
1820    offset = CharUnits::fromQuantity(CGF->LLVMPointerWidth/8);
1821    addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
1822    addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpDeref));
1823    addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpPlus));
1824    // offset of x field
1825    offset = CharUnits::fromQuantity(XOffset/8);
1826    addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
1827  }
1828
1829  // Create the descriptor for the variable.
1830  llvm::DIVariable D =
1831    DBuilder.CreateComplexVariable(Tag, llvm::DIDescriptor(RegionStack.back()),
1832                                   VD->getName(), Unit, Line, Ty,
1833                                   addr.data(), addr.size());
1834  // Insert an llvm.dbg.declare into the current block.
1835  llvm::Instruction *Call =
1836    DBuilder.InsertDeclare(Storage, D, Builder.GetInsertBlock());
1837
1838  llvm::MDNode *Scope = RegionStack.back();
1839  Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
1840}
1841
1842void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
1843                                            llvm::Value *Storage,
1844                                            CGBuilderTy &Builder) {
1845  EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, Builder);
1846}
1847
1848void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(
1849  const BlockDeclRefExpr *BDRE, llvm::Value *Storage, CGBuilderTy &Builder,
1850  CodeGenFunction *CGF) {
1851  EmitDeclare(BDRE, llvm::dwarf::DW_TAG_auto_variable, Storage, Builder, CGF);
1852}
1853
1854/// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
1855/// variable declaration.
1856void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
1857                                           CGBuilderTy &Builder) {
1858  EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, Builder);
1859}
1860
1861
1862
1863/// EmitGlobalVariable - Emit information about a global variable.
1864void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
1865                                     const VarDecl *D) {
1866
1867  // Create global variable debug descriptor.
1868  llvm::DIFile Unit = getOrCreateFile(D->getLocation());
1869  unsigned LineNo = getLineNumber(D->getLocation());
1870
1871  QualType T = D->getType();
1872  if (T->isIncompleteArrayType()) {
1873
1874    // CodeGen turns int[] into int[1] so we'll do the same here.
1875    llvm::APSInt ConstVal(32);
1876
1877    ConstVal = 1;
1878    QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
1879
1880    T = CGM.getContext().getConstantArrayType(ET, ConstVal,
1881                                           ArrayType::Normal, 0);
1882  }
1883  llvm::StringRef DeclName = D->getName();
1884  llvm::StringRef LinkageName;
1885  if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext()))
1886    LinkageName = Var->getName();
1887  if (LinkageName == DeclName)
1888    LinkageName = llvm::StringRef();
1889  llvm::DIDescriptor DContext =
1890    getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
1891  DBuilder.CreateStaticVariable(DContext, DeclName, LinkageName,
1892                                Unit, LineNo, getOrCreateType(T, Unit),
1893                                Var->hasInternalLinkage(), Var);
1894}
1895
1896/// EmitGlobalVariable - Emit information about an objective-c interface.
1897void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
1898                                     ObjCInterfaceDecl *ID) {
1899  // Create global variable debug descriptor.
1900  llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
1901  unsigned LineNo = getLineNumber(ID->getLocation());
1902
1903  llvm::StringRef Name = ID->getName();
1904
1905  QualType T = CGM.getContext().getObjCInterfaceType(ID);
1906  if (T->isIncompleteArrayType()) {
1907
1908    // CodeGen turns int[] into int[1] so we'll do the same here.
1909    llvm::APSInt ConstVal(32);
1910
1911    ConstVal = 1;
1912    QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
1913
1914    T = CGM.getContext().getConstantArrayType(ET, ConstVal,
1915                                           ArrayType::Normal, 0);
1916  }
1917
1918  DBuilder.CreateGlobalVariable(Name, Unit, LineNo,
1919                                getOrCreateType(T, Unit),
1920                                Var->hasInternalLinkage(), Var);
1921}
1922
1923/// EmitGlobalVariable - Emit global variable's debug info.
1924void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
1925                                     llvm::Constant *Init) {
1926  // Create the descriptor for the variable.
1927  llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
1928  llvm::StringRef Name = VD->getName();
1929  llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
1930  if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
1931    if (const EnumDecl *ED = dyn_cast<EnumDecl>(ECD->getDeclContext()))
1932      Ty = CreateEnumType(ED, Unit);
1933  }
1934  // Do not use DIGlobalVariable for enums.
1935  if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
1936    return;
1937  DBuilder.CreateStaticVariable(Unit, Name, Name, Unit,
1938                                getLineNumber(VD->getLocation()),
1939                                Ty, true, Init);
1940}
1941
1942/// getOrCreateNamesSpace - Return namespace descriptor for the given
1943/// namespace decl.
1944llvm::DINameSpace
1945CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
1946  llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
1947    NameSpaceCache.find(NSDecl);
1948  if (I != NameSpaceCache.end())
1949    return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
1950
1951  unsigned LineNo = getLineNumber(NSDecl->getLocation());
1952  llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
1953  llvm::DIDescriptor Context =
1954    getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
1955  llvm::DINameSpace NS =
1956    DBuilder.CreateNameSpace(Context, NSDecl->getName(), FileD, LineNo);
1957  NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
1958  return NS;
1959}
1960