]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/CodeGen/CGDebugInfo.cpp
Merge from vendor: libdtrace MD parts needed by fasttrap.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / CodeGen / CGDebugInfo.cpp
1 //===--- CGDebugInfo.cpp - Emit Debug Information for a Module ------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This coordinates the debug information generation while generating code.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "CGDebugInfo.h"
15 #include "CodeGenFunction.h"
16 #include "CodeGenModule.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/AST/RecordLayout.h"
21 #include "clang/Basic/SourceManager.h"
22 #include "clang/Basic/FileManager.h"
23 #include "clang/Basic/Version.h"
24 #include "clang/CodeGen/CodeGenOptions.h"
25 #include "llvm/Constants.h"
26 #include "llvm/DerivedTypes.h"
27 #include "llvm/Instructions.h"
28 #include "llvm/Intrinsics.h"
29 #include "llvm/Module.h"
30 #include "llvm/ADT/StringExtras.h"
31 #include "llvm/ADT/SmallVector.h"
32 #include "llvm/Support/Dwarf.h"
33 #include "llvm/System/Path.h"
34 #include "llvm/Target/TargetMachine.h"
35 using namespace clang;
36 using namespace clang::CodeGen;
37
38 CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
39   : CGM(CGM), DebugFactory(CGM.getModule()),
40     FwdDeclCount(0), BlockLiteralGenericSet(false) {
41   CreateCompileUnit();
42 }
43
44 CGDebugInfo::~CGDebugInfo() {
45   assert(RegionStack.empty() && "Region stack mismatch, stack not empty!");
46 }
47
48 void CGDebugInfo::setLocation(SourceLocation Loc) {
49   if (Loc.isValid())
50     CurLoc = CGM.getContext().getSourceManager().getInstantiationLoc(Loc);
51 }
52
53 /// getContextDescriptor - Get context info for the decl.
54 llvm::DIDescriptor CGDebugInfo::getContextDescriptor(const Decl *Context,
55                                               llvm::DIDescriptor &CompileUnit) {
56   if (!Context)
57     return CompileUnit;
58
59   llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
60     I = RegionMap.find(Context);
61   if (I != RegionMap.end())
62     return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(I->second));
63
64   // Check namespace.
65   if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
66     return llvm::DIDescriptor(getOrCreateNameSpace(NSDecl, CompileUnit));
67
68   if (const RecordDecl *RDecl = dyn_cast<RecordDecl>(Context)) {
69     if (!RDecl->isDependentType()) {
70       llvm::DIType Ty = getOrCreateType(CGM.getContext().getTypeDeclType(RDecl), 
71                                         llvm::DIFile(CompileUnit));
72       return llvm::DIDescriptor(Ty);
73     }
74   }
75   return CompileUnit;
76 }
77
78 /// getFunctionName - Get function name for the given FunctionDecl. If the
79 /// name is constructred on demand (e.g. C++ destructor) then the name
80 /// is stored on the side.
81 llvm::StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
82   assert (FD && "Invalid FunctionDecl!");
83   IdentifierInfo *FII = FD->getIdentifier();
84   if (FII)
85     return FII->getName();
86
87   // Otherwise construct human readable name for debug info.
88   std::string NS = FD->getNameAsString();
89
90   // Copy this name on the side and use its reference.
91   char *StrPtr = DebugInfoNames.Allocate<char>(NS.length());
92   memcpy(StrPtr, NS.data(), NS.length());
93   return llvm::StringRef(StrPtr, NS.length());
94 }
95
96 /// getOrCreateFile - Get the file debug info descriptor for the input location.
97 llvm::DIFile CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
98   if (!Loc.isValid())
99     // If Location is not valid then use main input file.
100     return DebugFactory.CreateFile(TheCU.getFilename(), TheCU.getDirectory(),
101                                    TheCU);
102   SourceManager &SM = CGM.getContext().getSourceManager();
103   PresumedLoc PLoc = SM.getPresumedLoc(Loc);
104
105   // Cache the results.
106   const char *fname = PLoc.getFilename();
107   llvm::DenseMap<const char *, llvm::WeakVH>::iterator it =
108     DIFileCache.find(fname);
109
110   if (it != DIFileCache.end()) {
111     // Verify that the information still exists.
112     if (&*it->second)
113       return llvm::DIFile(cast<llvm::MDNode>(it->second));
114   }
115
116   // FIXME: We shouldn't even need to call 'makeAbsolute()' in the cases
117   // where we can consult the FileEntry.
118   llvm::sys::Path AbsFileName(PLoc.getFilename());
119   AbsFileName.makeAbsolute();
120
121   llvm::DIFile F = DebugFactory.CreateFile(AbsFileName.getLast(),
122                                            AbsFileName.getDirname(), TheCU);
123
124   DIFileCache[fname] = F;
125   return F;
126
127 }
128
129 /// getLineNumber - Get line number for the location. If location is invalid
130 /// then use current location.
131 unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
132   assert (CurLoc.isValid() && "Invalid current location!");
133   SourceManager &SM = CGM.getContext().getSourceManager();
134   PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
135   return PLoc.getLine();
136 }
137
138 /// getColumnNumber - Get column number for the location. If location is 
139 /// invalid then use current location.
140 unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc) {
141   assert (CurLoc.isValid() && "Invalid current location!");
142   SourceManager &SM = CGM.getContext().getSourceManager();
143   PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
144   return PLoc.getColumn();
145 }
146
147 /// CreateCompileUnit - Create new compile unit.
148 void CGDebugInfo::CreateCompileUnit() {
149
150   // Get absolute path name.
151   SourceManager &SM = CGM.getContext().getSourceManager();
152   std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
153   if (MainFileName.empty())
154     MainFileName = "<unknown>";
155
156   llvm::sys::Path AbsFileName(MainFileName);
157   AbsFileName.makeAbsolute();
158
159   // The main file name provided via the "-main-file-name" option contains just
160   // the file name itself with no path information. This file name may have had
161   // a relative path, so we look into the actual file entry for the main
162   // file to determine the real absolute path for the file.
163   std::string MainFileDir;
164   if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID()))
165     MainFileDir = MainFile->getDir()->getName();
166   else
167     MainFileDir = AbsFileName.getDirname();
168
169   unsigned LangTag;
170   const LangOptions &LO = CGM.getLangOptions();
171   if (LO.CPlusPlus) {
172     if (LO.ObjC1)
173       LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
174     else
175       LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
176   } else if (LO.ObjC1) {
177     LangTag = llvm::dwarf::DW_LANG_ObjC;
178   } else if (LO.C99) {
179     LangTag = llvm::dwarf::DW_LANG_C99;
180   } else {
181     LangTag = llvm::dwarf::DW_LANG_C89;
182   }
183
184   const char *Producer =
185 #ifdef CLANG_VENDOR
186     CLANG_VENDOR
187 #endif
188     "clang " CLANG_VERSION_STRING;
189
190   // Figure out which version of the ObjC runtime we have.
191   unsigned RuntimeVers = 0;
192   if (LO.ObjC1)
193     RuntimeVers = LO.ObjCNonFragileABI ? 2 : 1;
194
195   // Create new compile unit.
196   TheCU = DebugFactory.CreateCompileUnit(
197     LangTag, AbsFileName.getLast(), MainFileDir, Producer, true,
198     LO.Optimize, CGM.getCodeGenOpts().DwarfDebugFlags, RuntimeVers);
199 }
200
201 /// CreateType - Get the Basic type from the cache or create a new
202 /// one if necessary.
203 llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT,
204                                      llvm::DIFile Unit) {
205   unsigned Encoding = 0;
206   switch (BT->getKind()) {
207   default:
208   case BuiltinType::Void:
209     return llvm::DIType();
210   case BuiltinType::UChar:
211   case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break;
212   case BuiltinType::Char_S:
213   case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break;
214   case BuiltinType::UShort:
215   case BuiltinType::UInt:
216   case BuiltinType::ULong:
217   case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break;
218   case BuiltinType::Short:
219   case BuiltinType::Int:
220   case BuiltinType::Long:
221   case BuiltinType::LongLong:  Encoding = llvm::dwarf::DW_ATE_signed; break;
222   case BuiltinType::Bool:      Encoding = llvm::dwarf::DW_ATE_boolean; break;
223   case BuiltinType::Float:
224   case BuiltinType::LongDouble:
225   case BuiltinType::Double:    Encoding = llvm::dwarf::DW_ATE_float; break;
226   }
227   // Bit size, align and offset of the type.
228   uint64_t Size = CGM.getContext().getTypeSize(BT);
229   uint64_t Align = CGM.getContext().getTypeAlign(BT);
230   uint64_t Offset = 0;
231
232   llvm::DIType DbgTy = 
233     DebugFactory.CreateBasicType(Unit,
234                                  BT->getName(CGM.getContext().getLangOptions()),
235                                  Unit, 0, Size, Align,
236                                  Offset, /*flags*/ 0, Encoding);
237   return DbgTy;
238 }
239
240 llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty,
241                                      llvm::DIFile Unit) {
242   // Bit size, align and offset of the type.
243   unsigned Encoding = llvm::dwarf::DW_ATE_complex_float;
244   if (Ty->isComplexIntegerType())
245     Encoding = llvm::dwarf::DW_ATE_lo_user;
246
247   uint64_t Size = CGM.getContext().getTypeSize(Ty);
248   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
249   uint64_t Offset = 0;
250
251   llvm::DIType DbgTy = 
252     DebugFactory.CreateBasicType(Unit, "complex",
253                                  Unit, 0, Size, Align,
254                                  Offset, /*flags*/ 0, Encoding);
255   return DbgTy;
256 }
257
258 /// CreateCVRType - Get the qualified type from the cache or create
259 /// a new one if necessary.
260 llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit) {
261   QualifierCollector Qc;
262   const Type *T = Qc.strip(Ty);
263
264   // Ignore these qualifiers for now.
265   Qc.removeObjCGCAttr();
266   Qc.removeAddressSpace();
267
268   // We will create one Derived type for one qualifier and recurse to handle any
269   // additional ones.
270   unsigned Tag;
271   if (Qc.hasConst()) {
272     Tag = llvm::dwarf::DW_TAG_const_type;
273     Qc.removeConst();
274   } else if (Qc.hasVolatile()) {
275     Tag = llvm::dwarf::DW_TAG_volatile_type;
276     Qc.removeVolatile();
277   } else if (Qc.hasRestrict()) {
278     Tag = llvm::dwarf::DW_TAG_restrict_type;
279     Qc.removeRestrict();
280   } else {
281     assert(Qc.empty() && "Unknown type qualifier for debug info");
282     return getOrCreateType(QualType(T, 0), Unit);
283   }
284
285   llvm::DIType FromTy = getOrCreateType(Qc.apply(T), Unit);
286
287   // No need to fill in the Name, Line, Size, Alignment, Offset in case of
288   // CVR derived types.
289   llvm::DIType DbgTy =
290     DebugFactory.CreateDerivedType(Tag, Unit, "", Unit,
291                                    0, 0, 0, 0, 0, FromTy);
292   return DbgTy;
293 }
294
295 llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
296                                      llvm::DIFile Unit) {
297   llvm::DIType DbgTy =
298     CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty, 
299                           Ty->getPointeeType(), Unit);
300   return DbgTy;
301 }
302
303 llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
304                                      llvm::DIFile Unit) {
305   return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty, 
306                                Ty->getPointeeType(), Unit);
307 }
308
309 llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag,
310                                                 const Type *Ty, 
311                                                 QualType PointeeTy,
312                                                 llvm::DIFile Unit) {
313   llvm::DIType EltTy = getOrCreateType(PointeeTy, Unit);
314
315   // Bit size, align and offset of the type.
316   
317   // Size is always the size of a pointer. We can't use getTypeSize here
318   // because that does not return the correct value for references.
319   uint64_t Size = 
320     CGM.getContext().Target.getPointerWidth(PointeeTy.getAddressSpace());
321   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
322
323   return
324     DebugFactory.CreateDerivedType(Tag, Unit, "", Unit,
325                                    0, Size, Align, 0, 0, EltTy);
326   
327 }
328
329 llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
330                                      llvm::DIFile Unit) {
331   if (BlockLiteralGenericSet)
332     return BlockLiteralGeneric;
333
334   unsigned Tag = llvm::dwarf::DW_TAG_structure_type;
335
336   llvm::SmallVector<llvm::DIDescriptor, 5> EltTys;
337
338   llvm::DIType FieldTy;
339
340   QualType FType;
341   uint64_t FieldSize, FieldOffset;
342   unsigned FieldAlign;
343
344   llvm::DIArray Elements;
345   llvm::DIType EltTy, DescTy;
346
347   FieldOffset = 0;
348   FType = CGM.getContext().UnsignedLongTy;
349   EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
350   EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
351
352   Elements = DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
353   EltTys.clear();
354
355   unsigned Flags = llvm::DIType::FlagAppleBlock;
356   unsigned LineNo = getLineNumber(CurLoc);
357
358   EltTy = DebugFactory.CreateCompositeType(Tag, Unit, "__block_descriptor",
359                                            Unit, LineNo, FieldOffset, 0, 0, 
360                                            Flags, llvm::DIType(), Elements);
361
362   // Bit size, align and offset of the type.
363   uint64_t Size = CGM.getContext().getTypeSize(Ty);
364   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
365
366   DescTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type,
367                                           Unit, "", Unit,
368                                           LineNo, Size, Align, 0, 0, EltTy);
369
370   FieldOffset = 0;
371   FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
372   EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
373   FType = CGM.getContext().IntTy;
374   EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
375   EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
376   FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
377   EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
378
379   FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
380   FieldTy = DescTy;
381   FieldSize = CGM.getContext().getTypeSize(Ty);
382   FieldAlign = CGM.getContext().getTypeAlign(Ty);
383   FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
384                                            "__descriptor", Unit,
385                                            LineNo, FieldSize, FieldAlign,
386                                            FieldOffset, 0, FieldTy);
387   EltTys.push_back(FieldTy);
388
389   FieldOffset += FieldSize;
390   Elements = DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
391
392   EltTy = DebugFactory.CreateCompositeType(Tag, Unit, "__block_literal_generic",
393                                            Unit, LineNo, FieldOffset, 0, 0, 
394                                            Flags, llvm::DIType(), Elements);
395
396   BlockLiteralGenericSet = true;
397   BlockLiteralGeneric
398     = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type, Unit,
399                                      "", Unit,
400                                      LineNo, Size, Align, 0, 0, EltTy);
401   return BlockLiteralGeneric;
402 }
403
404 llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty,
405                                      llvm::DIFile Unit) {
406   // Typedefs are derived from some other type.  If we have a typedef of a
407   // typedef, make sure to emit the whole chain.
408   llvm::DIType Src = getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
409
410   // We don't set size information, but do specify where the typedef was
411   // declared.
412   unsigned Line = getLineNumber(Ty->getDecl()->getLocation());
413
414   llvm::DIDescriptor TyContext 
415     = getContextDescriptor(dyn_cast<Decl>(Ty->getDecl()->getDeclContext()),
416                            Unit);
417   llvm::DIType DbgTy = 
418     DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_typedef, 
419                                    TyContext,
420                                    Ty->getDecl()->getName(), Unit,
421                                    Line, 0, 0, 0, 0, Src);
422   return DbgTy;
423 }
424
425 llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
426                                      llvm::DIFile Unit) {
427   llvm::SmallVector<llvm::DIDescriptor, 16> EltTys;
428
429   // Add the result type at least.
430   EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit));
431
432   // Set up remainder of arguments if there is a prototype.
433   // FIXME: IF NOT, HOW IS THIS REPRESENTED?  llvm-gcc doesn't represent '...'!
434   if (const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(Ty)) {
435     for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i)
436       EltTys.push_back(getOrCreateType(FTP->getArgType(i), Unit));
437   } else {
438     // FIXME: Handle () case in C.  llvm-gcc doesn't do it either.
439   }
440
441   llvm::DIArray EltTypeArray =
442     DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
443
444   llvm::DIType DbgTy =
445     DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_subroutine_type,
446                                      Unit, "", Unit,
447                                      0, 0, 0, 0, 0,
448                                      llvm::DIType(), EltTypeArray);
449   return DbgTy;
450 }
451
452 /// CollectRecordFields - A helper function to collect debug info for
453 /// record fields. This is used while creating debug info entry for a Record.
454 void CGDebugInfo::
455 CollectRecordFields(const RecordDecl *RD, llvm::DIFile Unit,
456                     llvm::SmallVectorImpl<llvm::DIDescriptor> &EltTys) {
457   unsigned FieldNo = 0;
458   const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
459   for (RecordDecl::field_iterator I = RD->field_begin(),
460                                   E = RD->field_end();
461        I != E; ++I, ++FieldNo) {
462     FieldDecl *Field = *I;
463     llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
464
465     llvm::StringRef FieldName = Field->getName();
466
467     // Ignore unnamed fields. Do not ignore unnamed records.
468     if (FieldName.empty() && !isa<RecordType>(Field->getType()))
469       continue;
470
471     // Get the location for the field.
472     llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
473     unsigned FieldLine = getLineNumber(Field->getLocation());
474     QualType FType = Field->getType();
475     uint64_t FieldSize = 0;
476     unsigned FieldAlign = 0;
477     if (!FType->isIncompleteArrayType()) {
478
479       // Bit size, align and offset of the type.
480       FieldSize = CGM.getContext().getTypeSize(FType);
481       Expr *BitWidth = Field->getBitWidth();
482       if (BitWidth)
483         FieldSize = BitWidth->EvaluateAsInt(CGM.getContext()).getZExtValue();
484
485       FieldAlign =  CGM.getContext().getTypeAlign(FType);
486     }
487
488     uint64_t FieldOffset = RL.getFieldOffset(FieldNo);
489
490     unsigned Flags = 0;
491     AccessSpecifier Access = I->getAccess();
492     if (Access == clang::AS_private)
493       Flags |= llvm::DIType::FlagPrivate;
494     else if (Access == clang::AS_protected)
495       Flags |= llvm::DIType::FlagProtected;
496
497     // Create a DW_TAG_member node to remember the offset of this field in the
498     // struct.  FIXME: This is an absolutely insane way to capture this
499     // information.  When we gut debug info, this should be fixed.
500     FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
501                                              FieldName, FieldDefUnit,
502                                              FieldLine, FieldSize, FieldAlign,
503                                              FieldOffset, Flags, FieldTy);
504     EltTys.push_back(FieldTy);
505   }
506 }
507
508 /// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
509 /// function type is not updated to include implicit "this" pointer. Use this
510 /// routine to get a method type which includes "this" pointer.
511 llvm::DIType
512 CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
513                                    llvm::DIFile Unit) {
514   llvm::DIType FnTy
515     = getOrCreateType(QualType(Method->getType()->getAs<FunctionProtoType>(),
516                                0),
517                       Unit);
518   
519   // Static methods do not need "this" pointer argument.
520   if (Method->isStatic())
521     return FnTy;
522
523   // Add "this" pointer.
524
525   llvm::DIArray Args = llvm::DICompositeType(FnTy).getTypeArray();
526   assert (Args.getNumElements() && "Invalid number of arguments!");
527
528   llvm::SmallVector<llvm::DIDescriptor, 16> Elts;
529
530   // First element is always return type. For 'void' functions it is NULL.
531   Elts.push_back(Args.getElement(0));
532
533   // "this" pointer is always first argument.
534   ASTContext &Context = CGM.getContext();
535   QualType ThisPtr = 
536     Context.getPointerType(Context.getTagDeclType(Method->getParent()));
537   llvm::DIType ThisPtrType = 
538     DebugFactory.CreateArtificialType(getOrCreateType(ThisPtr, Unit));
539   TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;  
540   Elts.push_back(ThisPtrType);
541
542   // Copy rest of the arguments.
543   for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
544     Elts.push_back(Args.getElement(i));
545
546   llvm::DIArray EltTypeArray =
547     DebugFactory.GetOrCreateArray(Elts.data(), Elts.size());
548
549   return
550     DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_subroutine_type,
551                                      Unit, "", Unit,
552                                      0, 0, 0, 0, 0,
553                                      llvm::DIType(), EltTypeArray);
554 }
555
556 /// CreateCXXMemberFunction - A helper function to create a DISubprogram for
557 /// a single member function GlobalDecl.
558 llvm::DISubprogram
559 CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
560                                      llvm::DIFile Unit,
561                                      llvm::DICompositeType &RecordTy) {
562   bool IsCtorOrDtor = 
563     isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
564   
565   llvm::StringRef MethodName = getFunctionName(Method);
566   llvm::DIType MethodTy = getOrCreateMethodType(Method, Unit);
567   
568   // Since a single ctor/dtor corresponds to multiple functions, it doesn't
569   // make sense to give a single ctor/dtor a linkage name.
570   MangleBuffer MethodLinkageName;
571   if (!IsCtorOrDtor)
572     CGM.getMangledName(MethodLinkageName, Method);
573
574   // Get the location for the method.
575   llvm::DIFile MethodDefUnit = getOrCreateFile(Method->getLocation());
576   unsigned MethodLine = getLineNumber(Method->getLocation());
577
578   // Collect virtual method info.
579   llvm::DIType ContainingType;
580   unsigned Virtuality = 0; 
581   unsigned VIndex = 0;
582   
583   if (Method->isVirtual()) {
584     if (Method->isPure())
585       Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
586     else
587       Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
588     
589     // It doesn't make sense to give a virtual destructor a vtable index,
590     // since a single destructor has two entries in the vtable.
591     if (!isa<CXXDestructorDecl>(Method))
592       VIndex = CGM.getVTables().getMethodVTableIndex(Method);
593     ContainingType = RecordTy;
594   }
595
596   llvm::DISubprogram SP =
597     DebugFactory.CreateSubprogram(RecordTy , MethodName, MethodName, 
598                                   MethodLinkageName,
599                                   MethodDefUnit, MethodLine,
600                                   MethodTy, /*isLocalToUnit=*/false, 
601                                   Method->isThisDeclarationADefinition(),
602                                   Virtuality, VIndex, ContainingType);
603   
604   // Don't cache ctors or dtors since we have to emit multiple functions for
605   // a single ctor or dtor.
606   if (!IsCtorOrDtor && Method->isThisDeclarationADefinition())
607     SPCache[Method] = llvm::WeakVH(SP);
608
609   return SP;
610 }
611
612 /// CollectCXXMemberFunctions - A helper function to collect debug info for
613 /// C++ member functions.This is used while creating debug info entry for 
614 /// a Record.
615 void CGDebugInfo::
616 CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
617                           llvm::SmallVectorImpl<llvm::DIDescriptor> &EltTys,
618                           llvm::DICompositeType &RecordTy) {
619   for(CXXRecordDecl::method_iterator I = RD->method_begin(),
620         E = RD->method_end(); I != E; ++I) {
621     const CXXMethodDecl *Method = *I;
622     
623     if (Method->isImplicit() && !Method->isUsed())
624       continue;
625
626     EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
627   }
628 }                                 
629
630 /// CollectCXXBases - A helper function to collect debug info for
631 /// C++ base classes. This is used while creating debug info entry for 
632 /// a Record.
633 void CGDebugInfo::
634 CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
635                 llvm::SmallVectorImpl<llvm::DIDescriptor> &EltTys,
636                 llvm::DICompositeType &RecordTy) {
637
638   const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
639   for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
640          BE = RD->bases_end(); BI != BE; ++BI) {
641     unsigned BFlags = 0;
642     uint64_t BaseOffset;
643     
644     const CXXRecordDecl *Base =
645       cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl());
646     
647     if (BI->isVirtual()) {
648       // virtual base offset offset is -ve. The code generator emits dwarf
649       // expression where it expects +ve number.
650       BaseOffset = 0 - CGM.getVTables().getVirtualBaseOffsetOffset(RD, Base);
651       BFlags = llvm::DIType::FlagVirtual;
652     } else
653       BaseOffset = RL.getBaseClassOffset(Base);
654     
655     AccessSpecifier Access = BI->getAccessSpecifier();
656     if (Access == clang::AS_private)
657       BFlags |= llvm::DIType::FlagPrivate;
658     else if (Access == clang::AS_protected)
659       BFlags |= llvm::DIType::FlagProtected;
660     
661     llvm::DIType DTy =
662       DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_inheritance,
663                                      RecordTy, llvm::StringRef(), 
664                                      Unit, 0, 0, 0,
665                                      BaseOffset, BFlags,
666                                      getOrCreateType(BI->getType(),
667                                                      Unit));
668     EltTys.push_back(DTy);
669   }
670 }
671
672 /// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
673 llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
674   if (VTablePtrType.isValid())
675     return VTablePtrType;
676
677   ASTContext &Context = CGM.getContext();
678
679   /* Function type */
680   llvm::DIDescriptor STy = getOrCreateType(Context.IntTy, Unit);
681   llvm::DIArray SElements = DebugFactory.GetOrCreateArray(&STy, 1);
682   llvm::DIType SubTy =
683     DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_subroutine_type,
684                                      Unit, "", Unit,
685                                      0, 0, 0, 0, 0, llvm::DIType(), SElements);
686
687   unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
688   llvm::DIType vtbl_ptr_type 
689     = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type,
690                                      Unit, "__vtbl_ptr_type", Unit,
691                                      0, Size, 0, 0, 0, SubTy);
692
693   VTablePtrType = 
694     DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type,
695                                    Unit, "", Unit,
696                                    0, Size, 0, 0, 0, vtbl_ptr_type);
697   return VTablePtrType;
698 }
699
700 /// getVTableName - Get vtable name for the given Class.
701 llvm::StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
702   // Otherwise construct gdb compatible name name.
703   std::string Name = "_vptr$" + RD->getNameAsString();
704
705   // Copy this name on the side and use its reference.
706   char *StrPtr = DebugInfoNames.Allocate<char>(Name.length());
707   memcpy(StrPtr, Name.data(), Name.length());
708   return llvm::StringRef(StrPtr, Name.length());
709 }
710
711
712 /// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
713 /// debug info entry in EltTys vector.
714 void CGDebugInfo::
715 CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
716                   llvm::SmallVectorImpl<llvm::DIDescriptor> &EltTys) {
717   const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
718
719   // If there is a primary base then it will hold vtable info.
720   if (RL.getPrimaryBase())
721     return;
722
723   // If this class is not dynamic then there is not any vtable info to collect.
724   if (!RD->isDynamicClass())
725     return;
726
727   unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
728   llvm::DIType VPTR
729     = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
730                                      getVTableName(RD), Unit,
731                                      0, Size, 0, 0, 0, 
732                                      getOrCreateVTablePtrType(Unit));
733   EltTys.push_back(VPTR);
734 }
735
736 /// CreateType - get structure or union type.
737 llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty,
738                                      llvm::DIFile Unit) {
739   RecordDecl *RD = Ty->getDecl();
740
741   unsigned Tag;
742   if (RD->isStruct())
743     Tag = llvm::dwarf::DW_TAG_structure_type;
744   else if (RD->isUnion())
745     Tag = llvm::dwarf::DW_TAG_union_type;
746   else {
747     assert(RD->isClass() && "Unknown RecordType!");
748     Tag = llvm::dwarf::DW_TAG_class_type;
749   }
750
751   // Get overall information about the record type for the debug info.
752   llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
753   unsigned Line = getLineNumber(RD->getLocation());
754
755   // Records and classes and unions can all be recursive.  To handle them, we
756   // first generate a debug descriptor for the struct as a forward declaration.
757   // Then (if it is a definition) we go through and get debug info for all of
758   // its members.  Finally, we create a descriptor for the complete type (which
759   // may refer to the forward decl if the struct is recursive) and replace all
760   // uses of the forward declaration with the final definition.
761
762   // A RD->getName() is not unique. However, the debug info descriptors 
763   // are uniqued so use type name to ensure uniquness.
764   llvm::SmallString<128> FwdDeclName;
765   llvm::raw_svector_ostream(FwdDeclName) << "fwd.type." << FwdDeclCount++;
766   llvm::DIDescriptor FDContext = 
767     getContextDescriptor(dyn_cast<Decl>(RD->getDeclContext()), Unit);
768   llvm::DICompositeType FwdDecl =
769     DebugFactory.CreateCompositeType(Tag, FDContext, FwdDeclName,
770                                      DefUnit, Line, 0, 0, 0, 0,
771                                      llvm::DIType(), llvm::DIArray());
772
773   // If this is just a forward declaration, return it.
774   if (!RD->getDefinition())
775     return FwdDecl;
776
777   llvm::MDNode *MN = FwdDecl;
778   llvm::TrackingVH<llvm::MDNode> FwdDeclNode = MN;
779   // Otherwise, insert it into the TypeCache so that recursive uses will find
780   // it.
781   TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
782   // Push the struct on region stack.
783   RegionStack.push_back(FwdDeclNode);
784   RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
785
786   // Convert all the elements.
787   llvm::SmallVector<llvm::DIDescriptor, 16> EltTys;
788
789   const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
790   if (CXXDecl) {
791     CollectCXXBases(CXXDecl, Unit, EltTys, FwdDecl);
792     CollectVTableInfo(CXXDecl, Unit, EltTys);
793   }
794   CollectRecordFields(RD, Unit, EltTys);
795   llvm::MDNode *ContainingType = NULL;
796   if (CXXDecl) {
797     CollectCXXMemberFunctions(CXXDecl, Unit, EltTys, FwdDecl);
798
799     // A class's primary base or the class itself contains the vtable.
800     const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
801     if (const CXXRecordDecl *PBase = RL.getPrimaryBase())
802       ContainingType = 
803         getOrCreateType(QualType(PBase->getTypeForDecl(), 0), Unit);
804     else if (CXXDecl->isDynamicClass()) 
805       ContainingType = FwdDecl;
806   }
807
808   llvm::DIArray Elements =
809     DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
810
811   // Bit size, align and offset of the type.
812   uint64_t Size = CGM.getContext().getTypeSize(Ty);
813   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
814
815   RegionStack.pop_back();
816   llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator RI = 
817     RegionMap.find(Ty->getDecl());
818   if (RI != RegionMap.end())
819     RegionMap.erase(RI);
820
821   llvm::DIDescriptor RDContext =  
822     getContextDescriptor(dyn_cast<Decl>(RD->getDeclContext()), Unit);
823   llvm::DICompositeType RealDecl =
824     DebugFactory.CreateCompositeType(Tag, RDContext,
825                                      RD->getName(),
826                                      DefUnit, Line, Size, Align, 0, 0, 
827                                      llvm::DIType(), Elements, 
828                                      0, ContainingType);
829
830   // Now that we have a real decl for the struct, replace anything using the
831   // old decl with the new one.  This will recursively update the debug info.
832   llvm::DIDerivedType(FwdDeclNode).replaceAllUsesWith(RealDecl);
833   RegionMap[RD] = llvm::WeakVH(RealDecl);
834   return RealDecl;
835 }
836
837 /// CreateType - get objective-c object type.
838 llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
839                                      llvm::DIFile Unit) {
840   // Ignore protocols.
841   return getOrCreateType(Ty->getBaseType(), Unit);
842 }
843
844 /// CreateType - get objective-c interface type.
845 llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
846                                      llvm::DIFile Unit) {
847   ObjCInterfaceDecl *ID = Ty->getDecl();
848   unsigned Tag = llvm::dwarf::DW_TAG_structure_type;
849
850   // Get overall information about the record type for the debug info.
851   llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
852   unsigned Line = getLineNumber(ID->getLocation());
853   unsigned RuntimeLang = TheCU.getLanguage();
854
855   // To handle recursive interface, we
856   // first generate a debug descriptor for the struct as a forward declaration.
857   // Then (if it is a definition) we go through and get debug info for all of
858   // its members.  Finally, we create a descriptor for the complete type (which
859   // may refer to the forward decl if the struct is recursive) and replace all
860   // uses of the forward declaration with the final definition.
861   llvm::DICompositeType FwdDecl =
862     DebugFactory.CreateCompositeType(Tag, Unit, ID->getName(),
863                                      DefUnit, Line, 0, 0, 0, 0,
864                                      llvm::DIType(), llvm::DIArray(),
865                                      RuntimeLang);
866
867   // If this is just a forward declaration, return it.
868   if (ID->isForwardDecl())
869     return FwdDecl;
870
871   llvm::MDNode *MN = FwdDecl;
872   llvm::TrackingVH<llvm::MDNode> FwdDeclNode = MN;
873   // Otherwise, insert it into the TypeCache so that recursive uses will find
874   // it.
875   TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
876   // Push the struct on region stack.
877   RegionStack.push_back(FwdDeclNode);
878   RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
879
880   // Convert all the elements.
881   llvm::SmallVector<llvm::DIDescriptor, 16> EltTys;
882
883   ObjCInterfaceDecl *SClass = ID->getSuperClass();
884   if (SClass) {
885     llvm::DIType SClassTy =
886       getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
887     llvm::DIType InhTag =
888       DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_inheritance,
889                                      Unit, "", Unit, 0, 0, 0,
890                                      0 /* offset */, 0, SClassTy);
891     EltTys.push_back(InhTag);
892   }
893
894   const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
895
896   unsigned FieldNo = 0;
897   for (ObjCInterfaceDecl::ivar_iterator I = ID->ivar_begin(),
898          E = ID->ivar_end();  I != E; ++I, ++FieldNo) {
899     ObjCIvarDecl *Field = *I;
900     llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
901
902     llvm::StringRef FieldName = Field->getName();
903
904     // Ignore unnamed fields.
905     if (FieldName.empty())
906       continue;
907
908     // Get the location for the field.
909     llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
910     unsigned FieldLine = getLineNumber(Field->getLocation());
911     QualType FType = Field->getType();
912     uint64_t FieldSize = 0;
913     unsigned FieldAlign = 0;
914
915     if (!FType->isIncompleteArrayType()) {
916
917       // Bit size, align and offset of the type.
918       FieldSize = CGM.getContext().getTypeSize(FType);
919       Expr *BitWidth = Field->getBitWidth();
920       if (BitWidth)
921         FieldSize = BitWidth->EvaluateAsInt(CGM.getContext()).getZExtValue();
922
923       FieldAlign =  CGM.getContext().getTypeAlign(FType);
924     }
925
926     uint64_t FieldOffset = RL.getFieldOffset(FieldNo);
927
928     unsigned Flags = 0;
929     if (Field->getAccessControl() == ObjCIvarDecl::Protected)
930       Flags = llvm::DIType::FlagProtected;
931     else if (Field->getAccessControl() == ObjCIvarDecl::Private)
932       Flags = llvm::DIType::FlagPrivate;
933
934     // Create a DW_TAG_member node to remember the offset of this field in the
935     // struct.  FIXME: This is an absolutely insane way to capture this
936     // information.  When we gut debug info, this should be fixed.
937     FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
938                                              FieldName, FieldDefUnit,
939                                              FieldLine, FieldSize, FieldAlign,
940                                              FieldOffset, Flags, FieldTy);
941     EltTys.push_back(FieldTy);
942   }
943
944   llvm::DIArray Elements =
945     DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
946
947   RegionStack.pop_back();
948   llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator RI = 
949     RegionMap.find(Ty->getDecl());
950   if (RI != RegionMap.end())
951     RegionMap.erase(RI);
952
953   // Bit size, align and offset of the type.
954   uint64_t Size = CGM.getContext().getTypeSize(Ty);
955   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
956
957   llvm::DICompositeType RealDecl =
958     DebugFactory.CreateCompositeType(Tag, Unit, ID->getName(), DefUnit,
959                                      Line, Size, Align, 0, 0, llvm::DIType(), 
960                                      Elements, RuntimeLang);
961
962   // Now that we have a real decl for the struct, replace anything using the
963   // old decl with the new one.  This will recursively update the debug info.
964   llvm::DIDerivedType(FwdDeclNode).replaceAllUsesWith(RealDecl);
965   RegionMap[ID] = llvm::WeakVH(RealDecl);
966
967   return RealDecl;
968 }
969
970 llvm::DIType CGDebugInfo::CreateType(const EnumType *Ty,
971                                      llvm::DIFile Unit) {
972   EnumDecl *ED = Ty->getDecl();
973
974   llvm::SmallVector<llvm::DIDescriptor, 32> Enumerators;
975
976   // Create DIEnumerator elements for each enumerator.
977   for (EnumDecl::enumerator_iterator
978          Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
979        Enum != EnumEnd; ++Enum) {
980     Enumerators.push_back(DebugFactory.CreateEnumerator(Enum->getName(),
981                                             Enum->getInitVal().getZExtValue()));
982   }
983
984   // Return a CompositeType for the enum itself.
985   llvm::DIArray EltArray =
986     DebugFactory.GetOrCreateArray(Enumerators.data(), Enumerators.size());
987
988   llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
989   unsigned Line = getLineNumber(ED->getLocation());
990
991   // Size and align of the type.
992   uint64_t Size = 0;
993   unsigned Align = 0;
994   if (!Ty->isIncompleteType()) {
995     Size = CGM.getContext().getTypeSize(Ty);
996     Align = CGM.getContext().getTypeAlign(Ty);
997   }
998
999   llvm::DIType DbgTy = 
1000     DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_enumeration_type,
1001                                      Unit, ED->getName(), DefUnit, Line,
1002                                      Size, Align, 0, 0,
1003                                      llvm::DIType(), EltArray);
1004   return DbgTy;
1005 }
1006
1007 llvm::DIType CGDebugInfo::CreateType(const TagType *Ty,
1008                                      llvm::DIFile Unit) {
1009   if (const RecordType *RT = dyn_cast<RecordType>(Ty))
1010     return CreateType(RT, Unit);
1011   else if (const EnumType *ET = dyn_cast<EnumType>(Ty))
1012     return CreateType(ET, Unit);
1013
1014   return llvm::DIType();
1015 }
1016
1017 llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty,
1018                                      llvm::DIFile Unit) {
1019   llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1020   uint64_t NumElems = Ty->getNumElements();
1021   if (NumElems > 0)
1022     --NumElems;
1023
1024   llvm::DIDescriptor Subscript = DebugFactory.GetOrCreateSubrange(0, NumElems);
1025   llvm::DIArray SubscriptArray = DebugFactory.GetOrCreateArray(&Subscript, 1);
1026
1027   uint64_t Size = CGM.getContext().getTypeSize(Ty);
1028   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1029
1030   return
1031     DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_vector_type,
1032                                      Unit, "", Unit,
1033                                      0, Size, Align, 0, 0,
1034                                      ElementTy,  SubscriptArray);
1035 }
1036
1037 llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1038                                      llvm::DIFile Unit) {
1039   uint64_t Size;
1040   uint64_t Align;
1041
1042
1043   // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1044   if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1045     Size = 0;
1046     Align =
1047       CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1048   } else if (Ty->isIncompleteArrayType()) {
1049     Size = 0;
1050     Align = CGM.getContext().getTypeAlign(Ty->getElementType());
1051   } else {
1052     // Size and align of the whole array, not the element type.
1053     Size = CGM.getContext().getTypeSize(Ty);
1054     Align = CGM.getContext().getTypeAlign(Ty);
1055   }
1056
1057   // Add the dimensions of the array.  FIXME: This loses CV qualifiers from
1058   // interior arrays, do we care?  Why aren't nested arrays represented the
1059   // obvious/recursive way?
1060   llvm::SmallVector<llvm::DIDescriptor, 8> Subscripts;
1061   QualType EltTy(Ty, 0);
1062   while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1063     uint64_t Upper = 0;
1064     if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1065       if (CAT->getSize().getZExtValue())
1066         Upper = CAT->getSize().getZExtValue() - 1;
1067     // FIXME: Verify this is right for VLAs.
1068     Subscripts.push_back(DebugFactory.GetOrCreateSubrange(0, Upper));
1069     EltTy = Ty->getElementType();
1070   }
1071
1072   llvm::DIArray SubscriptArray =
1073     DebugFactory.GetOrCreateArray(Subscripts.data(), Subscripts.size());
1074
1075   llvm::DIType DbgTy = 
1076     DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_array_type,
1077                                      Unit, "", Unit,
1078                                      0, Size, Align, 0, 0,
1079                                      getOrCreateType(EltTy, Unit),
1080                                      SubscriptArray);
1081   return DbgTy;
1082 }
1083
1084 llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty, 
1085                                      llvm::DIFile Unit) {
1086   return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type, 
1087                                Ty, Ty->getPointeeType(), Unit);
1088 }
1089
1090 llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty, 
1091                                      llvm::DIFile U) {
1092   QualType PointerDiffTy = CGM.getContext().getPointerDiffType();
1093   llvm::DIType PointerDiffDITy = getOrCreateType(PointerDiffTy, U);
1094   
1095   if (!Ty->getPointeeType()->isFunctionType()) {
1096     // We have a data member pointer type.
1097     return PointerDiffDITy;
1098   }
1099   
1100   // We have a member function pointer type. Treat it as a struct with two
1101   // ptrdiff_t members.
1102   std::pair<uint64_t, unsigned> Info = CGM.getContext().getTypeInfo(Ty);
1103
1104   uint64_t FieldOffset = 0;
1105   llvm::DIDescriptor ElementTypes[2];
1106   
1107   // FIXME: This should probably be a function type instead.
1108   ElementTypes[0] =
1109     DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, U,
1110                                    "ptr", U, 0,
1111                                    Info.first, Info.second, FieldOffset, 0,
1112                                    PointerDiffDITy);
1113   FieldOffset += Info.first;
1114   
1115   ElementTypes[1] =
1116     DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, U,
1117                                    "ptr", U, 0,
1118                                    Info.first, Info.second, FieldOffset, 0,
1119                                    PointerDiffDITy);
1120   
1121   llvm::DIArray Elements = 
1122     DebugFactory.GetOrCreateArray(&ElementTypes[0],
1123                                   llvm::array_lengthof(ElementTypes));
1124
1125   return DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_structure_type, 
1126                                           U, llvm::StringRef("test"), 
1127                                           U, 0, FieldOffset, 
1128                                           0, 0, 0, llvm::DIType(), Elements);
1129 }
1130
1131 static QualType UnwrapTypeForDebugInfo(QualType T) {
1132   do {
1133     QualType LastT = T;
1134     switch (T->getTypeClass()) {
1135     default:
1136       return T;
1137     case Type::TemplateSpecialization:
1138       T = cast<TemplateSpecializationType>(T)->desugar();
1139       break;
1140     case Type::TypeOfExpr: {
1141       TypeOfExprType *Ty = cast<TypeOfExprType>(T);
1142       T = Ty->getUnderlyingExpr()->getType();
1143       break;
1144     }
1145     case Type::TypeOf:
1146       T = cast<TypeOfType>(T)->getUnderlyingType();
1147       break;
1148     case Type::Decltype:
1149       T = cast<DecltypeType>(T)->getUnderlyingType();
1150       break;
1151     case Type::Elaborated:
1152       T = cast<ElaboratedType>(T)->getNamedType();
1153       break;
1154     case Type::SubstTemplateTypeParm:
1155       T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
1156       break;
1157     }
1158     
1159     assert(T != LastT && "Type unwrapping failed to unwrap!");
1160     if (T == LastT)
1161       return T;
1162   } while (true);
1163   
1164   return T;
1165 }
1166
1167 /// getOrCreateType - Get the type from the cache or create a new
1168 /// one if necessary.
1169 llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty,
1170                                           llvm::DIFile Unit) {
1171   if (Ty.isNull())
1172     return llvm::DIType();
1173
1174   // Unwrap the type as needed for debug information.
1175   Ty = UnwrapTypeForDebugInfo(Ty);
1176   
1177   // Check for existing entry.
1178   llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1179     TypeCache.find(Ty.getAsOpaquePtr());
1180   if (it != TypeCache.end()) {
1181     // Verify that the debug info still exists.
1182     if (&*it->second)
1183       return llvm::DIType(cast<llvm::MDNode>(it->second));
1184   }
1185
1186   // Otherwise create the type.
1187   llvm::DIType Res = CreateTypeNode(Ty, Unit);
1188
1189   // And update the type cache.
1190   TypeCache[Ty.getAsOpaquePtr()] = Res;  
1191   return Res;
1192 }
1193
1194 /// CreateTypeNode - Create a new debug type node.
1195 llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty,
1196                                          llvm::DIFile Unit) {
1197   // Handle qualifiers, which recursively handles what they refer to.
1198   if (Ty.hasLocalQualifiers())
1199     return CreateQualifiedType(Ty, Unit);
1200
1201   const char *Diag = 0;
1202   
1203   // Work out details of type.
1204   switch (Ty->getTypeClass()) {
1205 #define TYPE(Class, Base)
1206 #define ABSTRACT_TYPE(Class, Base)
1207 #define NON_CANONICAL_TYPE(Class, Base)
1208 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1209 #include "clang/AST/TypeNodes.def"
1210     assert(false && "Dependent types cannot show up in debug information");
1211
1212   // FIXME: Handle these.
1213   case Type::ExtVector:
1214     return llvm::DIType();
1215
1216   case Type::Vector:
1217     return CreateType(cast<VectorType>(Ty), Unit);
1218   case Type::ObjCObjectPointer:
1219     return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
1220   case Type::ObjCObject:
1221     return CreateType(cast<ObjCObjectType>(Ty), Unit);
1222   case Type::ObjCInterface:
1223     return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
1224   case Type::Builtin: return CreateType(cast<BuiltinType>(Ty), Unit);
1225   case Type::Complex: return CreateType(cast<ComplexType>(Ty), Unit);
1226   case Type::Pointer: return CreateType(cast<PointerType>(Ty), Unit);
1227   case Type::BlockPointer:
1228     return CreateType(cast<BlockPointerType>(Ty), Unit);
1229   case Type::Typedef: return CreateType(cast<TypedefType>(Ty), Unit);
1230   case Type::Record:
1231   case Type::Enum:
1232     return CreateType(cast<TagType>(Ty), Unit);
1233   case Type::FunctionProto:
1234   case Type::FunctionNoProto:
1235     return CreateType(cast<FunctionType>(Ty), Unit);
1236   case Type::ConstantArray:
1237   case Type::VariableArray:
1238   case Type::IncompleteArray:
1239     return CreateType(cast<ArrayType>(Ty), Unit);
1240
1241   case Type::LValueReference:
1242     return CreateType(cast<LValueReferenceType>(Ty), Unit);
1243
1244   case Type::MemberPointer:
1245     return CreateType(cast<MemberPointerType>(Ty), Unit);
1246
1247   case Type::TemplateSpecialization:
1248   case Type::Elaborated:
1249   case Type::SubstTemplateTypeParm:
1250   case Type::TypeOfExpr:
1251   case Type::TypeOf:
1252   case Type::Decltype:
1253     llvm_unreachable("type should have been unwrapped!");
1254     return llvm::DIType();
1255       
1256   case Type::RValueReference:
1257     // FIXME: Implement!
1258     Diag = "rvalue references";
1259     break;
1260   }
1261   
1262   assert(Diag && "Fall through without a diagnostic?");
1263   unsigned DiagID = CGM.getDiags().getCustomDiagID(Diagnostic::Error,
1264                                "debug information for %0 is not yet supported");
1265   CGM.getDiags().Report(FullSourceLoc(), DiagID)
1266     << Diag;
1267   return llvm::DIType();
1268 }
1269
1270 /// CreateMemberType - Create new member and increase Offset by FType's size.
1271 llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
1272                                            llvm::StringRef Name,
1273                                            uint64_t *Offset) {
1274   llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1275   uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
1276   unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
1277   llvm::DIType Ty = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member,
1278                                                    Unit, Name, Unit, 0,
1279                                                    FieldSize, FieldAlign,
1280                                                    *Offset, 0, FieldTy);
1281   *Offset += FieldSize;
1282   return Ty;
1283 }
1284
1285 /// EmitFunctionStart - Constructs the debug code for entering a function -
1286 /// "llvm.dbg.func.start.".
1287 void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
1288                                     llvm::Function *Fn,
1289                                     CGBuilderTy &Builder) {
1290
1291   llvm::StringRef Name;
1292   MangleBuffer LinkageName;
1293
1294   const Decl *D = GD.getDecl();
1295   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1296     // If there is a DISubprogram for  this function available then use it.
1297     llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
1298       FI = SPCache.find(FD);
1299     if (FI != SPCache.end()) {
1300       llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(FI->second));
1301       if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
1302         llvm::MDNode *SPN = SP;
1303         RegionStack.push_back(SPN);
1304         RegionMap[D] = llvm::WeakVH(SP);
1305         return;
1306       }
1307     }
1308     Name = getFunctionName(FD);
1309     // Use mangled name as linkage name for c/c++ functions.
1310     CGM.getMangledName(LinkageName, GD);
1311   } else {
1312     // Use llvm function name as linkage name.
1313     Name = Fn->getName();
1314     LinkageName.setString(Name);
1315   }
1316   if (!Name.empty() && Name[0] == '\01')
1317     Name = Name.substr(1);
1318
1319   // It is expected that CurLoc is set before using EmitFunctionStart.
1320   // Usually, CurLoc points to the left bracket location of compound
1321   // statement representing function body.
1322   llvm::DIFile Unit = getOrCreateFile(CurLoc);
1323   unsigned LineNo = getLineNumber(CurLoc);
1324
1325   llvm::DISubprogram SP =
1326     DebugFactory.CreateSubprogram(Unit, Name, Name, LinkageName, Unit, LineNo,
1327                                   getOrCreateType(FnType, Unit),
1328                                   Fn->hasInternalLinkage(), true/*definition*/);
1329
1330   // Push function on region stack.
1331   llvm::MDNode *SPN = SP;
1332   RegionStack.push_back(SPN);
1333   RegionMap[D] = llvm::WeakVH(SP);
1334 }
1335
1336
1337 void CGDebugInfo::EmitStopPoint(llvm::Function *Fn, CGBuilderTy &Builder) {
1338   if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
1339
1340   // Don't bother if things are the same as last time.
1341   SourceManager &SM = CGM.getContext().getSourceManager();
1342   if (CurLoc == PrevLoc
1343        || (SM.getInstantiationLineNumber(CurLoc) ==
1344            SM.getInstantiationLineNumber(PrevLoc)
1345            && SM.isFromSameFile(CurLoc, PrevLoc)))
1346     // New Builder may not be in sync with CGDebugInfo.
1347     if (!Builder.getCurrentDebugLocation().isUnknown())
1348       return;
1349
1350   // Update last state.
1351   PrevLoc = CurLoc;
1352
1353   llvm::MDNode *Scope = RegionStack.back();
1354   Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(CurLoc),
1355                                                       getColumnNumber(CurLoc),
1356                                                       Scope));
1357 }
1358
1359 /// EmitRegionStart- Constructs the debug code for entering a declarative
1360 /// region - "llvm.dbg.region.start.".
1361 void CGDebugInfo::EmitRegionStart(llvm::Function *Fn, CGBuilderTy &Builder) {
1362   llvm::DIDescriptor D =
1363     DebugFactory.CreateLexicalBlock(RegionStack.empty() ? 
1364                                     llvm::DIDescriptor() : 
1365                                     llvm::DIDescriptor(RegionStack.back()),
1366                                     getLineNumber(CurLoc), 
1367                                     getColumnNumber(CurLoc));
1368   llvm::MDNode *DN = D;
1369   RegionStack.push_back(DN);
1370 }
1371
1372 /// EmitRegionEnd - Constructs the debug code for exiting a declarative
1373 /// region - "llvm.dbg.region.end."
1374 void CGDebugInfo::EmitRegionEnd(llvm::Function *Fn, CGBuilderTy &Builder) {
1375   assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
1376
1377   // Provide an region stop point.
1378   EmitStopPoint(Fn, Builder);
1379
1380   RegionStack.pop_back();
1381 }
1382
1383 // EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.  
1384 // See BuildByRefType.
1385 llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const ValueDecl *VD,
1386                                                        uint64_t *XOffset) {
1387
1388   llvm::SmallVector<llvm::DIDescriptor, 5> EltTys;
1389
1390   QualType FType;
1391   uint64_t FieldSize, FieldOffset;
1392   unsigned FieldAlign;
1393   
1394   llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
1395   QualType Type = VD->getType();  
1396
1397   FieldOffset = 0;
1398   FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1399   EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
1400   EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
1401   FType = CGM.getContext().IntTy;
1402   EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
1403   EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
1404
1405   bool HasCopyAndDispose = CGM.BlockRequiresCopying(Type);
1406   if (HasCopyAndDispose) {
1407     FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1408     EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
1409                                       &FieldOffset));
1410     EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
1411                                       &FieldOffset));
1412   }
1413   
1414   CharUnits Align = CGM.getContext().getDeclAlign(VD);
1415   if (Align > CharUnits::fromQuantity(
1416         CGM.getContext().Target.getPointerAlign(0) / 8)) {
1417     unsigned AlignedOffsetInBytes
1418       = llvm::RoundUpToAlignment(FieldOffset/8, Align.getQuantity());
1419     unsigned NumPaddingBytes
1420       = AlignedOffsetInBytes - FieldOffset/8;
1421     
1422     if (NumPaddingBytes > 0) {
1423       llvm::APInt pad(32, NumPaddingBytes);
1424       FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
1425                                                     pad, ArrayType::Normal, 0);
1426       EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
1427     }
1428   }
1429   
1430   FType = Type;
1431   llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1432   FieldSize = CGM.getContext().getTypeSize(FType);
1433   FieldAlign = Align.getQuantity()*8;
1434
1435   *XOffset = FieldOffset;  
1436   FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1437                                            VD->getName(), Unit,
1438                                            0, FieldSize, FieldAlign,
1439                                            FieldOffset, 0, FieldTy);
1440   EltTys.push_back(FieldTy);
1441   FieldOffset += FieldSize;
1442   
1443   llvm::DIArray Elements = 
1444     DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
1445   
1446   unsigned Flags = llvm::DIType::FlagBlockByrefStruct;
1447   
1448   return DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_structure_type, 
1449                                           Unit, "", Unit,
1450                                           0, FieldOffset, 0, 0, Flags,
1451                                           llvm::DIType(), Elements);
1452   
1453 }
1454 /// EmitDeclare - Emit local variable declaration debug info.
1455 void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
1456                               llvm::Value *Storage, CGBuilderTy &Builder) {
1457   assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
1458
1459   llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
1460   llvm::DIType Ty;
1461   uint64_t XOffset = 0;
1462   if (VD->hasAttr<BlocksAttr>())
1463     Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
1464   else 
1465     Ty = getOrCreateType(VD->getType(), Unit);
1466
1467   // If there is not any debug info for type then do not emit debug info
1468   // for this variable.
1469   if (!Ty)
1470     return;
1471
1472   // Get location information.
1473   unsigned Line = getLineNumber(VD->getLocation());
1474   unsigned Column = getColumnNumber(VD->getLocation());
1475
1476   // Create the descriptor for the variable.
1477   llvm::DIVariable D =
1478     DebugFactory.CreateVariable(Tag, llvm::DIDescriptor(RegionStack.back()),
1479                                 VD->getName(),
1480                                 Unit, Line, Ty);
1481   // Insert an llvm.dbg.declare into the current block.
1482   llvm::Instruction *Call =
1483     DebugFactory.InsertDeclare(Storage, D, Builder.GetInsertBlock());
1484
1485   llvm::MDNode *Scope = RegionStack.back();
1486   Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
1487 }
1488
1489 /// EmitDeclare - Emit local variable declaration debug info.
1490 void CGDebugInfo::EmitDeclare(const BlockDeclRefExpr *BDRE, unsigned Tag,
1491                               llvm::Value *Storage, CGBuilderTy &Builder,
1492                               CodeGenFunction *CGF) {
1493   const ValueDecl *VD = BDRE->getDecl();
1494   assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
1495
1496   if (Builder.GetInsertBlock() == 0)
1497     return;
1498
1499   uint64_t XOffset = 0;
1500   llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
1501   llvm::DIType Ty;
1502   if (VD->hasAttr<BlocksAttr>())
1503     Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
1504   else 
1505     Ty = getOrCreateType(VD->getType(), Unit);
1506
1507   // Get location information.
1508   unsigned Line = getLineNumber(VD->getLocation());
1509   unsigned Column = getColumnNumber(VD->getLocation());
1510
1511   CharUnits offset = CGF->BlockDecls[VD];
1512   llvm::SmallVector<llvm::Value *, 9> addr;
1513   const llvm::Type *Int64Ty = llvm::Type::getInt64Ty(CGM.getLLVMContext());
1514   addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpDeref));
1515   addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpPlus));
1516   addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
1517   if (BDRE->isByRef()) {
1518     addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpDeref));
1519     addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpPlus));
1520     // offset of __forwarding field
1521     offset = CharUnits::fromQuantity(CGF->LLVMPointerWidth/8);
1522     addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
1523     addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpDeref));
1524     addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpPlus));
1525     // offset of x field
1526     offset = CharUnits::fromQuantity(XOffset/8);
1527     addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
1528   }
1529
1530   // Create the descriptor for the variable.
1531   llvm::DIVariable D =
1532     DebugFactory.CreateComplexVariable(Tag,
1533                                        llvm::DIDescriptor(RegionStack.back()),
1534                                        VD->getName(), Unit, Line, Ty,
1535                                        addr);
1536   // Insert an llvm.dbg.declare into the current block.
1537   llvm::Instruction *Call = 
1538     DebugFactory.InsertDeclare(Storage, D, Builder.GetInsertBlock());
1539   
1540   llvm::MDNode *Scope = RegionStack.back();
1541   Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
1542 }
1543
1544 void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
1545                                             llvm::Value *Storage,
1546                                             CGBuilderTy &Builder) {
1547   EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, Builder);
1548 }
1549
1550 void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(
1551   const BlockDeclRefExpr *BDRE, llvm::Value *Storage, CGBuilderTy &Builder,
1552   CodeGenFunction *CGF) {
1553   EmitDeclare(BDRE, llvm::dwarf::DW_TAG_auto_variable, Storage, Builder, CGF);
1554 }
1555
1556 /// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
1557 /// variable declaration.
1558 void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
1559                                            CGBuilderTy &Builder) {
1560   EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, Builder);
1561 }
1562
1563
1564
1565 /// EmitGlobalVariable - Emit information about a global variable.
1566 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
1567                                      const VarDecl *D) {
1568   
1569   // Create global variable debug descriptor.
1570   llvm::DIFile Unit = getOrCreateFile(D->getLocation());
1571   unsigned LineNo = getLineNumber(D->getLocation());
1572
1573   QualType T = D->getType();
1574   if (T->isIncompleteArrayType()) {
1575
1576     // CodeGen turns int[] into int[1] so we'll do the same here.
1577     llvm::APSInt ConstVal(32);
1578
1579     ConstVal = 1;
1580     QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
1581
1582     T = CGM.getContext().getConstantArrayType(ET, ConstVal,
1583                                            ArrayType::Normal, 0);
1584   }
1585   llvm::StringRef DeclName = D->getName();
1586   llvm::StringRef LinkageName;
1587   if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext()))
1588     LinkageName = Var->getName();
1589   llvm::DIDescriptor DContext = 
1590     getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()), Unit);
1591   DebugFactory.CreateGlobalVariable(DContext, DeclName, DeclName, LinkageName,
1592                                     Unit, LineNo, getOrCreateType(T, Unit),
1593                                     Var->hasInternalLinkage(),
1594                                     true/*definition*/, Var);
1595 }
1596
1597 /// EmitGlobalVariable - Emit information about an objective-c interface.
1598 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
1599                                      ObjCInterfaceDecl *ID) {
1600   // Create global variable debug descriptor.
1601   llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
1602   unsigned LineNo = getLineNumber(ID->getLocation());
1603
1604   llvm::StringRef Name = ID->getName();
1605
1606   QualType T = CGM.getContext().getObjCInterfaceType(ID);
1607   if (T->isIncompleteArrayType()) {
1608
1609     // CodeGen turns int[] into int[1] so we'll do the same here.
1610     llvm::APSInt ConstVal(32);
1611
1612     ConstVal = 1;
1613     QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
1614
1615     T = CGM.getContext().getConstantArrayType(ET, ConstVal,
1616                                            ArrayType::Normal, 0);
1617   }
1618
1619   DebugFactory.CreateGlobalVariable(Unit, Name, Name, Name, Unit, LineNo,
1620                                     getOrCreateType(T, Unit),
1621                                     Var->hasInternalLinkage(),
1622                                     true/*definition*/, Var);
1623 }
1624
1625 /// getOrCreateNamesSpace - Return namespace descriptor for the given
1626 /// namespace decl.
1627 llvm::DINameSpace 
1628 CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl, 
1629                                   llvm::DIDescriptor Unit) {
1630   llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I = 
1631     NameSpaceCache.find(NSDecl);
1632   if (I != NameSpaceCache.end())
1633     return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
1634   
1635   unsigned LineNo = getLineNumber(NSDecl->getLocation());
1636
1637   llvm::DIDescriptor Context = 
1638     getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()), Unit);
1639   llvm::DINameSpace NS =
1640     DebugFactory.CreateNameSpace(Context, NSDecl->getName(), 
1641         llvm::DIFile(Unit), LineNo);
1642   NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
1643   return NS;
1644 }