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