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