CGDebugInfo.cpp revision 1513eb9284c23acfd19cf742b95996fbb11ca741
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 "CGBlocks.h"
16#include "CGObjCRuntime.h"
17#include "CodeGenFunction.h"
18#include "CodeGenModule.h"
19#include "clang/AST/ASTContext.h"
20#include "clang/AST/DeclFriend.h"
21#include "clang/AST/DeclObjC.h"
22#include "clang/AST/DeclTemplate.h"
23#include "clang/AST/Expr.h"
24#include "clang/AST/RecordLayout.h"
25#include "clang/Basic/FileManager.h"
26#include "clang/Basic/SourceManager.h"
27#include "clang/Basic/Version.h"
28#include "clang/Frontend/CodeGenOptions.h"
29#include "llvm/ADT/SmallVector.h"
30#include "llvm/ADT/StringExtras.h"
31#include "llvm/IR/Constants.h"
32#include "llvm/IR/DataLayout.h"
33#include "llvm/IR/DerivedTypes.h"
34#include "llvm/IR/Instructions.h"
35#include "llvm/IR/Intrinsics.h"
36#include "llvm/IR/Module.h"
37#include "llvm/Support/Dwarf.h"
38#include "llvm/Support/FileSystem.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(LexicalBlockStack.empty() &&
50         "Region stack mismatch, stack not empty!");
51}
52
53void CGDebugInfo::setLocation(SourceLocation Loc) {
54  // If the new location isn't valid return.
55  if (!Loc.isValid()) return;
56
57  CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc);
58
59  // If we've changed files in the middle of a lexical scope go ahead
60  // and create a new lexical scope with file node if it's different
61  // from the one in the scope.
62  if (LexicalBlockStack.empty()) return;
63
64  SourceManager &SM = CGM.getContext().getSourceManager();
65  PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
66  PresumedLoc PPLoc = SM.getPresumedLoc(PrevLoc);
67
68  if (PCLoc.isInvalid() || PPLoc.isInvalid() ||
69      !strcmp(PPLoc.getFilename(), PCLoc.getFilename()))
70    return;
71
72  llvm::MDNode *LB = LexicalBlockStack.back();
73  llvm::DIScope Scope = llvm::DIScope(LB);
74  if (Scope.isLexicalBlockFile()) {
75    llvm::DILexicalBlockFile LBF = llvm::DILexicalBlockFile(LB);
76    llvm::DIDescriptor D
77      = DBuilder.createLexicalBlockFile(LBF.getScope(),
78                                        getOrCreateFile(CurLoc));
79    llvm::MDNode *N = D;
80    LexicalBlockStack.pop_back();
81    LexicalBlockStack.push_back(N);
82  } else if (Scope.isLexicalBlock() || Scope.isSubprogram()) {
83    llvm::DIDescriptor D
84      = DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc));
85    llvm::MDNode *N = D;
86    LexicalBlockStack.pop_back();
87    LexicalBlockStack.push_back(N);
88  }
89}
90
91/// getContextDescriptor - Get context info for the decl.
92llvm::DIDescriptor CGDebugInfo::getContextDescriptor(const Decl *Context) {
93  if (!Context)
94    return TheCU;
95
96  llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
97    I = RegionMap.find(Context);
98  if (I != RegionMap.end()) {
99    llvm::Value *V = I->second;
100    return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
101  }
102
103  // Check namespace.
104  if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
105    return llvm::DIDescriptor(getOrCreateNameSpace(NSDecl));
106
107  if (const RecordDecl *RDecl = dyn_cast<RecordDecl>(Context)) {
108    if (!RDecl->isDependentType()) {
109      llvm::DIType Ty = getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
110                                        getOrCreateMainFile());
111      return llvm::DIDescriptor(Ty);
112    }
113  }
114
115  if (!LexicalBlockStack.empty())
116    return llvm::DIDescriptor(LexicalBlockStack.back());
117  return TheCU;
118}
119
120/// getFunctionName - Get function name for the given FunctionDecl. If the
121/// name is constructred on demand (e.g. C++ destructor) then the name
122/// is stored on the side.
123StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
124  assert (FD && "Invalid FunctionDecl!");
125  IdentifierInfo *FII = FD->getIdentifier();
126  FunctionTemplateSpecializationInfo *Info
127    = FD->getTemplateSpecializationInfo();
128  if (!Info && FII)
129    return FII->getName();
130
131  // Otherwise construct human readable name for debug info.
132  std::string NS = FD->getNameAsString();
133
134  // Add any template specialization args.
135  if (Info) {
136    const TemplateArgumentList *TArgs = Info->TemplateArguments;
137    const TemplateArgument *Args = TArgs->data();
138    unsigned NumArgs = TArgs->size();
139    PrintingPolicy Policy(CGM.getLangOpts());
140    NS += TemplateSpecializationType::PrintTemplateArgumentList(Args,
141                                                                NumArgs,
142                                                                Policy);
143  }
144
145  // Copy this name on the side and use its reference.
146  char *StrPtr = DebugInfoNames.Allocate<char>(NS.length());
147  memcpy(StrPtr, NS.data(), NS.length());
148  return StringRef(StrPtr, NS.length());
149}
150
151StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
152  SmallString<256> MethodName;
153  llvm::raw_svector_ostream OS(MethodName);
154  OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
155  const DeclContext *DC = OMD->getDeclContext();
156  if (const ObjCImplementationDecl *OID =
157      dyn_cast<const ObjCImplementationDecl>(DC)) {
158     OS << OID->getName();
159  } else if (const ObjCInterfaceDecl *OID =
160             dyn_cast<const ObjCInterfaceDecl>(DC)) {
161      OS << OID->getName();
162  } else if (const ObjCCategoryImplDecl *OCD =
163             dyn_cast<const ObjCCategoryImplDecl>(DC)){
164      OS << ((const NamedDecl *)OCD)->getIdentifier()->getNameStart() << '(' <<
165          OCD->getIdentifier()->getNameStart() << ')';
166  }
167  OS << ' ' << OMD->getSelector().getAsString() << ']';
168
169  char *StrPtr = DebugInfoNames.Allocate<char>(OS.tell());
170  memcpy(StrPtr, MethodName.begin(), OS.tell());
171  return StringRef(StrPtr, OS.tell());
172}
173
174/// getSelectorName - Return selector name. This is used for debugging
175/// info.
176StringRef CGDebugInfo::getSelectorName(Selector S) {
177  const std::string &SName = S.getAsString();
178  char *StrPtr = DebugInfoNames.Allocate<char>(SName.size());
179  memcpy(StrPtr, SName.data(), SName.size());
180  return StringRef(StrPtr, SName.size());
181}
182
183/// getClassName - Get class name including template argument list.
184StringRef
185CGDebugInfo::getClassName(const RecordDecl *RD) {
186  const ClassTemplateSpecializationDecl *Spec
187    = dyn_cast<ClassTemplateSpecializationDecl>(RD);
188  if (!Spec)
189    return RD->getName();
190
191  const TemplateArgument *Args;
192  unsigned NumArgs;
193  if (TypeSourceInfo *TAW = Spec->getTypeAsWritten()) {
194    const TemplateSpecializationType *TST =
195      cast<TemplateSpecializationType>(TAW->getType());
196    Args = TST->getArgs();
197    NumArgs = TST->getNumArgs();
198  } else {
199    const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
200    Args = TemplateArgs.data();
201    NumArgs = TemplateArgs.size();
202  }
203  StringRef Name = RD->getIdentifier()->getName();
204  PrintingPolicy Policy(CGM.getLangOpts());
205  std::string TemplateArgList =
206    TemplateSpecializationType::PrintTemplateArgumentList(Args, NumArgs, Policy);
207
208  // Copy this name on the side and use its reference.
209  size_t Length = Name.size() + TemplateArgList.size();
210  char *StrPtr = DebugInfoNames.Allocate<char>(Length);
211  memcpy(StrPtr, Name.data(), Name.size());
212  memcpy(StrPtr + Name.size(), TemplateArgList.data(), TemplateArgList.size());
213  return StringRef(StrPtr, Length);
214}
215
216/// getOrCreateFile - Get the file debug info descriptor for the input location.
217llvm::DIFile CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
218  if (!Loc.isValid())
219    // If Location is not valid then use main input file.
220    return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
221
222  SourceManager &SM = CGM.getContext().getSourceManager();
223  PresumedLoc PLoc = SM.getPresumedLoc(Loc);
224
225  if (PLoc.isInvalid() || StringRef(PLoc.getFilename()).empty())
226    // If the location is not valid then use main input file.
227    return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
228
229  // Cache the results.
230  const char *fname = PLoc.getFilename();
231  llvm::DenseMap<const char *, llvm::WeakVH>::iterator it =
232    DIFileCache.find(fname);
233
234  if (it != DIFileCache.end()) {
235    // Verify that the information still exists.
236    if (llvm::Value *V = it->second)
237      return llvm::DIFile(cast<llvm::MDNode>(V));
238  }
239
240  llvm::DIFile F = DBuilder.createFile(PLoc.getFilename(), getCurrentDirname());
241
242  DIFileCache[fname] = F;
243  return F;
244}
245
246/// getOrCreateMainFile - Get the file info for main compile unit.
247llvm::DIFile CGDebugInfo::getOrCreateMainFile() {
248  return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
249}
250
251/// getLineNumber - Get line number for the location. If location is invalid
252/// then use current location.
253unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
254  if (Loc.isInvalid() && CurLoc.isInvalid())
255    return 0;
256  SourceManager &SM = CGM.getContext().getSourceManager();
257  PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
258  return PLoc.isValid()? PLoc.getLine() : 0;
259}
260
261/// getColumnNumber - Get column number for the location.
262unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc) {
263  // We may not want column information at all.
264  if (!CGM.getCodeGenOpts().DebugColumnInfo)
265    return 0;
266
267  // If the location is invalid then use the current column.
268  if (Loc.isInvalid() && CurLoc.isInvalid())
269    return 0;
270  SourceManager &SM = CGM.getContext().getSourceManager();
271  PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
272  return PLoc.isValid()? PLoc.getColumn() : 0;
273}
274
275StringRef CGDebugInfo::getCurrentDirname() {
276  if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
277    return CGM.getCodeGenOpts().DebugCompilationDir;
278
279  if (!CWDName.empty())
280    return CWDName;
281  SmallString<256> CWD;
282  llvm::sys::fs::current_path(CWD);
283  char *CompDirnamePtr = DebugInfoNames.Allocate<char>(CWD.size());
284  memcpy(CompDirnamePtr, CWD.data(), CWD.size());
285  return CWDName = StringRef(CompDirnamePtr, CWD.size());
286}
287
288/// CreateCompileUnit - Create new compile unit.
289void CGDebugInfo::CreateCompileUnit() {
290
291  // Get absolute path name.
292  SourceManager &SM = CGM.getContext().getSourceManager();
293  std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
294  if (MainFileName.empty())
295    MainFileName = "<unknown>";
296
297  // The main file name provided via the "-main-file-name" option contains just
298  // the file name itself with no path information. This file name may have had
299  // a relative path, so we look into the actual file entry for the main
300  // file to determine the real absolute path for the file.
301  std::string MainFileDir;
302  if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
303    MainFileDir = MainFile->getDir()->getName();
304    if (MainFileDir != ".")
305      MainFileName = MainFileDir + "/" + MainFileName;
306  }
307
308  // Save filename string.
309  char *FilenamePtr = DebugInfoNames.Allocate<char>(MainFileName.length());
310  memcpy(FilenamePtr, MainFileName.c_str(), MainFileName.length());
311  StringRef Filename(FilenamePtr, MainFileName.length());
312
313  unsigned LangTag;
314  const LangOptions &LO = CGM.getLangOpts();
315  if (LO.CPlusPlus) {
316    if (LO.ObjC1)
317      LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
318    else
319      LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
320  } else if (LO.ObjC1) {
321    LangTag = llvm::dwarf::DW_LANG_ObjC;
322  } else if (LO.C99) {
323    LangTag = llvm::dwarf::DW_LANG_C99;
324  } else {
325    LangTag = llvm::dwarf::DW_LANG_C89;
326  }
327
328  std::string Producer = getClangFullVersion();
329
330  // Figure out which version of the ObjC runtime we have.
331  unsigned RuntimeVers = 0;
332  if (LO.ObjC1)
333    RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
334
335  // Create new compile unit.
336  DBuilder.createCompileUnit(
337    LangTag, Filename, getCurrentDirname(),
338    Producer,
339    LO.Optimize, CGM.getCodeGenOpts().DwarfDebugFlags, RuntimeVers);
340  // FIXME - Eliminate TheCU.
341  TheCU = llvm::DICompileUnit(DBuilder.getCU());
342}
343
344/// CreateType - Get the Basic type from the cache or create a new
345/// one if necessary.
346llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT) {
347  unsigned Encoding = 0;
348  StringRef BTName;
349  switch (BT->getKind()) {
350#define BUILTIN_TYPE(Id, SingletonId)
351#define PLACEHOLDER_TYPE(Id, SingletonId) \
352  case BuiltinType::Id:
353#include "clang/AST/BuiltinTypes.def"
354  case BuiltinType::Dependent:
355    llvm_unreachable("Unexpected builtin type");
356  case BuiltinType::NullPtr:
357    return DBuilder.
358      createNullPtrType(BT->getName(CGM.getLangOpts()));
359  case BuiltinType::Void:
360    return llvm::DIType();
361  case BuiltinType::ObjCClass:
362    if (ClassTy.Verify())
363      return ClassTy;
364    ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
365                                         "objc_class", TheCU,
366                                         getOrCreateMainFile(), 0);
367    return ClassTy;
368  case BuiltinType::ObjCId: {
369    // typedef struct objc_class *Class;
370    // typedef struct objc_object {
371    //  Class isa;
372    // } *id;
373
374    if (ObjTy.Verify())
375      return ObjTy;
376
377    if (!ClassTy.Verify())
378      ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
379                                           "objc_class", TheCU,
380                                           getOrCreateMainFile(), 0);
381
382    unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
383
384    llvm::DIType ISATy = DBuilder.createPointerType(ClassTy, Size);
385
386    llvm::DIType FwdTy =  DBuilder.createStructType(TheCU, "objc_object",
387                                                    getOrCreateMainFile(),
388                                                    0, 0, 0, 0,
389                                                    llvm::DIArray());
390
391    llvm::TrackingVH<llvm::MDNode> ObjNode(FwdTy);
392    SmallVector<llvm::Value *, 1> EltTys;
393    llvm::DIType FieldTy =
394      DBuilder.createMemberType(llvm::DIDescriptor(ObjNode), "isa",
395                                getOrCreateMainFile(), 0, Size,
396                                0, 0, 0, ISATy);
397    EltTys.push_back(FieldTy);
398    llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
399
400    ObjNode->replaceOperandWith(10, Elements);
401    ObjTy = llvm::DIType(ObjNode);
402    return ObjTy;
403  }
404  case BuiltinType::ObjCSel: {
405    if (SelTy.Verify())
406      return SelTy;
407    SelTy =
408      DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
409                                 "objc_selector", TheCU, getOrCreateMainFile(),
410                                 0);
411    return SelTy;
412  }
413
414  case BuiltinType::OCLImage1d:
415    return getOrCreateStructPtrType("opencl_image1d_t",
416                                    OCLImage1dDITy);
417  case BuiltinType::OCLImage1dArray:
418    return getOrCreateStructPtrType("opencl_image1d_array_t",
419                                    OCLImage1dArrayDITy);
420  case BuiltinType::OCLImage1dBuffer:
421    return getOrCreateStructPtrType("opencl_image1d_buffer_t",
422                                    OCLImage1dBufferDITy);
423  case BuiltinType::OCLImage2d:
424    return getOrCreateStructPtrType("opencl_image2d_t",
425                                    OCLImage2dDITy);
426  case BuiltinType::OCLImage2dArray:
427    return getOrCreateStructPtrType("opencl_image2d_array_t",
428                                    OCLImage2dArrayDITy);
429  case BuiltinType::OCLImage3d:
430    return getOrCreateStructPtrType("opencl_image3d_t",
431                                    OCLImage3dDITy);
432  case BuiltinType::OCLEvent:
433    return getOrCreateStructPtrType("opencl_event_t",
434                                    OCLEventDITy);
435
436  case BuiltinType::UChar:
437  case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break;
438  case BuiltinType::Char_S:
439  case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break;
440  case BuiltinType::Char16:
441  case BuiltinType::Char32: Encoding = llvm::dwarf::DW_ATE_UTF; break;
442  case BuiltinType::UShort:
443  case BuiltinType::UInt:
444  case BuiltinType::UInt128:
445  case BuiltinType::ULong:
446  case BuiltinType::WChar_U:
447  case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break;
448  case BuiltinType::Short:
449  case BuiltinType::Int:
450  case BuiltinType::Int128:
451  case BuiltinType::Long:
452  case BuiltinType::WChar_S:
453  case BuiltinType::LongLong:  Encoding = llvm::dwarf::DW_ATE_signed; break;
454  case BuiltinType::Bool:      Encoding = llvm::dwarf::DW_ATE_boolean; break;
455  case BuiltinType::Half:
456  case BuiltinType::Float:
457  case BuiltinType::LongDouble:
458  case BuiltinType::Double:    Encoding = llvm::dwarf::DW_ATE_float; break;
459  }
460
461  switch (BT->getKind()) {
462  case BuiltinType::Long:      BTName = "long int"; break;
463  case BuiltinType::LongLong:  BTName = "long long int"; break;
464  case BuiltinType::ULong:     BTName = "long unsigned int"; break;
465  case BuiltinType::ULongLong: BTName = "long long unsigned int"; break;
466  default:
467    BTName = BT->getName(CGM.getLangOpts());
468    break;
469  }
470  // Bit size, align and offset of the type.
471  uint64_t Size = CGM.getContext().getTypeSize(BT);
472  uint64_t Align = CGM.getContext().getTypeAlign(BT);
473  llvm::DIType DbgTy =
474    DBuilder.createBasicType(BTName, Size, Align, Encoding);
475  return DbgTy;
476}
477
478llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty) {
479  // Bit size, align and offset of the type.
480  unsigned Encoding = llvm::dwarf::DW_ATE_complex_float;
481  if (Ty->isComplexIntegerType())
482    Encoding = llvm::dwarf::DW_ATE_lo_user;
483
484  uint64_t Size = CGM.getContext().getTypeSize(Ty);
485  uint64_t Align = CGM.getContext().getTypeAlign(Ty);
486  llvm::DIType DbgTy =
487    DBuilder.createBasicType("complex", Size, Align, Encoding);
488
489  return DbgTy;
490}
491
492/// CreateCVRType - Get the qualified type from the cache or create
493/// a new one if necessary.
494llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit) {
495  QualifierCollector Qc;
496  const Type *T = Qc.strip(Ty);
497
498  // Ignore these qualifiers for now.
499  Qc.removeObjCGCAttr();
500  Qc.removeAddressSpace();
501  Qc.removeObjCLifetime();
502
503  // We will create one Derived type for one qualifier and recurse to handle any
504  // additional ones.
505  unsigned Tag;
506  if (Qc.hasConst()) {
507    Tag = llvm::dwarf::DW_TAG_const_type;
508    Qc.removeConst();
509  } else if (Qc.hasVolatile()) {
510    Tag = llvm::dwarf::DW_TAG_volatile_type;
511    Qc.removeVolatile();
512  } else if (Qc.hasRestrict()) {
513    Tag = llvm::dwarf::DW_TAG_restrict_type;
514    Qc.removeRestrict();
515  } else {
516    assert(Qc.empty() && "Unknown type qualifier for debug info");
517    return getOrCreateType(QualType(T, 0), Unit);
518  }
519
520  llvm::DIType FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
521
522  // No need to fill in the Name, Line, Size, Alignment, Offset in case of
523  // CVR derived types.
524  llvm::DIType DbgTy = DBuilder.createQualifiedType(Tag, FromTy);
525
526  return DbgTy;
527}
528
529llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
530                                     llvm::DIFile Unit) {
531  llvm::DIType DbgTy =
532    CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
533                          Ty->getPointeeType(), Unit);
534  return DbgTy;
535}
536
537llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
538                                     llvm::DIFile Unit) {
539  return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
540                               Ty->getPointeeType(), Unit);
541}
542
543// Creates a forward declaration for a RecordDecl in the given context.
544llvm::DIType CGDebugInfo::createRecordFwdDecl(const RecordDecl *RD,
545                                              llvm::DIDescriptor Ctx) {
546  llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
547  unsigned Line = getLineNumber(RD->getLocation());
548  StringRef RDName = getClassName(RD);
549
550  unsigned Tag = 0;
551  if (RD->isStruct() || RD->isInterface())
552    Tag = llvm::dwarf::DW_TAG_structure_type;
553  else if (RD->isUnion())
554    Tag = llvm::dwarf::DW_TAG_union_type;
555  else {
556    assert(RD->isClass());
557    Tag = llvm::dwarf::DW_TAG_class_type;
558  }
559
560  // Create the type.
561  return DBuilder.createForwardDecl(Tag, RDName, Ctx, DefUnit, Line);
562}
563
564// Walk up the context chain and create forward decls for record decls,
565// and normal descriptors for namespaces.
566llvm::DIDescriptor CGDebugInfo::createContextChain(const Decl *Context) {
567  if (!Context)
568    return TheCU;
569
570  // See if we already have the parent.
571  llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
572    I = RegionMap.find(Context);
573  if (I != RegionMap.end()) {
574    llvm::Value *V = I->second;
575    return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
576  }
577
578  // Check namespace.
579  if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
580    return llvm::DIDescriptor(getOrCreateNameSpace(NSDecl));
581
582  if (const RecordDecl *RD = dyn_cast<RecordDecl>(Context)) {
583    if (!RD->isDependentType()) {
584      llvm::DIType Ty = getOrCreateLimitedType(CGM.getContext().getTypeDeclType(RD),
585					       getOrCreateMainFile());
586      return llvm::DIDescriptor(Ty);
587    }
588  }
589  return TheCU;
590}
591
592/// CreatePointeeType - Create Pointee type. If Pointee is a record
593/// then emit record's fwd if debug info size reduction is enabled.
594llvm::DIType CGDebugInfo::CreatePointeeType(QualType PointeeTy,
595                                            llvm::DIFile Unit) {
596  if (CGM.getCodeGenOpts().getDebugInfo() != CodeGenOptions::LimitedDebugInfo)
597    return getOrCreateType(PointeeTy, Unit);
598
599  // Limit debug info for the pointee type.
600
601  // If we have an existing type, use that, it's still smaller than creating
602  // a new type.
603  llvm::DIType Ty = getTypeOrNull(PointeeTy);
604  if (Ty.Verify()) return Ty;
605
606  // Handle qualifiers.
607  if (PointeeTy.hasLocalQualifiers())
608    return CreateQualifiedType(PointeeTy, Unit);
609
610  if (const RecordType *RTy = dyn_cast<RecordType>(PointeeTy)) {
611    RecordDecl *RD = RTy->getDecl();
612    llvm::DIDescriptor FDContext =
613      getContextDescriptor(cast<Decl>(RD->getDeclContext()));
614    llvm::DIType RetTy = createRecordFwdDecl(RD, FDContext);
615    TypeCache[QualType(RTy, 0).getAsOpaquePtr()] = RetTy;
616    return RetTy;
617  }
618  return getOrCreateType(PointeeTy, Unit);
619
620}
621
622llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag,
623                                                const Type *Ty,
624                                                QualType PointeeTy,
625                                                llvm::DIFile Unit) {
626  if (Tag == llvm::dwarf::DW_TAG_reference_type ||
627      Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
628    return DBuilder.createReferenceType(Tag,
629                                        CreatePointeeType(PointeeTy, Unit));
630
631  // Bit size, align and offset of the type.
632  // Size is always the size of a pointer. We can't use getTypeSize here
633  // because that does not return the correct value for references.
634  unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
635  uint64_t Size = CGM.getContext().getTargetInfo().getPointerWidth(AS);
636  uint64_t Align = CGM.getContext().getTypeAlign(Ty);
637
638  return DBuilder.createPointerType(CreatePointeeType(PointeeTy, Unit),
639                                    Size, Align);
640}
641
642llvm::DIType CGDebugInfo::getOrCreateStructPtrType(StringRef Name, llvm::DIType &Cache) {
643    if (Cache.Verify())
644      return Cache;
645    Cache =
646      DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
647                                 Name, TheCU, getOrCreateMainFile(),
648                                 0);
649    unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
650    Cache = DBuilder.createPointerType(Cache, Size);
651    return Cache;
652}
653
654llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
655                                     llvm::DIFile Unit) {
656  if (BlockLiteralGenericSet)
657    return BlockLiteralGeneric;
658
659  SmallVector<llvm::Value *, 8> EltTys;
660  llvm::DIType FieldTy;
661  QualType FType;
662  uint64_t FieldSize, FieldOffset;
663  unsigned FieldAlign;
664  llvm::DIArray Elements;
665  llvm::DIType EltTy, DescTy;
666
667  FieldOffset = 0;
668  FType = CGM.getContext().UnsignedLongTy;
669  EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
670  EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
671
672  Elements = DBuilder.getOrCreateArray(EltTys);
673  EltTys.clear();
674
675  unsigned Flags = llvm::DIDescriptor::FlagAppleBlock;
676  unsigned LineNo = getLineNumber(CurLoc);
677
678  EltTy = DBuilder.createStructType(Unit, "__block_descriptor",
679                                    Unit, LineNo, FieldOffset, 0,
680                                    Flags, Elements);
681
682  // Bit size, align and offset of the type.
683  uint64_t Size = CGM.getContext().getTypeSize(Ty);
684
685  DescTy = DBuilder.createPointerType(EltTy, Size);
686
687  FieldOffset = 0;
688  FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
689  EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
690  FType = CGM.getContext().IntTy;
691  EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
692  EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
693  FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
694  EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
695
696  FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
697  FieldTy = DescTy;
698  FieldSize = CGM.getContext().getTypeSize(Ty);
699  FieldAlign = CGM.getContext().getTypeAlign(Ty);
700  FieldTy = DBuilder.createMemberType(Unit, "__descriptor", Unit,
701                                      LineNo, FieldSize, FieldAlign,
702                                      FieldOffset, 0, FieldTy);
703  EltTys.push_back(FieldTy);
704
705  FieldOffset += FieldSize;
706  Elements = DBuilder.getOrCreateArray(EltTys);
707
708  EltTy = DBuilder.createStructType(Unit, "__block_literal_generic",
709                                    Unit, LineNo, FieldOffset, 0,
710                                    Flags, Elements);
711
712  BlockLiteralGenericSet = true;
713  BlockLiteralGeneric = DBuilder.createPointerType(EltTy, Size);
714  return BlockLiteralGeneric;
715}
716
717llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty, llvm::DIFile Unit) {
718  // Typedefs are derived from some other type.  If we have a typedef of a
719  // typedef, make sure to emit the whole chain.
720  llvm::DIType Src = getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
721  if (!Src.Verify())
722    return llvm::DIType();
723  // We don't set size information, but do specify where the typedef was
724  // declared.
725  unsigned Line = getLineNumber(Ty->getDecl()->getLocation());
726  const TypedefNameDecl *TyDecl = Ty->getDecl();
727
728  llvm::DIDescriptor TypedefContext =
729    getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext()));
730
731  return
732    DBuilder.createTypedef(Src, TyDecl->getName(), Unit, Line, TypedefContext);
733}
734
735llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
736                                     llvm::DIFile Unit) {
737  SmallVector<llvm::Value *, 16> EltTys;
738
739  // Add the result type at least.
740  EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit));
741
742  // Set up remainder of arguments if there is a prototype.
743  // FIXME: IF NOT, HOW IS THIS REPRESENTED?  llvm-gcc doesn't represent '...'!
744  if (isa<FunctionNoProtoType>(Ty))
745    EltTys.push_back(DBuilder.createUnspecifiedParameter());
746  else if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Ty)) {
747    for (unsigned i = 0, e = FPT->getNumArgs(); i != e; ++i)
748      EltTys.push_back(getOrCreateType(FPT->getArgType(i), Unit));
749  }
750
751  llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
752  return DBuilder.createSubroutineType(Unit, EltTypeArray);
753}
754
755
756llvm::DIType CGDebugInfo::createFieldType(StringRef name,
757                                          QualType type,
758                                          uint64_t sizeInBitsOverride,
759                                          SourceLocation loc,
760                                          AccessSpecifier AS,
761                                          uint64_t offsetInBits,
762                                          llvm::DIFile tunit,
763                                          llvm::DIDescriptor scope) {
764  llvm::DIType debugType = getOrCreateType(type, tunit);
765
766  // Get the location for the field.
767  llvm::DIFile file = getOrCreateFile(loc);
768  unsigned line = getLineNumber(loc);
769
770  uint64_t sizeInBits = 0;
771  unsigned alignInBits = 0;
772  if (!type->isIncompleteArrayType()) {
773    llvm::tie(sizeInBits, alignInBits) = CGM.getContext().getTypeInfo(type);
774
775    if (sizeInBitsOverride)
776      sizeInBits = sizeInBitsOverride;
777  }
778
779  unsigned flags = 0;
780  if (AS == clang::AS_private)
781    flags |= llvm::DIDescriptor::FlagPrivate;
782  else if (AS == clang::AS_protected)
783    flags |= llvm::DIDescriptor::FlagProtected;
784
785  return DBuilder.createMemberType(scope, name, file, line, sizeInBits,
786                                   alignInBits, offsetInBits, flags, debugType);
787}
788
789/// CollectRecordLambdaFields - Helper for CollectRecordFields.
790void CGDebugInfo::
791CollectRecordLambdaFields(const CXXRecordDecl *CXXDecl,
792                          SmallVectorImpl<llvm::Value *> &elements,
793                          llvm::DIType RecordTy) {
794  // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
795  // has the name and the location of the variable so we should iterate over
796  // both concurrently.
797  const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
798  RecordDecl::field_iterator Field = CXXDecl->field_begin();
799  unsigned fieldno = 0;
800  for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
801         E = CXXDecl->captures_end(); I != E; ++I, ++Field, ++fieldno) {
802    const LambdaExpr::Capture C = *I;
803    if (C.capturesVariable()) {
804      VarDecl *V = C.getCapturedVar();
805      llvm::DIFile VUnit = getOrCreateFile(C.getLocation());
806      StringRef VName = V->getName();
807      uint64_t SizeInBitsOverride = 0;
808      if (Field->isBitField()) {
809        SizeInBitsOverride = Field->getBitWidthValue(CGM.getContext());
810        assert(SizeInBitsOverride && "found named 0-width bitfield");
811      }
812      llvm::DIType fieldType
813        = createFieldType(VName, Field->getType(), SizeInBitsOverride,
814                          C.getLocation(), Field->getAccess(),
815                          layout.getFieldOffset(fieldno), VUnit, RecordTy);
816      elements.push_back(fieldType);
817    } else {
818      // TODO: Need to handle 'this' in some way by probably renaming the
819      // this of the lambda class and having a field member of 'this' or
820      // by using AT_object_pointer for the function and having that be
821      // used as 'this' for semantic references.
822      assert(C.capturesThis() && "Field that isn't captured and isn't this?");
823      FieldDecl *f = *Field;
824      llvm::DIFile VUnit = getOrCreateFile(f->getLocation());
825      QualType type = f->getType();
826      llvm::DIType fieldType
827        = createFieldType("this", type, 0, f->getLocation(), f->getAccess(),
828                          layout.getFieldOffset(fieldno), VUnit, RecordTy);
829
830      elements.push_back(fieldType);
831    }
832  }
833}
834
835/// CollectRecordStaticField - Helper for CollectRecordFields.
836void CGDebugInfo::
837CollectRecordStaticField(const VarDecl *Var,
838                         SmallVectorImpl<llvm::Value *> &elements,
839                         llvm::DIType RecordTy) {
840  // Create the descriptor for the static variable, with or without
841  // constant initializers.
842  llvm::DIFile VUnit = getOrCreateFile(Var->getLocation());
843  llvm::DIType VTy = getOrCreateType(Var->getType(), VUnit);
844
845  // Do not describe enums as static members.
846  if (VTy.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
847    return;
848
849  unsigned LineNumber = getLineNumber(Var->getLocation());
850  StringRef VName = Var->getName();
851  llvm::Constant *C = NULL;
852  if (Var->getInit()) {
853    const APValue *Value = Var->evaluateValue();
854    if (Value) {
855      if (Value->isInt())
856        C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
857      if (Value->isFloat())
858        C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
859    }
860  }
861
862  unsigned Flags = 0;
863  AccessSpecifier Access = Var->getAccess();
864  if (Access == clang::AS_private)
865    Flags |= llvm::DIDescriptor::FlagPrivate;
866  else if (Access == clang::AS_protected)
867    Flags |= llvm::DIDescriptor::FlagProtected;
868
869  llvm::DIType GV = DBuilder.createStaticMemberType(RecordTy, VName, VUnit,
870                                                    LineNumber, VTy, Flags, C);
871  elements.push_back(GV);
872  StaticDataMemberCache[Var->getCanonicalDecl()] = llvm::WeakVH(GV);
873}
874
875/// CollectRecordNormalField - Helper for CollectRecordFields.
876void CGDebugInfo::
877CollectRecordNormalField(const FieldDecl *field, uint64_t OffsetInBits,
878                         llvm::DIFile tunit,
879                         SmallVectorImpl<llvm::Value *> &elements,
880                         llvm::DIType RecordTy) {
881  StringRef name = field->getName();
882  QualType type = field->getType();
883
884  // Ignore unnamed fields unless they're anonymous structs/unions.
885  if (name.empty() && !type->isRecordType())
886    return;
887
888  uint64_t SizeInBitsOverride = 0;
889  if (field->isBitField()) {
890    SizeInBitsOverride = field->getBitWidthValue(CGM.getContext());
891    assert(SizeInBitsOverride && "found named 0-width bitfield");
892  }
893
894  llvm::DIType fieldType
895    = createFieldType(name, type, SizeInBitsOverride,
896                      field->getLocation(), field->getAccess(),
897                      OffsetInBits, tunit, RecordTy);
898
899  elements.push_back(fieldType);
900}
901
902/// CollectRecordFields - A helper function to collect debug info for
903/// record fields. This is used while creating debug info entry for a Record.
904void CGDebugInfo::
905CollectRecordFields(const RecordDecl *record, llvm::DIFile tunit,
906                    SmallVectorImpl<llvm::Value *> &elements,
907                    llvm::DIType RecordTy) {
908  const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(record);
909
910  if (CXXDecl && CXXDecl->isLambda())
911    CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
912  else {
913    const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
914
915    // Field number for non-static fields.
916    unsigned fieldNo = 0;
917
918    // Bookkeeping for an ms struct, which ignores certain fields.
919    bool IsMsStruct = record->isMsStruct(CGM.getContext());
920    const FieldDecl *LastFD = 0;
921
922    // Static and non-static members should appear in the same order as
923    // the corresponding declarations in the source program.
924    for (RecordDecl::decl_iterator I = record->decls_begin(),
925           E = record->decls_end(); I != E; ++I)
926      if (const VarDecl *V = dyn_cast<VarDecl>(*I))
927        CollectRecordStaticField(V, elements, RecordTy);
928      else if (FieldDecl *field = dyn_cast<FieldDecl>(*I)) {
929        if (IsMsStruct) {
930          // Zero-length bitfields following non-bitfield members are
931          // completely ignored; we don't even count them.
932          if (CGM.getContext().ZeroBitfieldFollowsNonBitfield((field), LastFD))
933            continue;
934          LastFD = field;
935        }
936        CollectRecordNormalField(field, layout.getFieldOffset(fieldNo),
937                                 tunit, elements, RecordTy);
938
939        // Bump field number for next field.
940        ++fieldNo;
941      }
942  }
943}
944
945/// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
946/// function type is not updated to include implicit "this" pointer. Use this
947/// routine to get a method type which includes "this" pointer.
948llvm::DIType
949CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
950                                   llvm::DIFile Unit) {
951  const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
952  if (Method->isStatic())
953    return getOrCreateType(QualType(Func, 0), Unit);
954  return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()),
955                                       Func, Unit);
956}
957
958llvm::DIType CGDebugInfo::getOrCreateInstanceMethodType(
959    QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile Unit) {
960  // Add "this" pointer.
961  llvm::DIArray Args = llvm::DICompositeType(
962      getOrCreateType(QualType(Func, 0), Unit)).getTypeArray();
963  assert (Args.getNumElements() && "Invalid number of arguments!");
964
965  SmallVector<llvm::Value *, 16> Elts;
966
967  // First element is always return type. For 'void' functions it is NULL.
968  Elts.push_back(Args.getElement(0));
969
970  // "this" pointer is always first argument.
971  const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
972  if (isa<ClassTemplateSpecializationDecl>(RD)) {
973    // Create pointer type directly in this case.
974    const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
975    QualType PointeeTy = ThisPtrTy->getPointeeType();
976    unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
977    uint64_t Size = CGM.getContext().getTargetInfo().getPointerWidth(AS);
978    uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy);
979    llvm::DIType PointeeType = getOrCreateType(PointeeTy, Unit);
980    llvm::DIType ThisPtrType = DBuilder.createPointerType(PointeeType, Size, Align);
981    TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
982    // TODO: This and the artificial type below are misleading, the
983    // types aren't artificial the argument is, but the current
984    // metadata doesn't represent that.
985    ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
986    Elts.push_back(ThisPtrType);
987  } else {
988    llvm::DIType ThisPtrType = getOrCreateType(ThisPtr, Unit);
989    TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
990    ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
991    Elts.push_back(ThisPtrType);
992  }
993
994  // Copy rest of the arguments.
995  for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
996    Elts.push_back(Args.getElement(i));
997
998  llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
999
1000  return DBuilder.createSubroutineType(Unit, EltTypeArray);
1001}
1002
1003/// isFunctionLocalClass - Return true if CXXRecordDecl is defined
1004/// inside a function.
1005static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
1006  if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
1007    return isFunctionLocalClass(NRD);
1008  if (isa<FunctionDecl>(RD->getDeclContext()))
1009    return true;
1010  return false;
1011}
1012
1013/// CreateCXXMemberFunction - A helper function to create a DISubprogram for
1014/// a single member function GlobalDecl.
1015llvm::DISubprogram
1016CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
1017                                     llvm::DIFile Unit,
1018                                     llvm::DIType RecordTy) {
1019  bool IsCtorOrDtor =
1020    isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
1021
1022  StringRef MethodName = getFunctionName(Method);
1023  llvm::DIType MethodTy = getOrCreateMethodType(Method, Unit);
1024
1025  // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1026  // make sense to give a single ctor/dtor a linkage name.
1027  StringRef MethodLinkageName;
1028  if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1029    MethodLinkageName = CGM.getMangledName(Method);
1030
1031  // Get the location for the method.
1032  llvm::DIFile MethodDefUnit = getOrCreateFile(Method->getLocation());
1033  unsigned MethodLine = getLineNumber(Method->getLocation());
1034
1035  // Collect virtual method info.
1036  llvm::DIType ContainingType;
1037  unsigned Virtuality = 0;
1038  unsigned VIndex = 0;
1039
1040  if (Method->isVirtual()) {
1041    if (Method->isPure())
1042      Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
1043    else
1044      Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
1045
1046    // It doesn't make sense to give a virtual destructor a vtable index,
1047    // since a single destructor has two entries in the vtable.
1048    if (!isa<CXXDestructorDecl>(Method))
1049      VIndex = CGM.getVTableContext().getMethodVTableIndex(Method);
1050    ContainingType = RecordTy;
1051  }
1052
1053  unsigned Flags = 0;
1054  if (Method->isImplicit())
1055    Flags |= llvm::DIDescriptor::FlagArtificial;
1056  AccessSpecifier Access = Method->getAccess();
1057  if (Access == clang::AS_private)
1058    Flags |= llvm::DIDescriptor::FlagPrivate;
1059  else if (Access == clang::AS_protected)
1060    Flags |= llvm::DIDescriptor::FlagProtected;
1061  if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
1062    if (CXXC->isExplicit())
1063      Flags |= llvm::DIDescriptor::FlagExplicit;
1064  } else if (const CXXConversionDecl *CXXC =
1065             dyn_cast<CXXConversionDecl>(Method)) {
1066    if (CXXC->isExplicit())
1067      Flags |= llvm::DIDescriptor::FlagExplicit;
1068  }
1069  if (Method->hasPrototype())
1070    Flags |= llvm::DIDescriptor::FlagPrototyped;
1071
1072  llvm::DIArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1073  llvm::DISubprogram SP =
1074    DBuilder.createMethod(RecordTy, MethodName, MethodLinkageName,
1075                          MethodDefUnit, MethodLine,
1076                          MethodTy, /*isLocalToUnit=*/false,
1077                          /* isDefinition=*/ false,
1078                          Virtuality, VIndex, ContainingType,
1079                          Flags, CGM.getLangOpts().Optimize, NULL,
1080                          TParamsArray);
1081
1082  SPCache[Method->getCanonicalDecl()] = llvm::WeakVH(SP);
1083
1084  return SP;
1085}
1086
1087/// CollectCXXMemberFunctions - A helper function to collect debug info for
1088/// C++ member functions. This is used while creating debug info entry for
1089/// a Record.
1090void CGDebugInfo::
1091CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
1092                          SmallVectorImpl<llvm::Value *> &EltTys,
1093                          llvm::DIType RecordTy) {
1094
1095  // Since we want more than just the individual member decls if we
1096  // have templated functions iterate over every declaration to gather
1097  // the functions.
1098  for(DeclContext::decl_iterator I = RD->decls_begin(),
1099        E = RD->decls_end(); I != E; ++I) {
1100    Decl *D = *I;
1101    if (D->isImplicit() && !D->isUsed())
1102      continue;
1103
1104    if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1105      EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
1106    else if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
1107      for (FunctionTemplateDecl::spec_iterator SI = FTD->spec_begin(),
1108             SE = FTD->spec_end(); SI != SE; ++SI)
1109        EltTys.push_back(CreateCXXMemberFunction(cast<CXXMethodDecl>(*SI), Unit,
1110                                                 RecordTy));
1111  }
1112}
1113
1114/// CollectCXXFriends - A helper function to collect debug info for
1115/// C++ base classes. This is used while creating debug info entry for
1116/// a Record.
1117void CGDebugInfo::
1118CollectCXXFriends(const CXXRecordDecl *RD, llvm::DIFile Unit,
1119                SmallVectorImpl<llvm::Value *> &EltTys,
1120                llvm::DIType RecordTy) {
1121  for (CXXRecordDecl::friend_iterator BI = RD->friend_begin(),
1122         BE = RD->friend_end(); BI != BE; ++BI) {
1123    if ((*BI)->isUnsupportedFriend())
1124      continue;
1125    if (TypeSourceInfo *TInfo = (*BI)->getFriendType())
1126      EltTys.push_back(DBuilder.createFriend(RecordTy,
1127                                             getOrCreateType(TInfo->getType(),
1128                                                             Unit)));
1129  }
1130}
1131
1132/// CollectCXXBases - A helper function to collect debug info for
1133/// C++ base classes. This is used while creating debug info entry for
1134/// a Record.
1135void CGDebugInfo::
1136CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
1137                SmallVectorImpl<llvm::Value *> &EltTys,
1138                llvm::DIType RecordTy) {
1139
1140  const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1141  for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
1142         BE = RD->bases_end(); BI != BE; ++BI) {
1143    unsigned BFlags = 0;
1144    uint64_t BaseOffset;
1145
1146    const CXXRecordDecl *Base =
1147      cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl());
1148
1149    if (BI->isVirtual()) {
1150      // virtual base offset offset is -ve. The code generator emits dwarf
1151      // expression where it expects +ve number.
1152      BaseOffset =
1153        0 - CGM.getVTableContext()
1154               .getVirtualBaseOffsetOffset(RD, Base).getQuantity();
1155      BFlags = llvm::DIDescriptor::FlagVirtual;
1156    } else
1157      BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1158    // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1159    // BI->isVirtual() and bits when not.
1160
1161    AccessSpecifier Access = BI->getAccessSpecifier();
1162    if (Access == clang::AS_private)
1163      BFlags |= llvm::DIDescriptor::FlagPrivate;
1164    else if (Access == clang::AS_protected)
1165      BFlags |= llvm::DIDescriptor::FlagProtected;
1166
1167    llvm::DIType DTy =
1168      DBuilder.createInheritance(RecordTy,
1169                                 getOrCreateType(BI->getType(), Unit),
1170                                 BaseOffset, BFlags);
1171    EltTys.push_back(DTy);
1172  }
1173}
1174
1175/// CollectTemplateParams - A helper function to collect template parameters.
1176llvm::DIArray CGDebugInfo::
1177CollectTemplateParams(const TemplateParameterList *TPList,
1178                      const TemplateArgumentList &TAList,
1179                      llvm::DIFile Unit) {
1180  SmallVector<llvm::Value *, 16> TemplateParams;
1181  for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1182    const TemplateArgument &TA = TAList[i];
1183    const NamedDecl *ND = TPList->getParam(i);
1184    if (TA.getKind() == TemplateArgument::Type) {
1185      llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit);
1186      llvm::DITemplateTypeParameter TTP =
1187        DBuilder.createTemplateTypeParameter(TheCU, ND->getName(), TTy);
1188      TemplateParams.push_back(TTP);
1189    } else if (TA.getKind() == TemplateArgument::Integral) {
1190      llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit);
1191      llvm::DITemplateValueParameter TVP =
1192        DBuilder.createTemplateValueParameter(TheCU, ND->getName(), TTy,
1193                                             TA.getAsIntegral().getZExtValue());
1194      TemplateParams.push_back(TVP);
1195    }
1196  }
1197  return DBuilder.getOrCreateArray(TemplateParams);
1198}
1199
1200/// CollectFunctionTemplateParams - A helper function to collect debug
1201/// info for function template parameters.
1202llvm::DIArray CGDebugInfo::
1203CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) {
1204  if (FD->getTemplatedKind() ==
1205      FunctionDecl::TK_FunctionTemplateSpecialization) {
1206    const TemplateParameterList *TList =
1207      FD->getTemplateSpecializationInfo()->getTemplate()
1208      ->getTemplateParameters();
1209    return
1210      CollectTemplateParams(TList, *FD->getTemplateSpecializationArgs(), Unit);
1211  }
1212  return llvm::DIArray();
1213}
1214
1215/// CollectCXXTemplateParams - A helper function to collect debug info for
1216/// template parameters.
1217llvm::DIArray CGDebugInfo::
1218CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial,
1219                         llvm::DIFile Unit) {
1220  llvm::PointerUnion<ClassTemplateDecl *,
1221                     ClassTemplatePartialSpecializationDecl *>
1222    PU = TSpecial->getSpecializedTemplateOrPartial();
1223
1224  TemplateParameterList *TPList = PU.is<ClassTemplateDecl *>() ?
1225    PU.get<ClassTemplateDecl *>()->getTemplateParameters() :
1226    PU.get<ClassTemplatePartialSpecializationDecl *>()->getTemplateParameters();
1227  const TemplateArgumentList &TAList = TSpecial->getTemplateInstantiationArgs();
1228  return CollectTemplateParams(TPList, TAList, Unit);
1229}
1230
1231/// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
1232llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
1233  if (VTablePtrType.isValid())
1234    return VTablePtrType;
1235
1236  ASTContext &Context = CGM.getContext();
1237
1238  /* Function type */
1239  llvm::Value *STy = getOrCreateType(Context.IntTy, Unit);
1240  llvm::DIArray SElements = DBuilder.getOrCreateArray(STy);
1241  llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements);
1242  unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1243  llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0,
1244                                                          "__vtbl_ptr_type");
1245  VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1246  return VTablePtrType;
1247}
1248
1249/// getVTableName - Get vtable name for the given Class.
1250StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
1251  // Construct gdb compatible name name.
1252  std::string Name = "_vptr$" + RD->getNameAsString();
1253
1254  // Copy this name on the side and use its reference.
1255  char *StrPtr = DebugInfoNames.Allocate<char>(Name.length());
1256  memcpy(StrPtr, Name.data(), Name.length());
1257  return StringRef(StrPtr, Name.length());
1258}
1259
1260
1261/// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
1262/// debug info entry in EltTys vector.
1263void CGDebugInfo::
1264CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
1265                  SmallVectorImpl<llvm::Value *> &EltTys) {
1266  const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1267
1268  // If there is a primary base then it will hold vtable info.
1269  if (RL.getPrimaryBase())
1270    return;
1271
1272  // If this class is not dynamic then there is not any vtable info to collect.
1273  if (!RD->isDynamicClass())
1274    return;
1275
1276  unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1277  llvm::DIType VPTR
1278    = DBuilder.createMemberType(Unit, getVTableName(RD), Unit,
1279                                0, Size, 0, 0, llvm::DIDescriptor::FlagArtificial,
1280                                getOrCreateVTablePtrType(Unit));
1281  EltTys.push_back(VPTR);
1282}
1283
1284/// getOrCreateRecordType - Emit record type's standalone debug info.
1285llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy,
1286                                                SourceLocation Loc) {
1287  assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
1288  llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc));
1289  return T;
1290}
1291
1292/// getOrCreateInterfaceType - Emit an objective c interface type standalone
1293/// debug info.
1294llvm::DIType CGDebugInfo::getOrCreateInterfaceType(QualType D,
1295						   SourceLocation Loc) {
1296  assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
1297  llvm::DIType T = getOrCreateType(D, getOrCreateFile(Loc));
1298  DBuilder.retainType(T);
1299  return T;
1300}
1301
1302/// CreateType - get structure or union type.
1303llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty) {
1304  RecordDecl *RD = Ty->getDecl();
1305
1306  // Get overall information about the record type for the debug info.
1307  llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1308
1309  // Records and classes and unions can all be recursive.  To handle them, we
1310  // first generate a debug descriptor for the struct as a forward declaration.
1311  // Then (if it is a definition) we go through and get debug info for all of
1312  // its members.  Finally, we create a descriptor for the complete type (which
1313  // may refer to the forward decl if the struct is recursive) and replace all
1314  // uses of the forward declaration with the final definition.
1315
1316  llvm::DIType FwdDecl = getOrCreateLimitedType(QualType(Ty, 0), DefUnit);
1317
1318  if (FwdDecl.isForwardDecl())
1319    return FwdDecl;
1320
1321  llvm::TrackingVH<llvm::MDNode> FwdDeclNode(FwdDecl);
1322
1323  // Push the struct on region stack.
1324  LexicalBlockStack.push_back(FwdDeclNode);
1325  RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1326
1327  // Add this to the completed types cache since we're completing it.
1328  CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1329
1330  // Convert all the elements.
1331  SmallVector<llvm::Value *, 16> EltTys;
1332
1333  // Note: The split of CXXDecl information here is intentional, the
1334  // gdb tests will depend on a certain ordering at printout. The debug
1335  // information offsets are still correct if we merge them all together
1336  // though.
1337  const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1338  if (CXXDecl) {
1339    CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1340    CollectVTableInfo(CXXDecl, DefUnit, EltTys);
1341  }
1342
1343  // Collect data fields (including static variables and any initializers).
1344  CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
1345  llvm::DIArray TParamsArray;
1346  if (CXXDecl) {
1347    CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
1348    CollectCXXFriends(CXXDecl, DefUnit, EltTys, FwdDecl);
1349    if (const ClassTemplateSpecializationDecl *TSpecial
1350        = dyn_cast<ClassTemplateSpecializationDecl>(RD))
1351      TParamsArray = CollectCXXTemplateParams(TSpecial, DefUnit);
1352  }
1353
1354  LexicalBlockStack.pop_back();
1355  RegionMap.erase(Ty->getDecl());
1356
1357  llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
1358  // FIXME: Magic numbers ahoy! These should be changed when we
1359  // get some enums in llvm/Analysis/DebugInfo.h to refer to
1360  // them.
1361  if (RD->isUnion())
1362    FwdDeclNode->replaceOperandWith(10, Elements);
1363  else if (CXXDecl) {
1364    FwdDeclNode->replaceOperandWith(10, Elements);
1365    FwdDeclNode->replaceOperandWith(13, TParamsArray);
1366  } else
1367    FwdDeclNode->replaceOperandWith(10, Elements);
1368
1369  RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDeclNode);
1370  return llvm::DIType(FwdDeclNode);
1371}
1372
1373/// CreateType - get objective-c object type.
1374llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1375                                     llvm::DIFile Unit) {
1376  // Ignore protocols.
1377  return getOrCreateType(Ty->getBaseType(), Unit);
1378}
1379
1380/// CreateType - get objective-c interface type.
1381llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1382                                     llvm::DIFile Unit) {
1383  ObjCInterfaceDecl *ID = Ty->getDecl();
1384  if (!ID)
1385    return llvm::DIType();
1386
1387  // Get overall information about the record type for the debug info.
1388  llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1389  unsigned Line = getLineNumber(ID->getLocation());
1390  unsigned RuntimeLang = TheCU.getLanguage();
1391
1392  // If this is just a forward declaration return a special forward-declaration
1393  // debug type since we won't be able to lay out the entire type.
1394  ObjCInterfaceDecl *Def = ID->getDefinition();
1395  if (!Def) {
1396    llvm::DIType FwdDecl =
1397      DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
1398				 ID->getName(), TheCU, DefUnit, Line,
1399				 RuntimeLang);
1400    return FwdDecl;
1401  }
1402
1403  ID = Def;
1404
1405  // Bit size, align and offset of the type.
1406  uint64_t Size = CGM.getContext().getTypeSize(Ty);
1407  uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1408
1409  unsigned Flags = 0;
1410  if (ID->getImplementation())
1411    Flags |= llvm::DIDescriptor::FlagObjcClassComplete;
1412
1413  llvm::DIType RealDecl =
1414    DBuilder.createStructType(Unit, ID->getName(), DefUnit,
1415                              Line, Size, Align, Flags,
1416                              llvm::DIArray(), RuntimeLang);
1417
1418  // Otherwise, insert it into the CompletedTypeCache so that recursive uses
1419  // will find it and we're emitting the complete type.
1420  CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl;
1421  // Push the struct on region stack.
1422  llvm::TrackingVH<llvm::MDNode> FwdDeclNode(RealDecl);
1423
1424  LexicalBlockStack.push_back(FwdDeclNode);
1425  RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1426
1427  // Convert all the elements.
1428  SmallVector<llvm::Value *, 16> EltTys;
1429
1430  ObjCInterfaceDecl *SClass = ID->getSuperClass();
1431  if (SClass) {
1432    llvm::DIType SClassTy =
1433      getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1434    if (!SClassTy.isValid())
1435      return llvm::DIType();
1436
1437    llvm::DIType InhTag =
1438      DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
1439    EltTys.push_back(InhTag);
1440  }
1441
1442  for (ObjCContainerDecl::prop_iterator I = ID->prop_begin(),
1443         E = ID->prop_end(); I != E; ++I) {
1444    const ObjCPropertyDecl *PD = *I;
1445    SourceLocation Loc = PD->getLocation();
1446    llvm::DIFile PUnit = getOrCreateFile(Loc);
1447    unsigned PLine = getLineNumber(Loc);
1448    ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1449    ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1450    llvm::MDNode *PropertyNode =
1451      DBuilder.createObjCProperty(PD->getName(),
1452				  PUnit, PLine,
1453                                  (Getter && Getter->isImplicit()) ? "" :
1454                                  getSelectorName(PD->getGetterName()),
1455                                  (Setter && Setter->isImplicit()) ? "" :
1456                                  getSelectorName(PD->getSetterName()),
1457                                  PD->getPropertyAttributes(),
1458				  getOrCreateType(PD->getType(), PUnit));
1459    EltTys.push_back(PropertyNode);
1460  }
1461
1462  const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1463  unsigned FieldNo = 0;
1464  for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1465       Field = Field->getNextIvar(), ++FieldNo) {
1466    llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1467    if (!FieldTy.isValid())
1468      return llvm::DIType();
1469
1470    StringRef FieldName = Field->getName();
1471
1472    // Ignore unnamed fields.
1473    if (FieldName.empty())
1474      continue;
1475
1476    // Get the location for the field.
1477    llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1478    unsigned FieldLine = getLineNumber(Field->getLocation());
1479    QualType FType = Field->getType();
1480    uint64_t FieldSize = 0;
1481    unsigned FieldAlign = 0;
1482
1483    if (!FType->isIncompleteArrayType()) {
1484
1485      // Bit size, align and offset of the type.
1486      FieldSize = Field->isBitField()
1487        ? Field->getBitWidthValue(CGM.getContext())
1488        : CGM.getContext().getTypeSize(FType);
1489      FieldAlign = CGM.getContext().getTypeAlign(FType);
1490    }
1491
1492    uint64_t FieldOffset;
1493    if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1494      // We don't know the runtime offset of an ivar if we're using the
1495      // non-fragile ABI.  For bitfields, use the bit offset into the first
1496      // byte of storage of the bitfield.  For other fields, use zero.
1497      if (Field->isBitField()) {
1498        FieldOffset = CGM.getObjCRuntime().ComputeBitfieldBitOffset(
1499            CGM, ID, Field);
1500        FieldOffset %= CGM.getContext().getCharWidth();
1501      } else {
1502        FieldOffset = 0;
1503      }
1504    } else {
1505      FieldOffset = RL.getFieldOffset(FieldNo);
1506    }
1507
1508    unsigned Flags = 0;
1509    if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1510      Flags = llvm::DIDescriptor::FlagProtected;
1511    else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1512      Flags = llvm::DIDescriptor::FlagPrivate;
1513
1514    llvm::MDNode *PropertyNode = NULL;
1515    if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
1516      if (ObjCPropertyImplDecl *PImpD =
1517          ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
1518        if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
1519	  SourceLocation Loc = PD->getLocation();
1520	  llvm::DIFile PUnit = getOrCreateFile(Loc);
1521	  unsigned PLine = getLineNumber(Loc);
1522          ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1523          ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1524          PropertyNode =
1525            DBuilder.createObjCProperty(PD->getName(),
1526                                        PUnit, PLine,
1527                                        (Getter && Getter->isImplicit()) ? "" :
1528                                        getSelectorName(PD->getGetterName()),
1529                                        (Setter && Setter->isImplicit()) ? "" :
1530                                        getSelectorName(PD->getSetterName()),
1531                                        PD->getPropertyAttributes(),
1532                                        getOrCreateType(PD->getType(), PUnit));
1533        }
1534      }
1535    }
1536    FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit,
1537                                      FieldLine, FieldSize, FieldAlign,
1538                                      FieldOffset, Flags, FieldTy,
1539                                      PropertyNode);
1540    EltTys.push_back(FieldTy);
1541  }
1542
1543  llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
1544  FwdDeclNode->replaceOperandWith(10, Elements);
1545
1546  LexicalBlockStack.pop_back();
1547  return llvm::DIType(FwdDeclNode);
1548}
1549
1550llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) {
1551  llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1552  int64_t Count = Ty->getNumElements();
1553  if (Count == 0)
1554    // If number of elements are not known then this is an unbounded array.
1555    // Use Count == -1 to express such arrays.
1556    Count = -1;
1557
1558  llvm::Value *Subscript = DBuilder.getOrCreateSubrange(0, Count);
1559  llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1560
1561  uint64_t Size = CGM.getContext().getTypeSize(Ty);
1562  uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1563
1564  return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1565}
1566
1567llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1568                                     llvm::DIFile Unit) {
1569  uint64_t Size;
1570  uint64_t Align;
1571
1572  // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1573  if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1574    Size = 0;
1575    Align =
1576      CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1577  } else if (Ty->isIncompleteArrayType()) {
1578    Size = 0;
1579    if (Ty->getElementType()->isIncompleteType())
1580      Align = 0;
1581    else
1582      Align = CGM.getContext().getTypeAlign(Ty->getElementType());
1583  } else if (Ty->isDependentSizedArrayType() || Ty->isIncompleteType()) {
1584    Size = 0;
1585    Align = 0;
1586  } else {
1587    // Size and align of the whole array, not the element type.
1588    Size = CGM.getContext().getTypeSize(Ty);
1589    Align = CGM.getContext().getTypeAlign(Ty);
1590  }
1591
1592  // Add the dimensions of the array.  FIXME: This loses CV qualifiers from
1593  // interior arrays, do we care?  Why aren't nested arrays represented the
1594  // obvious/recursive way?
1595  SmallVector<llvm::Value *, 8> Subscripts;
1596  QualType EltTy(Ty, 0);
1597  while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1598    // If the number of elements is known, then count is that number. Otherwise,
1599    // it's -1. This allows us to represent a subrange with an array of 0
1600    // elements, like this:
1601    //
1602    //   struct foo {
1603    //     int x[0];
1604    //   };
1605    int64_t Count = -1;         // Count == -1 is an unbounded array.
1606    if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1607      Count = CAT->getSize().getZExtValue();
1608
1609    // FIXME: Verify this is right for VLAs.
1610    Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
1611    EltTy = Ty->getElementType();
1612  }
1613
1614  llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1615
1616  llvm::DIType DbgTy =
1617    DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1618                             SubscriptArray);
1619  return DbgTy;
1620}
1621
1622llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
1623                                     llvm::DIFile Unit) {
1624  return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
1625                               Ty, Ty->getPointeeType(), Unit);
1626}
1627
1628llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
1629                                     llvm::DIFile Unit) {
1630  return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type,
1631                               Ty, Ty->getPointeeType(), Unit);
1632}
1633
1634llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
1635                                     llvm::DIFile U) {
1636  llvm::DIType ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
1637  if (!Ty->getPointeeType()->isFunctionType())
1638    return DBuilder.createMemberPointerType(
1639        CreatePointeeType(Ty->getPointeeType(), U), ClassType);
1640  return DBuilder.createMemberPointerType(getOrCreateInstanceMethodType(
1641      CGM.getContext().getPointerType(
1642          QualType(Ty->getClass(), Ty->getPointeeType().getCVRQualifiers())),
1643      Ty->getPointeeType()->getAs<FunctionProtoType>(), U),
1644                                          ClassType);
1645}
1646
1647llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty,
1648                                     llvm::DIFile U) {
1649  // Ignore the atomic wrapping
1650  // FIXME: What is the correct representation?
1651  return getOrCreateType(Ty->getValueType(), U);
1652}
1653
1654/// CreateEnumType - get enumeration type.
1655llvm::DIType CGDebugInfo::CreateEnumType(const EnumDecl *ED) {
1656  uint64_t Size = 0;
1657  uint64_t Align = 0;
1658  if (!ED->getTypeForDecl()->isIncompleteType()) {
1659    Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1660    Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1661  }
1662
1663  // If this is just a forward declaration, construct an appropriately
1664  // marked node and just return it.
1665  if (!ED->getDefinition()) {
1666    llvm::DIDescriptor EDContext;
1667    EDContext = getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1668    llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1669    unsigned Line = getLineNumber(ED->getLocation());
1670    StringRef EDName = ED->getName();
1671    return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_enumeration_type,
1672                                      EDName, EDContext, DefUnit, Line, 0,
1673                                      Size, Align);
1674  }
1675
1676  // Create DIEnumerator elements for each enumerator.
1677  SmallVector<llvm::Value *, 16> Enumerators;
1678  ED = ED->getDefinition();
1679  for (EnumDecl::enumerator_iterator
1680         Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
1681       Enum != EnumEnd; ++Enum) {
1682    Enumerators.push_back(
1683      DBuilder.createEnumerator(Enum->getName(),
1684                                Enum->getInitVal().getZExtValue()));
1685  }
1686
1687  // Return a CompositeType for the enum itself.
1688  llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1689
1690  llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1691  unsigned Line = getLineNumber(ED->getLocation());
1692  llvm::DIDescriptor EnumContext =
1693    getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1694  llvm::DIType ClassTy = ED->isScopedUsingClassTag() ?
1695    getOrCreateType(ED->getIntegerType(), DefUnit) : llvm::DIType();
1696  llvm::DIType DbgTy =
1697    DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1698                                   Size, Align, EltArray,
1699                                   ClassTy);
1700  return DbgTy;
1701}
1702
1703static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
1704  Qualifiers Quals;
1705  do {
1706    Quals += T.getLocalQualifiers();
1707    QualType LastT = T;
1708    switch (T->getTypeClass()) {
1709    default:
1710      return C.getQualifiedType(T.getTypePtr(), Quals);
1711    case Type::TemplateSpecialization:
1712      T = cast<TemplateSpecializationType>(T)->desugar();
1713      break;
1714    case Type::TypeOfExpr:
1715      T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1716      break;
1717    case Type::TypeOf:
1718      T = cast<TypeOfType>(T)->getUnderlyingType();
1719      break;
1720    case Type::Decltype:
1721      T = cast<DecltypeType>(T)->getUnderlyingType();
1722      break;
1723    case Type::UnaryTransform:
1724      T = cast<UnaryTransformType>(T)->getUnderlyingType();
1725      break;
1726    case Type::Attributed:
1727      T = cast<AttributedType>(T)->getEquivalentType();
1728      break;
1729    case Type::Elaborated:
1730      T = cast<ElaboratedType>(T)->getNamedType();
1731      break;
1732    case Type::Paren:
1733      T = cast<ParenType>(T)->getInnerType();
1734      break;
1735    case Type::SubstTemplateTypeParm:
1736      T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
1737      break;
1738    case Type::Auto:
1739      T = cast<AutoType>(T)->getDeducedType();
1740      break;
1741    }
1742
1743    assert(T != LastT && "Type unwrapping failed to unwrap!");
1744    (void)LastT;
1745  } while (true);
1746}
1747
1748/// getType - Get the type from the cache or return null type if it doesn't exist.
1749llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) {
1750
1751  // Unwrap the type as needed for debug information.
1752  Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
1753
1754  // Check for existing entry.
1755  llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1756    TypeCache.find(Ty.getAsOpaquePtr());
1757  if (it != TypeCache.end()) {
1758    // Verify that the debug info still exists.
1759    if (llvm::Value *V = it->second)
1760      return llvm::DIType(cast<llvm::MDNode>(V));
1761  }
1762
1763  return llvm::DIType();
1764}
1765
1766/// getCompletedTypeOrNull - Get the type from the cache or return null if it
1767/// doesn't exist.
1768llvm::DIType CGDebugInfo::getCompletedTypeOrNull(QualType Ty) {
1769
1770  // Unwrap the type as needed for debug information.
1771  Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
1772
1773  // Check for existing entry.
1774  llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1775    CompletedTypeCache.find(Ty.getAsOpaquePtr());
1776  if (it != CompletedTypeCache.end()) {
1777    // Verify that the debug info still exists.
1778    if (llvm::Value *V = it->second)
1779      return llvm::DIType(cast<llvm::MDNode>(V));
1780  }
1781
1782  return llvm::DIType();
1783}
1784
1785
1786/// getOrCreateType - Get the type from the cache or create a new
1787/// one if necessary.
1788llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit) {
1789  if (Ty.isNull())
1790    return llvm::DIType();
1791
1792  // Unwrap the type as needed for debug information.
1793  Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
1794
1795  llvm::DIType T = getCompletedTypeOrNull(Ty);
1796
1797  if (T.Verify())
1798    return T;
1799
1800  // Otherwise create the type.
1801  llvm::DIType Res = CreateTypeNode(Ty, Unit);
1802
1803  llvm::DIType TC = getTypeOrNull(Ty);
1804  if (TC.Verify() && TC.isForwardDecl())
1805    ReplaceMap.push_back(std::make_pair(Ty.getAsOpaquePtr(),
1806                                        static_cast<llvm::Value*>(TC)));
1807
1808  // And update the type cache.
1809  TypeCache[Ty.getAsOpaquePtr()] = Res;
1810
1811  if (!Res.isForwardDecl())
1812    CompletedTypeCache[Ty.getAsOpaquePtr()] = Res;
1813
1814  return Res;
1815}
1816
1817/// CreateTypeNode - Create a new debug type node.
1818llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit) {
1819  // Handle qualifiers, which recursively handles what they refer to.
1820  if (Ty.hasLocalQualifiers())
1821    return CreateQualifiedType(Ty, Unit);
1822
1823  const char *Diag = 0;
1824
1825  // Work out details of type.
1826  switch (Ty->getTypeClass()) {
1827#define TYPE(Class, Base)
1828#define ABSTRACT_TYPE(Class, Base)
1829#define NON_CANONICAL_TYPE(Class, Base)
1830#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1831#include "clang/AST/TypeNodes.def"
1832    llvm_unreachable("Dependent types cannot show up in debug information");
1833
1834  case Type::ExtVector:
1835  case Type::Vector:
1836    return CreateType(cast<VectorType>(Ty), Unit);
1837  case Type::ObjCObjectPointer:
1838    return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
1839  case Type::ObjCObject:
1840    return CreateType(cast<ObjCObjectType>(Ty), Unit);
1841  case Type::ObjCInterface:
1842    return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
1843  case Type::Builtin:
1844    return CreateType(cast<BuiltinType>(Ty));
1845  case Type::Complex:
1846    return CreateType(cast<ComplexType>(Ty));
1847  case Type::Pointer:
1848    return CreateType(cast<PointerType>(Ty), Unit);
1849  case Type::BlockPointer:
1850    return CreateType(cast<BlockPointerType>(Ty), Unit);
1851  case Type::Typedef:
1852    return CreateType(cast<TypedefType>(Ty), Unit);
1853  case Type::Record:
1854    return CreateType(cast<RecordType>(Ty));
1855  case Type::Enum:
1856    return CreateEnumType(cast<EnumType>(Ty)->getDecl());
1857  case Type::FunctionProto:
1858  case Type::FunctionNoProto:
1859    return CreateType(cast<FunctionType>(Ty), Unit);
1860  case Type::ConstantArray:
1861  case Type::VariableArray:
1862  case Type::IncompleteArray:
1863    return CreateType(cast<ArrayType>(Ty), Unit);
1864
1865  case Type::LValueReference:
1866    return CreateType(cast<LValueReferenceType>(Ty), Unit);
1867  case Type::RValueReference:
1868    return CreateType(cast<RValueReferenceType>(Ty), Unit);
1869
1870  case Type::MemberPointer:
1871    return CreateType(cast<MemberPointerType>(Ty), Unit);
1872
1873  case Type::Atomic:
1874    return CreateType(cast<AtomicType>(Ty), Unit);
1875
1876  case Type::Attributed:
1877  case Type::TemplateSpecialization:
1878  case Type::Elaborated:
1879  case Type::Paren:
1880  case Type::SubstTemplateTypeParm:
1881  case Type::TypeOfExpr:
1882  case Type::TypeOf:
1883  case Type::Decltype:
1884  case Type::UnaryTransform:
1885  case Type::Auto:
1886    llvm_unreachable("type should have been unwrapped!");
1887  }
1888
1889  assert(Diag && "Fall through without a diagnostic?");
1890  unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error,
1891                               "debug information for %0 is not yet supported");
1892  CGM.getDiags().Report(DiagID)
1893    << Diag;
1894  return llvm::DIType();
1895}
1896
1897/// getOrCreateLimitedType - Get the type from the cache or create a new
1898/// limited type if necessary.
1899llvm::DIType CGDebugInfo::getOrCreateLimitedType(QualType Ty,
1900						 llvm::DIFile Unit) {
1901  if (Ty.isNull())
1902    return llvm::DIType();
1903
1904  // Unwrap the type as needed for debug information.
1905  Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
1906
1907  llvm::DIType T = getTypeOrNull(Ty);
1908
1909  // We may have cached a forward decl when we could have created
1910  // a non-forward decl. Go ahead and create a non-forward decl
1911  // now.
1912  if (T.Verify() && !T.isForwardDecl()) return T;
1913
1914  // Otherwise create the type.
1915  llvm::DIType Res = CreateLimitedTypeNode(Ty, Unit);
1916
1917  if (T.Verify() && T.isForwardDecl())
1918    ReplaceMap.push_back(std::make_pair(Ty.getAsOpaquePtr(),
1919                                        static_cast<llvm::Value*>(T)));
1920
1921  // And update the type cache.
1922  TypeCache[Ty.getAsOpaquePtr()] = Res;
1923  return Res;
1924}
1925
1926// TODO: Currently used for context chains when limiting debug info.
1927llvm::DIType CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
1928  RecordDecl *RD = Ty->getDecl();
1929
1930  // Get overall information about the record type for the debug info.
1931  llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1932  unsigned Line = getLineNumber(RD->getLocation());
1933  StringRef RDName = getClassName(RD);
1934
1935  llvm::DIDescriptor RDContext;
1936  if (CGM.getCodeGenOpts().getDebugInfo() == CodeGenOptions::LimitedDebugInfo)
1937    RDContext = createContextChain(cast<Decl>(RD->getDeclContext()));
1938  else
1939    RDContext = getContextDescriptor(cast<Decl>(RD->getDeclContext()));
1940
1941  // If this is just a forward declaration, construct an appropriately
1942  // marked node and just return it.
1943  if (!RD->getDefinition())
1944    return createRecordFwdDecl(RD, RDContext);
1945
1946  uint64_t Size = CGM.getContext().getTypeSize(Ty);
1947  uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1948  const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1949  llvm::TrackingVH<llvm::MDNode> RealDecl;
1950
1951  if (RD->isUnion())
1952    RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
1953					Size, Align, 0, llvm::DIArray());
1954  else if (RD->isClass()) {
1955    // FIXME: This could be a struct type giving a default visibility different
1956    // than C++ class type, but needs llvm metadata changes first.
1957    RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
1958					Size, Align, 0, 0, llvm::DIType(),
1959					llvm::DIArray(), llvm::DIType(),
1960					llvm::DIArray());
1961  } else
1962    RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line,
1963					 Size, Align, 0, llvm::DIArray());
1964
1965  RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1966  TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = llvm::DIType(RealDecl);
1967
1968  if (CXXDecl) {
1969    // A class's primary base or the class itself contains the vtable.
1970    llvm::MDNode *ContainingType = NULL;
1971    const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1972    if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
1973      // Seek non virtual primary base root.
1974      while (1) {
1975	const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
1976	const CXXRecordDecl *PBT = BRL.getPrimaryBase();
1977	if (PBT && !BRL.isPrimaryBaseVirtual())
1978	  PBase = PBT;
1979	else
1980	  break;
1981      }
1982      ContainingType =
1983	getOrCreateType(QualType(PBase->getTypeForDecl(), 0), DefUnit);
1984    }
1985    else if (CXXDecl->isDynamicClass())
1986      ContainingType = RealDecl;
1987
1988    RealDecl->replaceOperandWith(12, ContainingType);
1989  }
1990  return llvm::DIType(RealDecl);
1991}
1992
1993/// CreateLimitedTypeNode - Create a new debug type node, but only forward
1994/// declare composite types that haven't been processed yet.
1995llvm::DIType CGDebugInfo::CreateLimitedTypeNode(QualType Ty,llvm::DIFile Unit) {
1996
1997  // Work out details of type.
1998  switch (Ty->getTypeClass()) {
1999#define TYPE(Class, Base)
2000#define ABSTRACT_TYPE(Class, Base)
2001#define NON_CANONICAL_TYPE(Class, Base)
2002#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2003        #include "clang/AST/TypeNodes.def"
2004    llvm_unreachable("Dependent types cannot show up in debug information");
2005
2006  case Type::Record:
2007    return CreateLimitedType(cast<RecordType>(Ty));
2008  default:
2009    return CreateTypeNode(Ty, Unit);
2010  }
2011}
2012
2013/// CreateMemberType - Create new member and increase Offset by FType's size.
2014llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
2015                                           StringRef Name,
2016                                           uint64_t *Offset) {
2017  llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2018  uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
2019  unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
2020  llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0,
2021                                              FieldSize, FieldAlign,
2022                                              *Offset, 0, FieldTy);
2023  *Offset += FieldSize;
2024  return Ty;
2025}
2026
2027/// getFunctionDeclaration - Return debug info descriptor to describe method
2028/// declaration for the given method definition.
2029llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
2030  const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
2031  if (!FD) return llvm::DISubprogram();
2032
2033  // Setup context.
2034  getContextDescriptor(cast<Decl>(D->getDeclContext()));
2035
2036  llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2037    MI = SPCache.find(FD->getCanonicalDecl());
2038  if (MI != SPCache.end()) {
2039    llvm::Value *V = MI->second;
2040    llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
2041    if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
2042      return SP;
2043  }
2044
2045  for (FunctionDecl::redecl_iterator I = FD->redecls_begin(),
2046         E = FD->redecls_end(); I != E; ++I) {
2047    const FunctionDecl *NextFD = *I;
2048    llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2049      MI = SPCache.find(NextFD->getCanonicalDecl());
2050    if (MI != SPCache.end()) {
2051      llvm::Value *V = MI->second;
2052      llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
2053      if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
2054        return SP;
2055    }
2056  }
2057  return llvm::DISubprogram();
2058}
2059
2060// getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
2061// implicit parameter "this".
2062llvm::DIType CGDebugInfo::getOrCreateFunctionType(const Decl *D,
2063                                                  QualType FnType,
2064                                                  llvm::DIFile F) {
2065
2066  if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
2067    return getOrCreateMethodType(Method, F);
2068  if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
2069    // Add "self" and "_cmd"
2070    SmallVector<llvm::Value *, 16> Elts;
2071
2072    // First element is always return type. For 'void' functions it is NULL.
2073    Elts.push_back(getOrCreateType(OMethod->getResultType(), F));
2074    // "self" pointer is always first argument.
2075    llvm::DIType SelfTy = getOrCreateType(OMethod->getSelfDecl()->getType(), F);
2076    Elts.push_back(DBuilder.createObjectPointerType(SelfTy));
2077    // "_cmd" pointer is always second argument.
2078    llvm::DIType CmdTy = getOrCreateType(OMethod->getCmdDecl()->getType(), F);
2079    Elts.push_back(DBuilder.createArtificialType(CmdTy));
2080    // Get rest of the arguments.
2081    for (ObjCMethodDecl::param_const_iterator PI = OMethod->param_begin(),
2082           PE = OMethod->param_end(); PI != PE; ++PI)
2083      Elts.push_back(getOrCreateType((*PI)->getType(), F));
2084
2085    llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2086    return DBuilder.createSubroutineType(F, EltTypeArray);
2087  }
2088  return getOrCreateType(FnType, F);
2089}
2090
2091/// EmitFunctionStart - Constructs the debug code for entering a function.
2092void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
2093                                    llvm::Function *Fn,
2094                                    CGBuilderTy &Builder) {
2095
2096  StringRef Name;
2097  StringRef LinkageName;
2098
2099  FnBeginRegionCount.push_back(LexicalBlockStack.size());
2100
2101  const Decl *D = GD.getDecl();
2102  // Function may lack declaration in source code if it is created by Clang
2103  // CodeGen (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
2104  bool HasDecl = (D != 0);
2105  // Use the location of the declaration.
2106  SourceLocation Loc;
2107  if (HasDecl)
2108    Loc = D->getLocation();
2109
2110  unsigned Flags = 0;
2111  llvm::DIFile Unit = getOrCreateFile(Loc);
2112  llvm::DIDescriptor FDContext(Unit);
2113  llvm::DIArray TParamsArray;
2114  if (!HasDecl) {
2115    // Use llvm function name.
2116    Name = Fn->getName();
2117  } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2118    // If there is a DISubprogram for this function available then use it.
2119    llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2120      FI = SPCache.find(FD->getCanonicalDecl());
2121    if (FI != SPCache.end()) {
2122      llvm::Value *V = FI->second;
2123      llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(V));
2124      if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
2125        llvm::MDNode *SPN = SP;
2126        LexicalBlockStack.push_back(SPN);
2127        RegionMap[D] = llvm::WeakVH(SP);
2128        return;
2129      }
2130    }
2131    Name = getFunctionName(FD);
2132    // Use mangled name as linkage name for c/c++ functions.
2133    if (FD->hasPrototype()) {
2134      LinkageName = CGM.getMangledName(GD);
2135      Flags |= llvm::DIDescriptor::FlagPrototyped;
2136    }
2137    if (LinkageName == Name ||
2138        CGM.getCodeGenOpts().getDebugInfo() <= CodeGenOptions::DebugLineTablesOnly)
2139      LinkageName = StringRef();
2140
2141    if (CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
2142      if (const NamespaceDecl *NSDecl =
2143          dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
2144        FDContext = getOrCreateNameSpace(NSDecl);
2145      else if (const RecordDecl *RDecl =
2146               dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
2147        FDContext = getContextDescriptor(cast<Decl>(RDecl->getDeclContext()));
2148
2149      // Collect template parameters.
2150      TParamsArray = CollectFunctionTemplateParams(FD, Unit);
2151    }
2152  } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
2153    Name = getObjCMethodName(OMD);
2154    Flags |= llvm::DIDescriptor::FlagPrototyped;
2155  } else {
2156    // Use llvm function name.
2157    Name = Fn->getName();
2158    Flags |= llvm::DIDescriptor::FlagPrototyped;
2159  }
2160  if (!Name.empty() && Name[0] == '\01')
2161    Name = Name.substr(1);
2162
2163  unsigned LineNo = getLineNumber(Loc);
2164  if (!HasDecl || D->isImplicit())
2165    Flags |= llvm::DIDescriptor::FlagArtificial;
2166
2167  llvm::DIType DIFnType;
2168  llvm::DISubprogram SPDecl;
2169  if (HasDecl &&
2170      CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
2171    DIFnType = getOrCreateFunctionType(D, FnType, Unit);
2172    SPDecl = getFunctionDeclaration(D);
2173  } else {
2174    // Create fake but valid subroutine type. Otherwise
2175    // llvm::DISubprogram::Verify() would return false, and
2176    // subprogram DIE will miss DW_AT_decl_file and
2177    // DW_AT_decl_line fields.
2178    SmallVector<llvm::Value*, 16> Elts;
2179    llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2180    DIFnType = DBuilder.createSubroutineType(Unit, EltTypeArray);
2181  }
2182  llvm::DISubprogram SP;
2183  SP = DBuilder.createFunction(FDContext, Name, LinkageName, Unit,
2184                               LineNo, DIFnType,
2185                               Fn->hasInternalLinkage(), true/*definition*/,
2186                               getLineNumber(CurLoc), Flags,
2187                               CGM.getLangOpts().Optimize,
2188                               Fn, TParamsArray, SPDecl);
2189
2190  // Push function on region stack.
2191  llvm::MDNode *SPN = SP;
2192  LexicalBlockStack.push_back(SPN);
2193  if (HasDecl)
2194    RegionMap[D] = llvm::WeakVH(SP);
2195}
2196
2197/// EmitLocation - Emit metadata to indicate a change in line/column
2198/// information in the source file.
2199void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc) {
2200
2201  // Update our current location
2202  setLocation(Loc);
2203
2204  if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
2205
2206  // Don't bother if things are the same as last time.
2207  SourceManager &SM = CGM.getContext().getSourceManager();
2208  if (CurLoc == PrevLoc ||
2209      SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc))
2210    // New Builder may not be in sync with CGDebugInfo.
2211    if (!Builder.getCurrentDebugLocation().isUnknown() &&
2212        Builder.getCurrentDebugLocation().getScope(CGM.getLLVMContext()) ==
2213          LexicalBlockStack.back())
2214      return;
2215
2216  // Update last state.
2217  PrevLoc = CurLoc;
2218
2219  llvm::MDNode *Scope = LexicalBlockStack.back();
2220  Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(CurLoc),
2221                                                      getColumnNumber(CurLoc),
2222                                                      Scope));
2223}
2224
2225/// CreateLexicalBlock - Creates a new lexical block node and pushes it on
2226/// the stack.
2227void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
2228  llvm::DIDescriptor D =
2229    DBuilder.createLexicalBlock(LexicalBlockStack.empty() ?
2230                                llvm::DIDescriptor() :
2231                                llvm::DIDescriptor(LexicalBlockStack.back()),
2232                                getOrCreateFile(CurLoc),
2233                                getLineNumber(CurLoc),
2234                                getColumnNumber(CurLoc));
2235  llvm::MDNode *DN = D;
2236  LexicalBlockStack.push_back(DN);
2237}
2238
2239/// EmitLexicalBlockStart - Constructs the debug code for entering a declarative
2240/// region - beginning of a DW_TAG_lexical_block.
2241void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder, SourceLocation Loc) {
2242  // Set our current location.
2243  setLocation(Loc);
2244
2245  // Create a new lexical block and push it on the stack.
2246  CreateLexicalBlock(Loc);
2247
2248  // Emit a line table change for the current location inside the new scope.
2249  Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc),
2250                                  getColumnNumber(Loc),
2251                                  LexicalBlockStack.back()));
2252}
2253
2254/// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative
2255/// region - end of a DW_TAG_lexical_block.
2256void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder, SourceLocation Loc) {
2257  assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2258
2259  // Provide an entry in the line table for the end of the block.
2260  EmitLocation(Builder, Loc);
2261
2262  LexicalBlockStack.pop_back();
2263}
2264
2265/// EmitFunctionEnd - Constructs the debug code for exiting a function.
2266void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
2267  assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2268  unsigned RCount = FnBeginRegionCount.back();
2269  assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
2270
2271  // Pop all regions for this function.
2272  while (LexicalBlockStack.size() != RCount)
2273    EmitLexicalBlockEnd(Builder, CurLoc);
2274  FnBeginRegionCount.pop_back();
2275}
2276
2277// EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
2278// See BuildByRefType.
2279llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
2280                                                       uint64_t *XOffset) {
2281
2282  SmallVector<llvm::Value *, 5> EltTys;
2283  QualType FType;
2284  uint64_t FieldSize, FieldOffset;
2285  unsigned FieldAlign;
2286
2287  llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2288  QualType Type = VD->getType();
2289
2290  FieldOffset = 0;
2291  FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2292  EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
2293  EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
2294  FType = CGM.getContext().IntTy;
2295  EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
2296  EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
2297
2298  bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
2299  if (HasCopyAndDispose) {
2300    FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2301    EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
2302                                      &FieldOffset));
2303    EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
2304                                      &FieldOffset));
2305  }
2306  bool HasByrefExtendedLayout;
2307  Qualifiers::ObjCLifetime Lifetime;
2308  if (CGM.getContext().getByrefLifetime(Type,
2309                                        Lifetime, HasByrefExtendedLayout)
2310      && HasByrefExtendedLayout)
2311    EltTys.push_back(CreateMemberType(Unit, FType,
2312                                      "__byref_variable_layout",
2313                                      &FieldOffset));
2314
2315  CharUnits Align = CGM.getContext().getDeclAlign(VD);
2316  if (Align > CGM.getContext().toCharUnitsFromBits(
2317        CGM.getContext().getTargetInfo().getPointerAlign(0))) {
2318    CharUnits FieldOffsetInBytes
2319      = CGM.getContext().toCharUnitsFromBits(FieldOffset);
2320    CharUnits AlignedOffsetInBytes
2321      = FieldOffsetInBytes.RoundUpToAlignment(Align);
2322    CharUnits NumPaddingBytes
2323      = AlignedOffsetInBytes - FieldOffsetInBytes;
2324
2325    if (NumPaddingBytes.isPositive()) {
2326      llvm::APInt pad(32, NumPaddingBytes.getQuantity());
2327      FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
2328                                                    pad, ArrayType::Normal, 0);
2329      EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
2330    }
2331  }
2332
2333  FType = Type;
2334  llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2335  FieldSize = CGM.getContext().getTypeSize(FType);
2336  FieldAlign = CGM.getContext().toBits(Align);
2337
2338  *XOffset = FieldOffset;
2339  FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit,
2340                                      0, FieldSize, FieldAlign,
2341                                      FieldOffset, 0, FieldTy);
2342  EltTys.push_back(FieldTy);
2343  FieldOffset += FieldSize;
2344
2345  llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
2346
2347  unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
2348
2349  return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
2350                                   Elements);
2351}
2352
2353/// EmitDeclare - Emit local variable declaration debug info.
2354void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
2355                              llvm::Value *Storage,
2356                              unsigned ArgNo, CGBuilderTy &Builder) {
2357  assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2358  assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2359
2360  llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2361  llvm::DIType Ty;
2362  uint64_t XOffset = 0;
2363  if (VD->hasAttr<BlocksAttr>())
2364    Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
2365  else
2366    Ty = getOrCreateType(VD->getType(), Unit);
2367
2368  // If there is no debug info for this type then do not emit debug info
2369  // for this variable.
2370  if (!Ty)
2371    return;
2372
2373  if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage)) {
2374    // If Storage is an aggregate returned as 'sret' then let debugger know
2375    // about this.
2376    if (Arg->hasStructRetAttr())
2377      Ty = DBuilder.createReferenceType(llvm::dwarf::DW_TAG_reference_type, Ty);
2378    else if (CXXRecordDecl *Record = VD->getType()->getAsCXXRecordDecl()) {
2379      // If an aggregate variable has non trivial destructor or non trivial copy
2380      // constructor than it is pass indirectly. Let debug info know about this
2381      // by using reference of the aggregate type as a argument type.
2382      if (Record->hasNonTrivialCopyConstructor() ||
2383          !Record->hasTrivialDestructor())
2384        Ty = DBuilder.createReferenceType(llvm::dwarf::DW_TAG_reference_type, Ty);
2385    }
2386  }
2387
2388  // Get location information.
2389  unsigned Line = getLineNumber(VD->getLocation());
2390  unsigned Column = getColumnNumber(VD->getLocation());
2391  unsigned Flags = 0;
2392  if (VD->isImplicit())
2393    Flags |= llvm::DIDescriptor::FlagArtificial;
2394  // If this is the first argument and it is implicit then
2395  // give it an object pointer flag.
2396  // FIXME: There has to be a better way to do this, but for static
2397  // functions there won't be an implicit param at arg1 and
2398  // otherwise it is 'self' or 'this'.
2399  if (isa<ImplicitParamDecl>(VD) && ArgNo == 1)
2400    Flags |= llvm::DIDescriptor::FlagObjectPointer;
2401
2402  llvm::MDNode *Scope = LexicalBlockStack.back();
2403
2404  StringRef Name = VD->getName();
2405  if (!Name.empty()) {
2406    if (VD->hasAttr<BlocksAttr>()) {
2407      CharUnits offset = CharUnits::fromQuantity(32);
2408      SmallVector<llvm::Value *, 9> addr;
2409      llvm::Type *Int64Ty = CGM.Int64Ty;
2410      addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2411      // offset of __forwarding field
2412      offset = CGM.getContext().toCharUnitsFromBits(
2413        CGM.getContext().getTargetInfo().getPointerWidth(0));
2414      addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2415      addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2416      addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2417      // offset of x field
2418      offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2419      addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2420
2421      // Create the descriptor for the variable.
2422      llvm::DIVariable D =
2423        DBuilder.createComplexVariable(Tag,
2424                                       llvm::DIDescriptor(Scope),
2425                                       VD->getName(), Unit, Line, Ty,
2426                                       addr, ArgNo);
2427
2428      // Insert an llvm.dbg.declare into the current block.
2429      llvm::Instruction *Call =
2430        DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2431      Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2432      return;
2433    } else if (isa<VariableArrayType>(VD->getType())) {
2434      // These are "complex" variables in that they need an op_deref.
2435      // Create the descriptor for the variable.
2436      llvm::Value *Addr = llvm::ConstantInt::get(CGM.Int64Ty,
2437                                                 llvm::DIBuilder::OpDeref);
2438      llvm::DIVariable D =
2439        DBuilder.createComplexVariable(Tag,
2440                                       llvm::DIDescriptor(Scope),
2441                                       Name, Unit, Line, Ty,
2442                                       Addr, ArgNo);
2443
2444      // Insert an llvm.dbg.declare into the current block.
2445      llvm::Instruction *Call =
2446        DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2447      Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2448      return;
2449    }
2450  } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2451    // If VD is an anonymous union then Storage represents value for
2452    // all union fields.
2453    const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
2454    if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
2455      for (RecordDecl::field_iterator I = RD->field_begin(),
2456             E = RD->field_end();
2457           I != E; ++I) {
2458        FieldDecl *Field = *I;
2459        llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
2460        StringRef FieldName = Field->getName();
2461
2462        // Ignore unnamed fields. Do not ignore unnamed records.
2463        if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2464          continue;
2465
2466        // Use VarDecl's Tag, Scope and Line number.
2467        llvm::DIVariable D =
2468          DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2469                                       FieldName, Unit, Line, FieldTy,
2470                                       CGM.getLangOpts().Optimize, Flags,
2471                                       ArgNo);
2472
2473        // Insert an llvm.dbg.declare into the current block.
2474        llvm::Instruction *Call =
2475          DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2476        Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2477      }
2478      return;
2479    }
2480  }
2481
2482  // Create the descriptor for the variable.
2483  llvm::DIVariable D =
2484    DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2485                                 Name, Unit, Line, Ty,
2486                                 CGM.getLangOpts().Optimize, Flags, ArgNo);
2487
2488  // Insert an llvm.dbg.declare into the current block.
2489  llvm::Instruction *Call =
2490    DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2491  Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2492}
2493
2494void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2495                                            llvm::Value *Storage,
2496                                            CGBuilderTy &Builder) {
2497  assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2498  EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2499}
2500
2501void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(const VarDecl *VD,
2502                                                    llvm::Value *Storage,
2503                                                    CGBuilderTy &Builder,
2504                                                 const CGBlockInfo &blockInfo) {
2505  assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2506  assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2507
2508  if (Builder.GetInsertBlock() == 0)
2509    return;
2510
2511  bool isByRef = VD->hasAttr<BlocksAttr>();
2512
2513  uint64_t XOffset = 0;
2514  llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2515  llvm::DIType Ty;
2516  if (isByRef)
2517    Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
2518  else
2519    Ty = getOrCreateType(VD->getType(), Unit);
2520
2521  // Self is passed along as an implicit non-arg variable in a
2522  // block. Mark it as the object pointer.
2523  if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self")
2524    Ty = DBuilder.createObjectPointerType(Ty);
2525
2526  // Get location information.
2527  unsigned Line = getLineNumber(VD->getLocation());
2528  unsigned Column = getColumnNumber(VD->getLocation());
2529
2530  const llvm::DataLayout &target = CGM.getDataLayout();
2531
2532  CharUnits offset = CharUnits::fromQuantity(
2533    target.getStructLayout(blockInfo.StructureType)
2534          ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2535
2536  SmallVector<llvm::Value *, 9> addr;
2537  llvm::Type *Int64Ty = CGM.Int64Ty;
2538  addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2539  addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2540  if (isByRef) {
2541    addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2542    addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2543    // offset of __forwarding field
2544    offset = CGM.getContext()
2545                .toCharUnitsFromBits(target.getPointerSizeInBits(0));
2546    addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2547    addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2548    addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2549    // offset of x field
2550    offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2551    addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2552  }
2553
2554  // Create the descriptor for the variable.
2555  llvm::DIVariable D =
2556    DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable,
2557                                   llvm::DIDescriptor(LexicalBlockStack.back()),
2558                                   VD->getName(), Unit, Line, Ty, addr);
2559  // Insert an llvm.dbg.declare into the current block.
2560  llvm::Instruction *Call =
2561    DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint());
2562  Call->setDebugLoc(llvm::DebugLoc::get(Line, Column,
2563                                        LexicalBlockStack.back()));
2564}
2565
2566/// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
2567/// variable declaration.
2568void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2569                                           unsigned ArgNo,
2570                                           CGBuilderTy &Builder) {
2571  assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2572  EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2573}
2574
2575namespace {
2576  struct BlockLayoutChunk {
2577    uint64_t OffsetInBits;
2578    const BlockDecl::Capture *Capture;
2579  };
2580  bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2581    return l.OffsetInBits < r.OffsetInBits;
2582  }
2583}
2584
2585void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
2586                                                       llvm::Value *addr,
2587                                                       CGBuilderTy &Builder) {
2588  assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2589  ASTContext &C = CGM.getContext();
2590  const BlockDecl *blockDecl = block.getBlockDecl();
2591
2592  // Collect some general information about the block's location.
2593  SourceLocation loc = blockDecl->getCaretLocation();
2594  llvm::DIFile tunit = getOrCreateFile(loc);
2595  unsigned line = getLineNumber(loc);
2596  unsigned column = getColumnNumber(loc);
2597
2598  // Build the debug-info type for the block literal.
2599  getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
2600
2601  const llvm::StructLayout *blockLayout =
2602    CGM.getDataLayout().getStructLayout(block.StructureType);
2603
2604  SmallVector<llvm::Value*, 16> fields;
2605  fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
2606                                   blockLayout->getElementOffsetInBits(0),
2607                                   tunit, tunit));
2608  fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
2609                                   blockLayout->getElementOffsetInBits(1),
2610                                   tunit, tunit));
2611  fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
2612                                   blockLayout->getElementOffsetInBits(2),
2613                                   tunit, tunit));
2614  fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public,
2615                                   blockLayout->getElementOffsetInBits(3),
2616                                   tunit, tunit));
2617  fields.push_back(createFieldType("__descriptor",
2618                                   C.getPointerType(block.NeedsCopyDispose ?
2619                                        C.getBlockDescriptorExtendedType() :
2620                                        C.getBlockDescriptorType()),
2621                                   0, loc, AS_public,
2622                                   blockLayout->getElementOffsetInBits(4),
2623                                   tunit, tunit));
2624
2625  // We want to sort the captures by offset, not because DWARF
2626  // requires this, but because we're paranoid about debuggers.
2627  SmallVector<BlockLayoutChunk, 8> chunks;
2628
2629  // 'this' capture.
2630  if (blockDecl->capturesCXXThis()) {
2631    BlockLayoutChunk chunk;
2632    chunk.OffsetInBits =
2633      blockLayout->getElementOffsetInBits(block.CXXThisIndex);
2634    chunk.Capture = 0;
2635    chunks.push_back(chunk);
2636  }
2637
2638  // Variable captures.
2639  for (BlockDecl::capture_const_iterator
2640         i = blockDecl->capture_begin(), e = blockDecl->capture_end();
2641       i != e; ++i) {
2642    const BlockDecl::Capture &capture = *i;
2643    const VarDecl *variable = capture.getVariable();
2644    const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
2645
2646    // Ignore constant captures.
2647    if (captureInfo.isConstant())
2648      continue;
2649
2650    BlockLayoutChunk chunk;
2651    chunk.OffsetInBits =
2652      blockLayout->getElementOffsetInBits(captureInfo.getIndex());
2653    chunk.Capture = &capture;
2654    chunks.push_back(chunk);
2655  }
2656
2657  // Sort by offset.
2658  llvm::array_pod_sort(chunks.begin(), chunks.end());
2659
2660  for (SmallVectorImpl<BlockLayoutChunk>::iterator
2661         i = chunks.begin(), e = chunks.end(); i != e; ++i) {
2662    uint64_t offsetInBits = i->OffsetInBits;
2663    const BlockDecl::Capture *capture = i->Capture;
2664
2665    // If we have a null capture, this must be the C++ 'this' capture.
2666    if (!capture) {
2667      const CXXMethodDecl *method =
2668        cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
2669      QualType type = method->getThisType(C);
2670
2671      fields.push_back(createFieldType("this", type, 0, loc, AS_public,
2672                                       offsetInBits, tunit, tunit));
2673      continue;
2674    }
2675
2676    const VarDecl *variable = capture->getVariable();
2677    StringRef name = variable->getName();
2678
2679    llvm::DIType fieldType;
2680    if (capture->isByRef()) {
2681      std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy);
2682
2683      // FIXME: this creates a second copy of this type!
2684      uint64_t xoffset;
2685      fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
2686      fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first);
2687      fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
2688                                            ptrInfo.first, ptrInfo.second,
2689                                            offsetInBits, 0, fieldType);
2690    } else {
2691      fieldType = createFieldType(name, variable->getType(), 0,
2692                                  loc, AS_public, offsetInBits, tunit, tunit);
2693    }
2694    fields.push_back(fieldType);
2695  }
2696
2697  SmallString<36> typeName;
2698  llvm::raw_svector_ostream(typeName)
2699    << "__block_literal_" << CGM.getUniqueBlockCount();
2700
2701  llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
2702
2703  llvm::DIType type =
2704    DBuilder.createStructType(tunit, typeName.str(), tunit, line,
2705                              CGM.getContext().toBits(block.BlockSize),
2706                              CGM.getContext().toBits(block.BlockAlign),
2707                              0, fieldsArray);
2708  type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
2709
2710  // Get overall information about the block.
2711  unsigned flags = llvm::DIDescriptor::FlagArtificial;
2712  llvm::MDNode *scope = LexicalBlockStack.back();
2713  StringRef name = ".block_descriptor";
2714
2715  // Create the descriptor for the parameter.
2716  llvm::DIVariable debugVar =
2717    DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
2718                                 llvm::DIDescriptor(scope),
2719                                 name, tunit, line, type,
2720                                 CGM.getLangOpts().Optimize, flags,
2721                                 cast<llvm::Argument>(addr)->getArgNo() + 1);
2722
2723  // Insert an llvm.dbg.value into the current block.
2724  llvm::Instruction *declare =
2725    DBuilder.insertDbgValueIntrinsic(addr, 0, debugVar,
2726                                     Builder.GetInsertBlock());
2727  declare->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
2728}
2729
2730/// getStaticDataMemberDeclaration - If D is an out-of-class definition of
2731/// a static data member of a class, find its corresponding in-class
2732/// declaration.
2733llvm::DIDerivedType CGDebugInfo::getStaticDataMemberDeclaration(const Decl *D) {
2734  if (cast<VarDecl>(D)->isStaticDataMember()) {
2735    llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
2736      MI = StaticDataMemberCache.find(D->getCanonicalDecl());
2737    if (MI != StaticDataMemberCache.end())
2738      // Verify the info still exists.
2739      if (llvm::Value *V = MI->second)
2740        return llvm::DIDerivedType(cast<llvm::MDNode>(V));
2741  }
2742  return llvm::DIDerivedType();
2743}
2744
2745/// EmitGlobalVariable - Emit information about a global variable.
2746void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
2747                                     const VarDecl *D) {
2748  assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2749  // Create global variable debug descriptor.
2750  llvm::DIFile Unit = getOrCreateFile(D->getLocation());
2751  unsigned LineNo = getLineNumber(D->getLocation());
2752
2753  setLocation(D->getLocation());
2754
2755  QualType T = D->getType();
2756  if (T->isIncompleteArrayType()) {
2757
2758    // CodeGen turns int[] into int[1] so we'll do the same here.
2759    llvm::APInt ConstVal(32, 1);
2760    QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
2761
2762    T = CGM.getContext().getConstantArrayType(ET, ConstVal,
2763                                              ArrayType::Normal, 0);
2764  }
2765  StringRef DeclName = D->getName();
2766  StringRef LinkageName;
2767  if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext())
2768      && !isa<ObjCMethodDecl>(D->getDeclContext()))
2769    LinkageName = Var->getName();
2770  if (LinkageName == DeclName)
2771    LinkageName = StringRef();
2772  llvm::DIDescriptor DContext =
2773    getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
2774  DBuilder.createStaticVariable(DContext, DeclName, LinkageName,
2775                                Unit, LineNo, getOrCreateType(T, Unit),
2776                                Var->hasInternalLinkage(), Var,
2777                                getStaticDataMemberDeclaration(D));
2778}
2779
2780/// EmitGlobalVariable - Emit information about an objective-c interface.
2781void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
2782                                     ObjCInterfaceDecl *ID) {
2783  assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2784  // Create global variable debug descriptor.
2785  llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
2786  unsigned LineNo = getLineNumber(ID->getLocation());
2787
2788  StringRef Name = ID->getName();
2789
2790  QualType T = CGM.getContext().getObjCInterfaceType(ID);
2791  if (T->isIncompleteArrayType()) {
2792
2793    // CodeGen turns int[] into int[1] so we'll do the same here.
2794    llvm::APInt ConstVal(32, 1);
2795    QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
2796
2797    T = CGM.getContext().getConstantArrayType(ET, ConstVal,
2798                                           ArrayType::Normal, 0);
2799  }
2800
2801  DBuilder.createGlobalVariable(Name, Unit, LineNo,
2802                                getOrCreateType(T, Unit),
2803                                Var->hasInternalLinkage(), Var);
2804}
2805
2806/// EmitGlobalVariable - Emit global variable's debug info.
2807void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
2808                                     llvm::Constant *Init) {
2809  assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2810  // Create the descriptor for the variable.
2811  llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2812  StringRef Name = VD->getName();
2813  llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
2814  if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
2815    const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext());
2816    assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
2817    Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
2818  }
2819  // Do not use DIGlobalVariable for enums.
2820  if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
2821    return;
2822  DBuilder.createStaticVariable(Unit, Name, Name, Unit,
2823                                getLineNumber(VD->getLocation()),
2824                                Ty, true, Init,
2825                                getStaticDataMemberDeclaration(VD));
2826}
2827
2828void CGDebugInfo::EmitUsingDirectiveDecl(const UsingDirectiveDecl &UD) {
2829  SourceLocation Loc = UD.getNamespaceKeyLocation();
2830  llvm::DIFile Unit = getOrCreateFile(Loc);
2831  DBuilder.createUsingDirective(getContextDescriptor(&UD), Unit, getLineNumber(Loc), getOrCreateNameSpace(UD.getNominatedNamespace()));
2832}
2833
2834/// getOrCreateNamesSpace - Return namespace descriptor for the given
2835/// namespace decl.
2836llvm::DINameSpace
2837CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
2838  llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
2839    NameSpaceCache.find(NSDecl);
2840  if (I != NameSpaceCache.end())
2841    return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
2842
2843  unsigned LineNo = getLineNumber(NSDecl->getLocation());
2844  llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
2845  llvm::DIDescriptor Context =
2846    getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
2847  llvm::DINameSpace NS =
2848    DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
2849  NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
2850  return NS;
2851}
2852
2853void CGDebugInfo::finalize() {
2854  for (std::vector<std::pair<void *, llvm::WeakVH> >::const_iterator VI
2855         = ReplaceMap.begin(), VE = ReplaceMap.end(); VI != VE; ++VI) {
2856    llvm::DIType Ty, RepTy;
2857    // Verify that the debug info still exists.
2858    if (llvm::Value *V = VI->second)
2859      Ty = llvm::DIType(cast<llvm::MDNode>(V));
2860
2861    llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
2862      TypeCache.find(VI->first);
2863    if (it != TypeCache.end()) {
2864      // Verify that the debug info still exists.
2865      if (llvm::Value *V = it->second)
2866        RepTy = llvm::DIType(cast<llvm::MDNode>(V));
2867    }
2868
2869    if (Ty.Verify() && Ty.isForwardDecl() && RepTy.Verify()) {
2870      Ty.replaceAllUsesWith(RepTy);
2871    }
2872  }
2873  DBuilder.finalize();
2874}
2875