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