CGDebugInfo.cpp revision 9c85ba33ac85bbf5915f300a4b228bad7c693ee7
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/Decl.h"
18#include "clang/AST/RecordLayout.h"
19#include "clang/Basic/SourceManager.h"
20#include "clang/Basic/FileManager.h"
21#include "llvm/Constants.h"
22#include "llvm/DerivedTypes.h"
23#include "llvm/Instructions.h"
24#include "llvm/Intrinsics.h"
25#include "llvm/Module.h"
26#include "llvm/ADT/StringExtras.h"
27#include "llvm/ADT/SmallVector.h"
28#include "llvm/Support/Dwarf.h"
29#include "llvm/Target/TargetMachine.h"
30using namespace clang;
31using namespace clang::CodeGen;
32
33CGDebugInfo::CGDebugInfo(CodeGenModule *m)
34  : M(m), DebugFactory(M->getModule()) {
35}
36
37CGDebugInfo::~CGDebugInfo() {
38  assert(RegionStack.empty() && "Region stack mismatch, stack not empty!");
39}
40
41void CGDebugInfo::setLocation(SourceLocation Loc) {
42  if (Loc.isValid())
43    CurLoc = M->getContext().getSourceManager().getLogicalLoc(Loc);
44}
45
46/// getOrCreateCompileUnit - Get the compile unit from the cache or create a new
47/// one if necessary. This returns null for invalid source locations.
48llvm::DICompileUnit CGDebugInfo::getOrCreateCompileUnit(SourceLocation Loc) {
49  if (Loc.isInvalid())
50    return llvm::DICompileUnit();
51
52  SourceManager &SM = M->getContext().getSourceManager();
53  const FileEntry *FE = SM.getFileEntryForLoc(Loc);
54  if (FE == 0) return llvm::DICompileUnit();
55
56  // See if this compile unit has been used before.
57  llvm::DICompileUnit &Unit = CompileUnitCache[FE];
58  if (!Unit.isNull()) return Unit;
59
60  // Get source file information.
61  const char *FileName = FE->getName();
62  const char *DirName = FE->getDir()->getName();
63
64  // Create new compile unit.
65  // FIXME: Handle other language IDs as well.
66  // FIXME: Do not know how to get clang version yet.
67  return Unit = DebugFactory.CreateCompileUnit(llvm::dwarf::DW_LANG_C89,
68                                               FileName, DirName, "clang");
69}
70
71/// getOrCreateBuiltinType - Get the Basic type from the cache or create a new
72/// one if necessary.
73llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT,
74                                     llvm::DICompileUnit Unit){
75  unsigned Encoding = 0;
76  switch (BT->getKind()) {
77  default:
78  case BuiltinType::Void:
79    return llvm::DIType();
80  case BuiltinType::UChar:
81  case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break;
82  case BuiltinType::Char_S:
83  case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break;
84  case BuiltinType::UShort:
85  case BuiltinType::UInt:
86  case BuiltinType::ULong:
87  case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break;
88  case BuiltinType::Short:
89  case BuiltinType::Int:
90  case BuiltinType::Long:
91  case BuiltinType::LongLong:  Encoding = llvm::dwarf::DW_ATE_signed; break;
92  case BuiltinType::Bool:      Encoding = llvm::dwarf::DW_ATE_boolean; break;
93  case BuiltinType::Float:
94  case BuiltinType::Double:    Encoding = llvm::dwarf::DW_ATE_float; break;
95  }
96  // Bit size, align and offset of the type.
97  uint64_t Size = M->getContext().getTypeSize(BT);
98  uint64_t Align = M->getContext().getTypeAlign(BT);
99  uint64_t Offset = 0;
100
101  return DebugFactory.CreateBasicType(Unit, BT->getName(), Unit, 0, Size, Align,
102                                      Offset, /*flags*/ 0, Encoding);
103}
104
105/// getOrCreateCVRType - Get the CVR qualified type from the cache or create
106/// a new one if necessary.
107llvm::DIType CGDebugInfo::CreateCVRType(QualType Ty, llvm::DICompileUnit Unit) {
108  // We will create one Derived type for one qualifier and recurse to handle any
109  // additional ones.
110  llvm::DIType FromTy;
111  unsigned Tag;
112  if (Ty.isConstQualified()) {
113    Tag = llvm::dwarf::DW_TAG_const_type;
114    Ty.removeConst();
115    FromTy = getOrCreateType(Ty, Unit);
116  } else if (Ty.isVolatileQualified()) {
117    Tag = llvm::dwarf::DW_TAG_volatile_type;
118    Ty.removeVolatile();
119    FromTy = getOrCreateType(Ty, Unit);
120  } else {
121    assert(Ty.isRestrictQualified() && "Unknown type qualifier for debug info");
122    Tag = llvm::dwarf::DW_TAG_restrict_type;
123    Ty.removeRestrict();
124    FromTy = getOrCreateType(Ty, Unit);
125  }
126
127  // No need to fill in the Name, Line, Size, Alignment, Offset in case of
128  // CVR derived types.
129  return DebugFactory.CreateDerivedType(Tag, Unit, "", llvm::DICompileUnit(),
130                                        0, 0, 0, 0, 0, FromTy);
131}
132
133llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
134                                     llvm::DICompileUnit Unit) {
135  llvm::DIType EltTy = getOrCreateType(Ty->getPointeeType(), Unit);
136
137  // Bit size, align and offset of the type.
138  uint64_t Size = M->getContext().getTypeSize(Ty);
139  uint64_t Align = M->getContext().getTypeAlign(Ty);
140
141  return DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type, Unit,
142                                        "", llvm::DICompileUnit(),
143                                        0, Size, Align, 0, 0, EltTy);
144}
145
146llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty,
147                                     llvm::DICompileUnit Unit) {
148  // Typedefs are derived from some other type.  If we have a typedef of a
149  // typedef, make sure to emit the whole chain.
150  llvm::DIType Src = getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
151
152  // We don't set size information, but do specify where the typedef was
153  // declared.
154  const char *TyName = Ty->getDecl()->getName();
155  SourceLocation DefLoc = Ty->getDecl()->getLocation();
156  llvm::DICompileUnit DefUnit = getOrCreateCompileUnit(DefLoc);
157
158  SourceManager &SM = M->getContext().getSourceManager();
159  uint64_t Line = SM.getLogicalLineNumber(DefLoc);
160
161  return DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_typedef, Unit,
162                                        TyName, DefUnit, Line, 0, 0, 0, 0, Src);
163}
164
165llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
166                                     llvm::DICompileUnit Unit) {
167  llvm::SmallVector<llvm::DIDescriptor, 16> EltTys;
168
169  // Add the result type at least.
170  EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit));
171
172  // Set up remainder of arguments if there is a prototype.
173  // FIXME: IF NOT, HOW IS THIS REPRESENTED?  llvm-gcc doesn't represent '...'!
174  if (const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(Ty)) {
175    for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i)
176      EltTys.push_back(getOrCreateType(FTP->getArgType(i), Unit));
177  } else {
178    // FIXME: Handle () case in C.  llvm-gcc doesn't do it either.
179  }
180
181  llvm::DIArray EltTypeArray =
182    DebugFactory.GetOrCreateArray(&EltTys[0], EltTys.size());
183
184  return DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_subroutine_type,
185                                          Unit, "", llvm::DICompileUnit(),
186                                          0, 0, 0, 0, 0,
187                                          llvm::DIType(), EltTypeArray);
188}
189
190/// getOrCreateRecordType - get structure or union type.
191llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty,
192                                     llvm::DICompileUnit Unit) {
193  const RecordDecl *Decl = Ty->getDecl();
194
195  if (!Decl->getDefinition(M->getContext()))
196    return llvm::DIType();
197
198  unsigned Tag;
199  if (Decl->isStruct())
200    Tag = llvm::dwarf::DW_TAG_structure_type;
201  else if (Decl->isUnion())
202    Tag = llvm::dwarf::DW_TAG_union_type;
203  else {
204    assert(Decl->isClass() && "Unknown RecordType!");
205    Tag = llvm::dwarf::DW_TAG_class_type;
206  }
207
208  SourceManager &SM = M->getContext().getSourceManager();
209
210  // Get overall information about the record type for the debug info.
211  const char *Name = Decl->getName();
212  if (Name == 0) Name = "";
213
214  llvm::DICompileUnit DefUnit = getOrCreateCompileUnit(Decl->getLocation());
215  uint64_t Line = SM.getLogicalLineNumber(Decl->getLocation());
216
217
218  // Records and classes and unions can all be recursive.  To handle them, we
219  // first generate a debug descriptor for the struct as a forward declaration.
220  // Then (if it is a definition) we go through and get debug info for all of
221  // its members.  Finally, we create a descriptor for the complete type (which
222  // may refer to the forward decl if the struct is recursive) and replace all
223  // uses of the forward declaration with the final definition.
224  llvm::DIType FwdDecl =
225    DebugFactory.CreateCompositeType(Tag, Unit, Name, DefUnit, Line, 0, 0, 0, 0,
226                                     llvm::DIType(), llvm::DIArray());
227
228  // If this is just a forward declaration, return it.
229  if (!Decl->getDefinition(M->getContext()))
230    return FwdDecl;
231
232  // Otherwise, insert it into the TypeCache so that recursive uses will find
233  // it.
234  TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
235
236  // Convert all the elements.
237  llvm::SmallVector<llvm::DIDescriptor, 16> EltTys;
238
239  const ASTRecordLayout &RL = M->getContext().getASTRecordLayout(Decl);
240
241  unsigned FieldNo = 0;
242  for (RecordDecl::field_const_iterator I = Decl->field_begin(),
243       E = Decl->field_end(); I != E; ++I, ++FieldNo) {
244    FieldDecl *Field = *I;
245    llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
246
247#if 0
248    const char *FieldName = Field->getName();
249    if (FieldName == 0) FieldName = "";
250
251    // Get the location for the field.
252    SourceLocation FieldDefLoc = Field->getLocation();
253    llvm::DICompileUnit FieldDefUnit = getOrCreateCompileUnit(FieldDefLoc);
254    uint64_t FieldLine = SM.getLogicalLineNumber(FieldDefLoc);
255
256    // Bit size, align and offset of the type.
257    uint64_t FieldSize = M->getContext().getTypeSize(Ty);
258    uint64_t FieldAlign = M->getContext().getTypeAlign(Ty);
259    uint64_t FieldOffset = RL.getFieldOffset(FieldNo);
260
261    // Create a DW_TAG_member node to remember the offset of this field in the
262    // struct.  FIXME: This is an absolutely insane way to capture this
263    // information.  When we gut debug info, this should be fixed.
264    FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
265                                             FieldName, FieldDefUnit,
266                                             FieldLine, FieldSize, FieldAlign,
267                                             FieldOffset, 0, FieldTy);
268#endif
269    EltTys.push_back(FieldTy);
270  }
271
272  llvm::DIArray Elements =
273    DebugFactory.GetOrCreateArray(&EltTys[0], EltTys.size());
274
275  // Bit size, align and offset of the type.
276  uint64_t Size = M->getContext().getTypeSize(Ty);
277  uint64_t Align = M->getContext().getTypeAlign(Ty);
278
279  llvm::DIType RealDecl =
280    DebugFactory.CreateCompositeType(Tag, Unit, Name, DefUnit, Line, Size,
281                                     Align, 0, 0, llvm::DIType(), Elements);
282
283  // Now that we have a real decl for the struct, replace anything using the
284  // old decl with the new one.  This will recursively update the debug info.
285  FwdDecl.getGV()->replaceAllUsesWith(RealDecl.getGV());
286  FwdDecl.getGV()->eraseFromParent();
287
288  return RealDecl;
289}
290
291llvm::DIType CGDebugInfo::CreateType(const EnumType *Ty,
292                                     llvm::DICompileUnit Unit) {
293  EnumDecl *Decl = Ty->getDecl();
294
295  llvm::SmallVector<llvm::DIDescriptor, 32> Enumerators;
296
297  // Create DIEnumerator elements for each enumerator.
298  for (EnumConstantDecl *Elt = Decl->getEnumConstantList(); Elt;
299       Elt = dyn_cast_or_null<EnumConstantDecl>(Elt->getNextDeclarator())) {
300    Enumerators.push_back(DebugFactory.CreateEnumerator(Elt->getName(),
301                                            Elt->getInitVal().getZExtValue()));
302  }
303
304  // Return a CompositeType for the enum itself.
305  llvm::DIArray EltArray =
306    DebugFactory.GetOrCreateArray(&Enumerators[0], Enumerators.size());
307
308  const char *EnumName = Decl->getName() ? Decl->getName() : "";
309  SourceLocation DefLoc = Decl->getLocation();
310  llvm::DICompileUnit DefUnit = getOrCreateCompileUnit(DefLoc);
311  SourceManager &SM = M->getContext().getSourceManager();
312  uint64_t Line = SM.getLogicalLineNumber(DefLoc);
313
314  // Size and align of the type.
315  uint64_t Size = M->getContext().getTypeSize(Ty);
316  uint64_t Align = M->getContext().getTypeAlign(Ty);
317
318  return DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_enumeration_type,
319                                          Unit, EnumName, DefUnit, Line,
320                                          Size, Align, 0, 0,
321                                          llvm::DIType(), EltArray);
322}
323
324llvm::DIType CGDebugInfo::CreateType(const TagType *Ty,
325                                     llvm::DICompileUnit Unit) {
326  if (const RecordType *RT = dyn_cast<RecordType>(Ty))
327    return CreateType(RT, Unit);
328  else if (const EnumType *ET = dyn_cast<EnumType>(Ty))
329    return CreateType(ET, Unit);
330
331  return llvm::DIType();
332}
333
334llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
335                                     llvm::DICompileUnit Unit) {
336  // Size and align of the whole array, not the element type.
337  uint64_t Size = M->getContext().getTypeSize(Ty);
338  uint64_t Align = M->getContext().getTypeAlign(Ty);
339
340  // Add the dimensions of the array.  FIXME: This loses CV qualifiers from
341  // interior arrays, do we care?  Why aren't nested arrays represented the
342  // obvious/recursive way?
343  llvm::SmallVector<llvm::DIDescriptor, 8> Subscripts;
344  QualType EltTy(Ty, 0);
345  while ((Ty = dyn_cast<ArrayType>(EltTy))) {
346    uint64_t Upper = 0;
347    if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
348      Upper = CAT->getSize().getZExtValue() - 1;
349    // FIXME: Verify this is right for VLAs.
350    Subscripts.push_back(DebugFactory.GetOrCreateSubrange(0, Upper));
351    EltTy = Ty->getElementType();
352  }
353
354  llvm::DIArray SubscriptArray =
355    DebugFactory.GetOrCreateArray(&Subscripts[0], Subscripts.size());
356
357  return DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_array_type,
358                                          Unit, "", llvm::DICompileUnit(),
359                                          0, Size, Align, 0, 0,
360                                          getOrCreateType(EltTy, Unit),
361                                          SubscriptArray);
362}
363
364
365/// getOrCreateType - Get the type from the cache or create a new
366/// one if necessary.
367llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty,
368                                          llvm::DICompileUnit Unit) {
369  if (Ty.isNull())
370    return llvm::DIType();
371
372  // Check to see if the compile unit already has created this type.
373  llvm::DIType &Slot = TypeCache[Ty.getAsOpaquePtr()];
374  if (!Slot.isNull()) return Slot;
375
376  // Handle CVR qualifiers, which recursively handles what they refer to.
377  if (Ty.getCVRQualifiers())
378    return Slot = CreateCVRType(Ty, Unit);
379
380  // Work out details of type.
381  switch (Ty->getTypeClass()) {
382  case Type::Complex:
383  case Type::Reference:
384  case Type::Vector:
385  case Type::ExtVector:
386  case Type::ASQual:
387  case Type::ObjCInterface:
388  case Type::ObjCQualifiedInterface:
389  case Type::ObjCQualifiedId:
390  case Type::TypeOfExp:
391  case Type::TypeOfTyp:
392  default:
393    return llvm::DIType();
394
395  case Type::Builtin: Slot = CreateType(cast<BuiltinType>(Ty), Unit); break;
396  case Type::Pointer: Slot = CreateType(cast<PointerType>(Ty), Unit); break;
397  case Type::TypeName: Slot = CreateType(cast<TypedefType>(Ty), Unit); break;
398  case Type::Tagged: Slot = CreateType(cast<TagType>(Ty), Unit); break;
399  case Type::FunctionProto:
400  case Type::FunctionNoProto:
401    Slot = CreateType(cast<FunctionType>(Ty), Unit);
402    break;
403
404  case Type::ConstantArray:
405  case Type::VariableArray:
406  case Type::IncompleteArray:
407    Slot = CreateType(cast<ArrayType>(Ty), Unit);
408    break;
409  }
410
411  return Slot;
412}
413
414/// EmitFunctionStart - Constructs the debug code for entering a function -
415/// "llvm.dbg.func.start.".
416void CGDebugInfo::EmitFunctionStart(const char *Name, QualType ReturnType,
417                                    llvm::Function *Fn,
418                                    CGBuilderTy &Builder) {
419  // FIXME: Why is this using CurLoc???
420  llvm::DICompileUnit Unit = getOrCreateCompileUnit(CurLoc);
421  SourceManager &SM = M->getContext().getSourceManager();
422  uint64_t LineNo = SM.getLogicalLineNumber(CurLoc);
423
424  llvm::DISubprogram SP =
425    DebugFactory.CreateSubprogram(Unit, Name, Name, "", Unit, LineNo,
426                                  getOrCreateType(ReturnType, Unit),
427                                  Fn->hasInternalLinkage(), true/*definition*/);
428
429  DebugFactory.InsertSubprogramStart(SP, Builder.GetInsertBlock());
430
431  // Push function on region stack.
432  RegionStack.push_back(SP);
433}
434
435
436void CGDebugInfo::EmitStopPoint(llvm::Function *Fn, CGBuilderTy &Builder) {
437  if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
438
439  // Don't bother if things are the same as last time.
440  SourceManager &SM = M->getContext().getSourceManager();
441  if (CurLoc == PrevLoc
442       || (SM.getLineNumber(CurLoc) == SM.getLineNumber(PrevLoc)
443           && SM.isFromSameFile(CurLoc, PrevLoc)))
444    return;
445
446  // Update last state.
447  PrevLoc = CurLoc;
448
449  // Get the appropriate compile unit.
450  llvm::DICompileUnit Unit = getOrCreateCompileUnit(CurLoc);
451  DebugFactory.InsertStopPoint(Unit, SM.getLogicalLineNumber(CurLoc),
452                               SM.getLogicalColumnNumber(CurLoc),
453                               Builder.GetInsertBlock());
454}
455
456/// EmitRegionStart- Constructs the debug code for entering a declarative
457/// region - "llvm.dbg.region.start.".
458void CGDebugInfo::EmitRegionStart(llvm::Function *Fn, CGBuilderTy &Builder) {
459  llvm::DIDescriptor D;
460  if (!RegionStack.empty())
461    D = RegionStack.back();
462  D = DebugFactory.CreateBlock(D);
463  RegionStack.push_back(D);
464  DebugFactory.InsertRegionStart(D, Builder.GetInsertBlock());
465}
466
467/// EmitRegionEnd - Constructs the debug code for exiting a declarative
468/// region - "llvm.dbg.region.end."
469void CGDebugInfo::EmitRegionEnd(llvm::Function *Fn, CGBuilderTy &Builder) {
470  assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
471
472  // Provide an region stop point.
473  EmitStopPoint(Fn, Builder);
474
475  DebugFactory.InsertRegionEnd(RegionStack.back(), Builder.GetInsertBlock());
476  RegionStack.pop_back();
477}
478
479/// EmitDeclare - Emit local variable declaration debug info.
480void CGDebugInfo::EmitDeclare(const VarDecl *Decl, unsigned Tag,
481                              llvm::Value *Storage, CGBuilderTy &Builder) {
482  assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
483
484  // Get location information.
485  SourceManager &SM = M->getContext().getSourceManager();
486  uint64_t Line = SM.getLogicalLineNumber(Decl->getLocation());
487  llvm::DICompileUnit Unit = getOrCreateCompileUnit(Decl->getLocation());
488
489  // Create the descriptor for the variable.
490  llvm::DIVariable D =
491    DebugFactory.CreateVariable(Tag, RegionStack.back(), Decl->getName(),
492                                Unit, Line,
493                                getOrCreateType(Decl->getType(), Unit));
494  // Insert an llvm.dbg.declare into the current block.
495  DebugFactory.InsertDeclare(Storage, D, Builder.GetInsertBlock());
496}
497
498void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *Decl,
499                                            llvm::Value *Storage,
500                                            CGBuilderTy &Builder) {
501  EmitDeclare(Decl, llvm::dwarf::DW_TAG_auto_variable, Storage, Builder);
502}
503
504/// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
505/// variable declaration.
506void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *Decl, llvm::Value *AI,
507                                           CGBuilderTy &Builder) {
508  EmitDeclare(Decl, llvm::dwarf::DW_TAG_arg_variable, AI, Builder);
509}
510
511
512
513/// EmitGlobalVariable - Emit information about a global variable.
514void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
515                                     const VarDecl *Decl) {
516  // Create global variable debug descriptor.
517  llvm::DICompileUnit Unit = getOrCreateCompileUnit(Decl->getLocation());
518  SourceManager &SM = M->getContext().getSourceManager();
519  uint64_t LineNo = SM.getLogicalLineNumber(Decl->getLocation());
520  const char *Name = Decl->getName();
521
522  DebugFactory.CreateGlobalVariable(Unit, Name, Name, "", Unit, LineNo,
523                                    getOrCreateType(Decl->getType(), Unit),
524                                    Var->hasInternalLinkage(),
525                                    true/*definition*/, Var);
526}
527
528