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