CGDebugInfo.cpp revision 9881cf0f09aeada2894b203c854bd12b1babfd5d
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/CodeGen/MachineModuleInfo.h"
29#include "llvm/Support/Dwarf.h"
30#include "llvm/Support/IRBuilder.h"
31#include "llvm/Target/TargetMachine.h"
32using namespace clang;
33using namespace clang::CodeGen;
34
35CGDebugInfo::CGDebugInfo(CodeGenModule *m)
36: M(m)
37, CurLoc()
38, PrevLoc()
39, CompileUnitCache()
40, TypeCache()
41, StopPointFn(NULL)
42, FuncStartFn(NULL)
43, DeclareFn(NULL)
44, RegionStartFn(NULL)
45, RegionEndFn(NULL)
46, CompileUnitAnchor(NULL)
47, SubprogramAnchor(NULL)
48, GlobalVariableAnchor(NULL)
49, RegionStack()
50, VariableDescList()
51, GlobalVarDescList()
52, EnumDescList()
53, SubrangeDescList()
54, Subprogram(NULL)
55{
56  SR = new llvm::DISerializer();
57  SR->setModule (&M->getModule());
58}
59
60CGDebugInfo::~CGDebugInfo()
61{
62  assert(RegionStack.empty() && "Region stack mismatch, stack not empty!");
63
64  delete SR;
65
66  // Free CompileUnitCache.
67  for (std::map<const FileEntry*, llvm::CompileUnitDesc *>::iterator I
68       = CompileUnitCache.begin(); I != CompileUnitCache.end(); ++I) {
69    delete I->second;
70  }
71  CompileUnitCache.clear();
72
73  // Free TypeCache.
74  for (std::map<void *, llvm::TypeDesc *>::iterator I
75       = TypeCache.begin(); I != TypeCache.end(); ++I) {
76    delete I->second;
77  }
78  TypeCache.clear();
79
80  // Free region descriptors.
81  for (std::vector<llvm::DebugInfoDesc *>::iterator I
82       = RegionStack.begin(); I != RegionStack.end(); ++I) {
83    delete *I;
84  }
85
86  // Free local var descriptors.
87  for (std::vector<llvm::VariableDesc *>::iterator I
88       = VariableDescList.begin(); I != VariableDescList.end(); ++I) {
89    delete *I;
90  }
91
92  // Free global var descriptors.
93  for (std::vector<llvm::GlobalVariableDesc *>::iterator I
94       = GlobalVarDescList.begin(); I != GlobalVarDescList.end(); ++I) {
95    delete *I;
96  }
97
98  // Free enum constants descriptors.
99  for (std::vector<llvm::EnumeratorDesc *>::iterator I
100       = EnumDescList.begin(); I != EnumDescList.end(); ++I) {
101    delete *I;
102  }
103
104  // Free subrange descriptors.
105  for (std::vector<llvm::SubrangeDesc *>::iterator I
106       = SubrangeDescList.begin(); I != SubrangeDescList.end(); ++I) {
107    delete *I;
108  }
109
110  delete CompileUnitAnchor;
111  delete SubprogramAnchor;
112  delete GlobalVariableAnchor;
113}
114
115void CGDebugInfo::setLocation(SourceLocation loc) {
116  if (loc.isValid())
117    CurLoc = M->getContext().getSourceManager().getLogicalLoc(loc);
118}
119
120/// getCastValueFor - Return a llvm representation for a given debug information
121/// descriptor cast to an empty struct pointer.
122llvm::Value *CGDebugInfo::getCastValueFor(llvm::DebugInfoDesc *DD) {
123  return llvm::ConstantExpr::getBitCast(SR->Serialize(DD),
124                                        SR->getEmptyStructPtrType());
125}
126
127/// getValueFor - Return a llvm representation for a given debug information
128/// descriptor.
129llvm::Value *CGDebugInfo::getValueFor(llvm::DebugInfoDesc *DD) {
130  return SR->Serialize(DD);
131}
132
133/// getOrCreateCompileUnit - Get the compile unit from the cache or create a new
134/// one if necessary. This returns null for invalid source locations.
135llvm::CompileUnitDesc*
136CGDebugInfo::getOrCreateCompileUnit(const SourceLocation Loc) {
137  if (Loc.isInvalid())
138    return NULL;
139
140  SourceManager &SM = M->getContext().getSourceManager();
141  const FileEntry *FE = SM.getFileEntryForLoc(Loc);
142
143  // See if this compile unit has been used before.
144  llvm::CompileUnitDesc *&Unit = CompileUnitCache[FE];
145  if (Unit) return Unit;
146
147  // Create new compile unit.
148  // FIXME: Where to free these?
149  // One way is to iterate over the CompileUnitCache in ~CGDebugInfo.
150  Unit = new llvm::CompileUnitDesc();
151
152  // Make sure we have an anchor.
153  if (!CompileUnitAnchor) {
154    CompileUnitAnchor = new llvm::AnchorDesc(Unit);
155  }
156
157  // Get source file information.
158  const char *FileName, *DirName;
159  if (FE) {
160    FileName = FE->getName();
161    DirName = FE->getDir()->getName();
162  } else {
163    FileName = SM.getSourceName(Loc);
164    DirName = "";
165  }
166
167  Unit->setAnchor(CompileUnitAnchor);
168  Unit->setFileName(FileName);
169  Unit->setDirectory(DirName);
170
171  // Set up producer name.
172  // FIXME: Do not know how to get clang version yet.
173  Unit->setProducer("clang");
174
175  // Set up Language number.
176  // FIXME: Handle other languages as well.
177  Unit->setLanguage(llvm::dwarf::DW_LANG_C89);
178
179  return Unit;
180}
181
182
183/// getOrCreateCVRType - Get the CVR qualified type from the cache or create
184/// a new one if necessary.
185llvm::TypeDesc *
186CGDebugInfo::getOrCreateCVRType(QualType type, llvm::CompileUnitDesc *Unit)
187{
188  // We will create a Derived type.
189  llvm::DerivedTypeDesc *DTy = NULL;
190  llvm::TypeDesc *FromTy = NULL;
191
192  if (type.isConstQualified()) {
193    DTy = new llvm::DerivedTypeDesc(llvm::dwarf::DW_TAG_const_type);
194    type.removeConst();
195    FromTy = getOrCreateType(type, Unit);
196  } else if (type.isVolatileQualified()) {
197    DTy = new llvm::DerivedTypeDesc(llvm::dwarf::DW_TAG_volatile_type);
198    type.removeVolatile();
199    FromTy = getOrCreateType(type, Unit);
200  } else if (type.isRestrictQualified()) {
201    DTy = new llvm::DerivedTypeDesc(llvm::dwarf::DW_TAG_restrict_type);
202    type.removeRestrict();
203    FromTy = getOrCreateType(type, Unit);
204  }
205
206  // No need to fill in the Name, Line, Size, Alignment, Offset in case of
207  // CVR derived types.
208  DTy->setContext(Unit);
209  DTy->setFromType(FromTy);
210
211  return DTy;
212}
213
214
215/// getOrCreateBuiltinType - Get the Basic type from the cache or create a new
216/// one if necessary.
217llvm::TypeDesc *
218CGDebugInfo::getOrCreateBuiltinType(QualType type, llvm::CompileUnitDesc *Unit)
219{
220  assert (type->getTypeClass() == Type::Builtin);
221
222  const BuiltinType *BT = type->getAsBuiltinType();
223
224  unsigned Encoding = 0;
225  switch (BT->getKind())
226  {
227    case BuiltinType::Void:
228      return NULL;
229    case BuiltinType::UChar:
230    case BuiltinType::Char_U:
231      Encoding = llvm::dwarf::DW_ATE_unsigned_char;
232      break;
233    case BuiltinType::Char_S:
234    case BuiltinType::SChar:
235      Encoding = llvm::dwarf::DW_ATE_signed_char;
236      break;
237    case BuiltinType::UShort:
238    case BuiltinType::UInt:
239    case BuiltinType::ULong:
240    case BuiltinType::ULongLong:
241      Encoding = llvm::dwarf::DW_ATE_unsigned;
242      break;
243    case BuiltinType::Short:
244    case BuiltinType::Int:
245    case BuiltinType::Long:
246    case BuiltinType::LongLong:
247      Encoding = llvm::dwarf::DW_ATE_signed;
248      break;
249    case BuiltinType::Bool:
250      Encoding = llvm::dwarf::DW_ATE_boolean;
251      break;
252    case BuiltinType::Float:
253    case BuiltinType::Double:
254      Encoding = llvm::dwarf::DW_ATE_float;
255      break;
256    default:
257      Encoding = llvm::dwarf::DW_ATE_signed;
258      break;
259  }
260
261  // Ty will have contain the resulting type.
262  llvm::BasicTypeDesc *BTy = new llvm::BasicTypeDesc();
263
264  // Get the name and location early to assist debugging.
265  const char *TyName = BT->getName();
266
267  // Bit size, align and offset of the type.
268  uint64_t Size = M->getContext().getTypeSize(type);
269  uint64_t Align = M->getContext().getTypeAlign(type);
270  uint64_t Offset = 0;
271
272  // If the type is defined, fill in the details.
273  if (BTy) {
274    BTy->setContext(Unit);
275    BTy->setName(TyName);
276    BTy->setSize(Size);
277    BTy->setAlign(Align);
278    BTy->setOffset(Offset);
279    BTy->setEncoding(Encoding);
280  }
281
282  return BTy;
283}
284
285llvm::TypeDesc *
286CGDebugInfo::getOrCreatePointerType(QualType type, llvm::CompileUnitDesc *Unit)
287{
288  // type*
289  llvm::DerivedTypeDesc *DTy =
290    new llvm::DerivedTypeDesc(llvm::dwarf::DW_TAG_pointer_type);
291
292  // Handle the derived type.
293  const PointerType *PTRT = type->getAsPointerType();
294  llvm::TypeDesc *FromTy = getOrCreateType(PTRT->getPointeeType(), Unit);
295
296  // Get the name and location early to assist debugging.
297  SourceManager &SM = M->getContext().getSourceManager();
298  uint64_t Line = SM.getLogicalLineNumber(CurLoc);
299
300  // Bit size, align and offset of the type.
301  uint64_t Size = M->getContext().getTypeSize(type);
302  uint64_t Align = M->getContext().getTypeAlign(type);
303  uint64_t Offset = 0;
304
305  // If the type is defined, fill in the details.
306  if (DTy) {
307    DTy->setContext(Unit);
308    DTy->setLine(Line);
309    DTy->setSize(Size);
310    DTy->setAlign(Align);
311    DTy->setOffset(Offset);
312    DTy->setFromType(FromTy);
313  }
314
315  return DTy;
316}
317
318llvm::TypeDesc *
319CGDebugInfo::getOrCreateTypedefType(QualType type, llvm::CompileUnitDesc *Unit)
320{
321  // typedefs are derived from some other type.
322  llvm::DerivedTypeDesc *DTy =
323    new llvm::DerivedTypeDesc(llvm::dwarf::DW_TAG_typedef);
324
325  // Handle derived type.
326  const TypedefType *TDT = type->getAsTypedefType();
327  llvm::TypeDesc *FromTy = getOrCreateType(TDT->LookThroughTypedefs(),
328                                               Unit);
329
330  // Get the name and location early to assist debugging.
331  const char *TyName = TDT->getDecl()->getName();
332  SourceManager &SM = M->getContext().getSourceManager();
333  uint64_t Line = SM.getLogicalLineNumber(TDT->getDecl()->getLocation());
334
335  // If the type is defined, fill in the details.
336  if (DTy) {
337    DTy->setContext(Unit);
338    DTy->setFile(getOrCreateCompileUnit(TDT->getDecl()->getLocation()));
339    DTy->setLine(Line);
340    DTy->setName(TyName);
341    DTy->setFromType(FromTy);
342  }
343
344  return DTy;
345}
346
347llvm::TypeDesc *
348CGDebugInfo::getOrCreateFunctionType(QualType type, llvm::CompileUnitDesc *Unit)
349{
350  llvm::CompositeTypeDesc *SubrTy =
351    new llvm::CompositeTypeDesc(llvm::dwarf::DW_TAG_subroutine_type);
352
353  // Prepare to add the arguments for the subroutine.
354  std::vector<llvm::DebugInfoDesc *> &Elements = SubrTy->getElements();
355
356  // Get result type.
357  const FunctionType *FT = type->getAsFunctionType();
358  llvm::TypeDesc *ArgTy = getOrCreateType(FT->getResultType(), Unit);
359  Elements.push_back(ArgTy);
360
361  // Set up remainder of arguments.
362  if (type->getTypeClass() == Type::FunctionProto) {
363    const FunctionTypeProto *FTPro = dyn_cast<FunctionTypeProto>(type);
364    for (unsigned int i =0; i < FTPro->getNumArgs(); i++) {
365      QualType ParamType = FTPro->getArgType(i);
366      ArgTy = getOrCreateType(ParamType, Unit);
367      if (ArgTy) Elements.push_back(ArgTy);
368    }
369  }
370
371  // FIXME: set other fields file, line here.
372  SubrTy->setContext(Unit);
373
374  return SubrTy;
375}
376
377/// getOrCreateRecordType - get structure or union type.
378void CGDebugInfo::getOrCreateRecordType(QualType type,
379                                        llvm::CompileUnitDesc *Unit,
380                                        llvm::TypeDesc *&Slot)
381{
382  // Prevent recursing in type generation by initializing the slot
383  // here.
384  llvm::CompositeTypeDesc *RecType;
385  if (type->isStructureType())
386    Slot = RecType =
387      new llvm::CompositeTypeDesc(llvm::dwarf::DW_TAG_structure_type);
388  else if (type->isUnionType())
389    Slot = RecType =
390      new llvm::CompositeTypeDesc(llvm::dwarf::DW_TAG_union_type);
391  else
392    return;
393
394  RecordDecl *RecDecl = type->getAsRecordType()->getDecl();
395  // We can not get the type for forward declarations.
396  // FIXME: What *should* we be doing here?
397  if (!RecDecl->getDefinition(M->getContext()))
398    return;
399  const ASTRecordLayout &RL = M->getContext().getASTRecordLayout(RecDecl);
400
401  SourceManager &SM = M->getContext().getSourceManager();
402  uint64_t Line = SM.getLogicalLineNumber(RecDecl->getLocation());
403
404  std::vector<llvm::DebugInfoDesc *> &Elements = RecType->getElements();
405
406  // Add the members.
407  int NumMembers = RecDecl->getNumMembers();
408  for (int i = 0; i < NumMembers; i++) {
409    FieldDecl *Member = RecDecl->getMember(i);
410    llvm::TypeDesc *MemberTy = getOrCreateType(Member->getType(), Unit);
411    MemberTy->setOffset(RL.getFieldOffset(i));
412    Elements.push_back(MemberTy);
413  }
414
415  // Fill in the blanks.
416  if (RecType) {
417    RecType->setContext(Unit);
418    RecType->setName(RecDecl->getName());
419    RecType->setFile(getOrCreateCompileUnit(RecDecl->getLocation()));
420    RecType->setLine(Line);
421    RecType->setSize(RL.getSize());
422    RecType->setAlign(RL.getAlignment());
423    RecType->setOffset(0);
424  }
425}
426
427/// getOrCreateEnumType - get Enum type.
428llvm::TypeDesc *
429CGDebugInfo::getOrCreateEnumType(QualType type, llvm::CompileUnitDesc *Unit)
430{
431  llvm::CompositeTypeDesc *EnumTy
432    = new llvm::CompositeTypeDesc(llvm::dwarf::DW_TAG_enumeration_type);
433
434  EnumType *EType = dyn_cast<EnumType>(type);
435  if (!EType) return(NULL);
436
437  EnumDecl *EDecl = EType->getDecl();
438  SourceManager &SM = M->getContext().getSourceManager();
439  uint64_t Line = SM.getLogicalLineNumber(EDecl->getLocation());
440
441  // Size, align and offset of the type.
442  uint64_t Size = M->getContext().getTypeSize(type);
443  uint64_t Align = M->getContext().getTypeAlign(type);
444
445  // Create descriptors for enum members.
446  std::vector<llvm::DebugInfoDesc *> &Elements = EnumTy->getElements();
447  EnumConstantDecl *ElementList = EDecl->getEnumConstantList();
448  while (ElementList) {
449    llvm::EnumeratorDesc *EnumDesc = new llvm::EnumeratorDesc();
450    // push it to the enum desc list so that we can free it later.
451    EnumDescList.push_back(EnumDesc);
452
453    const char *ElementName = ElementList->getName();
454    uint64_t Value = ElementList->getInitVal().getZExtValue();
455
456    EnumDesc->setName(ElementName);
457    EnumDesc->setValue(Value);
458    Elements.push_back(EnumDesc);
459    if (ElementList->getNextDeclarator())
460      ElementList
461        = dyn_cast<EnumConstantDecl>(ElementList->getNextDeclarator());
462    else
463      break;
464  }
465
466  // Fill in the blanks.
467  if (EnumTy) {
468    EnumTy->setContext(Unit);
469    EnumTy->setName(EDecl->getName());
470    EnumTy->setSize(Size);
471    EnumTy->setAlign(Align);
472    EnumTy->setOffset(0);
473    EnumTy->setFile(getOrCreateCompileUnit(EDecl->getLocation()));
474    EnumTy->setLine(Line);
475  }
476  return EnumTy;
477}
478
479/// getOrCreateArrayType - get or create array types.
480llvm::TypeDesc *
481CGDebugInfo::getOrCreateArrayType(QualType type, llvm::CompileUnitDesc *Unit)
482{
483  llvm::CompositeTypeDesc *ArrayTy
484    = new llvm::CompositeTypeDesc(llvm::dwarf::DW_TAG_array_type);
485
486  // Size, align and offset of the type.
487  uint64_t Size = M->getContext().getTypeSize(type);
488  uint64_t Align = M->getContext().getTypeAlign(type);
489
490  SourceManager &SM = M->getContext().getSourceManager();
491  uint64_t Line = SM.getLogicalLineNumber(CurLoc);
492
493  // Add the dimensions of the array.
494  std::vector<llvm::DebugInfoDesc *> &Elements = ArrayTy->getElements();
495  do {
496    const ArrayType *AT = M->getContext().getAsArrayType(type);
497    llvm::SubrangeDesc *Subrange = new llvm::SubrangeDesc();
498
499    // push it back on the subrange desc list so that we can free it later.
500    SubrangeDescList.push_back(Subrange);
501
502    uint64_t Upper = 0;
503    if (const ConstantArrayType *ConstArrTy = dyn_cast<ConstantArrayType>(AT)) {
504      Upper = ConstArrTy->getSize().getZExtValue() - 1;
505    }
506    Subrange->setLo(0);
507    Subrange->setHi(Upper);
508    Elements.push_back(Subrange);
509    type = AT->getElementType();
510  } while (type->isArrayType());
511
512  ArrayTy->setFromType(getOrCreateType(type, Unit));
513
514  if (ArrayTy) {
515    ArrayTy->setContext(Unit);
516    ArrayTy->setSize(Size);
517    ArrayTy->setAlign(Align);
518    ArrayTy->setOffset(0);
519    ArrayTy->setFile(getOrCreateCompileUnit(CurLoc));
520    ArrayTy->setLine(Line);
521  }
522  return ArrayTy;
523}
524
525
526/// getOrCreateTaggedType - get or create structure/union/Enum type.
527void CGDebugInfo::getOrCreateTaggedType(QualType type,
528                                        llvm::CompileUnitDesc *Unit,
529                                        llvm::TypeDesc *&Slot)
530{
531  if (type->isStructureType() || type->isUnionType())
532    getOrCreateRecordType(type, Unit, Slot);
533  else if (type->isEnumeralType())
534    Slot = getOrCreateEnumType(type, Unit);
535}
536
537/// getOrCreateType - Get the type from the cache or create a new
538/// one if necessary.
539llvm::TypeDesc *
540CGDebugInfo::getOrCreateType(QualType type, llvm::CompileUnitDesc *Unit)
541{
542  if (type.isNull())
543    return NULL;
544
545  // Check to see if the compile unit already has created this type.
546  llvm::TypeDesc *&Slot = TypeCache[type.getAsOpaquePtr()];
547  if (Slot) return Slot;
548
549  // We need to check for the CVR qualifiers as the first thing.
550  if (type.getCVRQualifiers()) {
551    Slot = getOrCreateCVRType(type, Unit);
552    return Slot;
553  }
554
555  // Work out details of type.
556  switch (type->getTypeClass()) {
557    case Type::Complex:
558    case Type::Reference:
559    case Type::Vector:
560    case Type::ExtVector:
561    case Type::ASQual:
562    case Type::ObjCInterface:
563    case Type::ObjCQualifiedInterface:
564    case Type::ObjCQualifiedId:
565    case Type::TypeOfExp:
566    case Type::TypeOfTyp:
567    default:
568      return NULL;
569
570    case Type::TypeName:
571      Slot = getOrCreateTypedefType(type, Unit);
572      break;
573
574    case Type::FunctionProto:
575    case Type::FunctionNoProto:
576      Slot = getOrCreateFunctionType(type, Unit);
577      break;
578
579    case Type::Builtin:
580      Slot = getOrCreateBuiltinType(type, Unit);
581      break;
582
583    case Type::Pointer:
584      Slot = getOrCreatePointerType(type, Unit);
585      break;
586
587    case Type::Tagged:
588      getOrCreateTaggedType(type, Unit, Slot);
589      break;
590
591    case Type::ConstantArray:
592    case Type::VariableArray:
593    case Type::IncompleteArray:
594      Slot = getOrCreateArrayType(type, Unit);
595      break;
596  }
597
598  return Slot;
599}
600
601/// EmitFunctionStart - Constructs the debug code for entering a function -
602/// "llvm.dbg.func.start.".
603void CGDebugInfo::EmitFunctionStart(const char *Name,
604                                    QualType ReturnType,
605                                    llvm::Function *Fn,
606                                    llvm::IRBuilder<> &Builder)
607{
608  // Create subprogram descriptor.
609  Subprogram = new llvm::SubprogramDesc();
610
611  // Make sure we have an anchor.
612  if (!SubprogramAnchor) {
613    SubprogramAnchor = new llvm::AnchorDesc(Subprogram);
614  }
615
616  // Get name information.
617  Subprogram->setName(Name);
618  Subprogram->setFullName(Name);
619
620  // Gather location information.
621  llvm::CompileUnitDesc *Unit = getOrCreateCompileUnit(CurLoc);
622  SourceManager &SM = M->getContext().getSourceManager();
623  uint64_t Loc = SM.getLogicalLineNumber(CurLoc);
624
625  // Get Function Type.
626  llvm::TypeDesc *SPTy = getOrCreateType(ReturnType, Unit);
627
628  Subprogram->setAnchor(SubprogramAnchor);
629  Subprogram->setContext(Unit);
630  Subprogram->setFile(Unit);
631  Subprogram->setLine(Loc);
632  Subprogram->setType(SPTy);
633  Subprogram->setIsStatic(Fn->hasInternalLinkage());
634  Subprogram->setIsDefinition(true);
635
636  // Lazily construct llvm.dbg.func.start.
637  if (!FuncStartFn)
638    FuncStartFn = llvm::Intrinsic::getDeclaration(&M->getModule(),
639                    llvm::Intrinsic::dbg_func_start);
640
641  // Call llvm.dbg.func.start which also implicitly calls llvm.dbg.stoppoint.
642  Builder.CreateCall(FuncStartFn, getCastValueFor(Subprogram), "");
643
644  // Push function on region stack.
645  RegionStack.push_back(Subprogram);
646}
647
648
649void
650CGDebugInfo::EmitStopPoint(llvm::Function *Fn, llvm::IRBuilder<> &Builder)
651{
652  if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
653
654  // Don't bother if things are the same as last time.
655  SourceManager &SM = M->getContext().getSourceManager();
656  if (CurLoc == PrevLoc
657       || (SM.getLineNumber(CurLoc) == SM.getLineNumber(PrevLoc)
658           && SM.isFromSameFile(CurLoc, PrevLoc)))
659    return;
660
661  // Update last state.
662  PrevLoc = CurLoc;
663
664  // Get the appropriate compile unit.
665  llvm::CompileUnitDesc *Unit = getOrCreateCompileUnit(CurLoc);
666
667  // Lazily construct llvm.dbg.stoppoint function.
668  if (!StopPointFn)
669    StopPointFn = llvm::Intrinsic::getDeclaration(&M->getModule(),
670                                        llvm::Intrinsic::dbg_stoppoint);
671
672  uint64_t CurLineNo = SM.getLogicalLineNumber(CurLoc);
673  uint64_t ColumnNo = SM.getLogicalColumnNumber(CurLoc);
674
675  // Invoke llvm.dbg.stoppoint
676  Builder.CreateCall3(StopPointFn,
677                      llvm::ConstantInt::get(llvm::Type::Int32Ty, CurLineNo),
678                      llvm::ConstantInt::get(llvm::Type::Int32Ty, ColumnNo),
679                      getCastValueFor(Unit), "");
680}
681
682/// EmitRegionStart- Constructs the debug code for entering a declarative
683/// region - "llvm.dbg.region.start.".
684void CGDebugInfo::EmitRegionStart(llvm::Function *Fn,
685                                  llvm::IRBuilder<> &Builder)
686{
687  llvm::BlockDesc *Block = new llvm::BlockDesc();
688  if (!RegionStack.empty())
689    Block->setContext(RegionStack.back());
690  RegionStack.push_back(Block);
691
692  // Lazily construct llvm.dbg.region.start function.
693  if (!RegionStartFn)
694    RegionStartFn = llvm::Intrinsic::getDeclaration(&M->getModule(),
695                                llvm::Intrinsic::dbg_region_start);
696
697  // Call llvm.dbg.func.start.
698  Builder.CreateCall(RegionStartFn, getCastValueFor(Block), "");
699}
700
701/// EmitRegionEnd - Constructs the debug code for exiting a declarative
702/// region - "llvm.dbg.region.end."
703void CGDebugInfo::EmitRegionEnd(llvm::Function *Fn, llvm::IRBuilder<> &Builder)
704{
705  assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
706
707  // Lazily construct llvm.dbg.region.end function.
708  if (!RegionEndFn)
709    RegionEndFn =llvm::Intrinsic::getDeclaration(&M->getModule(),
710                                llvm::Intrinsic::dbg_region_end);
711
712  // Provide an region stop point.
713  EmitStopPoint(Fn, Builder);
714
715  // Call llvm.dbg.func.end.
716  llvm::DebugInfoDesc *DID = RegionStack.back();
717  Builder.CreateCall(RegionEndFn, getCastValueFor(DID), "");
718  RegionStack.pop_back();
719  // FIXME: Should be freeing here?
720}
721
722/// EmitDeclare - Emit local variable declaration debug info.
723void CGDebugInfo::EmitDeclare(const VarDecl *decl, unsigned Tag,
724                              llvm::Value *AI,
725                              llvm::IRBuilder<> &Builder)
726{
727  assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
728
729  // FIXME: If it is a compiler generated temporary then return.
730
731  // Construct llvm.dbg.declare function.
732  if (!DeclareFn)
733    DeclareFn = llvm::Intrinsic::getDeclaration(&M->getModule(),
734                        llvm::Intrinsic::dbg_declare);
735
736  // Get type information.
737  llvm::CompileUnitDesc *Unit = getOrCreateCompileUnit(CurLoc);
738  llvm::TypeDesc *TyDesc = getOrCreateType(decl->getType(), Unit);
739
740  SourceManager &SM = M->getContext().getSourceManager();
741  uint64_t Loc = SM.getLogicalLineNumber(CurLoc);
742
743  // Construct variable.
744  llvm::VariableDesc *Variable = new llvm::VariableDesc(Tag);
745  Variable->setContext(RegionStack.back());
746  Variable->setName(decl->getName());
747  Variable->setFile(Unit);
748  Variable->setLine(Loc);
749  Variable->setType(TyDesc);
750
751  // Push it onto the list so that we can free it.
752  VariableDescList.push_back(Variable);
753
754  // Cast the AllocA result to a {}* for the call to llvm.dbg.declare.
755  // These bit cast instructions will get freed when the basic block is
756  // deleted. So do not need to free them explicity.
757  const llvm::PointerType *EmpPtr = SR->getEmptyStructPtrType();
758  llvm::Value *AllocACast =  new llvm::BitCastInst(AI, EmpPtr, decl->getName(),
759                               Builder.GetInsertBlock());
760
761  // Call llvm.dbg.declare.
762  Builder.CreateCall2(DeclareFn, AllocACast, getCastValueFor(Variable), "");
763}
764
765/// EmitGlobalVariable - Emit information about a global variable.
766void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *GV,
767                                     const VarDecl *decl)
768{
769  // Create global variable debug descriptor.
770  llvm::GlobalVariableDesc *Global = new llvm::GlobalVariableDesc();
771
772  // Push it onto the list so that we can free it.
773  GlobalVarDescList.push_back(Global);
774
775  // Make sure we have an anchor.
776  if (!GlobalVariableAnchor)
777    GlobalVariableAnchor = new llvm::AnchorDesc(Global);
778
779  // Get name information.
780  Global->setName(decl->getName());
781  Global->setFullName(decl->getName());
782
783  llvm::CompileUnitDesc *Unit = getOrCreateCompileUnit(CurLoc);
784  SourceManager &SM = M->getContext().getSourceManager();
785  uint64_t Loc = SM.getLogicalLineNumber(CurLoc);
786
787  llvm::TypeDesc *TyD = getOrCreateType(decl->getType(), Unit);
788
789  // Fill in the Global information.
790  Global->setAnchor(GlobalVariableAnchor);
791  Global->setContext(Unit);
792  Global->setFile(Unit);
793  Global->setLine(Loc);
794  Global->setType(TyD);
795  Global->setIsDefinition(true);
796  Global->setIsStatic(GV->hasInternalLinkage());
797  Global->setGlobalVariable(GV);
798
799  // Make sure global is created if needed.
800  getValueFor(Global);
801}
802
803