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