CGDebugInfo.cpp revision 590838badd46e0559a6b709857fb87530e546276
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 "clang/AST/ASTContext.h"
18#include "clang/AST/DeclObjC.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/RecordLayout.h"
21#include "clang/Basic/SourceManager.h"
22#include "clang/Basic/FileManager.h"
23#include "clang/Basic/Version.h"
24#include "clang/CodeGen/CodeGenOptions.h"
25#include "llvm/Constants.h"
26#include "llvm/DerivedTypes.h"
27#include "llvm/Instructions.h"
28#include "llvm/Intrinsics.h"
29#include "llvm/Module.h"
30#include "llvm/ADT/StringExtras.h"
31#include "llvm/ADT/SmallVector.h"
32#include "llvm/Support/Dwarf.h"
33#include "llvm/System/Path.h"
34#include "llvm/Target/TargetMachine.h"
35using namespace clang;
36using namespace clang::CodeGen;
37
38CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
39  : CGM(CGM), DebugFactory(CGM.getModule()),
40    FwdDeclCount(0), BlockLiteralGenericSet(false) {
41  CreateCompileUnit();
42}
43
44CGDebugInfo::~CGDebugInfo() {
45  assert(RegionStack.empty() && "Region stack mismatch, stack not empty!");
46}
47
48void CGDebugInfo::setLocation(SourceLocation Loc) {
49  if (Loc.isValid())
50    CurLoc = CGM.getContext().getSourceManager().getInstantiationLoc(Loc);
51}
52
53/// getContextDescriptor - Get context info for the decl.
54llvm::DIDescriptor CGDebugInfo::getContextDescriptor(const Decl *Context,
55                                              llvm::DIDescriptor &CompileUnit) {
56  if (!Context)
57    return CompileUnit;
58
59  llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
60    I = RegionMap.find(Context);
61  if (I != RegionMap.end())
62    return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(I->second));
63
64  // Check namespace.
65  if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
66    return llvm::DIDescriptor(getOrCreateNameSpace(NSDecl, CompileUnit));
67
68  return CompileUnit;
69}
70
71/// getFunctionName - Get function name for the given FunctionDecl. If the
72/// name is constructred on demand (e.g. C++ destructor) then the name
73/// is stored on the side.
74llvm::StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
75  assert (FD && "Invalid FunctionDecl!");
76  IdentifierInfo *FII = FD->getIdentifier();
77  if (FII)
78    return FII->getName();
79
80  // Otherwise construct human readable name for debug info.
81  std::string NS = FD->getNameAsString();
82
83  // Copy this name on the side and use its reference.
84  char *StrPtr = DebugInfoNames.Allocate<char>(NS.length());
85  memcpy(StrPtr, NS.data(), NS.length());
86  return llvm::StringRef(StrPtr, NS.length());
87}
88
89/// getOrCreateFile - Get the file debug info descriptor for the input location.
90llvm::DIFile CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
91  if (!Loc.isValid())
92    // If Location is not valid then use main input file.
93    return DebugFactory.CreateFile(TheCU.getFilename(), TheCU.getDirectory(),
94                                   TheCU);
95  SourceManager &SM = CGM.getContext().getSourceManager();
96  PresumedLoc PLoc = SM.getPresumedLoc(Loc);
97  llvm::sys::Path AbsFileName(PLoc.getFilename());
98  AbsFileName.makeAbsolute();
99
100  return DebugFactory.CreateFile(AbsFileName.getLast(),
101                                 AbsFileName.getDirname(), TheCU);
102}
103/// CreateCompileUnit - Create new compile unit.
104void CGDebugInfo::CreateCompileUnit() {
105
106  // Get absolute path name.
107  SourceManager &SM = CGM.getContext().getSourceManager();
108  std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
109  if (MainFileName.empty())
110    MainFileName = "<unknown>";
111
112  llvm::sys::Path AbsFileName(MainFileName);
113  AbsFileName.makeAbsolute();
114
115  // The main file name provided via the "-main-file-name" option contains just
116  // the file name itself with no path information. This file name may have had
117  // a relative path, so we look into the actual file entry for the main
118  // file to determine the real absolute path for the file.
119  std::string MainFileDir;
120  if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID()))
121    MainFileDir = MainFile->getDir()->getName();
122  else
123    MainFileDir = AbsFileName.getDirname();
124
125  unsigned LangTag;
126  const LangOptions &LO = CGM.getLangOptions();
127  if (LO.CPlusPlus) {
128    if (LO.ObjC1)
129      LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
130    else
131      LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
132  } else if (LO.ObjC1) {
133    LangTag = llvm::dwarf::DW_LANG_ObjC;
134  } else if (LO.C99) {
135    LangTag = llvm::dwarf::DW_LANG_C99;
136  } else {
137    LangTag = llvm::dwarf::DW_LANG_C89;
138  }
139
140  const char *Producer =
141#ifdef CLANG_VENDOR
142    CLANG_VENDOR
143#endif
144    "clang " CLANG_VERSION_STRING;
145
146  // Figure out which version of the ObjC runtime we have.
147  unsigned RuntimeVers = 0;
148  if (LO.ObjC1)
149    RuntimeVers = LO.ObjCNonFragileABI ? 2 : 1;
150
151  // Create new compile unit.
152  TheCU = DebugFactory.CreateCompileUnit(
153    LangTag, AbsFileName.getLast(), MainFileDir, Producer, true,
154    LO.Optimize, CGM.getCodeGenOpts().DwarfDebugFlags, RuntimeVers);
155}
156
157/// CreateType - Get the Basic type from the cache or create a new
158/// one if necessary.
159llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT,
160                                     llvm::DIFile Unit) {
161  unsigned Encoding = 0;
162  switch (BT->getKind()) {
163  default:
164  case BuiltinType::Void:
165    return llvm::DIType();
166  case BuiltinType::UChar:
167  case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break;
168  case BuiltinType::Char_S:
169  case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break;
170  case BuiltinType::UShort:
171  case BuiltinType::UInt:
172  case BuiltinType::ULong:
173  case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break;
174  case BuiltinType::Short:
175  case BuiltinType::Int:
176  case BuiltinType::Long:
177  case BuiltinType::LongLong:  Encoding = llvm::dwarf::DW_ATE_signed; break;
178  case BuiltinType::Bool:      Encoding = llvm::dwarf::DW_ATE_boolean; break;
179  case BuiltinType::Float:
180  case BuiltinType::LongDouble:
181  case BuiltinType::Double:    Encoding = llvm::dwarf::DW_ATE_float; break;
182  }
183  // Bit size, align and offset of the type.
184  uint64_t Size = CGM.getContext().getTypeSize(BT);
185  uint64_t Align = CGM.getContext().getTypeAlign(BT);
186  uint64_t Offset = 0;
187
188  llvm::DIType DbgTy =
189    DebugFactory.CreateBasicType(Unit,
190                                 BT->getName(CGM.getContext().getLangOptions()),
191                                 Unit, 0, Size, Align,
192                                 Offset, /*flags*/ 0, Encoding);
193  return DbgTy;
194}
195
196llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty,
197                                     llvm::DIFile Unit) {
198  // Bit size, align and offset of the type.
199  unsigned Encoding = llvm::dwarf::DW_ATE_complex_float;
200  if (Ty->isComplexIntegerType())
201    Encoding = llvm::dwarf::DW_ATE_lo_user;
202
203  uint64_t Size = CGM.getContext().getTypeSize(Ty);
204  uint64_t Align = CGM.getContext().getTypeAlign(Ty);
205  uint64_t Offset = 0;
206
207  llvm::DIType DbgTy =
208    DebugFactory.CreateBasicType(Unit, "complex",
209                                 Unit, 0, Size, Align,
210                                 Offset, /*flags*/ 0, Encoding);
211  return DbgTy;
212}
213
214/// CreateCVRType - Get the qualified type from the cache or create
215/// a new one if necessary.
216llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit) {
217  QualifierCollector Qc;
218  const Type *T = Qc.strip(Ty);
219
220  // Ignore these qualifiers for now.
221  Qc.removeObjCGCAttr();
222  Qc.removeAddressSpace();
223
224  // We will create one Derived type for one qualifier and recurse to handle any
225  // additional ones.
226  unsigned Tag;
227  if (Qc.hasConst()) {
228    Tag = llvm::dwarf::DW_TAG_const_type;
229    Qc.removeConst();
230  } else if (Qc.hasVolatile()) {
231    Tag = llvm::dwarf::DW_TAG_volatile_type;
232    Qc.removeVolatile();
233  } else if (Qc.hasRestrict()) {
234    Tag = llvm::dwarf::DW_TAG_restrict_type;
235    Qc.removeRestrict();
236  } else {
237    assert(Qc.empty() && "Unknown type qualifier for debug info");
238    return getOrCreateType(QualType(T, 0), Unit);
239  }
240
241  llvm::DIType FromTy = getOrCreateType(Qc.apply(T), Unit);
242
243  // No need to fill in the Name, Line, Size, Alignment, Offset in case of
244  // CVR derived types.
245  llvm::DIType DbgTy =
246    DebugFactory.CreateDerivedType(Tag, Unit, "", Unit,
247                                   0, 0, 0, 0, 0, FromTy);
248  return DbgTy;
249}
250
251llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
252                                     llvm::DIFile Unit) {
253  llvm::DIType DbgTy =
254    CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
255                          Ty->getPointeeType(), Unit);
256  return DbgTy;
257}
258
259llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
260                                     llvm::DIFile Unit) {
261  return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
262                               Ty->getPointeeType(), Unit);
263}
264
265llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag,
266                                                const Type *Ty,
267                                                QualType PointeeTy,
268                                                llvm::DIFile Unit) {
269  llvm::DIType EltTy = getOrCreateType(PointeeTy, Unit);
270
271  // Bit size, align and offset of the type.
272
273  // Size is always the size of a pointer. We can't use getTypeSize here
274  // because that does not return the correct value for references.
275  uint64_t Size =
276    CGM.getContext().Target.getPointerWidth(PointeeTy.getAddressSpace());
277  uint64_t Align = CGM.getContext().getTypeAlign(Ty);
278
279  return
280    DebugFactory.CreateDerivedType(Tag, Unit, "", Unit,
281                                   0, Size, Align, 0, 0, EltTy);
282
283}
284
285llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
286                                     llvm::DIFile Unit) {
287  if (BlockLiteralGenericSet)
288    return BlockLiteralGeneric;
289
290  unsigned Tag = llvm::dwarf::DW_TAG_structure_type;
291
292  llvm::SmallVector<llvm::DIDescriptor, 5> EltTys;
293
294  llvm::DIType FieldTy;
295
296  QualType FType;
297  uint64_t FieldSize, FieldOffset;
298  unsigned FieldAlign;
299
300  llvm::DIArray Elements;
301  llvm::DIType EltTy, DescTy;
302
303  FieldOffset = 0;
304  FType = CGM.getContext().UnsignedLongTy;
305  FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
306  FieldSize = CGM.getContext().getTypeSize(FType);
307  FieldAlign = CGM.getContext().getTypeAlign(FType);
308  FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
309                                           "reserved", Unit,
310                                           0, FieldSize, FieldAlign,
311                                           FieldOffset, 0, FieldTy);
312  EltTys.push_back(FieldTy);
313
314  FieldOffset += FieldSize;
315  FType = CGM.getContext().UnsignedLongTy;
316  FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
317  FieldSize = CGM.getContext().getTypeSize(FType);
318  FieldAlign = CGM.getContext().getTypeAlign(FType);
319  FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
320                                           "Size", Unit,
321                                           0, FieldSize, FieldAlign,
322                                           FieldOffset, 0, FieldTy);
323  EltTys.push_back(FieldTy);
324
325  FieldOffset += FieldSize;
326  Elements = DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
327  EltTys.clear();
328
329  unsigned Flags = llvm::DIType::FlagAppleBlock;
330
331  EltTy = DebugFactory.CreateCompositeType(Tag, Unit, "__block_descriptor",
332                                           Unit, 0, FieldOffset, 0, 0, Flags,
333                                           llvm::DIType(), Elements);
334
335  // Bit size, align and offset of the type.
336  uint64_t Size = CGM.getContext().getTypeSize(Ty);
337  uint64_t Align = CGM.getContext().getTypeAlign(Ty);
338
339  DescTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type,
340                                          Unit, "", Unit,
341                                          0, Size, Align, 0, 0, EltTy);
342
343  FieldOffset = 0;
344  FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
345  FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
346  FieldSize = CGM.getContext().getTypeSize(FType);
347  FieldAlign = CGM.getContext().getTypeAlign(FType);
348  FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
349                                           "__isa", Unit,
350                                           0, FieldSize, FieldAlign,
351                                           FieldOffset, 0, FieldTy);
352  EltTys.push_back(FieldTy);
353
354  FieldOffset += FieldSize;
355  FType = CGM.getContext().IntTy;
356  FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
357  FieldSize = CGM.getContext().getTypeSize(FType);
358  FieldAlign = CGM.getContext().getTypeAlign(FType);
359  FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
360                                           "__flags", Unit,
361                                           0, FieldSize, FieldAlign,
362                                           FieldOffset, 0, FieldTy);
363  EltTys.push_back(FieldTy);
364
365  FieldOffset += FieldSize;
366  FType = CGM.getContext().IntTy;
367  FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
368  FieldSize = CGM.getContext().getTypeSize(FType);
369  FieldAlign = CGM.getContext().getTypeAlign(FType);
370  FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
371                                           "__reserved", Unit,
372                                           0, FieldSize, FieldAlign,
373                                           FieldOffset, 0, FieldTy);
374  EltTys.push_back(FieldTy);
375
376  FieldOffset += FieldSize;
377  FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
378  FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
379  FieldSize = CGM.getContext().getTypeSize(FType);
380  FieldAlign = CGM.getContext().getTypeAlign(FType);
381  FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
382                                           "__FuncPtr", Unit,
383                                           0, FieldSize, FieldAlign,
384                                           FieldOffset, 0, FieldTy);
385  EltTys.push_back(FieldTy);
386
387  FieldOffset += FieldSize;
388  FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
389  FieldTy = DescTy;
390  FieldSize = CGM.getContext().getTypeSize(Ty);
391  FieldAlign = CGM.getContext().getTypeAlign(Ty);
392  FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
393                                           "__descriptor", Unit,
394                                           0, FieldSize, FieldAlign,
395                                           FieldOffset, 0, FieldTy);
396  EltTys.push_back(FieldTy);
397
398  FieldOffset += FieldSize;
399  Elements = DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
400
401  EltTy = DebugFactory.CreateCompositeType(Tag, Unit, "__block_literal_generic",
402                                           Unit, 0, FieldOffset, 0, 0, Flags,
403                                           llvm::DIType(), Elements);
404
405  BlockLiteralGenericSet = true;
406  BlockLiteralGeneric
407    = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type, Unit,
408                                     "", Unit,
409                                     0, Size, Align, 0, 0, EltTy);
410  return BlockLiteralGeneric;
411}
412
413llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty,
414                                     llvm::DIFile Unit) {
415  // Typedefs are derived from some other type.  If we have a typedef of a
416  // typedef, make sure to emit the whole chain.
417  llvm::DIType Src = getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
418
419  // We don't set size information, but do specify where the typedef was
420  // declared.
421  SourceManager &SM = CGM.getContext().getSourceManager();
422  PresumedLoc PLoc = SM.getPresumedLoc(Ty->getDecl()->getLocation());
423  unsigned Line = PLoc.isInvalid() ? 0 : PLoc.getLine();
424
425  llvm::DIDescriptor TyContext
426    = getContextDescriptor(dyn_cast<Decl>(Ty->getDecl()->getDeclContext()),
427                           Unit);
428  llvm::DIType DbgTy =
429    DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_typedef,
430                                   TyContext,
431                                   Ty->getDecl()->getName(), Unit,
432                                   Line, 0, 0, 0, 0, Src);
433  return DbgTy;
434}
435
436llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
437                                     llvm::DIFile Unit) {
438  llvm::SmallVector<llvm::DIDescriptor, 16> EltTys;
439
440  // Add the result type at least.
441  EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit));
442
443  // Set up remainder of arguments if there is a prototype.
444  // FIXME: IF NOT, HOW IS THIS REPRESENTED?  llvm-gcc doesn't represent '...'!
445  if (const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(Ty)) {
446    for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i)
447      EltTys.push_back(getOrCreateType(FTP->getArgType(i), Unit));
448  } else {
449    // FIXME: Handle () case in C.  llvm-gcc doesn't do it either.
450  }
451
452  llvm::DIArray EltTypeArray =
453    DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
454
455  llvm::DIType DbgTy =
456    DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_subroutine_type,
457                                     Unit, "", Unit,
458                                     0, 0, 0, 0, 0,
459                                     llvm::DIType(), EltTypeArray);
460  return DbgTy;
461}
462
463/// CollectRecordFields - A helper function to collect debug info for
464/// record fields. This is used while creating debug info entry for a Record.
465void CGDebugInfo::
466CollectRecordFields(const RecordDecl *RD, llvm::DIFile Unit,
467                    llvm::SmallVectorImpl<llvm::DIDescriptor> &EltTys) {
468  unsigned FieldNo = 0;
469  SourceManager &SM = CGM.getContext().getSourceManager();
470  const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
471  for (RecordDecl::field_iterator I = RD->field_begin(),
472                                  E = RD->field_end();
473       I != E; ++I, ++FieldNo) {
474    FieldDecl *Field = *I;
475    llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
476
477    llvm::StringRef FieldName = Field->getName();
478
479    // Ignore unnamed fields. Do not ignore unnamed records.
480    if (FieldName.empty() && !isa<RecordType>(Field->getType()))
481      continue;
482
483    // Get the location for the field.
484    SourceLocation FieldDefLoc = Field->getLocation();
485    PresumedLoc PLoc = SM.getPresumedLoc(FieldDefLoc);
486    llvm::DIFile FieldDefUnit;
487    unsigned FieldLine = 0;
488
489    if (!PLoc.isInvalid()) {
490      FieldDefUnit = getOrCreateFile(FieldDefLoc);
491      FieldLine = PLoc.getLine();
492    }
493
494    QualType FType = Field->getType();
495    uint64_t FieldSize = 0;
496    unsigned FieldAlign = 0;
497    if (!FType->isIncompleteArrayType()) {
498
499      // Bit size, align and offset of the type.
500      FieldSize = CGM.getContext().getTypeSize(FType);
501      Expr *BitWidth = Field->getBitWidth();
502      if (BitWidth)
503        FieldSize = BitWidth->EvaluateAsInt(CGM.getContext()).getZExtValue();
504
505      FieldAlign =  CGM.getContext().getTypeAlign(FType);
506    }
507
508    uint64_t FieldOffset = RL.getFieldOffset(FieldNo);
509
510    // Create a DW_TAG_member node to remember the offset of this field in the
511    // struct.  FIXME: This is an absolutely insane way to capture this
512    // information.  When we gut debug info, this should be fixed.
513    FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
514                                             FieldName, FieldDefUnit,
515                                             FieldLine, FieldSize, FieldAlign,
516                                             FieldOffset, 0, FieldTy);
517    EltTys.push_back(FieldTy);
518  }
519}
520
521/// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
522/// function type is not updated to include implicit "this" pointer. Use this
523/// routine to get a method type which includes "this" pointer.
524llvm::DIType
525CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
526                                   llvm::DIFile Unit) {
527  llvm::DIType FnTy = getOrCreateType(Method->getType(), Unit);
528
529  // Static methods do not need "this" pointer argument.
530  if (Method->isStatic())
531    return FnTy;
532
533  // Add "this" pointer.
534
535  llvm::DIArray Args = llvm::DICompositeType(FnTy.getNode()).getTypeArray();
536  assert (Args.getNumElements() && "Invalid number of arguments!");
537
538  llvm::SmallVector<llvm::DIDescriptor, 16> Elts;
539
540  // First element is always return type. For 'void' functions it is NULL.
541  Elts.push_back(Args.getElement(0));
542
543  // "this" pointer is always first argument.
544  ASTContext &Context = CGM.getContext();
545  QualType ThisPtr =
546    Context.getPointerType(Context.getTagDeclType(Method->getParent()));
547  llvm::DIType ThisPtrType =
548    DebugFactory.CreateArtificialType(getOrCreateType(ThisPtr, Unit));
549  TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType.getNode();
550  Elts.push_back(ThisPtrType);
551
552  // Copy rest of the arguments.
553  for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
554    Elts.push_back(Args.getElement(i));
555
556  llvm::DIArray EltTypeArray =
557    DebugFactory.GetOrCreateArray(Elts.data(), Elts.size());
558
559  return
560    DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_subroutine_type,
561                                     Unit, "", Unit,
562                                     0, 0, 0, 0, 0,
563                                     llvm::DIType(), EltTypeArray);
564}
565
566/// CreateCXXMemberFunction - A helper function to create a DISubprogram for
567/// a single member function GlobalDecl.
568llvm::DISubprogram
569CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
570                                     llvm::DIFile Unit,
571                                     llvm::DICompositeType &RecordTy) {
572  bool IsCtorOrDtor =
573    isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
574
575  llvm::StringRef MethodName = getFunctionName(Method);
576  llvm::DIType MethodTy = getOrCreateMethodType(Method, Unit);
577
578  // Since a single ctor/dtor corresponds to multiple functions, it doesn't
579  // make sense to give a single ctor/dtor a linkage name.
580  MangleBuffer MethodLinkageName;
581  if (!IsCtorOrDtor)
582    CGM.getMangledName(MethodLinkageName, Method);
583
584  SourceManager &SM = CGM.getContext().getSourceManager();
585
586  // Get the location for the method.
587  SourceLocation MethodDefLoc = Method->getLocation();
588  PresumedLoc PLoc = SM.getPresumedLoc(MethodDefLoc);
589  llvm::DIFile MethodDefUnit;
590  unsigned MethodLine = 0;
591
592  if (!PLoc.isInvalid()) {
593    MethodDefUnit = getOrCreateFile(MethodDefLoc);
594    MethodLine = PLoc.getLine();
595  }
596
597  // Collect virtual method info.
598  llvm::DIType ContainingType;
599  unsigned Virtuality = 0;
600  unsigned VIndex = 0;
601
602  if (Method->isVirtual()) {
603    if (Method->isPure())
604      Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
605    else
606      Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
607
608    // It doesn't make sense to give a virtual destructor a vtable index,
609    // since a single destructor has two entries in the vtable.
610    if (!isa<CXXDestructorDecl>(Method))
611      VIndex = CGM.getVTables().getMethodVtableIndex(Method);
612    ContainingType = RecordTy;
613  }
614
615  llvm::DISubprogram SP =
616    DebugFactory.CreateSubprogram(RecordTy , MethodName, MethodName,
617                                  MethodLinkageName,
618                                  MethodDefUnit, MethodLine,
619                                  MethodTy, /*isLocalToUnit=*/false,
620                                  Method->isThisDeclarationADefinition(),
621                                  Virtuality, VIndex, ContainingType);
622
623  // Don't cache ctors or dtors since we have to emit multiple functions for
624  // a single ctor or dtor.
625  if (!IsCtorOrDtor && Method->isThisDeclarationADefinition())
626    SPCache[Method] = llvm::WeakVH(SP.getNode());
627
628  return SP;
629}
630
631/// CollectCXXMemberFunctions - A helper function to collect debug info for
632/// C++ member functions.This is used while creating debug info entry for
633/// a Record.
634void CGDebugInfo::
635CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
636                          llvm::SmallVectorImpl<llvm::DIDescriptor> &EltTys,
637                          llvm::DICompositeType &RecordTy) {
638  for(CXXRecordDecl::method_iterator I = RD->method_begin(),
639        E = RD->method_end(); I != E; ++I) {
640    const CXXMethodDecl *Method = *I;
641
642    if (Method->isImplicit() && !Method->isUsed())
643      continue;
644
645    EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
646  }
647}
648
649/// CollectCXXBases - A helper function to collect debug info for
650/// C++ base classes. This is used while creating debug info entry for
651/// a Record.
652void CGDebugInfo::
653CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
654                llvm::SmallVectorImpl<llvm::DIDescriptor> &EltTys,
655                llvm::DICompositeType &RecordTy) {
656
657  const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
658  for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
659         BE = RD->bases_end(); BI != BE; ++BI) {
660    unsigned BFlags = 0;
661    uint64_t BaseOffset;
662
663    const CXXRecordDecl *Base =
664      cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl());
665
666    if (BI->isVirtual()) {
667      // virtual base offset offset is -ve. The code generator emits dwarf
668      // expression where it expects +ve number.
669      BaseOffset = 0 - CGM.getVTables().getVirtualBaseOffsetOffset(RD, Base);
670      BFlags = llvm::DIType::FlagVirtual;
671    } else
672      BaseOffset = RL.getBaseClassOffset(Base);
673
674    AccessSpecifier Access = BI->getAccessSpecifier();
675    if (Access == clang::AS_private)
676      BFlags |= llvm::DIType::FlagPrivate;
677    else if (Access == clang::AS_protected)
678      BFlags |= llvm::DIType::FlagProtected;
679
680    llvm::DIType DTy =
681      DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_inheritance,
682                                     RecordTy, llvm::StringRef(),
683                                     Unit, 0, 0, 0,
684                                     BaseOffset, BFlags,
685                                     getOrCreateType(BI->getType(),
686                                                     Unit));
687    EltTys.push_back(DTy);
688  }
689}
690
691/// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
692llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
693  if (VTablePtrType.isValid())
694    return VTablePtrType;
695
696  ASTContext &Context = CGM.getContext();
697
698  /* Function type */
699  llvm::SmallVector<llvm::DIDescriptor, 16> STys;
700  STys.push_back(getOrCreateType(Context.IntTy, Unit));
701  llvm::DIArray SElements =
702    DebugFactory.GetOrCreateArray(STys.data(), STys.size());
703  llvm::DIType SubTy =
704    DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_subroutine_type,
705                                     Unit, "", Unit,
706                                     0, 0, 0, 0, 0, llvm::DIType(), SElements);
707
708  unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
709  llvm::DIType vtbl_ptr_type
710    = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type,
711                                     Unit, "__vtbl_ptr_type", Unit,
712                                     0, Size, 0, 0, 0, SubTy);
713
714  VTablePtrType =
715    DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type,
716                                   Unit, "", Unit,
717                                   0, Size, 0, 0, 0, vtbl_ptr_type);
718  return VTablePtrType;
719}
720
721/// getVtableName - Get vtable name for the given Class.
722llvm::StringRef CGDebugInfo::getVtableName(const CXXRecordDecl *RD) {
723  // Otherwise construct gdb compatible name name.
724  std::string Name = "_vptr$" + RD->getNameAsString();
725
726  // Copy this name on the side and use its reference.
727  char *StrPtr = DebugInfoNames.Allocate<char>(Name.length());
728  memcpy(StrPtr, Name.data(), Name.length());
729  return llvm::StringRef(StrPtr, Name.length());
730}
731
732
733/// CollectVtableInfo - If the C++ class has vtable info then insert appropriate
734/// debug info entry in EltTys vector.
735void CGDebugInfo::
736CollectVtableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
737                  llvm::SmallVectorImpl<llvm::DIDescriptor> &EltTys) {
738  const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
739
740  // If there is a primary base then it will hold vtable info.
741  if (RL.getPrimaryBase())
742    return;
743
744  // If this class is not dynamic then there is not any vtable info to collect.
745  if (!RD->isDynamicClass())
746    return;
747
748  unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
749  llvm::DIType VPTR
750    = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
751                                     getVtableName(RD), Unit,
752                                     0, Size, 0, 0, 0,
753                                     getOrCreateVTablePtrType(Unit));
754  EltTys.push_back(VPTR);
755}
756
757/// CreateType - get structure or union type.
758llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty,
759                                     llvm::DIFile Unit) {
760  RecordDecl *RD = Ty->getDecl();
761
762  unsigned Tag;
763  if (RD->isStruct())
764    Tag = llvm::dwarf::DW_TAG_structure_type;
765  else if (RD->isUnion())
766    Tag = llvm::dwarf::DW_TAG_union_type;
767  else {
768    assert(RD->isClass() && "Unknown RecordType!");
769    Tag = llvm::dwarf::DW_TAG_class_type;
770  }
771
772  SourceManager &SM = CGM.getContext().getSourceManager();
773
774  // Get overall information about the record type for the debug info.
775  PresumedLoc PLoc = SM.getPresumedLoc(RD->getLocation());
776  llvm::DIFile DefUnit;
777  unsigned Line = 0;
778  if (!PLoc.isInvalid()) {
779    DefUnit = getOrCreateFile(RD->getLocation());
780    Line = PLoc.getLine();
781  }
782
783  // Records and classes and unions can all be recursive.  To handle them, we
784  // first generate a debug descriptor for the struct as a forward declaration.
785  // Then (if it is a definition) we go through and get debug info for all of
786  // its members.  Finally, we create a descriptor for the complete type (which
787  // may refer to the forward decl if the struct is recursive) and replace all
788  // uses of the forward declaration with the final definition.
789
790  // A RD->getName() is not unique. However, the debug info descriptors
791  // are uniqued so use type name to ensure uniquness.
792  llvm::SmallString<128> FwdDeclName;
793  llvm::raw_svector_ostream(FwdDeclName) << "fwd.type." << FwdDeclCount++;
794  llvm::DIDescriptor FDContext =
795    getContextDescriptor(dyn_cast<Decl>(RD->getDeclContext()), Unit);
796  llvm::DICompositeType FwdDecl =
797    DebugFactory.CreateCompositeType(Tag, FDContext, FwdDeclName,
798                                     DefUnit, Line, 0, 0, 0, 0,
799                                     llvm::DIType(), llvm::DIArray());
800
801  // If this is just a forward declaration, return it.
802  if (!RD->getDefinition())
803    return FwdDecl;
804
805  llvm::TrackingVH<llvm::MDNode> FwdDeclNode = FwdDecl.getNode();
806  // Otherwise, insert it into the TypeCache so that recursive uses will find
807  // it.
808  TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl.getNode();
809  // Push the struct on region stack.
810  RegionStack.push_back(FwdDecl.getNode());
811  RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl.getNode());
812
813  // Convert all the elements.
814  llvm::SmallVector<llvm::DIDescriptor, 16> EltTys;
815
816  const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
817  if (CXXDecl) {
818    CollectCXXBases(CXXDecl, Unit, EltTys, FwdDecl);
819    CollectVtableInfo(CXXDecl, Unit, EltTys);
820  }
821  CollectRecordFields(RD, Unit, EltTys);
822  llvm::MDNode *ContainingType = NULL;
823  if (CXXDecl) {
824    CollectCXXMemberFunctions(CXXDecl, Unit, EltTys, FwdDecl);
825
826    // A class's primary base or the class itself contains the vtable.
827    const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
828    if (const CXXRecordDecl *PBase = RL.getPrimaryBase())
829      ContainingType =
830        getOrCreateType(QualType(PBase->getTypeForDecl(), 0), Unit).getNode();
831    else if (CXXDecl->isDynamicClass())
832      ContainingType = FwdDecl.getNode();
833  }
834
835  llvm::DIArray Elements =
836    DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
837
838  // Bit size, align and offset of the type.
839  uint64_t Size = CGM.getContext().getTypeSize(Ty);
840  uint64_t Align = CGM.getContext().getTypeAlign(Ty);
841
842  RegionStack.pop_back();
843  llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator RI =
844    RegionMap.find(Ty->getDecl());
845  if (RI != RegionMap.end())
846    RegionMap.erase(RI);
847
848  llvm::DIDescriptor RDContext =
849    getContextDescriptor(dyn_cast<Decl>(RD->getDeclContext()), Unit);
850  llvm::DICompositeType RealDecl =
851    DebugFactory.CreateCompositeType(Tag, RDContext,
852                                     RD->getName(),
853                                     DefUnit, Line, Size, Align, 0, 0,
854                                     llvm::DIType(), Elements,
855                                     0, ContainingType);
856
857  // Now that we have a real decl for the struct, replace anything using the
858  // old decl with the new one.  This will recursively update the debug info.
859  llvm::DIDerivedType(FwdDeclNode).replaceAllUsesWith(RealDecl);
860  RegionMap[RD] = llvm::WeakVH(RealDecl.getNode());
861  return RealDecl;
862}
863
864/// CreateType - get objective-c interface type.
865llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
866                                     llvm::DIFile Unit) {
867  ObjCInterfaceDecl *ID = Ty->getDecl();
868
869  unsigned Tag = llvm::dwarf::DW_TAG_structure_type;
870  SourceManager &SM = CGM.getContext().getSourceManager();
871
872  // Get overall information about the record type for the debug info.
873  llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
874  PresumedLoc PLoc = SM.getPresumedLoc(ID->getLocation());
875  unsigned Line = PLoc.isInvalid() ? 0 : PLoc.getLine();
876
877
878  unsigned RuntimeLang = TheCU.getLanguage();
879
880  // To handle recursive interface, we
881  // first generate a debug descriptor for the struct as a forward declaration.
882  // Then (if it is a definition) we go through and get debug info for all of
883  // its members.  Finally, we create a descriptor for the complete type (which
884  // may refer to the forward decl if the struct is recursive) and replace all
885  // uses of the forward declaration with the final definition.
886  llvm::DICompositeType FwdDecl =
887    DebugFactory.CreateCompositeType(Tag, Unit, ID->getName(),
888                                     DefUnit, Line, 0, 0, 0, 0,
889                                     llvm::DIType(), llvm::DIArray(),
890                                     RuntimeLang);
891
892  // If this is just a forward declaration, return it.
893  if (ID->isForwardDecl())
894    return FwdDecl;
895
896  llvm::TrackingVH<llvm::MDNode> FwdDeclNode = FwdDecl.getNode();
897  // Otherwise, insert it into the TypeCache so that recursive uses will find
898  // it.
899  TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl.getNode();
900  // Push the struct on region stack.
901  RegionStack.push_back(FwdDecl.getNode());
902  RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl.getNode());
903
904  // Convert all the elements.
905  llvm::SmallVector<llvm::DIDescriptor, 16> EltTys;
906
907  ObjCInterfaceDecl *SClass = ID->getSuperClass();
908  if (SClass) {
909    llvm::DIType SClassTy =
910      getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
911    llvm::DIType InhTag =
912      DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_inheritance,
913                                     Unit, "", Unit, 0, 0, 0,
914                                     0 /* offset */, 0, SClassTy);
915    EltTys.push_back(InhTag);
916  }
917
918  const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
919
920  unsigned FieldNo = 0;
921  for (ObjCInterfaceDecl::ivar_iterator I = ID->ivar_begin(),
922         E = ID->ivar_end();  I != E; ++I, ++FieldNo) {
923    ObjCIvarDecl *Field = *I;
924    llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
925
926    llvm::StringRef FieldName = Field->getName();
927
928    // Ignore unnamed fields.
929    if (FieldName.empty())
930      continue;
931
932    // Get the location for the field.
933    SourceLocation FieldDefLoc = Field->getLocation();
934    llvm::DIFile FieldDefUnit = getOrCreateFile(FieldDefLoc);
935    PresumedLoc PLoc = SM.getPresumedLoc(FieldDefLoc);
936    unsigned FieldLine = PLoc.isInvalid() ? 0 : PLoc.getLine();
937
938
939    QualType FType = Field->getType();
940    uint64_t FieldSize = 0;
941    unsigned FieldAlign = 0;
942
943    if (!FType->isIncompleteArrayType()) {
944
945      // Bit size, align and offset of the type.
946      FieldSize = CGM.getContext().getTypeSize(FType);
947      Expr *BitWidth = Field->getBitWidth();
948      if (BitWidth)
949        FieldSize = BitWidth->EvaluateAsInt(CGM.getContext()).getZExtValue();
950
951      FieldAlign =  CGM.getContext().getTypeAlign(FType);
952    }
953
954    uint64_t FieldOffset = RL.getFieldOffset(FieldNo);
955
956    unsigned Flags = 0;
957    if (Field->getAccessControl() == ObjCIvarDecl::Protected)
958      Flags = llvm::DIType::FlagProtected;
959    else if (Field->getAccessControl() == ObjCIvarDecl::Private)
960      Flags = llvm::DIType::FlagPrivate;
961
962    // Create a DW_TAG_member node to remember the offset of this field in the
963    // struct.  FIXME: This is an absolutely insane way to capture this
964    // information.  When we gut debug info, this should be fixed.
965    FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
966                                             FieldName, FieldDefUnit,
967                                             FieldLine, FieldSize, FieldAlign,
968                                             FieldOffset, Flags, FieldTy);
969    EltTys.push_back(FieldTy);
970  }
971
972  llvm::DIArray Elements =
973    DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
974
975  RegionStack.pop_back();
976  llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator RI =
977    RegionMap.find(Ty->getDecl());
978  if (RI != RegionMap.end())
979    RegionMap.erase(RI);
980
981  // Bit size, align and offset of the type.
982  uint64_t Size = CGM.getContext().getTypeSize(Ty);
983  uint64_t Align = CGM.getContext().getTypeAlign(Ty);
984
985  llvm::DICompositeType RealDecl =
986    DebugFactory.CreateCompositeType(Tag, Unit, ID->getName(), DefUnit,
987                                     Line, Size, Align, 0, 0, llvm::DIType(),
988                                     Elements, RuntimeLang);
989
990  // Now that we have a real decl for the struct, replace anything using the
991  // old decl with the new one.  This will recursively update the debug info.
992  llvm::DIDerivedType(FwdDeclNode).replaceAllUsesWith(RealDecl);
993  RegionMap[ID] = llvm::WeakVH(RealDecl.getNode());
994
995  return RealDecl;
996}
997
998llvm::DIType CGDebugInfo::CreateType(const EnumType *Ty,
999                                     llvm::DIFile Unit) {
1000  EnumDecl *ED = Ty->getDecl();
1001
1002  llvm::SmallVector<llvm::DIDescriptor, 32> Enumerators;
1003
1004  // Create DIEnumerator elements for each enumerator.
1005  for (EnumDecl::enumerator_iterator
1006         Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
1007       Enum != EnumEnd; ++Enum) {
1008    Enumerators.push_back(DebugFactory.CreateEnumerator(Enum->getName(),
1009                                            Enum->getInitVal().getZExtValue()));
1010  }
1011
1012  // Return a CompositeType for the enum itself.
1013  llvm::DIArray EltArray =
1014    DebugFactory.GetOrCreateArray(Enumerators.data(), Enumerators.size());
1015
1016  SourceLocation DefLoc = ED->getLocation();
1017  llvm::DIFile DefUnit = getOrCreateFile(DefLoc);
1018  SourceManager &SM = CGM.getContext().getSourceManager();
1019  PresumedLoc PLoc = SM.getPresumedLoc(DefLoc);
1020  unsigned Line = PLoc.isInvalid() ? 0 : PLoc.getLine();
1021
1022
1023  // Size and align of the type.
1024  uint64_t Size = 0;
1025  unsigned Align = 0;
1026  if (!Ty->isIncompleteType()) {
1027    Size = CGM.getContext().getTypeSize(Ty);
1028    Align = CGM.getContext().getTypeAlign(Ty);
1029  }
1030
1031  llvm::DIType DbgTy =
1032    DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_enumeration_type,
1033                                     Unit, ED->getName(), DefUnit, Line,
1034                                     Size, Align, 0, 0,
1035                                     llvm::DIType(), EltArray);
1036  return DbgTy;
1037}
1038
1039llvm::DIType CGDebugInfo::CreateType(const TagType *Ty,
1040                                     llvm::DIFile Unit) {
1041  if (const RecordType *RT = dyn_cast<RecordType>(Ty))
1042    return CreateType(RT, Unit);
1043  else if (const EnumType *ET = dyn_cast<EnumType>(Ty))
1044    return CreateType(ET, Unit);
1045
1046  return llvm::DIType();
1047}
1048
1049llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty,
1050				     llvm::DIFile Unit) {
1051  llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1052  uint64_t NumElems = Ty->getNumElements();
1053  if (NumElems > 0)
1054    --NumElems;
1055  llvm::SmallVector<llvm::DIDescriptor, 8> Subscripts;
1056  Subscripts.push_back(DebugFactory.GetOrCreateSubrange(0, NumElems));
1057
1058  llvm::DIArray SubscriptArray =
1059    DebugFactory.GetOrCreateArray(Subscripts.data(), Subscripts.size());
1060
1061  uint64_t Size = CGM.getContext().getTypeSize(Ty);
1062  uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1063
1064  return
1065    DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_vector_type,
1066                                     Unit, "", Unit,
1067                                     0, Size, Align, 0, 0,
1068				     ElementTy,  SubscriptArray);
1069}
1070
1071llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1072                                     llvm::DIFile Unit) {
1073  uint64_t Size;
1074  uint64_t Align;
1075
1076
1077  // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1078  if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1079    Size = 0;
1080    Align =
1081      CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1082  } else if (Ty->isIncompleteArrayType()) {
1083    Size = 0;
1084    Align = CGM.getContext().getTypeAlign(Ty->getElementType());
1085  } else {
1086    // Size and align of the whole array, not the element type.
1087    Size = CGM.getContext().getTypeSize(Ty);
1088    Align = CGM.getContext().getTypeAlign(Ty);
1089  }
1090
1091  // Add the dimensions of the array.  FIXME: This loses CV qualifiers from
1092  // interior arrays, do we care?  Why aren't nested arrays represented the
1093  // obvious/recursive way?
1094  llvm::SmallVector<llvm::DIDescriptor, 8> Subscripts;
1095  QualType EltTy(Ty, 0);
1096  while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1097    uint64_t Upper = 0;
1098    if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1099      if (CAT->getSize().getZExtValue())
1100        Upper = CAT->getSize().getZExtValue() - 1;
1101    // FIXME: Verify this is right for VLAs.
1102    Subscripts.push_back(DebugFactory.GetOrCreateSubrange(0, Upper));
1103    EltTy = Ty->getElementType();
1104  }
1105
1106  llvm::DIArray SubscriptArray =
1107    DebugFactory.GetOrCreateArray(Subscripts.data(), Subscripts.size());
1108
1109  llvm::DIType DbgTy =
1110    DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_array_type,
1111                                     Unit, "", Unit,
1112                                     0, Size, Align, 0, 0,
1113                                     getOrCreateType(EltTy, Unit),
1114                                     SubscriptArray);
1115  return DbgTy;
1116}
1117
1118llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
1119                                     llvm::DIFile Unit) {
1120  return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
1121                               Ty, Ty->getPointeeType(), Unit);
1122}
1123
1124llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
1125                                     llvm::DIFile U) {
1126  QualType PointerDiffTy = CGM.getContext().getPointerDiffType();
1127  llvm::DIType PointerDiffDITy = getOrCreateType(PointerDiffTy, U);
1128
1129  if (!Ty->getPointeeType()->isFunctionType()) {
1130    // We have a data member pointer type.
1131    return PointerDiffDITy;
1132  }
1133
1134  // We have a member function pointer type. Treat it as a struct with two
1135  // ptrdiff_t members.
1136  std::pair<uint64_t, unsigned> Info = CGM.getContext().getTypeInfo(Ty);
1137
1138  uint64_t FieldOffset = 0;
1139  llvm::DIDescriptor ElementTypes[2];
1140
1141  // FIXME: This should probably be a function type instead.
1142  ElementTypes[0] =
1143    DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, U,
1144                                   "ptr", U, 0,
1145                                   Info.first, Info.second, FieldOffset, 0,
1146                                   PointerDiffDITy);
1147  FieldOffset += Info.first;
1148
1149  ElementTypes[1] =
1150    DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, U,
1151                                   "ptr", U, 0,
1152                                   Info.first, Info.second, FieldOffset, 0,
1153                                   PointerDiffDITy);
1154
1155  llvm::DIArray Elements =
1156    DebugFactory.GetOrCreateArray(&ElementTypes[0],
1157                                  llvm::array_lengthof(ElementTypes));
1158
1159  return DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_structure_type,
1160                                          U, llvm::StringRef("test"),
1161                                          U, 0, FieldOffset,
1162                                          0, 0, 0, llvm::DIType(), Elements);
1163}
1164
1165static QualType UnwrapTypeForDebugInfo(QualType T) {
1166  do {
1167    QualType LastT = T;
1168    switch (T->getTypeClass()) {
1169    default:
1170      return T;
1171    case Type::TemplateSpecialization:
1172      T = cast<TemplateSpecializationType>(T)->desugar();
1173      break;
1174    case Type::TypeOfExpr: {
1175      TypeOfExprType *Ty = cast<TypeOfExprType>(T);
1176      T = Ty->getUnderlyingExpr()->getType();
1177      break;
1178    }
1179    case Type::TypeOf:
1180      T = cast<TypeOfType>(T)->getUnderlyingType();
1181      break;
1182    case Type::Decltype:
1183      T = cast<DecltypeType>(T)->getUnderlyingType();
1184      break;
1185    case Type::QualifiedName:
1186      T = cast<QualifiedNameType>(T)->getNamedType();
1187      break;
1188    case Type::SubstTemplateTypeParm:
1189      T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
1190      break;
1191    case Type::Elaborated:
1192      T = cast<ElaboratedType>(T)->getUnderlyingType();
1193      break;
1194    }
1195
1196    assert(T != LastT && "Type unwrapping failed to unwrap!");
1197    if (T == LastT)
1198      return T;
1199  } while (true);
1200
1201  return T;
1202}
1203
1204/// getOrCreateType - Get the type from the cache or create a new
1205/// one if necessary.
1206llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty,
1207                                          llvm::DIFile Unit) {
1208  if (Ty.isNull())
1209    return llvm::DIType();
1210
1211  // Unwrap the type as needed for debug information.
1212  Ty = UnwrapTypeForDebugInfo(Ty);
1213
1214  // Check for existing entry.
1215  llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1216    TypeCache.find(Ty.getAsOpaquePtr());
1217  if (it != TypeCache.end()) {
1218    // Verify that the debug info still exists.
1219    if (&*it->second)
1220      return llvm::DIType(cast<llvm::MDNode>(it->second));
1221  }
1222
1223  // Otherwise create the type.
1224  llvm::DIType Res = CreateTypeNode(Ty, Unit);
1225
1226  // And update the type cache.
1227  TypeCache[Ty.getAsOpaquePtr()] = Res.getNode();
1228  return Res;
1229}
1230
1231/// CreateTypeNode - Create a new debug type node.
1232llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty,
1233                                         llvm::DIFile Unit) {
1234  // Handle qualifiers, which recursively handles what they refer to.
1235  if (Ty.hasLocalQualifiers())
1236    return CreateQualifiedType(Ty, Unit);
1237
1238  const char *Diag = 0;
1239
1240  // Work out details of type.
1241  switch (Ty->getTypeClass()) {
1242#define TYPE(Class, Base)
1243#define ABSTRACT_TYPE(Class, Base)
1244#define NON_CANONICAL_TYPE(Class, Base)
1245#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1246#include "clang/AST/TypeNodes.def"
1247    assert(false && "Dependent types cannot show up in debug information");
1248
1249  // FIXME: Handle these.
1250  case Type::ExtVector:
1251    return llvm::DIType();
1252
1253  case Type::Vector:
1254    return CreateType(cast<VectorType>(Ty), Unit);
1255  case Type::ObjCObjectPointer:
1256    return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
1257  case Type::ObjCInterface:
1258    return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
1259  case Type::Builtin: return CreateType(cast<BuiltinType>(Ty), Unit);
1260  case Type::Complex: return CreateType(cast<ComplexType>(Ty), Unit);
1261  case Type::Pointer: return CreateType(cast<PointerType>(Ty), Unit);
1262  case Type::BlockPointer:
1263    return CreateType(cast<BlockPointerType>(Ty), Unit);
1264  case Type::Typedef: return CreateType(cast<TypedefType>(Ty), Unit);
1265  case Type::Record:
1266  case Type::Enum:
1267    return CreateType(cast<TagType>(Ty), Unit);
1268  case Type::FunctionProto:
1269  case Type::FunctionNoProto:
1270    return CreateType(cast<FunctionType>(Ty), Unit);
1271  case Type::ConstantArray:
1272  case Type::VariableArray:
1273  case Type::IncompleteArray:
1274    return CreateType(cast<ArrayType>(Ty), Unit);
1275
1276  case Type::LValueReference:
1277    return CreateType(cast<LValueReferenceType>(Ty), Unit);
1278
1279  case Type::MemberPointer:
1280    return CreateType(cast<MemberPointerType>(Ty), Unit);
1281
1282  case Type::InjectedClassName:
1283  case Type::TemplateSpecialization:
1284  case Type::Elaborated:
1285  case Type::QualifiedName:
1286  case Type::SubstTemplateTypeParm:
1287  case Type::TypeOfExpr:
1288  case Type::TypeOf:
1289  case Type::Decltype:
1290    llvm_unreachable("type should have been unwrapped!");
1291    return llvm::DIType();
1292
1293  case Type::RValueReference:
1294    // FIXME: Implement!
1295    Diag = "rvalue references";
1296    break;
1297  }
1298
1299  assert(Diag && "Fall through without a diagnostic?");
1300  unsigned DiagID = CGM.getDiags().getCustomDiagID(Diagnostic::Error,
1301                               "debug information for %0 is not yet supported");
1302  CGM.getDiags().Report(FullSourceLoc(), DiagID)
1303    << Diag;
1304  return llvm::DIType();
1305}
1306
1307/// EmitFunctionStart - Constructs the debug code for entering a function -
1308/// "llvm.dbg.func.start.".
1309void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
1310                                    llvm::Function *Fn,
1311                                    CGBuilderTy &Builder) {
1312
1313  llvm::StringRef Name;
1314  MangleBuffer LinkageName;
1315
1316  const Decl *D = GD.getDecl();
1317  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1318    // If there is a DISubprogram for  this function available then use it.
1319    llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
1320      FI = SPCache.find(FD);
1321    if (FI != SPCache.end()) {
1322      llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(FI->second));
1323      if (SP.isSubprogram() && llvm::DISubprogram(SP.getNode()).isDefinition()) {
1324        RegionStack.push_back(SP.getNode());
1325        RegionMap[D] = llvm::WeakVH(SP.getNode());
1326        return;
1327      }
1328    }
1329    Name = getFunctionName(FD);
1330    if (!Name.empty() && Name[0] == '\01')
1331      Name = Name.substr(1);
1332    // Use mangled name as linkage name for c/c++ functions.
1333    CGM.getMangledName(LinkageName, GD);
1334  } else {
1335    // Use llvm function name as linkage name.
1336    Name = Fn->getName();
1337    LinkageName.setString(Name);
1338    if (!Name.empty() && Name[0] == '\01')
1339      Name = Name.substr(1);
1340  }
1341
1342  // It is expected that CurLoc is set before using EmitFunctionStart.
1343  // Usually, CurLoc points to the left bracket location of compound
1344  // statement representing function body.
1345  llvm::DIFile Unit = getOrCreateFile(CurLoc);
1346  SourceManager &SM = CGM.getContext().getSourceManager();
1347  unsigned LineNo = SM.getPresumedLoc(CurLoc).getLine();
1348
1349  llvm::DISubprogram SP =
1350    DebugFactory.CreateSubprogram(Unit, Name, Name, LinkageName, Unit, LineNo,
1351                                  getOrCreateType(FnType, Unit),
1352                                  Fn->hasInternalLinkage(), true/*definition*/);
1353
1354  // Push function on region stack.
1355  RegionStack.push_back(SP.getNode());
1356  RegionMap[D] = llvm::WeakVH(SP.getNode());
1357}
1358
1359
1360void CGDebugInfo::EmitStopPoint(llvm::Function *Fn, CGBuilderTy &Builder) {
1361  if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
1362
1363  // Don't bother if things are the same as last time.
1364  SourceManager &SM = CGM.getContext().getSourceManager();
1365  if (CurLoc == PrevLoc
1366       || (SM.getInstantiationLineNumber(CurLoc) ==
1367           SM.getInstantiationLineNumber(PrevLoc)
1368           && SM.isFromSameFile(CurLoc, PrevLoc)))
1369    return;
1370
1371  // Update last state.
1372  PrevLoc = CurLoc;
1373
1374  // Get the appropriate compile unit.
1375  llvm::DIFile Unit = getOrCreateFile(CurLoc);
1376  PresumedLoc PLoc = SM.getPresumedLoc(CurLoc);
1377
1378  llvm::DIDescriptor DR(RegionStack.back());
1379  llvm::DIScope DS = llvm::DIScope(DR.getNode());
1380  llvm::DILocation DO(NULL);
1381  llvm::DILocation DL =
1382    DebugFactory.CreateLocation(PLoc.getLine(), PLoc.getColumn(),
1383                                DS, DO);
1384  Builder.SetCurrentDebugLocation(DL.getNode());
1385}
1386
1387/// EmitRegionStart- Constructs the debug code for entering a declarative
1388/// region - "llvm.dbg.region.start.".
1389void CGDebugInfo::EmitRegionStart(llvm::Function *Fn, CGBuilderTy &Builder) {
1390  SourceManager &SM = CGM.getContext().getSourceManager();
1391  PresumedLoc PLoc = SM.getPresumedLoc(CurLoc);
1392  llvm::DIDescriptor D =
1393    DebugFactory.CreateLexicalBlock(RegionStack.empty() ?
1394                                    llvm::DIDescriptor() :
1395                                    llvm::DIDescriptor(RegionStack.back()),
1396                                    PLoc.getLine(), PLoc.getColumn());
1397  RegionStack.push_back(D.getNode());
1398}
1399
1400/// EmitRegionEnd - Constructs the debug code for exiting a declarative
1401/// region - "llvm.dbg.region.end."
1402void CGDebugInfo::EmitRegionEnd(llvm::Function *Fn, CGBuilderTy &Builder) {
1403  assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
1404
1405  // Provide an region stop point.
1406  EmitStopPoint(Fn, Builder);
1407
1408  RegionStack.pop_back();
1409}
1410
1411// EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
1412// See BuildByRefType.
1413llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const ValueDecl *VD,
1414                                                       uint64_t *XOffset) {
1415
1416  llvm::SmallVector<llvm::DIDescriptor, 5> EltTys;
1417
1418  QualType FType;
1419  uint64_t FieldSize, FieldOffset;
1420  unsigned FieldAlign;
1421
1422  llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
1423  QualType Type = VD->getType();
1424
1425  FieldOffset = 0;
1426  FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1427  llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1428  FieldSize = CGM.getContext().getTypeSize(FType);
1429  FieldAlign = CGM.getContext().getTypeAlign(FType);
1430  FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1431                                           "__isa", Unit,
1432                                           0, FieldSize, FieldAlign,
1433                                           FieldOffset, 0, FieldTy);
1434  EltTys.push_back(FieldTy);
1435  FieldOffset += FieldSize;
1436
1437  FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1438  FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1439  FieldSize = CGM.getContext().getTypeSize(FType);
1440  FieldAlign = CGM.getContext().getTypeAlign(FType);
1441  FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1442                                           "__forwarding", Unit,
1443                                           0, FieldSize, FieldAlign,
1444                                           FieldOffset, 0, FieldTy);
1445  EltTys.push_back(FieldTy);
1446  FieldOffset += FieldSize;
1447
1448  FType = CGM.getContext().IntTy;
1449  FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1450  FieldSize = CGM.getContext().getTypeSize(FType);
1451  FieldAlign = CGM.getContext().getTypeAlign(FType);
1452  FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1453                                           "__flags", Unit,
1454                                           0, FieldSize, FieldAlign,
1455                                           FieldOffset, 0, FieldTy);
1456  EltTys.push_back(FieldTy);
1457  FieldOffset += FieldSize;
1458
1459  FType = CGM.getContext().IntTy;
1460  FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1461  FieldSize = CGM.getContext().getTypeSize(FType);
1462  FieldAlign = CGM.getContext().getTypeAlign(FType);
1463  FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1464                                           "__size", Unit,
1465                                           0, FieldSize, FieldAlign,
1466                                           FieldOffset, 0, FieldTy);
1467  EltTys.push_back(FieldTy);
1468  FieldOffset += FieldSize;
1469
1470  bool HasCopyAndDispose = CGM.BlockRequiresCopying(Type);
1471  if (HasCopyAndDispose) {
1472    FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1473    FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1474    FieldSize = CGM.getContext().getTypeSize(FType);
1475    FieldAlign = CGM.getContext().getTypeAlign(FType);
1476    FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1477                                             "__copy_helper", Unit,
1478                                             0, FieldSize, FieldAlign,
1479                                             FieldOffset, 0, FieldTy);
1480    EltTys.push_back(FieldTy);
1481    FieldOffset += FieldSize;
1482
1483    FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1484    FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1485    FieldSize = CGM.getContext().getTypeSize(FType);
1486    FieldAlign = CGM.getContext().getTypeAlign(FType);
1487    FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1488                                             "__destroy_helper", Unit,
1489                                             0, FieldSize, FieldAlign,
1490                                             FieldOffset, 0, FieldTy);
1491    EltTys.push_back(FieldTy);
1492    FieldOffset += FieldSize;
1493  }
1494
1495  CharUnits Align = CGM.getContext().getDeclAlign(VD);
1496  if (Align > CharUnits::fromQuantity(
1497        CGM.getContext().Target.getPointerAlign(0) / 8)) {
1498    unsigned AlignedOffsetInBytes
1499      = llvm::RoundUpToAlignment(FieldOffset/8, Align.getQuantity());
1500    unsigned NumPaddingBytes
1501      = AlignedOffsetInBytes - FieldOffset/8;
1502
1503    if (NumPaddingBytes > 0) {
1504      llvm::APInt pad(32, NumPaddingBytes);
1505      FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
1506                                                    pad, ArrayType::Normal, 0);
1507      FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1508      FieldSize = CGM.getContext().getTypeSize(FType);
1509      FieldAlign = CGM.getContext().getTypeAlign(FType);
1510      FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member,
1511                                               Unit, "", Unit,
1512                                               0, FieldSize, FieldAlign,
1513                                               FieldOffset, 0, FieldTy);
1514      EltTys.push_back(FieldTy);
1515      FieldOffset += FieldSize;
1516    }
1517  }
1518
1519  FType = Type;
1520  FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1521  FieldSize = CGM.getContext().getTypeSize(FType);
1522  FieldAlign = Align.getQuantity()*8;
1523
1524  *XOffset = FieldOffset;
1525  FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1526                                           VD->getName(), Unit,
1527                                           0, FieldSize, FieldAlign,
1528                                           FieldOffset, 0, FieldTy);
1529  EltTys.push_back(FieldTy);
1530  FieldOffset += FieldSize;
1531
1532  llvm::DIArray Elements =
1533    DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
1534
1535  unsigned Flags = llvm::DIType::FlagBlockByrefStruct;
1536
1537  return DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_structure_type,
1538                                          Unit, "", Unit,
1539                                          0, FieldOffset, 0, 0, Flags,
1540                                          llvm::DIType(), Elements);
1541
1542}
1543/// EmitDeclare - Emit local variable declaration debug info.
1544void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
1545                              llvm::Value *Storage, CGBuilderTy &Builder) {
1546  assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
1547
1548  // Do not emit variable debug information while generating optimized code.
1549  // The llvm optimizer and code generator are not yet ready to support
1550  // optimized code debugging.
1551  const CodeGenOptions &CGO = CGM.getCodeGenOpts();
1552  if (CGO.OptimizationLevel)
1553    return;
1554
1555  llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
1556  llvm::DIType Ty;
1557  uint64_t XOffset = 0;
1558  if (VD->hasAttr<BlocksAttr>())
1559    Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
1560  else
1561    Ty = getOrCreateType(VD->getType(), Unit);
1562
1563  // Get location information.
1564  SourceManager &SM = CGM.getContext().getSourceManager();
1565  PresumedLoc PLoc = SM.getPresumedLoc(VD->getLocation());
1566  unsigned Line = 0;
1567  unsigned Column = 0;
1568  if (PLoc.isInvalid())
1569    PLoc = SM.getPresumedLoc(CurLoc);
1570  if (PLoc.isValid()) {
1571    Line = PLoc.getLine();
1572    Column = PLoc.getColumn();
1573    Unit = getOrCreateFile(CurLoc);
1574  } else {
1575    Unit = llvm::DIFile();
1576  }
1577
1578  // Create the descriptor for the variable.
1579  llvm::DIVariable D =
1580    DebugFactory.CreateVariable(Tag, llvm::DIDescriptor(RegionStack.back()),
1581                                VD->getName(),
1582                                Unit, Line, Ty);
1583  // Insert an llvm.dbg.declare into the current block.
1584  llvm::Instruction *Call =
1585    DebugFactory.InsertDeclare(Storage, D, Builder.GetInsertBlock());
1586
1587  llvm::DIScope DS(RegionStack.back());
1588  llvm::DILocation DO(NULL);
1589  llvm::DILocation DL = DebugFactory.CreateLocation(Line, Column, DS, DO);
1590
1591  Call->setMetadata("dbg", DL.getNode());
1592}
1593
1594/// EmitDeclare - Emit local variable declaration debug info.
1595void CGDebugInfo::EmitDeclare(const BlockDeclRefExpr *BDRE, unsigned Tag,
1596                              llvm::Value *Storage, CGBuilderTy &Builder,
1597                              CodeGenFunction *CGF) {
1598  const ValueDecl *VD = BDRE->getDecl();
1599  assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
1600
1601  // Do not emit variable debug information while generating optimized code.
1602  // The llvm optimizer and code generator are not yet ready to support
1603  // optimized code debugging.
1604  const CodeGenOptions &CGO = CGM.getCodeGenOpts();
1605  if (CGO.OptimizationLevel || Builder.GetInsertBlock() == 0)
1606    return;
1607
1608  uint64_t XOffset = 0;
1609  llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
1610  llvm::DIType Ty;
1611  if (VD->hasAttr<BlocksAttr>())
1612    Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
1613  else
1614    Ty = getOrCreateType(VD->getType(), Unit);
1615
1616  // Get location information.
1617  SourceManager &SM = CGM.getContext().getSourceManager();
1618  PresumedLoc PLoc = SM.getPresumedLoc(VD->getLocation());
1619  unsigned Line = 0;
1620  if (!PLoc.isInvalid())
1621    Line = PLoc.getLine();
1622  else
1623    Unit = llvm::DIFile();
1624
1625  CharUnits offset = CGF->BlockDecls[VD];
1626  llvm::SmallVector<llvm::Value *, 9> addr;
1627  const llvm::Type *Int64Ty = llvm::Type::getInt64Ty(CGM.getLLVMContext());
1628  addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpDeref));
1629  addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpPlus));
1630  addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
1631  if (BDRE->isByRef()) {
1632    addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpDeref));
1633    addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpPlus));
1634    // offset of __forwarding field
1635    offset = CharUnits::fromQuantity(CGF->LLVMPointerWidth/8);
1636    addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
1637    addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpDeref));
1638    addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpPlus));
1639    // offset of x field
1640    offset = CharUnits::fromQuantity(XOffset/8);
1641    addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
1642  }
1643
1644  // Create the descriptor for the variable.
1645  llvm::DIVariable D =
1646    DebugFactory.CreateComplexVariable(Tag,
1647                                       llvm::DIDescriptor(RegionStack.back()),
1648                                       VD->getName(), Unit, Line, Ty,
1649                                       addr);
1650  // Insert an llvm.dbg.declare into the current block.
1651  llvm::Instruction *Call =
1652    DebugFactory.InsertDeclare(Storage, D, Builder.GetInsertBlock());
1653
1654  llvm::DIScope DS(RegionStack.back());
1655  llvm::DILocation DO(NULL);
1656  llvm::DILocation DL =
1657    DebugFactory.CreateLocation(Line, PLoc.getColumn(), DS, DO);
1658
1659  Call->setMetadata("dbg", DL.getNode());
1660}
1661
1662void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
1663                                            llvm::Value *Storage,
1664                                            CGBuilderTy &Builder) {
1665  EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, Builder);
1666}
1667
1668void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(
1669  const BlockDeclRefExpr *BDRE, llvm::Value *Storage, CGBuilderTy &Builder,
1670  CodeGenFunction *CGF) {
1671  EmitDeclare(BDRE, llvm::dwarf::DW_TAG_auto_variable, Storage, Builder, CGF);
1672}
1673
1674/// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
1675/// variable declaration.
1676void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
1677                                           CGBuilderTy &Builder) {
1678  EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, Builder);
1679}
1680
1681
1682
1683/// EmitGlobalVariable - Emit information about a global variable.
1684void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
1685                                     const VarDecl *D) {
1686
1687  // Create global variable debug descriptor.
1688  llvm::DIFile Unit = getOrCreateFile(D->getLocation());
1689  SourceManager &SM = CGM.getContext().getSourceManager();
1690  PresumedLoc PLoc = SM.getPresumedLoc(D->getLocation());
1691  unsigned LineNo = PLoc.isInvalid() ? 0 : PLoc.getLine();
1692
1693  QualType T = D->getType();
1694  if (T->isIncompleteArrayType()) {
1695
1696    // CodeGen turns int[] into int[1] so we'll do the same here.
1697    llvm::APSInt ConstVal(32);
1698
1699    ConstVal = 1;
1700    QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
1701
1702    T = CGM.getContext().getConstantArrayType(ET, ConstVal,
1703                                           ArrayType::Normal, 0);
1704  }
1705  llvm::StringRef DeclName = Var->getName();
1706  llvm::DIDescriptor DContext =
1707    getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()), Unit);
1708  DebugFactory.CreateGlobalVariable(DContext, DeclName,
1709                                    DeclName, llvm::StringRef(), Unit, LineNo,
1710                                    getOrCreateType(T, Unit),
1711                                    Var->hasInternalLinkage(),
1712                                    true/*definition*/, Var);
1713}
1714
1715/// EmitGlobalVariable - Emit information about an objective-c interface.
1716void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
1717                                     ObjCInterfaceDecl *ID) {
1718  // Create global variable debug descriptor.
1719  llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
1720  SourceManager &SM = CGM.getContext().getSourceManager();
1721  PresumedLoc PLoc = SM.getPresumedLoc(ID->getLocation());
1722  unsigned LineNo = PLoc.isInvalid() ? 0 : PLoc.getLine();
1723
1724  llvm::StringRef Name = ID->getName();
1725
1726  QualType T = CGM.getContext().getObjCInterfaceType(ID);
1727  if (T->isIncompleteArrayType()) {
1728
1729    // CodeGen turns int[] into int[1] so we'll do the same here.
1730    llvm::APSInt ConstVal(32);
1731
1732    ConstVal = 1;
1733    QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
1734
1735    T = CGM.getContext().getConstantArrayType(ET, ConstVal,
1736                                           ArrayType::Normal, 0);
1737  }
1738
1739  DebugFactory.CreateGlobalVariable(Unit, Name, Name, Name, Unit, LineNo,
1740                                    getOrCreateType(T, Unit),
1741                                    Var->hasInternalLinkage(),
1742                                    true/*definition*/, Var);
1743}
1744
1745/// getOrCreateNamesSpace - Return namespace descriptor for the given
1746/// namespace decl.
1747llvm::DINameSpace
1748CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl,
1749                                  llvm::DIDescriptor Unit) {
1750  llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
1751    NameSpaceCache.find(NSDecl);
1752  if (I != NameSpaceCache.end())
1753    return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
1754
1755  SourceManager &SM = CGM.getContext().getSourceManager();
1756  PresumedLoc PLoc = SM.getPresumedLoc(NSDecl->getLocation());
1757  unsigned LineNo = PLoc.isInvalid() ? 0 : PLoc.getLine();
1758
1759  llvm::DIDescriptor Context =
1760    getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()), Unit);
1761  llvm::DINameSpace NS =
1762    DebugFactory.CreateNameSpace(Context, NSDecl->getName(),
1763	llvm::DIFile(Unit.getNode()), LineNo);
1764  NameSpaceCache[NSDecl] = llvm::WeakVH(NS.getNode());
1765  return NS;
1766}
1767