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