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