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