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"
33 using namespace clang;
34 using namespace clang::CodeGen;
35 
36 CGDebugInfo::CGDebugInfo(CodeGenModule *m)
37   : M(m), isMainCompileUnitCreated(false), DebugFactory(M->getModule()),
38     BlockLiteralGenericSet(false) {
39 }
40 
41 CGDebugInfo::~CGDebugInfo() {
42   assert(RegionStack.empty() && "Region stack mismatch, stack not empty!");
43 }
44 
45 void 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.
52 llvm::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.
125 llvm::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 
159 llvm::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.
177 llvm::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 
203 llvm::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 
216 llvm::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 
229 llvm::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 
356 llvm::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 
376 llvm::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.
402 llvm::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::DICompositeType 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::DICompositeType 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.replaceAllUsesWith(RealDecl);
516 
517   // Update TypeCache.
518   TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl;
519   return RealDecl;
520 }
521 
522 /// CreateType - get objective-c interface type.
523 llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
524                                      llvm::DICompileUnit Unit) {
525   ObjCInterfaceDecl *Decl = Ty->getDecl();
526 
527   unsigned Tag = llvm::dwarf::DW_TAG_structure_type;
528   SourceManager &SM = M->getContext().getSourceManager();
529 
530   // Get overall information about the record type for the debug info.
531   std::string Name = Decl->getNameAsString();
532 
533   llvm::DICompileUnit DefUnit = getOrCreateCompileUnit(Decl->getLocation());
534   PresumedLoc PLoc = SM.getPresumedLoc(Decl->getLocation());
535   unsigned Line = PLoc.isInvalid() ? 0 : PLoc.getLine();
536 
537 
538   unsigned RuntimeLang = DefUnit.getLanguage();
539 
540   // To handle recursive interface, we
541   // first generate a debug descriptor for the struct as a forward declaration.
542   // Then (if it is a definition) we go through and get debug info for all of
543   // its members.  Finally, we create a descriptor for the complete type (which
544   // may refer to the forward decl if the struct is recursive) and replace all
545   // uses of the forward declaration with the final definition.
546   llvm::DICompositeType FwdDecl =
547     DebugFactory.CreateCompositeType(Tag, Unit, Name, DefUnit, Line, 0, 0, 0, 0,
548                                      llvm::DIType(), llvm::DIArray(),
549                                      RuntimeLang);
550 
551   // If this is just a forward declaration, return it.
552   if (Decl->isForwardDecl())
553     return FwdDecl;
554 
555   // Otherwise, insert it into the TypeCache so that recursive uses will find
556   // it.
557   TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
558 
559   // Convert all the elements.
560   llvm::SmallVector<llvm::DIDescriptor, 16> EltTys;
561 
562   ObjCInterfaceDecl *SClass = Decl->getSuperClass();
563   if (SClass) {
564     llvm::DIType SClassTy =
565       getOrCreateType(M->getContext().getObjCInterfaceType(SClass), Unit);
566     llvm::DIType InhTag =
567       DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_inheritance,
568                                      Unit, "", llvm::DICompileUnit(), 0, 0, 0,
569                                      0 /* offset */, 0, SClassTy);
570     EltTys.push_back(InhTag);
571   }
572 
573   const ASTRecordLayout &RL = M->getContext().getASTObjCInterfaceLayout(Decl);
574 
575   unsigned FieldNo = 0;
576   for (ObjCInterfaceDecl::ivar_iterator I = Decl->ivar_begin(),
577          E = Decl->ivar_end();  I != E; ++I, ++FieldNo) {
578     ObjCIvarDecl *Field = *I;
579     llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
580 
581     std::string FieldName = Field->getNameAsString();
582 
583     // Ignore unnamed fields.
584     if (FieldName.empty())
585       continue;
586 
587     // Get the location for the field.
588     SourceLocation FieldDefLoc = Field->getLocation();
589     llvm::DICompileUnit FieldDefUnit = getOrCreateCompileUnit(FieldDefLoc);
590     PresumedLoc PLoc = SM.getPresumedLoc(FieldDefLoc);
591     unsigned FieldLine = PLoc.isInvalid() ? 0 : PLoc.getLine();
592 
593 
594     QualType FType = Field->getType();
595     uint64_t FieldSize = 0;
596     unsigned FieldAlign = 0;
597 
598     if (!FType->isIncompleteArrayType()) {
599 
600       // Bit size, align and offset of the type.
601       FieldSize = M->getContext().getTypeSize(FType);
602       Expr *BitWidth = Field->getBitWidth();
603       if (BitWidth)
604         FieldSize = BitWidth->EvaluateAsInt(M->getContext()).getZExtValue();
605 
606       FieldAlign =  M->getContext().getTypeAlign(FType);
607     }
608 
609     uint64_t FieldOffset = RL.getFieldOffset(FieldNo);
610 
611     unsigned Flags = 0;
612     if (Field->getAccessControl() == ObjCIvarDecl::Protected)
613       Flags = llvm::DIType::FlagProtected;
614     else if (Field->getAccessControl() == ObjCIvarDecl::Private)
615       Flags = llvm::DIType::FlagPrivate;
616 
617     // Create a DW_TAG_member node to remember the offset of this field in the
618     // struct.  FIXME: This is an absolutely insane way to capture this
619     // information.  When we gut debug info, this should be fixed.
620     FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
621                                              FieldName, FieldDefUnit,
622                                              FieldLine, FieldSize, FieldAlign,
623                                              FieldOffset, Flags, FieldTy);
624     EltTys.push_back(FieldTy);
625   }
626 
627   llvm::DIArray Elements =
628     DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
629 
630   // Bit size, align and offset of the type.
631   uint64_t Size = M->getContext().getTypeSize(Ty);
632   uint64_t Align = M->getContext().getTypeAlign(Ty);
633 
634   llvm::DICompositeType RealDecl =
635     DebugFactory.CreateCompositeType(Tag, Unit, Name, DefUnit, Line, Size,
636                                      Align, 0, 0, llvm::DIType(), Elements,
637                                      RuntimeLang);
638 
639   // Now that we have a real decl for the struct, replace anything using the
640   // old decl with the new one.  This will recursively update the debug info.
641   FwdDecl.replaceAllUsesWith(RealDecl);
642 
643   // Update TypeCache.
644   TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl;
645   return RealDecl;
646 }
647 
648 llvm::DIType CGDebugInfo::CreateType(const EnumType *Ty,
649                                      llvm::DICompileUnit Unit) {
650   EnumDecl *Decl = Ty->getDecl();
651 
652   llvm::SmallVector<llvm::DIDescriptor, 32> Enumerators;
653 
654   // Create DIEnumerator elements for each enumerator.
655   for (EnumDecl::enumerator_iterator
656          Enum = Decl->enumerator_begin(), EnumEnd = Decl->enumerator_end();
657        Enum != EnumEnd; ++Enum) {
658     Enumerators.push_back(DebugFactory.CreateEnumerator(Enum->getNameAsString(),
659                                             Enum->getInitVal().getZExtValue()));
660   }
661 
662   // Return a CompositeType for the enum itself.
663   llvm::DIArray EltArray =
664     DebugFactory.GetOrCreateArray(Enumerators.data(), Enumerators.size());
665 
666   std::string EnumName = Decl->getNameAsString();
667   SourceLocation DefLoc = Decl->getLocation();
668   llvm::DICompileUnit DefUnit = getOrCreateCompileUnit(DefLoc);
669   SourceManager &SM = M->getContext().getSourceManager();
670   PresumedLoc PLoc = SM.getPresumedLoc(DefLoc);
671   unsigned Line = PLoc.isInvalid() ? 0 : PLoc.getLine();
672 
673 
674   // Size and align of the type.
675   uint64_t Size = 0;
676   unsigned Align = 0;
677   if (!Ty->isIncompleteType()) {
678     Size = M->getContext().getTypeSize(Ty);
679     Align = M->getContext().getTypeAlign(Ty);
680   }
681 
682   return DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_enumeration_type,
683                                           Unit, EnumName, DefUnit, Line,
684                                           Size, Align, 0, 0,
685                                           llvm::DIType(), EltArray);
686 }
687 
688 llvm::DIType CGDebugInfo::CreateType(const TagType *Ty,
689                                      llvm::DICompileUnit Unit) {
690   if (const RecordType *RT = dyn_cast<RecordType>(Ty))
691     return CreateType(RT, Unit);
692   else if (const EnumType *ET = dyn_cast<EnumType>(Ty))
693     return CreateType(ET, Unit);
694 
695   return llvm::DIType();
696 }
697 
698 llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
699                                      llvm::DICompileUnit Unit) {
700   uint64_t Size;
701   uint64_t Align;
702 
703 
704   // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
705   if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
706     Size = 0;
707     Align =
708       M->getContext().getTypeAlign(M->getContext().getBaseElementType(VAT));
709   } else if (Ty->isIncompleteArrayType()) {
710     Size = 0;
711     Align = M->getContext().getTypeAlign(Ty->getElementType());
712   } else {
713     // Size and align of the whole array, not the element type.
714     Size = M->getContext().getTypeSize(Ty);
715     Align = M->getContext().getTypeAlign(Ty);
716   }
717 
718   // Add the dimensions of the array.  FIXME: This loses CV qualifiers from
719   // interior arrays, do we care?  Why aren't nested arrays represented the
720   // obvious/recursive way?
721   llvm::SmallVector<llvm::DIDescriptor, 8> Subscripts;
722   QualType EltTy(Ty, 0);
723   while ((Ty = dyn_cast<ArrayType>(EltTy))) {
724     uint64_t Upper = 0;
725     if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
726       if (CAT->getSize().getZExtValue())
727         Upper = CAT->getSize().getZExtValue() - 1;
728     // FIXME: Verify this is right for VLAs.
729     Subscripts.push_back(DebugFactory.GetOrCreateSubrange(0, Upper));
730     EltTy = Ty->getElementType();
731   }
732 
733   llvm::DIArray SubscriptArray =
734     DebugFactory.GetOrCreateArray(Subscripts.data(), Subscripts.size());
735 
736   return DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_array_type,
737                                           Unit, "", llvm::DICompileUnit(),
738                                           0, Size, Align, 0, 0,
739                                           getOrCreateType(EltTy, Unit),
740                                           SubscriptArray);
741 }
742 
743 
744 /// getOrCreateType - Get the type from the cache or create a new
745 /// one if necessary.
746 llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty,
747                                           llvm::DICompileUnit Unit) {
748   if (Ty.isNull())
749     return llvm::DIType();
750 
751   // Check TypeCache first.
752   llvm::DIType &Slot = TypeCache[Ty.getAsOpaquePtr()];
753   if (!Slot.isNull()) return Slot;
754 
755   // Handle CVR qualifiers, which recursively handles what they refer to.
756   if (Ty.getCVRQualifiers())
757     return Slot = CreateCVRType(Ty, Unit);
758 
759   // Work out details of type.
760   switch (Ty->getTypeClass()) {
761 #define TYPE(Class, Base)
762 #define ABSTRACT_TYPE(Class, Base)
763 #define NON_CANONICAL_TYPE(Class, Base)
764 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
765 #include "clang/AST/TypeNodes.def"
766     assert(false && "Dependent types cannot show up in debug information");
767 
768   case Type::LValueReference:
769   case Type::RValueReference:
770   case Type::Vector:
771   case Type::ExtVector:
772   case Type::ExtQual:
773   case Type::FixedWidthInt:
774   case Type::MemberPointer:
775   case Type::TemplateSpecialization:
776   case Type::QualifiedName:
777     // Unsupported types
778     return llvm::DIType();
779   case Type::ObjCObjectPointer:
780     return Slot = CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
781   case Type::ObjCInterface:
782     return Slot = CreateType(cast<ObjCInterfaceType>(Ty), Unit);
783   case Type::Builtin: return Slot = CreateType(cast<BuiltinType>(Ty), Unit);
784   case Type::Complex: return Slot = CreateType(cast<ComplexType>(Ty), Unit);
785   case Type::Pointer: return Slot = CreateType(cast<PointerType>(Ty), Unit);
786   case Type::BlockPointer:
787     return Slot = CreateType(cast<BlockPointerType>(Ty), Unit);
788   case Type::Typedef: return Slot = CreateType(cast<TypedefType>(Ty), Unit);
789   case Type::Record:
790   case Type::Enum:
791     return Slot = CreateType(cast<TagType>(Ty), Unit);
792   case Type::FunctionProto:
793   case Type::FunctionNoProto:
794     return Slot = CreateType(cast<FunctionType>(Ty), Unit);
795   case Type::Elaborated:
796     return Slot = getOrCreateType(cast<ElaboratedType>(Ty)->getUnderlyingType(),
797                                   Unit);
798 
799   case Type::ConstantArray:
800   case Type::ConstantArrayWithExpr:
801   case Type::ConstantArrayWithoutExpr:
802   case Type::VariableArray:
803   case Type::IncompleteArray:
804     return Slot = CreateType(cast<ArrayType>(Ty), Unit);
805   case Type::TypeOfExpr:
806     return Slot = getOrCreateType(cast<TypeOfExprType>(Ty)->getUnderlyingExpr()
807                                   ->getType(), Unit);
808   case Type::TypeOf:
809     return Slot = getOrCreateType(cast<TypeOfType>(Ty)->getUnderlyingType(),
810                                   Unit);
811   case Type::Decltype:
812     return Slot = getOrCreateType(cast<DecltypeType>(Ty)->getUnderlyingType(),
813                                   Unit);
814   }
815 
816   return Slot;
817 }
818 
819 /// EmitFunctionStart - Constructs the debug code for entering a function -
820 /// "llvm.dbg.func.start.".
821 void CGDebugInfo::EmitFunctionStart(const char *Name, QualType ReturnType,
822                                     llvm::Function *Fn,
823                                     CGBuilderTy &Builder) {
824   const char *LinkageName = Name;
825 
826   // Skip the asm prefix if it exists.
827   //
828   // FIXME: This should probably be the unmangled name?
829   if (Name[0] == '\01')
830     ++Name;
831 
832   // FIXME: Why is this using CurLoc???
833   llvm::DICompileUnit Unit = getOrCreateCompileUnit(CurLoc);
834   SourceManager &SM = M->getContext().getSourceManager();
835   unsigned LineNo = SM.getPresumedLoc(CurLoc).getLine();
836 
837   llvm::DISubprogram SP =
838     DebugFactory.CreateSubprogram(Unit, Name, Name, LinkageName, Unit, LineNo,
839                                   getOrCreateType(ReturnType, Unit),
840                                   Fn->hasInternalLinkage(), true/*definition*/);
841 
842   DebugFactory.InsertSubprogramStart(SP, Builder.GetInsertBlock());
843 
844   // Push function on region stack.
845   RegionStack.push_back(SP);
846 }
847 
848 
849 void CGDebugInfo::EmitStopPoint(llvm::Function *Fn, CGBuilderTy &Builder) {
850   if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
851 
852   // Don't bother if things are the same as last time.
853   SourceManager &SM = M->getContext().getSourceManager();
854   if (CurLoc == PrevLoc
855        || (SM.getInstantiationLineNumber(CurLoc) ==
856            SM.getInstantiationLineNumber(PrevLoc)
857            && SM.isFromSameFile(CurLoc, PrevLoc)))
858     return;
859 
860   // Update last state.
861   PrevLoc = CurLoc;
862 
863   // Get the appropriate compile unit.
864   llvm::DICompileUnit Unit = getOrCreateCompileUnit(CurLoc);
865   PresumedLoc PLoc = SM.getPresumedLoc(CurLoc);
866   DebugFactory.InsertStopPoint(Unit, PLoc.getLine(), PLoc.getColumn(),
867                                Builder.GetInsertBlock());
868 }
869 
870 /// EmitRegionStart- Constructs the debug code for entering a declarative
871 /// region - "llvm.dbg.region.start.".
872 void CGDebugInfo::EmitRegionStart(llvm::Function *Fn, CGBuilderTy &Builder) {
873   llvm::DIDescriptor D;
874   if (!RegionStack.empty())
875     D = RegionStack.back();
876   D = DebugFactory.CreateLexicalBlock(D);
877   RegionStack.push_back(D);
878   DebugFactory.InsertRegionStart(D, Builder.GetInsertBlock());
879 }
880 
881 /// EmitRegionEnd - Constructs the debug code for exiting a declarative
882 /// region - "llvm.dbg.region.end."
883 void CGDebugInfo::EmitRegionEnd(llvm::Function *Fn, CGBuilderTy &Builder) {
884   assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
885 
886   // Provide an region stop point.
887   EmitStopPoint(Fn, Builder);
888 
889   DebugFactory.InsertRegionEnd(RegionStack.back(), Builder.GetInsertBlock());
890   RegionStack.pop_back();
891 }
892 
893 /// EmitDeclare - Emit local variable declaration debug info.
894 void CGDebugInfo::EmitDeclare(const VarDecl *Decl, unsigned Tag,
895                               llvm::Value *Storage, CGBuilderTy &Builder) {
896   assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
897 
898   // Do not emit variable debug information while generating optimized code.
899   // The llvm optimizer and code generator are not yet ready to support
900   // optimized code debugging.
901   const CompileOptions &CO = M->getCompileOpts();
902   if (CO.OptimizationLevel)
903     return;
904 
905   llvm::DICompileUnit Unit = getOrCreateCompileUnit(Decl->getLocation());
906   llvm::DIType Ty = getOrCreateType(Decl->getType(), Unit);
907 
908   // Get location information.
909   SourceManager &SM = M->getContext().getSourceManager();
910   PresumedLoc PLoc = SM.getPresumedLoc(Decl->getLocation());
911   unsigned Line = 0;
912   if (!PLoc.isInvalid())
913     Line = PLoc.getLine();
914   else
915     Unit = llvm::DICompileUnit();
916 
917 
918   // Create the descriptor for the variable.
919   llvm::DIVariable D =
920     DebugFactory.CreateVariable(Tag, RegionStack.back(),Decl->getNameAsString(),
921                                 Unit, Line, Ty);
922   // Insert an llvm.dbg.declare into the current block.
923   DebugFactory.InsertDeclare(Storage, D, Builder.GetInsertBlock());
924 }
925 
926 void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *Decl,
927                                             llvm::Value *Storage,
928                                             CGBuilderTy &Builder) {
929   EmitDeclare(Decl, llvm::dwarf::DW_TAG_auto_variable, Storage, Builder);
930 }
931 
932 /// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
933 /// variable declaration.
934 void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *Decl, llvm::Value *AI,
935                                            CGBuilderTy &Builder) {
936   EmitDeclare(Decl, llvm::dwarf::DW_TAG_arg_variable, AI, Builder);
937 }
938 
939 
940 
941 /// EmitGlobalVariable - Emit information about a global variable.
942 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
943                                      const VarDecl *Decl) {
944 
945   // Do not emit variable debug information while generating optimized code.
946   // The llvm optimizer and code generator are not yet ready to support
947   // optimized code debugging.
948   const CompileOptions &CO = M->getCompileOpts();
949   if (CO.OptimizationLevel)
950     return;
951 
952   // Create global variable debug descriptor.
953   llvm::DICompileUnit Unit = getOrCreateCompileUnit(Decl->getLocation());
954   SourceManager &SM = M->getContext().getSourceManager();
955   PresumedLoc PLoc = SM.getPresumedLoc(Decl->getLocation());
956   unsigned LineNo = PLoc.isInvalid() ? 0 : PLoc.getLine();
957 
958   std::string Name = Decl->getNameAsString();
959 
960   QualType T = Decl->getType();
961   if (T->isIncompleteArrayType()) {
962 
963     // CodeGen turns int[] into int[1] so we'll do the same here.
964     llvm::APSInt ConstVal(32);
965 
966     ConstVal = 1;
967     QualType ET = M->getContext().getAsArrayType(T)->getElementType();
968 
969     T = M->getContext().getConstantArrayType(ET, ConstVal,
970                                            ArrayType::Normal, 0);
971   }
972 
973   DebugFactory.CreateGlobalVariable(Unit, Name, Name, "", Unit, LineNo,
974                                     getOrCreateType(T, Unit),
975                                     Var->hasInternalLinkage(),
976                                     true/*definition*/, Var);
977 }
978 
979 /// EmitGlobalVariable - Emit information about an objective-c interface.
980 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
981                                      ObjCInterfaceDecl *Decl) {
982   // Create global variable debug descriptor.
983   llvm::DICompileUnit Unit = getOrCreateCompileUnit(Decl->getLocation());
984   SourceManager &SM = M->getContext().getSourceManager();
985   PresumedLoc PLoc = SM.getPresumedLoc(Decl->getLocation());
986   unsigned LineNo = PLoc.isInvalid() ? 0 : PLoc.getLine();
987 
988   std::string Name = Decl->getNameAsString();
989 
990   QualType T = M->getContext().getObjCInterfaceType(Decl);
991   if (T->isIncompleteArrayType()) {
992 
993     // CodeGen turns int[] into int[1] so we'll do the same here.
994     llvm::APSInt ConstVal(32);
995 
996     ConstVal = 1;
997     QualType ET = M->getContext().getAsArrayType(T)->getElementType();
998 
999     T = M->getContext().getConstantArrayType(ET, ConstVal,
1000                                            ArrayType::Normal, 0);
1001   }
1002 
1003   DebugFactory.CreateGlobalVariable(Unit, Name, Name, "", Unit, LineNo,
1004                                     getOrCreateType(T, Unit),
1005                                     Var->hasInternalLinkage(),
1006                                     true/*definition*/, Var);
1007 }
1008 
1009