CGDebugInfo.cpp revision 23908b8a43adefd42b3635364cfab44de1064942
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 *m)
39  : M(m), isMainCompileUnitCreated(false), DebugFactory(M->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 = M->getContext().getSourceManager().getInstantiationLoc(Loc);
50}
51
52/// getContext - Get context info for the decl.
53llvm::DIDescriptor CGDebugInfo::getContext(const VarDecl *Decl,
54                                           llvm::DIDescriptor &CompileUnit) {
55  if (Decl->isFileVarDecl())
56    return CompileUnit;
57  if (Decl->getDeclContext()->isFunctionOrMethod()) {
58    // Find the last subprogram in region stack.
59    for (unsigned RI = RegionStack.size(), RE = 0; RI != RE; --RI) {
60      llvm::DIDescriptor R = RegionStack[RI - 1];
61      if (R.isSubprogram())
62        return R;
63    }
64  }
65  return CompileUnit;
66}
67
68/// getOrCreateCompileUnit - Get the compile unit from the cache or create a new
69/// one if necessary. This returns null for invalid source locations.
70llvm::DICompileUnit CGDebugInfo::getOrCreateCompileUnit(SourceLocation Loc) {
71  // Get source file information.
72  const char *FileName =  "<unknown>";
73  SourceManager &SM = M->getContext().getSourceManager();
74  unsigned FID = 0;
75  if (Loc.isValid()) {
76    PresumedLoc PLoc = SM.getPresumedLoc(Loc);
77    FileName = PLoc.getFilename();
78    FID = PLoc.getIncludeLoc().getRawEncoding();
79  }
80
81  // See if this compile unit has been used before.
82  llvm::DICompileUnit &Unit = CompileUnitCache[FID];
83  if (!Unit.isNull()) return Unit;
84
85  // Get absolute path name.
86  llvm::sys::Path AbsFileName(FileName);
87  if (!AbsFileName.isAbsolute()) {
88    llvm::sys::Path tmp = llvm::sys::Path::GetCurrentDirectory();
89    tmp.appendComponent(FileName);
90    AbsFileName = tmp;
91  }
92
93  // See if thie compile unit is representing main source file. Each source
94  // file has corresponding compile unit. There is only one main source
95  // file at a time.
96  bool isMain = false;
97  const LangOptions &LO = M->getLangOptions();
98  const char *MainFileName = LO.getMainFileName();
99  if (isMainCompileUnitCreated == false) {
100    if (MainFileName) {
101      if (!strcmp(AbsFileName.getLast().c_str(), MainFileName))
102        isMain = true;
103    } else {
104      if (Loc.isValid() && SM.isFromMainFile(Loc))
105        isMain = true;
106    }
107    if (isMain)
108      isMainCompileUnitCreated = true;
109  }
110
111  unsigned LangTag;
112  if (LO.CPlusPlus) {
113    if (LO.ObjC1)
114      LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
115    else
116      LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
117  } else if (LO.ObjC1) {
118    LangTag = llvm::dwarf::DW_LANG_ObjC;
119  } else if (LO.C99) {
120    LangTag = llvm::dwarf::DW_LANG_C99;
121  } else {
122    LangTag = llvm::dwarf::DW_LANG_C89;
123  }
124
125  std::string Producer =
126#ifdef CLANG_VENDOR
127    CLANG_VENDOR
128#endif
129    "clang " CLANG_VERSION_STRING;
130  bool isOptimized = LO.Optimize;
131  const char *Flags = "";   // FIXME: Encode command line options.
132
133  // Figure out which version of the ObjC runtime we have.
134  unsigned RuntimeVers = 0;
135  if (LO.ObjC1)
136    RuntimeVers = LO.ObjCNonFragileABI ? 2 : 1;
137
138  // Create new compile unit.
139  return Unit = DebugFactory.CreateCompileUnit(LangTag,
140                                               AbsFileName.getLast().c_str(),
141                                               AbsFileName.getDirname().c_str(),
142                                               Producer.c_str(), isMain,
143                                               isOptimized, Flags, RuntimeVers);
144}
145
146/// CreateType - Get the Basic type from the cache or create a new
147/// one if necessary.
148llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT,
149                                     llvm::DICompileUnit Unit) {
150  unsigned Encoding = 0;
151  switch (BT->getKind()) {
152  default:
153  case BuiltinType::Void:
154    return llvm::DIType();
155  case BuiltinType::UChar:
156  case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break;
157  case BuiltinType::Char_S:
158  case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break;
159  case BuiltinType::UShort:
160  case BuiltinType::UInt:
161  case BuiltinType::ULong:
162  case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break;
163  case BuiltinType::Short:
164  case BuiltinType::Int:
165  case BuiltinType::Long:
166  case BuiltinType::LongLong:  Encoding = llvm::dwarf::DW_ATE_signed; break;
167  case BuiltinType::Bool:      Encoding = llvm::dwarf::DW_ATE_boolean; break;
168  case BuiltinType::Float:
169  case BuiltinType::LongDouble:
170  case BuiltinType::Double:    Encoding = llvm::dwarf::DW_ATE_float; break;
171  }
172  // Bit size, align and offset of the type.
173  uint64_t Size = M->getContext().getTypeSize(BT);
174  uint64_t Align = M->getContext().getTypeAlign(BT);
175  uint64_t Offset = 0;
176
177  llvm::DIType DbgTy =
178    DebugFactory.CreateBasicType(Unit,
179                                 BT->getName(M->getContext().getLangOptions()),
180                                 Unit, 0, Size, Align,
181                                 Offset, /*flags*/ 0, Encoding);
182
183  TypeCache[QualType(BT, 0).getAsOpaquePtr()] = DbgTy.getNode();
184  return DbgTy;
185}
186
187llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty,
188                                     llvm::DICompileUnit Unit) {
189  // Bit size, align and offset of the type.
190  unsigned Encoding = llvm::dwarf::DW_ATE_complex_float;
191  if (Ty->isComplexIntegerType())
192    Encoding = llvm::dwarf::DW_ATE_lo_user;
193
194  uint64_t Size = M->getContext().getTypeSize(Ty);
195  uint64_t Align = M->getContext().getTypeAlign(Ty);
196  uint64_t Offset = 0;
197
198  llvm::DIType DbgTy =
199    DebugFactory.CreateBasicType(Unit, "complex",
200                                 Unit, 0, Size, Align,
201                                 Offset, /*flags*/ 0, Encoding);
202  TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = DbgTy.getNode();
203  return DbgTy;
204}
205
206/// CreateCVRType - Get the qualified type from the cache or create
207/// a new one if necessary.
208llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DICompileUnit Unit) {
209  QualifierCollector Qc;
210  const Type *T = Qc.strip(Ty);
211
212  // Ignore these qualifiers for now.
213  Qc.removeObjCGCAttr();
214  Qc.removeAddressSpace();
215
216  // We will create one Derived type for one qualifier and recurse to handle any
217  // additional ones.
218  unsigned Tag;
219  if (Qc.hasConst()) {
220    Tag = llvm::dwarf::DW_TAG_const_type;
221    Qc.removeConst();
222  } else if (Qc.hasVolatile()) {
223    Tag = llvm::dwarf::DW_TAG_volatile_type;
224    Qc.removeVolatile();
225  } else if (Qc.hasRestrict()) {
226    Tag = llvm::dwarf::DW_TAG_restrict_type;
227    Qc.removeRestrict();
228  } else {
229    assert(Qc.empty() && "Unknown type qualifier for debug info");
230    return getOrCreateType(QualType(T, 0), Unit);
231  }
232
233  llvm::DIType FromTy = getOrCreateType(Qc.apply(T), Unit);
234
235  // No need to fill in the Name, Line, Size, Alignment, Offset in case of
236  // CVR derived types.
237  llvm::DIType DbgTy =
238    DebugFactory.CreateDerivedType(Tag, Unit, "", llvm::DICompileUnit(),
239                                   0, 0, 0, 0, 0, FromTy);
240  TypeCache[Ty.getAsOpaquePtr()] = DbgTy.getNode();
241  return DbgTy;
242}
243
244llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
245                                     llvm::DICompileUnit Unit) {
246  llvm::DIType DbgTy =
247    CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
248                          Ty->getPointeeType(), Unit);
249  TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = DbgTy.getNode();
250  return DbgTy;
251}
252
253llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
254                                     llvm::DICompileUnit Unit) {
255  return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
256                               Ty->getPointeeType(), Unit);
257}
258
259llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag,
260                                                const Type *Ty,
261                                                QualType PointeeTy,
262                                                llvm::DICompileUnit Unit) {
263  llvm::DIType EltTy = getOrCreateType(PointeeTy, Unit);
264
265  // Bit size, align and offset of the type.
266
267  // Size is always the size of a pointer. We can't use getTypeSize here
268  // because that does not return the correct value for references.
269  uint64_t Size =
270    M->getContext().Target.getPointerWidth(PointeeTy.getAddressSpace());
271  uint64_t Align = M->getContext().getTypeAlign(Ty);
272
273  return
274    DebugFactory.CreateDerivedType(Tag, Unit, "", llvm::DICompileUnit(),
275                                   0, Size, Align, 0, 0, EltTy);
276
277}
278
279llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
280                                     llvm::DICompileUnit Unit) {
281  if (BlockLiteralGenericSet)
282    return BlockLiteralGeneric;
283
284  llvm::DICompileUnit DefUnit;
285  unsigned Tag = llvm::dwarf::DW_TAG_structure_type;
286
287  llvm::SmallVector<llvm::DIDescriptor, 5> EltTys;
288
289  llvm::DIType FieldTy;
290
291  QualType FType;
292  uint64_t FieldSize, FieldOffset;
293  unsigned FieldAlign;
294
295  llvm::DIArray Elements;
296  llvm::DIType EltTy, DescTy;
297
298  FieldOffset = 0;
299  FType = M->getContext().UnsignedLongTy;
300  FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
301  FieldSize = M->getContext().getTypeSize(FType);
302  FieldAlign = M->getContext().getTypeAlign(FType);
303  FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
304                                           "reserved", DefUnit,
305                                           0, FieldSize, FieldAlign,
306                                           FieldOffset, 0, FieldTy);
307  EltTys.push_back(FieldTy);
308
309  FieldOffset += FieldSize;
310  FType = M->getContext().UnsignedLongTy;
311  FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
312  FieldSize = M->getContext().getTypeSize(FType);
313  FieldAlign = M->getContext().getTypeAlign(FType);
314  FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
315                                           "Size", DefUnit,
316                                           0, FieldSize, FieldAlign,
317                                           FieldOffset, 0, FieldTy);
318  EltTys.push_back(FieldTy);
319
320  FieldOffset += FieldSize;
321  Elements = DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
322  EltTys.clear();
323
324  unsigned Flags = llvm::DIType::FlagAppleBlock;
325
326  EltTy = DebugFactory.CreateCompositeType(Tag, Unit, "__block_descriptor",
327                                           DefUnit, 0, FieldOffset, 0, 0, Flags,
328                                           llvm::DIType(), Elements);
329
330  // Bit size, align and offset of the type.
331  uint64_t Size = M->getContext().getTypeSize(Ty);
332  uint64_t Align = M->getContext().getTypeAlign(Ty);
333
334  DescTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type,
335                                          Unit, "", llvm::DICompileUnit(),
336                                          0, Size, Align, 0, 0, EltTy);
337
338  FieldOffset = 0;
339  FType = M->getContext().getPointerType(M->getContext().VoidTy);
340  FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
341  FieldSize = M->getContext().getTypeSize(FType);
342  FieldAlign = M->getContext().getTypeAlign(FType);
343  FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
344                                           "__isa", DefUnit,
345                                           0, FieldSize, FieldAlign,
346                                           FieldOffset, 0, FieldTy);
347  EltTys.push_back(FieldTy);
348
349  FieldOffset += FieldSize;
350  FType = M->getContext().IntTy;
351  FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
352  FieldSize = M->getContext().getTypeSize(FType);
353  FieldAlign = M->getContext().getTypeAlign(FType);
354  FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
355                                           "__flags", DefUnit,
356                                           0, FieldSize, FieldAlign,
357                                           FieldOffset, 0, FieldTy);
358  EltTys.push_back(FieldTy);
359
360  FieldOffset += FieldSize;
361  FType = M->getContext().IntTy;
362  FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
363  FieldSize = M->getContext().getTypeSize(FType);
364  FieldAlign = M->getContext().getTypeAlign(FType);
365  FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
366                                           "__reserved", DefUnit,
367                                           0, FieldSize, FieldAlign,
368                                           FieldOffset, 0, FieldTy);
369  EltTys.push_back(FieldTy);
370
371  FieldOffset += FieldSize;
372  FType = M->getContext().getPointerType(M->getContext().VoidTy);
373  FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
374  FieldSize = M->getContext().getTypeSize(FType);
375  FieldAlign = M->getContext().getTypeAlign(FType);
376  FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
377                                           "__FuncPtr", DefUnit,
378                                           0, FieldSize, FieldAlign,
379                                           FieldOffset, 0, FieldTy);
380  EltTys.push_back(FieldTy);
381
382  FieldOffset += FieldSize;
383  FType = M->getContext().getPointerType(M->getContext().VoidTy);
384  FieldTy = DescTy;
385  FieldSize = M->getContext().getTypeSize(Ty);
386  FieldAlign = M->getContext().getTypeAlign(Ty);
387  FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
388                                           "__descriptor", DefUnit,
389                                           0, FieldSize, FieldAlign,
390                                           FieldOffset, 0, FieldTy);
391  EltTys.push_back(FieldTy);
392
393  FieldOffset += FieldSize;
394  Elements = DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
395
396  EltTy = DebugFactory.CreateCompositeType(Tag, Unit, "__block_literal_generic",
397                                           DefUnit, 0, FieldOffset, 0, 0, Flags,
398                                           llvm::DIType(), Elements);
399
400  BlockLiteralGenericSet = true;
401  BlockLiteralGeneric
402    = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type, Unit,
403                                     "", llvm::DICompileUnit(),
404                                     0, Size, Align, 0, 0, EltTy);
405  return BlockLiteralGeneric;
406}
407
408llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty,
409                                     llvm::DICompileUnit Unit) {
410  // Typedefs are derived from some other type.  If we have a typedef of a
411  // typedef, make sure to emit the whole chain.
412  llvm::DIType Src = getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
413
414  // We don't set size information, but do specify where the typedef was
415  // declared.
416  SourceLocation DefLoc = Ty->getDecl()->getLocation();
417  llvm::DICompileUnit DefUnit = getOrCreateCompileUnit(DefLoc);
418
419  SourceManager &SM = M->getContext().getSourceManager();
420  PresumedLoc PLoc = SM.getPresumedLoc(DefLoc);
421  unsigned Line = PLoc.isInvalid() ? 0 : PLoc.getLine();
422
423  llvm::DIType DbgTy =
424    DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_typedef, Unit,
425                                   Ty->getDecl()->getNameAsCString(),
426                                   DefUnit, Line, 0, 0, 0, 0, Src);
427  TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = DbgTy.getNode();
428  return DbgTy;
429}
430
431llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
432                                     llvm::DICompileUnit Unit) {
433  llvm::SmallVector<llvm::DIDescriptor, 16> EltTys;
434
435  // Add the result type at least.
436  EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit));
437
438  // Set up remainder of arguments if there is a prototype.
439  // FIXME: IF NOT, HOW IS THIS REPRESENTED?  llvm-gcc doesn't represent '...'!
440  if (const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(Ty)) {
441    for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i)
442      EltTys.push_back(getOrCreateType(FTP->getArgType(i), Unit));
443  } else {
444    // FIXME: Handle () case in C.  llvm-gcc doesn't do it either.
445  }
446
447  llvm::DIArray EltTypeArray =
448    DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
449
450  llvm::DIType DbgTy =
451    DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_subroutine_type,
452                                     Unit, "", llvm::DICompileUnit(),
453                                     0, 0, 0, 0, 0,
454                                     llvm::DIType(), EltTypeArray);
455  TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = DbgTy.getNode();
456  return DbgTy;
457}
458
459/// CreateType - get structure or union type.
460llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty,
461                                     llvm::DICompileUnit Unit) {
462  RecordDecl *Decl = Ty->getDecl();
463
464  unsigned Tag;
465  if (Decl->isStruct())
466    Tag = llvm::dwarf::DW_TAG_structure_type;
467  else if (Decl->isUnion())
468    Tag = llvm::dwarf::DW_TAG_union_type;
469  else {
470    assert(Decl->isClass() && "Unknown RecordType!");
471    Tag = llvm::dwarf::DW_TAG_class_type;
472  }
473
474  SourceManager &SM = M->getContext().getSourceManager();
475
476  // Get overall information about the record type for the debug info.
477  PresumedLoc PLoc = SM.getPresumedLoc(Decl->getLocation());
478  llvm::DICompileUnit DefUnit;
479  unsigned Line = 0;
480  if (!PLoc.isInvalid()) {
481    DefUnit = getOrCreateCompileUnit(Decl->getLocation());
482    Line = PLoc.getLine();
483  }
484
485  // Records and classes and unions can all be recursive.  To handle them, we
486  // first generate a debug descriptor for the struct as a forward declaration.
487  // Then (if it is a definition) we go through and get debug info for all of
488  // its members.  Finally, we create a descriptor for the complete type (which
489  // may refer to the forward decl if the struct is recursive) and replace all
490  // uses of the forward declaration with the final definition.
491  llvm::DICompositeType FwdDecl =
492    DebugFactory.CreateCompositeType(Tag, Unit, Decl->getNameAsString().data(),
493                                     DefUnit, Line, 0, 0, 0, 0,
494                                     llvm::DIType(), llvm::DIArray());
495
496  // If this is just a forward declaration, return it.
497  if (!Decl->getDefinition(M->getContext()))
498    return FwdDecl;
499
500  // Otherwise, insert it into the TypeCache so that recursive uses will find
501  // it.
502  TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl.getNode();
503
504  // Convert all the elements.
505  llvm::SmallVector<llvm::DIDescriptor, 16> EltTys;
506
507  const ASTRecordLayout &RL = M->getContext().getASTRecordLayout(Decl);
508
509  unsigned FieldNo = 0;
510  for (RecordDecl::field_iterator I = Decl->field_begin(),
511                                  E = Decl->field_end();
512       I != E; ++I, ++FieldNo) {
513    FieldDecl *Field = *I;
514    llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
515
516    const char *FieldName = Field->getNameAsCString();
517
518    // Ignore unnamed fields.
519    if (!FieldName)
520      continue;
521
522    // Get the location for the field.
523    SourceLocation FieldDefLoc = Field->getLocation();
524    PresumedLoc PLoc = SM.getPresumedLoc(FieldDefLoc);
525    llvm::DICompileUnit FieldDefUnit;
526    unsigned FieldLine = 0;
527
528    if (!PLoc.isInvalid()) {
529      FieldDefUnit = getOrCreateCompileUnit(FieldDefLoc);
530      FieldLine = PLoc.getLine();
531    }
532
533    QualType FType = Field->getType();
534    uint64_t FieldSize = 0;
535    unsigned FieldAlign = 0;
536    if (!FType->isIncompleteArrayType()) {
537
538      // Bit size, align and offset of the type.
539      FieldSize = M->getContext().getTypeSize(FType);
540      Expr *BitWidth = Field->getBitWidth();
541      if (BitWidth)
542        FieldSize = BitWidth->EvaluateAsInt(M->getContext()).getZExtValue();
543
544      FieldAlign =  M->getContext().getTypeAlign(FType);
545    }
546
547    uint64_t FieldOffset = RL.getFieldOffset(FieldNo);
548
549    // Create a DW_TAG_member node to remember the offset of this field in the
550    // struct.  FIXME: This is an absolutely insane way to capture this
551    // information.  When we gut debug info, this should be fixed.
552    FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
553                                             FieldName, FieldDefUnit,
554                                             FieldLine, FieldSize, FieldAlign,
555                                             FieldOffset, 0, FieldTy);
556    EltTys.push_back(FieldTy);
557  }
558
559  llvm::DIArray Elements =
560    DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
561
562  // Bit size, align and offset of the type.
563  uint64_t Size = M->getContext().getTypeSize(Ty);
564  uint64_t Align = M->getContext().getTypeAlign(Ty);
565
566  llvm::DICompositeType RealDecl =
567    DebugFactory.CreateCompositeType(Tag, Unit, Decl->getNameAsString().data(),
568                                     DefUnit, Line, Size, Align, 0, 0,
569                                     llvm::DIType(), Elements);
570
571  // Update TypeCache.
572  TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl.getNode();
573
574  // Now that we have a real decl for the struct, replace anything using the
575  // old decl with the new one.  This will recursively update the debug info.
576  FwdDecl.replaceAllUsesWith(RealDecl);
577
578  return RealDecl;
579}
580
581/// CreateType - get objective-c interface type.
582llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
583                                     llvm::DICompileUnit Unit) {
584  ObjCInterfaceDecl *Decl = Ty->getDecl();
585
586  unsigned Tag = llvm::dwarf::DW_TAG_structure_type;
587  SourceManager &SM = M->getContext().getSourceManager();
588
589  // Get overall information about the record type for the debug info.
590  llvm::DICompileUnit DefUnit = getOrCreateCompileUnit(Decl->getLocation());
591  PresumedLoc PLoc = SM.getPresumedLoc(Decl->getLocation());
592  unsigned Line = PLoc.isInvalid() ? 0 : PLoc.getLine();
593
594
595  unsigned RuntimeLang = DefUnit.getLanguage();
596
597  // To handle recursive interface, we
598  // first generate a debug descriptor for the struct as a forward declaration.
599  // Then (if it is a definition) we go through and get debug info for all of
600  // its members.  Finally, we create a descriptor for the complete type (which
601  // may refer to the forward decl if the struct is recursive) and replace all
602  // uses of the forward declaration with the final definition.
603  llvm::DICompositeType FwdDecl =
604    DebugFactory.CreateCompositeType(Tag, Unit, Decl->getNameAsCString(),
605                                     DefUnit, Line, 0, 0, 0, 0,
606                                     llvm::DIType(), llvm::DIArray(),
607                                     RuntimeLang);
608
609  // If this is just a forward declaration, return it.
610  if (Decl->isForwardDecl())
611    return FwdDecl;
612
613  // Otherwise, insert it into the TypeCache so that recursive uses will find
614  // it.
615  TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl.getNode();
616
617  // Convert all the elements.
618  llvm::SmallVector<llvm::DIDescriptor, 16> EltTys;
619
620  ObjCInterfaceDecl *SClass = Decl->getSuperClass();
621  if (SClass) {
622    llvm::DIType SClassTy =
623      getOrCreateType(M->getContext().getObjCInterfaceType(SClass), Unit);
624    llvm::DIType InhTag =
625      DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_inheritance,
626                                     Unit, "", llvm::DICompileUnit(), 0, 0, 0,
627                                     0 /* offset */, 0, SClassTy);
628    EltTys.push_back(InhTag);
629  }
630
631  const ASTRecordLayout &RL = M->getContext().getASTObjCInterfaceLayout(Decl);
632
633  unsigned FieldNo = 0;
634  for (ObjCInterfaceDecl::ivar_iterator I = Decl->ivar_begin(),
635         E = Decl->ivar_end();  I != E; ++I, ++FieldNo) {
636    ObjCIvarDecl *Field = *I;
637    llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
638
639    const char *FieldName = Field->getNameAsCString();
640
641    // Ignore unnamed fields.
642    if (!FieldName)
643      continue;
644
645    // Get the location for the field.
646    SourceLocation FieldDefLoc = Field->getLocation();
647    llvm::DICompileUnit FieldDefUnit = getOrCreateCompileUnit(FieldDefLoc);
648    PresumedLoc PLoc = SM.getPresumedLoc(FieldDefLoc);
649    unsigned FieldLine = PLoc.isInvalid() ? 0 : PLoc.getLine();
650
651
652    QualType FType = Field->getType();
653    uint64_t FieldSize = 0;
654    unsigned FieldAlign = 0;
655
656    if (!FType->isIncompleteArrayType()) {
657
658      // Bit size, align and offset of the type.
659      FieldSize = M->getContext().getTypeSize(FType);
660      Expr *BitWidth = Field->getBitWidth();
661      if (BitWidth)
662        FieldSize = BitWidth->EvaluateAsInt(M->getContext()).getZExtValue();
663
664      FieldAlign =  M->getContext().getTypeAlign(FType);
665    }
666
667    uint64_t FieldOffset = RL.getFieldOffset(FieldNo);
668
669    unsigned Flags = 0;
670    if (Field->getAccessControl() == ObjCIvarDecl::Protected)
671      Flags = llvm::DIType::FlagProtected;
672    else if (Field->getAccessControl() == ObjCIvarDecl::Private)
673      Flags = llvm::DIType::FlagPrivate;
674
675    // Create a DW_TAG_member node to remember the offset of this field in the
676    // struct.  FIXME: This is an absolutely insane way to capture this
677    // information.  When we gut debug info, this should be fixed.
678    FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
679                                             FieldName, FieldDefUnit,
680                                             FieldLine, FieldSize, FieldAlign,
681                                             FieldOffset, Flags, FieldTy);
682    EltTys.push_back(FieldTy);
683  }
684
685  llvm::DIArray Elements =
686    DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
687
688  // Bit size, align and offset of the type.
689  uint64_t Size = M->getContext().getTypeSize(Ty);
690  uint64_t Align = M->getContext().getTypeAlign(Ty);
691
692  llvm::DICompositeType RealDecl =
693    DebugFactory.CreateCompositeType(Tag, Unit, Decl->getNameAsCString(), DefUnit,
694                                     Line, Size, Align, 0, 0, llvm::DIType(),
695                                     Elements, RuntimeLang);
696
697  // Update TypeCache.
698  TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl.getNode();
699
700  // Now that we have a real decl for the struct, replace anything using the
701  // old decl with the new one.  This will recursively update the debug info.
702  FwdDecl.replaceAllUsesWith(RealDecl);
703
704  return RealDecl;
705}
706
707llvm::DIType CGDebugInfo::CreateType(const EnumType *Ty,
708                                     llvm::DICompileUnit Unit) {
709  EnumDecl *Decl = Ty->getDecl();
710
711  llvm::SmallVector<llvm::DIDescriptor, 32> Enumerators;
712
713  // Create DIEnumerator elements for each enumerator.
714  for (EnumDecl::enumerator_iterator
715         Enum = Decl->enumerator_begin(), EnumEnd = Decl->enumerator_end();
716       Enum != EnumEnd; ++Enum) {
717    Enumerators.push_back(DebugFactory.CreateEnumerator(Enum->getNameAsCString(),
718                                            Enum->getInitVal().getZExtValue()));
719  }
720
721  // Return a CompositeType for the enum itself.
722  llvm::DIArray EltArray =
723    DebugFactory.GetOrCreateArray(Enumerators.data(), Enumerators.size());
724
725  SourceLocation DefLoc = Decl->getLocation();
726  llvm::DICompileUnit DefUnit = getOrCreateCompileUnit(DefLoc);
727  SourceManager &SM = M->getContext().getSourceManager();
728  PresumedLoc PLoc = SM.getPresumedLoc(DefLoc);
729  unsigned Line = PLoc.isInvalid() ? 0 : PLoc.getLine();
730
731
732  // Size and align of the type.
733  uint64_t Size = 0;
734  unsigned Align = 0;
735  if (!Ty->isIncompleteType()) {
736    Size = M->getContext().getTypeSize(Ty);
737    Align = M->getContext().getTypeAlign(Ty);
738  }
739
740  llvm::DIType DbgTy =
741    DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_enumeration_type,
742                                     Unit, Decl->getNameAsCString(), DefUnit, Line,
743                                     Size, Align, 0, 0,
744                                     llvm::DIType(), EltArray);
745
746  TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = DbgTy.getNode();
747  return DbgTy;
748}
749
750llvm::DIType CGDebugInfo::CreateType(const TagType *Ty,
751                                     llvm::DICompileUnit Unit) {
752  if (const RecordType *RT = dyn_cast<RecordType>(Ty))
753    return CreateType(RT, Unit);
754  else if (const EnumType *ET = dyn_cast<EnumType>(Ty))
755    return CreateType(ET, Unit);
756
757  return llvm::DIType();
758}
759
760llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
761                                     llvm::DICompileUnit Unit) {
762  uint64_t Size;
763  uint64_t Align;
764
765
766  // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
767  if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
768    Size = 0;
769    Align =
770      M->getContext().getTypeAlign(M->getContext().getBaseElementType(VAT));
771  } else if (Ty->isIncompleteArrayType()) {
772    Size = 0;
773    Align = M->getContext().getTypeAlign(Ty->getElementType());
774  } else {
775    // Size and align of the whole array, not the element type.
776    Size = M->getContext().getTypeSize(Ty);
777    Align = M->getContext().getTypeAlign(Ty);
778  }
779
780  // Add the dimensions of the array.  FIXME: This loses CV qualifiers from
781  // interior arrays, do we care?  Why aren't nested arrays represented the
782  // obvious/recursive way?
783  llvm::SmallVector<llvm::DIDescriptor, 8> Subscripts;
784  QualType EltTy(Ty, 0);
785  while ((Ty = dyn_cast<ArrayType>(EltTy))) {
786    uint64_t Upper = 0;
787    if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
788      if (CAT->getSize().getZExtValue())
789        Upper = CAT->getSize().getZExtValue() - 1;
790    // FIXME: Verify this is right for VLAs.
791    Subscripts.push_back(DebugFactory.GetOrCreateSubrange(0, Upper));
792    EltTy = Ty->getElementType();
793  }
794
795  llvm::DIArray SubscriptArray =
796    DebugFactory.GetOrCreateArray(Subscripts.data(), Subscripts.size());
797
798  llvm::DIType DbgTy =
799    DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_array_type,
800                                     Unit, "", llvm::DICompileUnit(),
801                                     0, Size, Align, 0, 0,
802                                     getOrCreateType(EltTy, Unit),
803                                     SubscriptArray);
804
805  TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = DbgTy.getNode();
806  return DbgTy;
807}
808
809llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
810                                     llvm::DICompileUnit Unit) {
811  return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
812                               Ty, Ty->getPointeeType(), Unit);
813}
814
815/// getOrCreateType - Get the type from the cache or create a new
816/// one if necessary.
817llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty,
818                                          llvm::DICompileUnit Unit) {
819  if (Ty.isNull())
820    return llvm::DIType();
821
822  // Check for existing entry.
823  std::map<void *, llvm::WeakVH>::iterator it =
824    TypeCache.find(Ty.getAsOpaquePtr());
825  if (it != TypeCache.end()) {
826    // Verify that the debug info still exists.
827    if (&*it->second)
828      return llvm::DIType(cast<llvm::MDNode>(it->second));
829  }
830
831  // Otherwise create the type.
832  llvm::DIType Res = CreateTypeNode(Ty, Unit);
833  return Res;
834}
835
836/// getOrCreateTypeNode - Get the type metadata node from the cache or create a
837/// new one if necessary.
838llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty,
839                                         llvm::DICompileUnit Unit) {
840  // Handle qualifiers, which recursively handles what they refer to.
841  if (Ty.hasQualifiers())
842    return CreateQualifiedType(Ty, Unit);
843
844  // Work out details of type.
845  switch (Ty->getTypeClass()) {
846#define TYPE(Class, Base)
847#define ABSTRACT_TYPE(Class, Base)
848#define NON_CANONICAL_TYPE(Class, Base)
849#define DEPENDENT_TYPE(Class, Base) case Type::Class:
850#include "clang/AST/TypeNodes.def"
851    assert(false && "Dependent types cannot show up in debug information");
852
853  // FIXME: Handle these.
854  case Type::ExtVector:
855  case Type::Vector:
856  case Type::FixedWidthInt:
857    return llvm::DIType();
858  default:
859    assert(false && "Unhandled type class!");
860    return llvm::DIType();
861  case Type::ObjCObjectPointer:
862    return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
863  case Type::ObjCInterface:
864    return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
865  case Type::Builtin: return CreateType(cast<BuiltinType>(Ty), Unit);
866  case Type::Complex: return CreateType(cast<ComplexType>(Ty), Unit);
867  case Type::Pointer: return CreateType(cast<PointerType>(Ty), Unit);
868  case Type::BlockPointer:
869    return CreateType(cast<BlockPointerType>(Ty), Unit);
870  case Type::Typedef: return CreateType(cast<TypedefType>(Ty), Unit);
871  case Type::Record:
872  case Type::Enum:
873    return CreateType(cast<TagType>(Ty), Unit);
874  case Type::FunctionProto:
875  case Type::FunctionNoProto:
876    return CreateType(cast<FunctionType>(Ty), Unit);
877  case Type::Elaborated:
878    return getOrCreateType(cast<ElaboratedType>(Ty)->getUnderlyingType(),
879                           Unit);
880
881  case Type::ConstantArray:
882  case Type::VariableArray:
883  case Type::IncompleteArray:
884    return CreateType(cast<ArrayType>(Ty), Unit);
885  case Type::TypeOfExpr:
886    return getOrCreateType(cast<TypeOfExprType>(Ty)->getUnderlyingExpr()
887                           ->getType(), Unit);
888  case Type::TypeOf:
889    return getOrCreateType(cast<TypeOfType>(Ty)->getUnderlyingType(), Unit);
890  case Type::Decltype:
891    return getOrCreateType(cast<DecltypeType>(Ty)->getUnderlyingType(), Unit);
892
893  case Type::QualifiedName: {
894    const QualifiedNameType *T = cast<QualifiedNameType>(Ty);
895    return CreateTypeNode(T->getNamedType(), Unit);
896  }
897
898  case Type::SubstTemplateTypeParm: {
899    const SubstTemplateTypeParmType *T = cast<SubstTemplateTypeParmType>(Ty);
900    return CreateTypeNode(T->getReplacementType(), Unit);
901  }
902
903  case Type::TemplateSpecialization: {
904    const TemplateSpecializationType *T = cast<TemplateSpecializationType>(Ty);
905    return CreateTypeNode(T->desugar(), Unit);
906  }
907
908  case Type::LValueReference:
909    return CreateType(cast<LValueReferenceType>(Ty), Unit);
910
911  }
912}
913
914/// EmitFunctionStart - Constructs the debug code for entering a function -
915/// "llvm.dbg.func.start.".
916void CGDebugInfo::EmitFunctionStart(const char *Name, QualType FnType,
917                                    llvm::Function *Fn,
918                                    CGBuilderTy &Builder) {
919  const char *LinkageName = Name;
920
921  // Skip the asm prefix if it exists.
922  //
923  // FIXME: This should probably be the unmangled name?
924  if (Name[0] == '\01')
925    ++Name;
926
927  // FIXME: Why is this using CurLoc???
928  llvm::DICompileUnit Unit = getOrCreateCompileUnit(CurLoc);
929  SourceManager &SM = M->getContext().getSourceManager();
930  unsigned LineNo = SM.getPresumedLoc(CurLoc).getLine();
931
932  llvm::DISubprogram SP =
933    DebugFactory.CreateSubprogram(Unit, Name, Name, LinkageName, Unit, LineNo,
934                                  getOrCreateType(FnType, Unit),
935                                  Fn->hasInternalLinkage(), true/*definition*/);
936
937  // Push function on region stack.
938  RegionStack.push_back(SP);
939}
940
941
942void CGDebugInfo::EmitStopPoint(llvm::Function *Fn, CGBuilderTy &Builder) {
943  if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
944
945  // Don't bother if things are the same as last time.
946  SourceManager &SM = M->getContext().getSourceManager();
947  if (CurLoc == PrevLoc
948       || (SM.getInstantiationLineNumber(CurLoc) ==
949           SM.getInstantiationLineNumber(PrevLoc)
950           && SM.isFromSameFile(CurLoc, PrevLoc)))
951    return;
952
953  // Update last state.
954  PrevLoc = CurLoc;
955
956  // Get the appropriate compile unit.
957  llvm::DICompileUnit Unit = getOrCreateCompileUnit(CurLoc);
958  PresumedLoc PLoc = SM.getPresumedLoc(CurLoc);
959
960  llvm::DIDescriptor DR = RegionStack.back();
961  llvm::DIScope DS = llvm::DIScope(DR.getNode());
962  llvm::DILocation DO(NULL);
963  llvm::DILocation DL =
964    DebugFactory.CreateLocation(PLoc.getLine(), PLoc.getColumn(),
965                                DS, DO);
966  Builder.SetCurrentDebugLocation(DL.getNode());
967}
968
969/// EmitRegionStart- Constructs the debug code for entering a declarative
970/// region - "llvm.dbg.region.start.".
971void CGDebugInfo::EmitRegionStart(llvm::Function *Fn, CGBuilderTy &Builder) {
972  llvm::DIDescriptor D;
973  if (!RegionStack.empty())
974    D = RegionStack.back();
975  D = DebugFactory.CreateLexicalBlock(D);
976  RegionStack.push_back(D);
977}
978
979/// EmitRegionEnd - Constructs the debug code for exiting a declarative
980/// region - "llvm.dbg.region.end."
981void CGDebugInfo::EmitRegionEnd(llvm::Function *Fn, CGBuilderTy &Builder) {
982  assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
983
984  // Provide an region stop point.
985  EmitStopPoint(Fn, Builder);
986
987  RegionStack.pop_back();
988}
989
990/// EmitDeclare - Emit local variable declaration debug info.
991void CGDebugInfo::EmitDeclare(const VarDecl *Decl, unsigned Tag,
992                              llvm::Value *Storage, CGBuilderTy &Builder) {
993  assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
994
995  // Do not emit variable debug information while generating optimized code.
996  // The llvm optimizer and code generator are not yet ready to support
997  // optimized code debugging.
998  const CodeGenOptions &CGO = M->getCodeGenOpts();
999  if (CGO.OptimizationLevel)
1000    return;
1001
1002  llvm::DICompileUnit Unit = getOrCreateCompileUnit(Decl->getLocation());
1003  QualType Type = Decl->getType();
1004  llvm::DIType Ty = getOrCreateType(Type, Unit);
1005  if (Decl->hasAttr<BlocksAttr>()) {
1006    llvm::DICompileUnit DefUnit;
1007    unsigned Tag = llvm::dwarf::DW_TAG_structure_type;
1008
1009    llvm::SmallVector<llvm::DIDescriptor, 5> EltTys;
1010
1011    llvm::DIType FieldTy;
1012
1013    QualType FType;
1014    uint64_t FieldSize, FieldOffset;
1015    unsigned FieldAlign;
1016
1017    llvm::DIArray Elements;
1018    llvm::DIType EltTy;
1019
1020    // Build up structure for the byref.  See BuildByRefType.
1021    FieldOffset = 0;
1022    FType = M->getContext().getPointerType(M->getContext().VoidTy);
1023    FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1024    FieldSize = M->getContext().getTypeSize(FType);
1025    FieldAlign = M->getContext().getTypeAlign(FType);
1026    FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1027                                             "__isa", DefUnit,
1028                                             0, FieldSize, FieldAlign,
1029                                             FieldOffset, 0, FieldTy);
1030    EltTys.push_back(FieldTy);
1031    FieldOffset += FieldSize;
1032
1033    FType = M->getContext().getPointerType(M->getContext().VoidTy);
1034    FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1035    FieldSize = M->getContext().getTypeSize(FType);
1036    FieldAlign = M->getContext().getTypeAlign(FType);
1037    FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1038                                             "__forwarding", DefUnit,
1039                                             0, FieldSize, FieldAlign,
1040                                             FieldOffset, 0, FieldTy);
1041    EltTys.push_back(FieldTy);
1042    FieldOffset += FieldSize;
1043
1044    FType = M->getContext().getFixedWidthIntType(32, true); // Int32Ty;
1045    FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1046    FieldSize = M->getContext().getTypeSize(FType);
1047    FieldAlign = M->getContext().getTypeAlign(FType);
1048    FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1049                                             "__flags", DefUnit,
1050                                             0, FieldSize, FieldAlign,
1051                                             FieldOffset, 0, FieldTy);
1052    EltTys.push_back(FieldTy);
1053    FieldOffset += FieldSize;
1054
1055    FType = M->getContext().getFixedWidthIntType(32, true); // Int32Ty;
1056    FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1057    FieldSize = M->getContext().getTypeSize(FType);
1058    FieldAlign = M->getContext().getTypeAlign(FType);
1059    FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1060                                             "__size", DefUnit,
1061                                             0, FieldSize, FieldAlign,
1062                                             FieldOffset, 0, FieldTy);
1063    EltTys.push_back(FieldTy);
1064    FieldOffset += FieldSize;
1065
1066    bool HasCopyAndDispose = M->BlockRequiresCopying(Type);
1067    if (HasCopyAndDispose) {
1068      FType = M->getContext().getPointerType(M->getContext().VoidTy);
1069      FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1070      FieldSize = M->getContext().getTypeSize(FType);
1071      FieldAlign = M->getContext().getTypeAlign(FType);
1072      FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1073                                               "__copy_helper", DefUnit,
1074                                               0, FieldSize, FieldAlign,
1075                                               FieldOffset, 0, FieldTy);
1076      EltTys.push_back(FieldTy);
1077      FieldOffset += FieldSize;
1078
1079      FType = M->getContext().getPointerType(M->getContext().VoidTy);
1080      FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1081      FieldSize = M->getContext().getTypeSize(FType);
1082      FieldAlign = M->getContext().getTypeAlign(FType);
1083      FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1084                                               "__destroy_helper", DefUnit,
1085                                               0, FieldSize, FieldAlign,
1086                                               FieldOffset, 0, FieldTy);
1087      EltTys.push_back(FieldTy);
1088      FieldOffset += FieldSize;
1089    }
1090
1091    unsigned Align = M->getContext().getDeclAlignInBytes(Decl);
1092    if (Align > M->getContext().Target.getPointerAlign(0) / 8) {
1093      unsigned AlignedOffsetInBytes
1094        = llvm::RoundUpToAlignment(FieldOffset/8, Align);
1095      unsigned NumPaddingBytes
1096        = AlignedOffsetInBytes - FieldOffset/8;
1097
1098      if (NumPaddingBytes > 0) {
1099        llvm::APInt pad(32, NumPaddingBytes);
1100        FType = M->getContext().getConstantArrayType(M->getContext().CharTy,
1101                                                     pad, ArrayType::Normal, 0);
1102        FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1103        FieldSize = M->getContext().getTypeSize(FType);
1104        FieldAlign = M->getContext().getTypeAlign(FType);
1105        FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member,
1106                                                 Unit, "", DefUnit,
1107                                                 0, FieldSize, FieldAlign,
1108                                                 FieldOffset, 0, FieldTy);
1109        EltTys.push_back(FieldTy);
1110        FieldOffset += FieldSize;
1111      }
1112    }
1113
1114    FType = Type;
1115    FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1116    FieldSize = M->getContext().getTypeSize(FType);
1117    FieldAlign = Align*8;
1118
1119    FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1120                                             Decl->getNameAsCString(), DefUnit,
1121                                             0, FieldSize, FieldAlign,
1122                                             FieldOffset, 0, FieldTy);
1123    EltTys.push_back(FieldTy);
1124    FieldOffset += FieldSize;
1125
1126    Elements = DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
1127
1128    unsigned Flags = llvm::DIType::FlagBlockByrefStruct;
1129
1130    Ty = DebugFactory.CreateCompositeType(Tag, Unit, "",
1131                                          llvm::DICompileUnit(),
1132                                          0, FieldOffset, 0, 0, Flags,
1133                                          llvm::DIType(), Elements);
1134  }
1135
1136  // Get location information.
1137  SourceManager &SM = M->getContext().getSourceManager();
1138  PresumedLoc PLoc = SM.getPresumedLoc(Decl->getLocation());
1139  unsigned Line = 0;
1140  if (!PLoc.isInvalid())
1141    Line = PLoc.getLine();
1142  else
1143    Unit = llvm::DICompileUnit();
1144
1145
1146  // Create the descriptor for the variable.
1147  llvm::DIVariable D =
1148    DebugFactory.CreateVariable(Tag, RegionStack.back(),Decl->getNameAsCString(),
1149                                Unit, Line, Ty);
1150  // Insert an llvm.dbg.declare into the current block.
1151  llvm::Instruction *Call =
1152    DebugFactory.InsertDeclare(Storage, D, Builder.GetInsertBlock());
1153
1154  llvm::DIDescriptor DR = RegionStack.back();
1155  llvm::DIScope DS = llvm::DIScope(DR.getNode());
1156  llvm::DILocation DO(NULL);
1157  llvm::DILocation DL =
1158    DebugFactory.CreateLocation(Line, PLoc.getColumn(), DS, DO);
1159  Builder.SetDebugLocation(Call, DL.getNode());
1160}
1161
1162/// EmitDeclare - Emit local variable declaration debug info.
1163void CGDebugInfo::EmitDeclare(const BlockDeclRefExpr *BDRE, unsigned Tag,
1164                              llvm::Value *Storage, CGBuilderTy &Builder,
1165                              CodeGenFunction *CGF) {
1166  const ValueDecl *Decl = BDRE->getDecl();
1167  assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
1168
1169  // Do not emit variable debug information while generating optimized code.
1170  // The llvm optimizer and code generator are not yet ready to support
1171  // optimized code debugging.
1172  const CodeGenOptions &CGO = M->getCodeGenOpts();
1173  if (CGO.OptimizationLevel || Builder.GetInsertBlock() == 0)
1174    return;
1175
1176  uint64_t XOffset = 0;
1177  llvm::DICompileUnit Unit = getOrCreateCompileUnit(Decl->getLocation());
1178  QualType Type = Decl->getType();
1179  llvm::DIType Ty = getOrCreateType(Type, Unit);
1180  if (Decl->hasAttr<BlocksAttr>()) {
1181    llvm::DICompileUnit DefUnit;
1182    unsigned Tag = llvm::dwarf::DW_TAG_structure_type;
1183
1184    llvm::SmallVector<llvm::DIDescriptor, 5> EltTys;
1185
1186    llvm::DIType FieldTy;
1187
1188    QualType FType;
1189    uint64_t FieldSize, FieldOffset;
1190    unsigned FieldAlign;
1191
1192    llvm::DIArray Elements;
1193    llvm::DIType EltTy;
1194
1195    // Build up structure for the byref.  See BuildByRefType.
1196    FieldOffset = 0;
1197    FType = M->getContext().getPointerType(M->getContext().VoidTy);
1198    FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1199    FieldSize = M->getContext().getTypeSize(FType);
1200    FieldAlign = M->getContext().getTypeAlign(FType);
1201    FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1202                                             "__isa", DefUnit,
1203                                             0, FieldSize, FieldAlign,
1204                                             FieldOffset, 0, FieldTy);
1205    EltTys.push_back(FieldTy);
1206    FieldOffset += FieldSize;
1207
1208    FType = M->getContext().getPointerType(M->getContext().VoidTy);
1209    FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1210    FieldSize = M->getContext().getTypeSize(FType);
1211    FieldAlign = M->getContext().getTypeAlign(FType);
1212    FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1213                                             "__forwarding", DefUnit,
1214                                             0, FieldSize, FieldAlign,
1215                                             FieldOffset, 0, FieldTy);
1216    EltTys.push_back(FieldTy);
1217    FieldOffset += FieldSize;
1218
1219    FType = M->getContext().getFixedWidthIntType(32, true); // Int32Ty;
1220    FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1221    FieldSize = M->getContext().getTypeSize(FType);
1222    FieldAlign = M->getContext().getTypeAlign(FType);
1223    FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1224                                             "__flags", DefUnit,
1225                                             0, FieldSize, FieldAlign,
1226                                             FieldOffset, 0, FieldTy);
1227    EltTys.push_back(FieldTy);
1228    FieldOffset += FieldSize;
1229
1230    FType = M->getContext().getFixedWidthIntType(32, true); // Int32Ty;
1231    FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1232    FieldSize = M->getContext().getTypeSize(FType);
1233    FieldAlign = M->getContext().getTypeAlign(FType);
1234    FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1235                                             "__size", DefUnit,
1236                                             0, FieldSize, FieldAlign,
1237                                             FieldOffset, 0, FieldTy);
1238    EltTys.push_back(FieldTy);
1239    FieldOffset += FieldSize;
1240
1241    bool HasCopyAndDispose = M->BlockRequiresCopying(Type);
1242    if (HasCopyAndDispose) {
1243      FType = M->getContext().getPointerType(M->getContext().VoidTy);
1244      FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1245      FieldSize = M->getContext().getTypeSize(FType);
1246      FieldAlign = M->getContext().getTypeAlign(FType);
1247      FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1248                                               "__copy_helper", DefUnit,
1249                                               0, FieldSize, FieldAlign,
1250                                               FieldOffset, 0, FieldTy);
1251      EltTys.push_back(FieldTy);
1252      FieldOffset += FieldSize;
1253
1254      FType = M->getContext().getPointerType(M->getContext().VoidTy);
1255      FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1256      FieldSize = M->getContext().getTypeSize(FType);
1257      FieldAlign = M->getContext().getTypeAlign(FType);
1258      FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1259                                               "__destroy_helper", DefUnit,
1260                                               0, FieldSize, FieldAlign,
1261                                               FieldOffset, 0, FieldTy);
1262      EltTys.push_back(FieldTy);
1263      FieldOffset += FieldSize;
1264    }
1265
1266    unsigned Align = M->getContext().getDeclAlignInBytes(Decl);
1267    if (Align > M->getContext().Target.getPointerAlign(0) / 8) {
1268      unsigned AlignedOffsetInBytes
1269        = llvm::RoundUpToAlignment(FieldOffset/8, Align);
1270      unsigned NumPaddingBytes
1271        = AlignedOffsetInBytes - FieldOffset/8;
1272
1273      if (NumPaddingBytes > 0) {
1274        llvm::APInt pad(32, NumPaddingBytes);
1275        FType = M->getContext().getConstantArrayType(M->getContext().CharTy,
1276                                                     pad, ArrayType::Normal, 0);
1277        FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1278        FieldSize = M->getContext().getTypeSize(FType);
1279        FieldAlign = M->getContext().getTypeAlign(FType);
1280        FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member,
1281                                                 Unit, "", DefUnit,
1282                                                 0, FieldSize, FieldAlign,
1283                                                 FieldOffset, 0, FieldTy);
1284        EltTys.push_back(FieldTy);
1285        FieldOffset += FieldSize;
1286      }
1287    }
1288
1289    FType = Type;
1290    FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1291    FieldSize = M->getContext().getTypeSize(FType);
1292    FieldAlign = Align*8;
1293
1294    XOffset = FieldOffset;
1295    FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1296                                             Decl->getNameAsCString(), DefUnit,
1297                                             0, FieldSize, FieldAlign,
1298                                             FieldOffset, 0, FieldTy);
1299    EltTys.push_back(FieldTy);
1300    FieldOffset += FieldSize;
1301
1302    Elements = DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
1303
1304    unsigned Flags = llvm::DIType::FlagBlockByrefStruct;
1305
1306    Ty = DebugFactory.CreateCompositeType(Tag, Unit, "",
1307                                          llvm::DICompileUnit(),
1308                                          0, FieldOffset, 0, 0, Flags,
1309                                          llvm::DIType(), Elements);
1310  }
1311
1312  // Get location information.
1313  SourceManager &SM = M->getContext().getSourceManager();
1314  PresumedLoc PLoc = SM.getPresumedLoc(Decl->getLocation());
1315  unsigned Line = 0;
1316  if (!PLoc.isInvalid())
1317    Line = PLoc.getLine();
1318  else
1319    Unit = llvm::DICompileUnit();
1320
1321  uint64_t offset = CGF->BlockDecls[Decl];
1322  llvm::SmallVector<llvm::Value *, 9> addr;
1323  llvm::LLVMContext &VMContext = M->getLLVMContext();
1324  addr.push_back(llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
1325                                        llvm::DIFactory::OpDeref));
1326  addr.push_back(llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
1327                                        llvm::DIFactory::OpPlus));
1328  addr.push_back(llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
1329                                        offset));
1330  if (BDRE->isByRef()) {
1331    addr.push_back(llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
1332                                          llvm::DIFactory::OpDeref));
1333    addr.push_back(llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
1334                                          llvm::DIFactory::OpPlus));
1335    offset = CGF->LLVMPointerWidth/8; // offset of __forwarding field
1336    addr.push_back(llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
1337                                          offset));
1338    addr.push_back(llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
1339                                          llvm::DIFactory::OpDeref));
1340    addr.push_back(llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
1341                                          llvm::DIFactory::OpPlus));
1342    offset = XOffset/8;               // offset of x field
1343    addr.push_back(llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
1344                                          offset));
1345  }
1346
1347  // Create the descriptor for the variable.
1348  llvm::DIVariable D =
1349    DebugFactory.CreateComplexVariable(Tag, RegionStack.back(),
1350                                       Decl->getNameAsCString(), Unit, Line, Ty,
1351                                       addr);
1352  // Insert an llvm.dbg.declare into the current block.
1353  llvm::Instruction *Call =
1354    DebugFactory.InsertDeclare(Storage, D, Builder.GetInsertPoint());
1355
1356  llvm::DIDescriptor DR = RegionStack.back();
1357  llvm::DIScope DS = llvm::DIScope(DR.getNode());
1358  llvm::DILocation DO(NULL);
1359  llvm::DILocation DL =
1360    DebugFactory.CreateLocation(Line, PLoc.getColumn(), DS, DO);
1361  Builder.SetDebugLocation(Call, DL.getNode());
1362}
1363
1364void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *Decl,
1365                                            llvm::Value *Storage,
1366                                            CGBuilderTy &Builder) {
1367  EmitDeclare(Decl, llvm::dwarf::DW_TAG_auto_variable, Storage, Builder);
1368}
1369
1370void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(
1371  const BlockDeclRefExpr *BDRE, llvm::Value *Storage, CGBuilderTy &Builder,
1372  CodeGenFunction *CGF) {
1373  EmitDeclare(BDRE, llvm::dwarf::DW_TAG_auto_variable, Storage, Builder, CGF);
1374}
1375
1376/// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
1377/// variable declaration.
1378void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *Decl, llvm::Value *AI,
1379                                           CGBuilderTy &Builder) {
1380  EmitDeclare(Decl, llvm::dwarf::DW_TAG_arg_variable, AI, Builder);
1381}
1382
1383
1384
1385/// EmitGlobalVariable - Emit information about a global variable.
1386void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
1387                                     const VarDecl *Decl) {
1388
1389  // Create global variable debug descriptor.
1390  llvm::DICompileUnit Unit = getOrCreateCompileUnit(Decl->getLocation());
1391  SourceManager &SM = M->getContext().getSourceManager();
1392  PresumedLoc PLoc = SM.getPresumedLoc(Decl->getLocation());
1393  unsigned LineNo = PLoc.isInvalid() ? 0 : PLoc.getLine();
1394
1395  QualType T = Decl->getType();
1396  if (T->isIncompleteArrayType()) {
1397
1398    // CodeGen turns int[] into int[1] so we'll do the same here.
1399    llvm::APSInt ConstVal(32);
1400
1401    ConstVal = 1;
1402    QualType ET = M->getContext().getAsArrayType(T)->getElementType();
1403
1404    T = M->getContext().getConstantArrayType(ET, ConstVal,
1405                                           ArrayType::Normal, 0);
1406  }
1407  const char *DeclName = Decl->getNameAsCString();
1408  DebugFactory.CreateGlobalVariable(getContext(Decl, Unit), DeclName, DeclName,
1409                                    NULL, Unit, LineNo,
1410                                    getOrCreateType(T, Unit),
1411                                    Var->hasInternalLinkage(),
1412                                    true/*definition*/, Var);
1413}
1414
1415/// EmitGlobalVariable - Emit information about an objective-c interface.
1416void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
1417                                     ObjCInterfaceDecl *Decl) {
1418  // Create global variable debug descriptor.
1419  llvm::DICompileUnit Unit = getOrCreateCompileUnit(Decl->getLocation());
1420  SourceManager &SM = M->getContext().getSourceManager();
1421  PresumedLoc PLoc = SM.getPresumedLoc(Decl->getLocation());
1422  unsigned LineNo = PLoc.isInvalid() ? 0 : PLoc.getLine();
1423
1424  const char *Name = Decl->getNameAsCString();
1425
1426  QualType T = M->getContext().getObjCInterfaceType(Decl);
1427  if (T->isIncompleteArrayType()) {
1428
1429    // CodeGen turns int[] into int[1] so we'll do the same here.
1430    llvm::APSInt ConstVal(32);
1431
1432    ConstVal = 1;
1433    QualType ET = M->getContext().getAsArrayType(T)->getElementType();
1434
1435    T = M->getContext().getConstantArrayType(ET, ConstVal,
1436                                           ArrayType::Normal, 0);
1437  }
1438
1439  DebugFactory.CreateGlobalVariable(Unit, Name, Name, Name, Unit, LineNo,
1440                                    getOrCreateType(T, Unit),
1441                                    Var->hasInternalLinkage(),
1442                                    true/*definition*/, Var);
1443}
1444