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