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