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