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