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