CGDebugInfo.cpp revision 9df4bb32dfafd963396155df8472904dde6a6827
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 "CodeGenModule.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/DeclObjC.h"
18#include "clang/AST/Expr.h"
19#include "clang/AST/RecordLayout.h"
20#include "clang/Basic/SourceManager.h"
21#include "clang/Basic/FileManager.h"
22#include "clang/Frontend/CompileOptions.h"
23#include "llvm/Constants.h"
24#include "llvm/DerivedTypes.h"
25#include "llvm/Instructions.h"
26#include "llvm/Intrinsics.h"
27#include "llvm/Module.h"
28#include "llvm/ADT/StringExtras.h"
29#include "llvm/ADT/SmallVector.h"
30#include "llvm/Support/Dwarf.h"
31#include "llvm/System/Path.h"
32#include "llvm/Target/TargetMachine.h"
33using namespace clang;
34using namespace clang::CodeGen;
35
36CGDebugInfo::CGDebugInfo(CodeGenModule *m)
37  : M(m), isMainCompileUnitCreated(false), DebugFactory(M->getModule()),
38    BlockLiteralGenericSet(false) {
39}
40
41CGDebugInfo::~CGDebugInfo() {
42  assert(RegionStack.empty() && "Region stack mismatch, stack not empty!");
43}
44
45void CGDebugInfo::setLocation(SourceLocation Loc) {
46  if (Loc.isValid())
47    CurLoc = M->getContext().getSourceManager().getInstantiationLoc(Loc);
48}
49
50/// getOrCreateCompileUnit - Get the compile unit from the cache or create a new
51/// one if necessary. This returns null for invalid source locations.
52llvm::DICompileUnit CGDebugInfo::getOrCreateCompileUnit(SourceLocation Loc) {
53  // Get source file information.
54  const char *FileName =  "<unknown>";
55  SourceManager &SM = M->getContext().getSourceManager();
56  unsigned FID = 0;
57  if (Loc.isValid()) {
58    PresumedLoc PLoc = SM.getPresumedLoc(Loc);
59    FileName = PLoc.getFilename();
60    FID = PLoc.getIncludeLoc().getRawEncoding();
61  }
62
63  // See if this compile unit has been used before.
64  llvm::DICompileUnit &Unit = CompileUnitCache[FID];
65  if (!Unit.isNull()) return Unit;
66
67  // Get absolute path name.
68  llvm::sys::Path AbsFileName(FileName);
69  if (!AbsFileName.isAbsolute()) {
70    llvm::sys::Path tmp = llvm::sys::Path::GetCurrentDirectory();
71    tmp.appendComponent(FileName);
72    AbsFileName = tmp;
73  }
74
75  // See if thie compile unit is representing main source file. Each source
76  // file has corresponding compile unit. There is only one main source
77  // file at a time.
78  bool isMain = false;
79  const LangOptions &LO = M->getLangOptions();
80  const char *MainFileName = LO.getMainFileName();
81  if (isMainCompileUnitCreated == false) {
82    if (MainFileName) {
83      if (!strcmp(AbsFileName.getLast().c_str(), MainFileName))
84        isMain = true;
85    } else {
86      if (Loc.isValid() && SM.isFromMainFile(Loc))
87        isMain = true;
88    }
89    if (isMain)
90      isMainCompileUnitCreated = true;
91  }
92
93  unsigned LangTag;
94  if (LO.CPlusPlus) {
95    if (LO.ObjC1)
96      LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
97    else
98      LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
99  } else if (LO.ObjC1) {
100    LangTag = llvm::dwarf::DW_LANG_ObjC;
101  } else if (LO.C99) {
102    LangTag = llvm::dwarf::DW_LANG_C99;
103  } else {
104    LangTag = llvm::dwarf::DW_LANG_C89;
105  }
106
107  std::string Producer = "clang 1.0";// FIXME: clang version.
108  bool isOptimized = LO.Optimize;
109  const char *Flags = "";   // FIXME: Encode command line options.
110
111  // Figure out which version of the ObjC runtime we have.
112  unsigned RuntimeVers = 0;
113  if (LO.ObjC1)
114    RuntimeVers = LO.ObjCNonFragileABI ? 2 : 1;
115
116  // Create new compile unit.
117  return Unit = DebugFactory.CreateCompileUnit(LangTag, AbsFileName.getLast(),
118                                               AbsFileName.getDirname(),
119                                               Producer, isMain, isOptimized,
120                                               Flags, RuntimeVers);
121}
122
123/// CreateType - Get the Basic type from the cache or create a new
124/// one if necessary.
125llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT,
126                                     llvm::DICompileUnit Unit) {
127  unsigned Encoding = 0;
128  switch (BT->getKind()) {
129  default:
130  case BuiltinType::Void:
131    return llvm::DIType();
132  case BuiltinType::UChar:
133  case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break;
134  case BuiltinType::Char_S:
135  case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break;
136  case BuiltinType::UShort:
137  case BuiltinType::UInt:
138  case BuiltinType::ULong:
139  case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break;
140  case BuiltinType::Short:
141  case BuiltinType::Int:
142  case BuiltinType::Long:
143  case BuiltinType::LongLong:  Encoding = llvm::dwarf::DW_ATE_signed; break;
144  case BuiltinType::Bool:      Encoding = llvm::dwarf::DW_ATE_boolean; break;
145  case BuiltinType::Float:
146  case BuiltinType::Double:    Encoding = llvm::dwarf::DW_ATE_float; break;
147  }
148  // Bit size, align and offset of the type.
149  uint64_t Size = M->getContext().getTypeSize(BT);
150  uint64_t Align = M->getContext().getTypeAlign(BT);
151  uint64_t Offset = 0;
152
153  return DebugFactory.CreateBasicType(Unit,
154                                  BT->getName(M->getContext().getLangOptions()),
155                                      Unit, 0, Size, Align,
156                                      Offset, /*flags*/ 0, Encoding);
157}
158
159llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty,
160                                     llvm::DICompileUnit Unit) {
161  // Bit size, align and offset of the type.
162  unsigned Encoding = llvm::dwarf::DW_ATE_complex_float;
163  if (Ty->isComplexIntegerType())
164    Encoding = llvm::dwarf::DW_ATE_lo_user;
165
166  uint64_t Size = M->getContext().getTypeSize(Ty);
167  uint64_t Align = M->getContext().getTypeAlign(Ty);
168  uint64_t Offset = 0;
169
170  return DebugFactory.CreateBasicType(Unit, "complex",
171                                      Unit, 0, Size, Align,
172                                      Offset, /*flags*/ 0, Encoding);
173}
174
175/// getOrCreateCVRType - Get the CVR qualified type from the cache or create
176/// a new one if necessary.
177llvm::DIType CGDebugInfo::CreateCVRType(QualType Ty, llvm::DICompileUnit Unit) {
178  // We will create one Derived type for one qualifier and recurse to handle any
179  // additional ones.
180  llvm::DIType FromTy;
181  unsigned Tag;
182  if (Ty.isConstQualified()) {
183    Tag = llvm::dwarf::DW_TAG_const_type;
184    Ty.removeConst();
185    FromTy = getOrCreateType(Ty, Unit);
186  } else if (Ty.isVolatileQualified()) {
187    Tag = llvm::dwarf::DW_TAG_volatile_type;
188    Ty.removeVolatile();
189    FromTy = getOrCreateType(Ty, Unit);
190  } else {
191    assert(Ty.isRestrictQualified() && "Unknown type qualifier for debug info");
192    Tag = llvm::dwarf::DW_TAG_restrict_type;
193    Ty.removeRestrict();
194    FromTy = getOrCreateType(Ty, Unit);
195  }
196
197  // No need to fill in the Name, Line, Size, Alignment, Offset in case of
198  // CVR derived types.
199  return DebugFactory.CreateDerivedType(Tag, Unit, "", llvm::DICompileUnit(),
200                                        0, 0, 0, 0, 0, FromTy);
201}
202
203llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
204                                     llvm::DICompileUnit Unit) {
205  llvm::DIType EltTy = getOrCreateType(Ty->getPointeeType(), Unit);
206
207  // Bit size, align and offset of the type.
208  uint64_t Size = M->getContext().getTypeSize(Ty);
209  uint64_t Align = M->getContext().getTypeAlign(Ty);
210
211  return DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type, Unit,
212                                        "", llvm::DICompileUnit(),
213                                        0, Size, Align, 0, 0, EltTy);
214}
215
216llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
217                                     llvm::DICompileUnit Unit) {
218  llvm::DIType EltTy = getOrCreateType(Ty->getPointeeType(), Unit);
219
220  // Bit size, align and offset of the type.
221  uint64_t Size = M->getContext().getTypeSize(Ty);
222  uint64_t Align = M->getContext().getTypeAlign(Ty);
223
224  return DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type, Unit,
225                                        "", llvm::DICompileUnit(),
226                                        0, Size, Align, 0, 0, EltTy);
227}
228
229llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
230                                     llvm::DICompileUnit Unit) {
231  if (BlockLiteralGenericSet)
232    return BlockLiteralGeneric;
233
234  llvm::DICompileUnit DefUnit;
235  unsigned Tag = llvm::dwarf::DW_TAG_structure_type;
236
237  llvm::SmallVector<llvm::DIDescriptor, 5> EltTys;
238
239  llvm::DIType FieldTy;
240
241  QualType FType;
242  uint64_t FieldSize, FieldOffset;
243  unsigned FieldAlign;
244
245  llvm::DIArray Elements;
246  llvm::DIType EltTy, DescTy;
247
248  FieldOffset = 0;
249  FType = M->getContext().UnsignedLongTy;
250  FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
251  FieldSize = M->getContext().getTypeSize(FType);
252  FieldAlign = M->getContext().getTypeAlign(FType);
253  FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
254                                           "reserved", DefUnit,
255                                           0, FieldSize, FieldAlign,
256                                           FieldOffset, 0, FieldTy);
257  EltTys.push_back(FieldTy);
258
259  FieldOffset += FieldSize;
260  FType = M->getContext().UnsignedLongTy;
261  FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
262  FieldSize = M->getContext().getTypeSize(FType);
263  FieldAlign = M->getContext().getTypeAlign(FType);
264  FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
265                                           "Size", DefUnit,
266                                           0, FieldSize, FieldAlign,
267                                           FieldOffset, 0, FieldTy);
268  EltTys.push_back(FieldTy);
269
270  FieldOffset += FieldSize;
271  Elements = DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
272  EltTys.clear();
273
274  EltTy = DebugFactory.CreateCompositeType(Tag, Unit, "__block_descriptor",
275                                           DefUnit, 0, FieldOffset, 0, 0, 0,
276                                           llvm::DIType(), Elements);
277
278  // Bit size, align and offset of the type.
279  uint64_t Size = M->getContext().getTypeSize(Ty);
280  uint64_t Align = M->getContext().getTypeAlign(Ty);
281
282  DescTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type,
283                                          Unit, "", llvm::DICompileUnit(),
284                                          0, Size, Align, 0, 0, EltTy);
285
286  FieldOffset = 0;
287  FType = M->getContext().getPointerType(M->getContext().VoidTy);
288  FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
289  FieldSize = M->getContext().getTypeSize(FType);
290  FieldAlign = M->getContext().getTypeAlign(FType);
291  FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
292                                           "__isa", DefUnit,
293                                           0, FieldSize, FieldAlign,
294                                           FieldOffset, 0, FieldTy);
295  EltTys.push_back(FieldTy);
296
297  FieldOffset += FieldSize;
298  FType = M->getContext().IntTy;
299  FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
300  FieldSize = M->getContext().getTypeSize(FType);
301  FieldAlign = M->getContext().getTypeAlign(FType);
302  FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
303                                           "__flags", DefUnit,
304                                           0, FieldSize, FieldAlign,
305                                           FieldOffset, 0, FieldTy);
306  EltTys.push_back(FieldTy);
307
308  FieldOffset += FieldSize;
309  FType = M->getContext().IntTy;
310  FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
311  FieldSize = M->getContext().getTypeSize(FType);
312  FieldAlign = M->getContext().getTypeAlign(FType);
313  FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
314                                           "__reserved", DefUnit,
315                                           0, FieldSize, FieldAlign,
316                                           FieldOffset, 0, FieldTy);
317  EltTys.push_back(FieldTy);
318
319  FieldOffset += FieldSize;
320  FType = M->getContext().getPointerType(M->getContext().VoidTy);
321  FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
322  FieldSize = M->getContext().getTypeSize(FType);
323  FieldAlign = M->getContext().getTypeAlign(FType);
324  FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
325                                           "__FuncPtr", DefUnit,
326                                           0, FieldSize, FieldAlign,
327                                           FieldOffset, 0, FieldTy);
328  EltTys.push_back(FieldTy);
329
330  FieldOffset += FieldSize;
331  FType = M->getContext().getPointerType(M->getContext().VoidTy);
332  FieldTy = DescTy;
333  FieldSize = M->getContext().getTypeSize(Ty);
334  FieldAlign = M->getContext().getTypeAlign(Ty);
335  FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
336                                           "__descriptor", DefUnit,
337                                           0, FieldSize, FieldAlign,
338                                           FieldOffset, 0, FieldTy);
339  EltTys.push_back(FieldTy);
340
341  FieldOffset += FieldSize;
342  Elements = DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
343
344  EltTy = DebugFactory.CreateCompositeType(Tag, Unit, "__block_literal_generic",
345                                           DefUnit, 0, FieldOffset, 0, 0, 0,
346                                           llvm::DIType(), Elements);
347
348  BlockLiteralGenericSet = true;
349  BlockLiteralGeneric
350    = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type, Unit,
351                                     "", llvm::DICompileUnit(),
352                                     0, Size, Align, 0, 0, EltTy);
353  return BlockLiteralGeneric;
354}
355
356llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty,
357                                     llvm::DICompileUnit Unit) {
358  // Typedefs are derived from some other type.  If we have a typedef of a
359  // typedef, make sure to emit the whole chain.
360  llvm::DIType Src = getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
361
362  // We don't set size information, but do specify where the typedef was
363  // declared.
364  std::string TyName = Ty->getDecl()->getNameAsString();
365  SourceLocation DefLoc = Ty->getDecl()->getLocation();
366  llvm::DICompileUnit DefUnit = getOrCreateCompileUnit(DefLoc);
367
368  SourceManager &SM = M->getContext().getSourceManager();
369  PresumedLoc PLoc = SM.getPresumedLoc(DefLoc);
370  unsigned Line = PLoc.isInvalid() ? 0 : PLoc.getLine();
371
372  return DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_typedef, Unit,
373                                        TyName, DefUnit, Line, 0, 0, 0, 0, Src);
374}
375
376llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
377                                     llvm::DICompileUnit Unit) {
378  llvm::SmallVector<llvm::DIDescriptor, 16> EltTys;
379
380  // Add the result type at least.
381  EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit));
382
383  // Set up remainder of arguments if there is a prototype.
384  // FIXME: IF NOT, HOW IS THIS REPRESENTED?  llvm-gcc doesn't represent '...'!
385  if (const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(Ty)) {
386    for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i)
387      EltTys.push_back(getOrCreateType(FTP->getArgType(i), Unit));
388  } else {
389    // FIXME: Handle () case in C.  llvm-gcc doesn't do it either.
390  }
391
392  llvm::DIArray EltTypeArray =
393    DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
394
395  return DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_subroutine_type,
396                                          Unit, "", llvm::DICompileUnit(),
397                                          0, 0, 0, 0, 0,
398                                          llvm::DIType(), EltTypeArray);
399}
400
401/// CreateType - get structure or union type.
402llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty,
403                                     llvm::DICompileUnit Unit) {
404  RecordDecl *Decl = Ty->getDecl();
405
406  unsigned Tag;
407  if (Decl->isStruct())
408    Tag = llvm::dwarf::DW_TAG_structure_type;
409  else if (Decl->isUnion())
410    Tag = llvm::dwarf::DW_TAG_union_type;
411  else {
412    assert(Decl->isClass() && "Unknown RecordType!");
413    Tag = llvm::dwarf::DW_TAG_class_type;
414  }
415
416  SourceManager &SM = M->getContext().getSourceManager();
417
418  // Get overall information about the record type for the debug info.
419  std::string Name = Decl->getNameAsString();
420
421  PresumedLoc PLoc = SM.getPresumedLoc(Decl->getLocation());
422  llvm::DICompileUnit DefUnit;
423  unsigned Line = 0;
424  if (!PLoc.isInvalid()) {
425    DefUnit = getOrCreateCompileUnit(Decl->getLocation());
426    Line = PLoc.getLine();
427  }
428
429  // Records and classes and unions can all be recursive.  To handle them, we
430  // first generate a debug descriptor for the struct as a forward declaration.
431  // Then (if it is a definition) we go through and get debug info for all of
432  // its members.  Finally, we create a descriptor for the complete type (which
433  // may refer to the forward decl if the struct is recursive) and replace all
434  // uses of the forward declaration with the final definition.
435  llvm::DIType FwdDecl =
436    DebugFactory.CreateCompositeType(Tag, Unit, Name, DefUnit, Line, 0, 0, 0, 0,
437                                     llvm::DIType(), llvm::DIArray());
438
439  // If this is just a forward declaration, return it.
440  if (!Decl->getDefinition(M->getContext()))
441    return FwdDecl;
442
443  // Otherwise, insert it into the TypeCache so that recursive uses will find
444  // it.
445  TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
446
447  // Convert all the elements.
448  llvm::SmallVector<llvm::DIDescriptor, 16> EltTys;
449
450  const ASTRecordLayout &RL = M->getContext().getASTRecordLayout(Decl);
451
452  unsigned FieldNo = 0;
453  for (RecordDecl::field_iterator I = Decl->field_begin(),
454                                  E = Decl->field_end();
455       I != E; ++I, ++FieldNo) {
456    FieldDecl *Field = *I;
457    llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
458
459    std::string FieldName = Field->getNameAsString();
460
461    // Ignore unnamed fields.
462    if (FieldName.empty())
463      continue;
464
465    // Get the location for the field.
466    SourceLocation FieldDefLoc = Field->getLocation();
467    PresumedLoc PLoc = SM.getPresumedLoc(FieldDefLoc);
468    llvm::DICompileUnit FieldDefUnit;
469    unsigned FieldLine = 0;
470
471    if (!PLoc.isInvalid()) {
472      FieldDefUnit = getOrCreateCompileUnit(FieldDefLoc);
473      FieldLine = PLoc.getLine();
474    }
475
476    QualType FType = Field->getType();
477    uint64_t FieldSize = 0;
478    unsigned FieldAlign = 0;
479    if (!FType->isIncompleteArrayType()) {
480
481      // Bit size, align and offset of the type.
482      FieldSize = M->getContext().getTypeSize(FType);
483      Expr *BitWidth = Field->getBitWidth();
484      if (BitWidth)
485        FieldSize = BitWidth->EvaluateAsInt(M->getContext()).getZExtValue();
486
487      FieldAlign =  M->getContext().getTypeAlign(FType);
488    }
489
490    uint64_t FieldOffset = RL.getFieldOffset(FieldNo);
491
492    // Create a DW_TAG_member node to remember the offset of this field in the
493    // struct.  FIXME: This is an absolutely insane way to capture this
494    // information.  When we gut debug info, this should be fixed.
495    FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
496                                             FieldName, FieldDefUnit,
497                                             FieldLine, FieldSize, FieldAlign,
498                                             FieldOffset, 0, FieldTy);
499    EltTys.push_back(FieldTy);
500  }
501
502  llvm::DIArray Elements =
503    DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
504
505  // Bit size, align and offset of the type.
506  uint64_t Size = M->getContext().getTypeSize(Ty);
507  uint64_t Align = M->getContext().getTypeAlign(Ty);
508
509  llvm::DIType RealDecl =
510    DebugFactory.CreateCompositeType(Tag, Unit, Name, DefUnit, Line, Size,
511                                     Align, 0, 0, llvm::DIType(), Elements);
512
513  // Now that we have a real decl for the struct, replace anything using the
514  // old decl with the new one.  This will recursively update the debug info.
515  FwdDecl.getGV()->replaceAllUsesWith(RealDecl.getGV());
516  FwdDecl.getGV()->eraseFromParent();
517
518  // Update TypeCache.
519  TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl;
520  return RealDecl;
521}
522
523/// CreateType - get objective-c interface type.
524llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
525                                     llvm::DICompileUnit Unit) {
526  ObjCInterfaceDecl *Decl = Ty->getDecl();
527
528  unsigned Tag = llvm::dwarf::DW_TAG_structure_type;
529  SourceManager &SM = M->getContext().getSourceManager();
530
531  // Get overall information about the record type for the debug info.
532  std::string Name = Decl->getNameAsString();
533
534  llvm::DICompileUnit DefUnit = getOrCreateCompileUnit(Decl->getLocation());
535  PresumedLoc PLoc = SM.getPresumedLoc(Decl->getLocation());
536  unsigned Line = PLoc.isInvalid() ? 0 : PLoc.getLine();
537
538
539  unsigned RuntimeLang = DefUnit.getLanguage();
540
541  // To handle recursive interface, we
542  // first generate a debug descriptor for the struct as a forward declaration.
543  // Then (if it is a definition) we go through and get debug info for all of
544  // its members.  Finally, we create a descriptor for the complete type (which
545  // may refer to the forward decl if the struct is recursive) and replace all
546  // uses of the forward declaration with the final definition.
547  llvm::DIType FwdDecl =
548    DebugFactory.CreateCompositeType(Tag, Unit, Name, DefUnit, Line, 0, 0, 0, 0,
549                                     llvm::DIType(), llvm::DIArray(),
550                                     RuntimeLang);
551
552  // If this is just a forward declaration, return it.
553  if (Decl->isForwardDecl())
554    return FwdDecl;
555
556  // Otherwise, insert it into the TypeCache so that recursive uses will find
557  // it.
558  TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
559
560  // Convert all the elements.
561  llvm::SmallVector<llvm::DIDescriptor, 16> EltTys;
562
563  ObjCInterfaceDecl *SClass = Decl->getSuperClass();
564  if (SClass) {
565    llvm::DIType SClassTy =
566      getOrCreateType(M->getContext().getObjCInterfaceType(SClass), Unit);
567    llvm::DIType InhTag =
568      DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_inheritance,
569                                     Unit, "", llvm::DICompileUnit(), 0, 0, 0,
570                                     0 /* offset */, 0, SClassTy);
571    EltTys.push_back(InhTag);
572  }
573
574  const ASTRecordLayout &RL = M->getContext().getASTObjCInterfaceLayout(Decl);
575
576  unsigned FieldNo = 0;
577  for (ObjCInterfaceDecl::ivar_iterator I = Decl->ivar_begin(),
578         E = Decl->ivar_end();  I != E; ++I, ++FieldNo) {
579    ObjCIvarDecl *Field = *I;
580    llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
581
582    std::string FieldName = Field->getNameAsString();
583
584    // Ignore unnamed fields.
585    if (FieldName.empty())
586      continue;
587
588    // Get the location for the field.
589    SourceLocation FieldDefLoc = Field->getLocation();
590    llvm::DICompileUnit FieldDefUnit = getOrCreateCompileUnit(FieldDefLoc);
591    PresumedLoc PLoc = SM.getPresumedLoc(FieldDefLoc);
592    unsigned FieldLine = PLoc.isInvalid() ? 0 : PLoc.getLine();
593
594
595    QualType FType = Field->getType();
596    uint64_t FieldSize = 0;
597    unsigned FieldAlign = 0;
598
599    if (!FType->isIncompleteArrayType()) {
600
601      // Bit size, align and offset of the type.
602      FieldSize = M->getContext().getTypeSize(FType);
603      Expr *BitWidth = Field->getBitWidth();
604      if (BitWidth)
605        FieldSize = BitWidth->EvaluateAsInt(M->getContext()).getZExtValue();
606
607      FieldAlign =  M->getContext().getTypeAlign(FType);
608    }
609
610    uint64_t FieldOffset = RL.getFieldOffset(FieldNo);
611
612    unsigned Flags = 0;
613    if (Field->getAccessControl() == ObjCIvarDecl::Protected)
614      Flags = llvm::DIType::FlagProtected;
615    else if (Field->getAccessControl() == ObjCIvarDecl::Private)
616      Flags = llvm::DIType::FlagPrivate;
617
618    // Create a DW_TAG_member node to remember the offset of this field in the
619    // struct.  FIXME: This is an absolutely insane way to capture this
620    // information.  When we gut debug info, this should be fixed.
621    FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
622                                             FieldName, FieldDefUnit,
623                                             FieldLine, FieldSize, FieldAlign,
624                                             FieldOffset, Flags, FieldTy);
625    EltTys.push_back(FieldTy);
626  }
627
628  llvm::DIArray Elements =
629    DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
630
631  // Bit size, align and offset of the type.
632  uint64_t Size = M->getContext().getTypeSize(Ty);
633  uint64_t Align = M->getContext().getTypeAlign(Ty);
634
635  llvm::DIType RealDecl =
636    DebugFactory.CreateCompositeType(Tag, Unit, Name, DefUnit, Line, Size,
637                                     Align, 0, 0, llvm::DIType(), Elements,
638                                     RuntimeLang);
639
640  // Now that we have a real decl for the struct, replace anything using the
641  // old decl with the new one.  This will recursively update the debug info.
642  FwdDecl.getGV()->replaceAllUsesWith(RealDecl.getGV());
643  FwdDecl.getGV()->eraseFromParent();
644
645  // Update TypeCache.
646  TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl;
647  return RealDecl;
648}
649
650llvm::DIType CGDebugInfo::CreateType(const EnumType *Ty,
651                                     llvm::DICompileUnit Unit) {
652  EnumDecl *Decl = Ty->getDecl();
653
654  llvm::SmallVector<llvm::DIDescriptor, 32> Enumerators;
655
656  // Create DIEnumerator elements for each enumerator.
657  for (EnumDecl::enumerator_iterator
658         Enum = Decl->enumerator_begin(), EnumEnd = Decl->enumerator_end();
659       Enum != EnumEnd; ++Enum) {
660    Enumerators.push_back(DebugFactory.CreateEnumerator(Enum->getNameAsString(),
661                                            Enum->getInitVal().getZExtValue()));
662  }
663
664  // Return a CompositeType for the enum itself.
665  llvm::DIArray EltArray =
666    DebugFactory.GetOrCreateArray(Enumerators.data(), Enumerators.size());
667
668  std::string EnumName = Decl->getNameAsString();
669  SourceLocation DefLoc = Decl->getLocation();
670  llvm::DICompileUnit DefUnit = getOrCreateCompileUnit(DefLoc);
671  SourceManager &SM = M->getContext().getSourceManager();
672  PresumedLoc PLoc = SM.getPresumedLoc(DefLoc);
673  unsigned Line = PLoc.isInvalid() ? 0 : PLoc.getLine();
674
675
676  // Size and align of the type.
677  uint64_t Size = 0;
678  unsigned Align = 0;
679  if (!Ty->isIncompleteType()) {
680    Size = M->getContext().getTypeSize(Ty);
681    Align = M->getContext().getTypeAlign(Ty);
682  }
683
684  return DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_enumeration_type,
685                                          Unit, EnumName, DefUnit, Line,
686                                          Size, Align, 0, 0,
687                                          llvm::DIType(), EltArray);
688}
689
690llvm::DIType CGDebugInfo::CreateType(const TagType *Ty,
691                                     llvm::DICompileUnit Unit) {
692  if (const RecordType *RT = dyn_cast<RecordType>(Ty))
693    return CreateType(RT, Unit);
694  else if (const EnumType *ET = dyn_cast<EnumType>(Ty))
695    return CreateType(ET, Unit);
696
697  return llvm::DIType();
698}
699
700llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
701                                     llvm::DICompileUnit Unit) {
702  uint64_t Size;
703  uint64_t Align;
704
705
706  // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
707  if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
708    Size = 0;
709    Align =
710      M->getContext().getTypeAlign(M->getContext().getBaseElementType(VAT));
711  } else if (Ty->isIncompleteArrayType()) {
712    Size = 0;
713    Align = M->getContext().getTypeAlign(Ty->getElementType());
714  } else {
715    // Size and align of the whole array, not the element type.
716    Size = M->getContext().getTypeSize(Ty);
717    Align = M->getContext().getTypeAlign(Ty);
718  }
719
720  // Add the dimensions of the array.  FIXME: This loses CV qualifiers from
721  // interior arrays, do we care?  Why aren't nested arrays represented the
722  // obvious/recursive way?
723  llvm::SmallVector<llvm::DIDescriptor, 8> Subscripts;
724  QualType EltTy(Ty, 0);
725  while ((Ty = dyn_cast<ArrayType>(EltTy))) {
726    uint64_t Upper = 0;
727    if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
728      Upper = CAT->getSize().getZExtValue() - 1;
729    // FIXME: Verify this is right for VLAs.
730    Subscripts.push_back(DebugFactory.GetOrCreateSubrange(0, Upper));
731    EltTy = Ty->getElementType();
732  }
733
734  llvm::DIArray SubscriptArray =
735    DebugFactory.GetOrCreateArray(Subscripts.data(), Subscripts.size());
736
737  return DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_array_type,
738                                          Unit, "", llvm::DICompileUnit(),
739                                          0, Size, Align, 0, 0,
740                                          getOrCreateType(EltTy, Unit),
741                                          SubscriptArray);
742}
743
744
745/// getOrCreateType - Get the type from the cache or create a new
746/// one if necessary.
747llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty,
748                                          llvm::DICompileUnit Unit) {
749  if (Ty.isNull())
750    return llvm::DIType();
751
752  // Check TypeCache first.
753  llvm::DIType &Slot = TypeCache[Ty.getAsOpaquePtr()];
754  if (!Slot.isNull()) return Slot;
755
756  // Handle CVR qualifiers, which recursively handles what they refer to.
757  if (Ty.getCVRQualifiers())
758    return Slot = CreateCVRType(Ty, Unit);
759
760  // Work out details of type.
761  switch (Ty->getTypeClass()) {
762#define TYPE(Class, Base)
763#define ABSTRACT_TYPE(Class, Base)
764#define NON_CANONICAL_TYPE(Class, Base)
765#define DEPENDENT_TYPE(Class, Base) case Type::Class:
766#include "clang/AST/TypeNodes.def"
767    assert(false && "Dependent types cannot show up in debug information");
768
769  case Type::LValueReference:
770  case Type::RValueReference:
771  case Type::Vector:
772  case Type::ExtVector:
773  case Type::ExtQual:
774  case Type::FixedWidthInt:
775  case Type::MemberPointer:
776  case Type::TemplateSpecialization:
777  case Type::QualifiedName:
778    // Unsupported types
779    return llvm::DIType();
780  case Type::ObjCObjectPointer:
781    return Slot = CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
782  case Type::ObjCQualifiedInterface:  // Drop protocols from interface.
783  case Type::ObjCInterface:
784    return Slot = CreateType(cast<ObjCInterfaceType>(Ty), Unit);
785  case Type::Builtin: return Slot = CreateType(cast<BuiltinType>(Ty), Unit);
786  case Type::Complex: return Slot = CreateType(cast<ComplexType>(Ty), Unit);
787  case Type::Pointer: return Slot = CreateType(cast<PointerType>(Ty), Unit);
788  case Type::BlockPointer:
789    return Slot = CreateType(cast<BlockPointerType>(Ty), Unit);
790  case Type::Typedef: return Slot = CreateType(cast<TypedefType>(Ty), Unit);
791  case Type::Record:
792  case Type::Enum:
793    return Slot = CreateType(cast<TagType>(Ty), Unit);
794  case Type::FunctionProto:
795  case Type::FunctionNoProto:
796    return Slot = CreateType(cast<FunctionType>(Ty), Unit);
797
798  case Type::ConstantArray:
799  case Type::ConstantArrayWithExpr:
800  case Type::ConstantArrayWithoutExpr:
801  case Type::VariableArray:
802  case Type::IncompleteArray:
803    return Slot = CreateType(cast<ArrayType>(Ty), Unit);
804  case Type::TypeOfExpr:
805    return Slot = getOrCreateType(cast<TypeOfExprType>(Ty)->getUnderlyingExpr()
806                                  ->getType(), Unit);
807  case Type::TypeOf:
808    return Slot = getOrCreateType(cast<TypeOfType>(Ty)->getUnderlyingType(),
809                                  Unit);
810  case Type::Decltype:
811    return Slot = getOrCreateType(cast<DecltypeType>(Ty)->getUnderlyingType(),
812                                  Unit);
813  }
814
815  return Slot;
816}
817
818/// EmitFunctionStart - Constructs the debug code for entering a function -
819/// "llvm.dbg.func.start.".
820void CGDebugInfo::EmitFunctionStart(const char *Name, QualType ReturnType,
821                                    llvm::Function *Fn,
822                                    CGBuilderTy &Builder) {
823  const char *LinkageName = Name;
824
825  // Skip the asm prefix if it exists.
826  //
827  // FIXME: This should probably be the unmangled name?
828  if (Name[0] == '\01')
829    ++Name;
830
831  // FIXME: Why is this using CurLoc???
832  llvm::DICompileUnit Unit = getOrCreateCompileUnit(CurLoc);
833  SourceManager &SM = M->getContext().getSourceManager();
834  unsigned LineNo = SM.getPresumedLoc(CurLoc).getLine();
835
836  llvm::DISubprogram SP =
837    DebugFactory.CreateSubprogram(Unit, Name, Name, LinkageName, Unit, LineNo,
838                                  getOrCreateType(ReturnType, Unit),
839                                  Fn->hasInternalLinkage(), true/*definition*/);
840
841  DebugFactory.InsertSubprogramStart(SP, Builder.GetInsertBlock());
842
843  // Push function on region stack.
844  RegionStack.push_back(SP);
845}
846
847
848void CGDebugInfo::EmitStopPoint(llvm::Function *Fn, CGBuilderTy &Builder) {
849  if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
850
851  // Don't bother if things are the same as last time.
852  SourceManager &SM = M->getContext().getSourceManager();
853  if (CurLoc == PrevLoc
854       || (SM.getInstantiationLineNumber(CurLoc) ==
855           SM.getInstantiationLineNumber(PrevLoc)
856           && SM.isFromSameFile(CurLoc, PrevLoc)))
857    return;
858
859  // Update last state.
860  PrevLoc = CurLoc;
861
862  // Get the appropriate compile unit.
863  llvm::DICompileUnit Unit = getOrCreateCompileUnit(CurLoc);
864  PresumedLoc PLoc = SM.getPresumedLoc(CurLoc);
865  DebugFactory.InsertStopPoint(Unit, PLoc.getLine(), PLoc.getColumn(),
866                               Builder.GetInsertBlock());
867}
868
869/// EmitRegionStart- Constructs the debug code for entering a declarative
870/// region - "llvm.dbg.region.start.".
871void CGDebugInfo::EmitRegionStart(llvm::Function *Fn, CGBuilderTy &Builder) {
872  llvm::DIDescriptor D;
873  if (!RegionStack.empty())
874    D = RegionStack.back();
875  D = DebugFactory.CreateBlock(D);
876  RegionStack.push_back(D);
877  DebugFactory.InsertRegionStart(D, Builder.GetInsertBlock());
878}
879
880/// EmitRegionEnd - Constructs the debug code for exiting a declarative
881/// region - "llvm.dbg.region.end."
882void CGDebugInfo::EmitRegionEnd(llvm::Function *Fn, CGBuilderTy &Builder) {
883  assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
884
885  // Provide an region stop point.
886  EmitStopPoint(Fn, Builder);
887
888  DebugFactory.InsertRegionEnd(RegionStack.back(), Builder.GetInsertBlock());
889  RegionStack.pop_back();
890}
891
892/// EmitDeclare - Emit local variable declaration debug info.
893void CGDebugInfo::EmitDeclare(const VarDecl *Decl, unsigned Tag,
894                              llvm::Value *Storage, CGBuilderTy &Builder) {
895  assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
896
897  // Do not emit variable debug information while generating optimized code.
898  // The llvm optimizer and code generator are not yet ready to support
899  // optimized code debugging.
900  const CompileOptions &CO = M->getCompileOpts();
901  if (CO.OptimizationLevel)
902    return;
903
904  llvm::DICompileUnit Unit = getOrCreateCompileUnit(Decl->getLocation());
905  llvm::DIType Ty = getOrCreateType(Decl->getType(), Unit);
906
907  // Get location information.
908  SourceManager &SM = M->getContext().getSourceManager();
909  PresumedLoc PLoc = SM.getPresumedLoc(Decl->getLocation());
910  unsigned Line = 0;
911  if (!PLoc.isInvalid())
912    Line = PLoc.getLine();
913  else
914    Unit = llvm::DICompileUnit();
915
916
917  // Create the descriptor for the variable.
918  llvm::DIVariable D =
919    DebugFactory.CreateVariable(Tag, RegionStack.back(),Decl->getNameAsString(),
920                                Unit, Line, Ty);
921  // Insert an llvm.dbg.declare into the current block.
922  DebugFactory.InsertDeclare(Storage, D, Builder.GetInsertBlock());
923}
924
925void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *Decl,
926                                            llvm::Value *Storage,
927                                            CGBuilderTy &Builder) {
928  EmitDeclare(Decl, llvm::dwarf::DW_TAG_auto_variable, Storage, Builder);
929}
930
931/// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
932/// variable declaration.
933void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *Decl, llvm::Value *AI,
934                                           CGBuilderTy &Builder) {
935  EmitDeclare(Decl, llvm::dwarf::DW_TAG_arg_variable, AI, Builder);
936}
937
938
939
940/// EmitGlobalVariable - Emit information about a global variable.
941void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
942                                     const VarDecl *Decl) {
943
944  // Do not emit variable debug information while generating optimized code.
945  // The llvm optimizer and code generator are not yet ready to support
946  // optimized code debugging.
947  const CompileOptions &CO = M->getCompileOpts();
948  if (CO.OptimizationLevel)
949    return;
950
951  // Create global variable debug descriptor.
952  llvm::DICompileUnit Unit = getOrCreateCompileUnit(Decl->getLocation());
953  SourceManager &SM = M->getContext().getSourceManager();
954  PresumedLoc PLoc = SM.getPresumedLoc(Decl->getLocation());
955  unsigned LineNo = PLoc.isInvalid() ? 0 : PLoc.getLine();
956
957  std::string Name = Decl->getNameAsString();
958
959  QualType T = Decl->getType();
960  if (T->isIncompleteArrayType()) {
961
962    // CodeGen turns int[] into int[1] so we'll do the same here.
963    llvm::APSInt ConstVal(32);
964
965    ConstVal = 1;
966    QualType ET = M->getContext().getAsArrayType(T)->getElementType();
967
968    T = M->getContext().getConstantArrayType(ET, ConstVal,
969                                           ArrayType::Normal, 0);
970  }
971
972  DebugFactory.CreateGlobalVariable(Unit, Name, Name, "", Unit, LineNo,
973                                    getOrCreateType(T, Unit),
974                                    Var->hasInternalLinkage(),
975                                    true/*definition*/, Var);
976}
977
978/// EmitGlobalVariable - Emit information about an objective-c interface.
979void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
980                                     ObjCInterfaceDecl *Decl) {
981  // Create global variable debug descriptor.
982  llvm::DICompileUnit Unit = getOrCreateCompileUnit(Decl->getLocation());
983  SourceManager &SM = M->getContext().getSourceManager();
984  PresumedLoc PLoc = SM.getPresumedLoc(Decl->getLocation());
985  unsigned LineNo = PLoc.isInvalid() ? 0 : PLoc.getLine();
986
987  std::string Name = Decl->getNameAsString();
988
989  QualType T = M->getContext().getObjCInterfaceType(Decl);
990  if (T->isIncompleteArrayType()) {
991
992    // CodeGen turns int[] into int[1] so we'll do the same here.
993    llvm::APSInt ConstVal(32);
994
995    ConstVal = 1;
996    QualType ET = M->getContext().getAsArrayType(T)->getElementType();
997
998    T = M->getContext().getConstantArrayType(ET, ConstVal,
999                                           ArrayType::Normal, 0);
1000  }
1001
1002  DebugFactory.CreateGlobalVariable(Unit, Name, Name, "", Unit, LineNo,
1003                                    getOrCreateType(T, Unit),
1004                                    Var->hasInternalLinkage(),
1005                                    true/*definition*/, Var);
1006}
1007
1008