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