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