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 "CGBlocks.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/DeclFriend.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/RecordLayout.h"
24 #include "clang/Basic/SourceManager.h"
25 #include "clang/Basic/FileManager.h"
26 #include "clang/Basic/Version.h"
27 #include "clang/Frontend/CodeGenOptions.h"
28 #include "llvm/Constants.h"
29 #include "llvm/DerivedTypes.h"
30 #include "llvm/Instructions.h"
31 #include "llvm/Intrinsics.h"
32 #include "llvm/Module.h"
33 #include "llvm/ADT/StringExtras.h"
34 #include "llvm/ADT/SmallVector.h"
35 #include "llvm/Support/Dwarf.h"
36 #include "llvm/Support/Path.h"
37 #include "llvm/Target/TargetData.h"
38 #include "llvm/Target/TargetMachine.h"
39 using namespace clang;
40 using namespace clang::CodeGen;
41 
42 CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
43   : CGM(CGM), DBuilder(CGM.getModule()),
44     BlockLiteralGenericSet(false) {
45   CreateCompileUnit();
46 }
47 
48 CGDebugInfo::~CGDebugInfo() {
49   assert(LexicalBlockStack.empty() &&
50          "Region stack mismatch, stack not empty!");
51 }
52 
53 void CGDebugInfo::setLocation(SourceLocation Loc) {
54   // If the new location isn't valid return.
55   if (!Loc.isValid()) return;
56 
57   CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc);
58 }
59 
60 /// getContextDescriptor - Get context info for the decl.
61 llvm::DIDescriptor CGDebugInfo::getContextDescriptor(const Decl *Context) {
62   if (!Context)
63     return TheCU;
64 
65   llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
66     I = RegionMap.find(Context);
67   if (I != RegionMap.end())
68     return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(&*I->second));
69 
70   // Check namespace.
71   if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
72     return llvm::DIDescriptor(getOrCreateNameSpace(NSDecl));
73 
74   if (const RecordDecl *RDecl = dyn_cast<RecordDecl>(Context)) {
75     if (!RDecl->isDependentType()) {
76       llvm::DIType Ty = getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
77                                         getOrCreateMainFile());
78       return llvm::DIDescriptor(Ty);
79     }
80   }
81   return TheCU;
82 }
83 
84 /// getFunctionName - Get function name for the given FunctionDecl. If the
85 /// name is constructred on demand (e.g. C++ destructor) then the name
86 /// is stored on the side.
87 StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
88   assert (FD && "Invalid FunctionDecl!");
89   IdentifierInfo *FII = FD->getIdentifier();
90   if (FII)
91     return FII->getName();
92 
93   // Otherwise construct human readable name for debug info.
94   std::string NS = FD->getNameAsString();
95 
96   // Copy this name on the side and use its reference.
97   char *StrPtr = DebugInfoNames.Allocate<char>(NS.length());
98   memcpy(StrPtr, NS.data(), NS.length());
99   return StringRef(StrPtr, NS.length());
100 }
101 
102 StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
103   llvm::SmallString<256> MethodName;
104   llvm::raw_svector_ostream OS(MethodName);
105   OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
106   const DeclContext *DC = OMD->getDeclContext();
107   if (const ObjCImplementationDecl *OID =
108       dyn_cast<const ObjCImplementationDecl>(DC)) {
109      OS << OID->getName();
110   } else if (const ObjCInterfaceDecl *OID =
111              dyn_cast<const ObjCInterfaceDecl>(DC)) {
112       OS << OID->getName();
113   } else if (const ObjCCategoryImplDecl *OCD =
114              dyn_cast<const ObjCCategoryImplDecl>(DC)){
115       OS << ((NamedDecl *)OCD)->getIdentifier()->getNameStart() << '(' <<
116           OCD->getIdentifier()->getNameStart() << ')';
117   }
118   OS << ' ' << OMD->getSelector().getAsString() << ']';
119 
120   char *StrPtr = DebugInfoNames.Allocate<char>(OS.tell());
121   memcpy(StrPtr, MethodName.begin(), OS.tell());
122   return StringRef(StrPtr, OS.tell());
123 }
124 
125 /// getSelectorName - Return selector name. This is used for debugging
126 /// info.
127 StringRef CGDebugInfo::getSelectorName(Selector S) {
128   llvm::SmallString<256> SName;
129   llvm::raw_svector_ostream OS(SName);
130   OS << S.getAsString();
131   char *StrPtr = DebugInfoNames.Allocate<char>(OS.tell());
132   memcpy(StrPtr, SName.begin(), OS.tell());
133   return StringRef(StrPtr, OS.tell());
134 }
135 
136 /// getClassName - Get class name including template argument list.
137 StringRef
138 CGDebugInfo::getClassName(RecordDecl *RD) {
139   ClassTemplateSpecializationDecl *Spec
140     = dyn_cast<ClassTemplateSpecializationDecl>(RD);
141   if (!Spec)
142     return RD->getName();
143 
144   const TemplateArgument *Args;
145   unsigned NumArgs;
146   std::string Buffer;
147   if (TypeSourceInfo *TAW = Spec->getTypeAsWritten()) {
148     const TemplateSpecializationType *TST =
149       cast<TemplateSpecializationType>(TAW->getType());
150     Args = TST->getArgs();
151     NumArgs = TST->getNumArgs();
152   } else {
153     const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
154     Args = TemplateArgs.data();
155     NumArgs = TemplateArgs.size();
156   }
157   Buffer = RD->getIdentifier()->getNameStart();
158   PrintingPolicy Policy(CGM.getLangOptions());
159   Buffer += TemplateSpecializationType::PrintTemplateArgumentList(Args,
160                                                                   NumArgs,
161                                                                   Policy);
162 
163   // Copy this name on the side and use its reference.
164   char *StrPtr = DebugInfoNames.Allocate<char>(Buffer.length());
165   memcpy(StrPtr, Buffer.data(), Buffer.length());
166   return StringRef(StrPtr, Buffer.length());
167 }
168 
169 /// getOrCreateFile - Get the file debug info descriptor for the input location.
170 llvm::DIFile CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
171   if (!Loc.isValid())
172     // If Location is not valid then use main input file.
173     return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
174 
175   SourceManager &SM = CGM.getContext().getSourceManager();
176   PresumedLoc PLoc = SM.getPresumedLoc(Loc);
177 
178   if (PLoc.isInvalid() || StringRef(PLoc.getFilename()).empty())
179     // If the location is not valid then use main input file.
180     return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
181 
182   // Cache the results.
183   const char *fname = PLoc.getFilename();
184   llvm::DenseMap<const char *, llvm::WeakVH>::iterator it =
185     DIFileCache.find(fname);
186 
187   if (it != DIFileCache.end()) {
188     // Verify that the information still exists.
189     if (&*it->second)
190       return llvm::DIFile(cast<llvm::MDNode>(it->second));
191   }
192 
193   llvm::DIFile F = DBuilder.createFile(PLoc.getFilename(), getCurrentDirname());
194 
195   DIFileCache[fname] = F;
196   return F;
197 
198 }
199 
200 /// getOrCreateMainFile - Get the file info for main compile unit.
201 llvm::DIFile CGDebugInfo::getOrCreateMainFile() {
202   return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
203 }
204 
205 /// getLineNumber - Get line number for the location. If location is invalid
206 /// then use current location.
207 unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
208   assert (CurLoc.isValid() && "Invalid current location!");
209   SourceManager &SM = CGM.getContext().getSourceManager();
210   PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
211   return PLoc.isValid()? PLoc.getLine() : 0;
212 }
213 
214 /// getColumnNumber - Get column number for the location. If location is
215 /// invalid then use current location.
216 unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc) {
217   assert (CurLoc.isValid() && "Invalid current location!");
218   SourceManager &SM = CGM.getContext().getSourceManager();
219   PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
220   return PLoc.isValid()? PLoc.getColumn() : 0;
221 }
222 
223 StringRef CGDebugInfo::getCurrentDirname() {
224   if (!CWDName.empty())
225     return CWDName;
226   char *CompDirnamePtr = NULL;
227   llvm::sys::Path CWD = llvm::sys::Path::GetCurrentDirectory();
228   CompDirnamePtr = DebugInfoNames.Allocate<char>(CWD.size());
229   memcpy(CompDirnamePtr, CWD.c_str(), CWD.size());
230   return CWDName = StringRef(CompDirnamePtr, CWD.size());
231 }
232 
233 /// CreateCompileUnit - Create new compile unit.
234 void CGDebugInfo::CreateCompileUnit() {
235 
236   // Get absolute path name.
237   SourceManager &SM = CGM.getContext().getSourceManager();
238   std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
239   if (MainFileName.empty())
240     MainFileName = "<unknown>";
241 
242   // The main file name provided via the "-main-file-name" option contains just
243   // the file name itself with no path information. This file name may have had
244   // a relative path, so we look into the actual file entry for the main
245   // file to determine the real absolute path for the file.
246   std::string MainFileDir;
247   if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
248     MainFileDir = MainFile->getDir()->getName();
249     if (MainFileDir != ".")
250       MainFileName = MainFileDir + "/" + MainFileName;
251   }
252 
253   // Save filename string.
254   char *FilenamePtr = DebugInfoNames.Allocate<char>(MainFileName.length());
255   memcpy(FilenamePtr, MainFileName.c_str(), MainFileName.length());
256   StringRef Filename(FilenamePtr, MainFileName.length());
257 
258   unsigned LangTag;
259   const LangOptions &LO = CGM.getLangOptions();
260   if (LO.CPlusPlus) {
261     if (LO.ObjC1)
262       LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
263     else
264       LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
265   } else if (LO.ObjC1) {
266     LangTag = llvm::dwarf::DW_LANG_ObjC;
267   } else if (LO.C99) {
268     LangTag = llvm::dwarf::DW_LANG_C99;
269   } else {
270     LangTag = llvm::dwarf::DW_LANG_C89;
271   }
272 
273   std::string Producer = getClangFullVersion();
274 
275   // Figure out which version of the ObjC runtime we have.
276   unsigned RuntimeVers = 0;
277   if (LO.ObjC1)
278     RuntimeVers = LO.ObjCNonFragileABI ? 2 : 1;
279 
280   // Create new compile unit.
281   DBuilder.createCompileUnit(
282     LangTag, Filename, getCurrentDirname(),
283     Producer,
284     LO.Optimize, CGM.getCodeGenOpts().DwarfDebugFlags, RuntimeVers);
285   // FIXME - Eliminate TheCU.
286   TheCU = llvm::DICompileUnit(DBuilder.getCU());
287 }
288 
289 /// CreateType - Get the Basic type from the cache or create a new
290 /// one if necessary.
291 llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT) {
292   unsigned Encoding = 0;
293   const char *BTName = NULL;
294   switch (BT->getKind()) {
295   case BuiltinType::Dependent:
296     llvm_unreachable("Unexpected builtin type Dependent");
297   case BuiltinType::Overload:
298     llvm_unreachable("Unexpected builtin type Overload");
299   case BuiltinType::BoundMember:
300     llvm_unreachable("Unexpected builtin type BoundMember");
301   case BuiltinType::UnknownAny:
302     llvm_unreachable("Unexpected builtin type UnknownAny");
303   case BuiltinType::NullPtr:
304     return DBuilder.
305       createNullPtrType(BT->getName(CGM.getContext().getLangOptions()));
306   case BuiltinType::Void:
307     return llvm::DIType();
308   case BuiltinType::ObjCClass:
309     return DBuilder.createStructType(TheCU, "objc_class",
310                                      getOrCreateMainFile(), 0, 0, 0,
311                                      llvm::DIDescriptor::FlagFwdDecl,
312                                      llvm::DIArray());
313   case BuiltinType::ObjCId: {
314     // typedef struct objc_class *Class;
315     // typedef struct objc_object {
316     //  Class isa;
317     // } *id;
318 
319     llvm::DIType OCTy =
320       DBuilder.createStructType(TheCU, "objc_class",
321                                 getOrCreateMainFile(), 0, 0, 0,
322                                 llvm::DIDescriptor::FlagFwdDecl,
323                                 llvm::DIArray());
324     unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
325 
326     llvm::DIType ISATy = DBuilder.createPointerType(OCTy, Size);
327 
328     SmallVector<llvm::Value *, 16> EltTys;
329     llvm::DIType FieldTy =
330       DBuilder.createMemberType(getOrCreateMainFile(), "isa",
331                                 getOrCreateMainFile(), 0, Size,
332                                 0, 0, 0, ISATy);
333     EltTys.push_back(FieldTy);
334     llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
335 
336     return DBuilder.createStructType(TheCU, "objc_object",
337                                      getOrCreateMainFile(),
338                                      0, 0, 0, 0, Elements);
339   }
340   case BuiltinType::ObjCSel: {
341     return  DBuilder.createStructType(TheCU, "objc_selector",
342                                       getOrCreateMainFile(), 0, 0, 0,
343                                       llvm::DIDescriptor::FlagFwdDecl,
344                                       llvm::DIArray());
345   }
346   case BuiltinType::UChar:
347   case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break;
348   case BuiltinType::Char_S:
349   case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break;
350   case BuiltinType::Char16:
351   case BuiltinType::Char32: Encoding = llvm::dwarf::DW_ATE_UTF; break;
352   case BuiltinType::UShort:
353   case BuiltinType::UInt:
354   case BuiltinType::UInt128:
355   case BuiltinType::ULong:
356   case BuiltinType::WChar_U:
357   case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break;
358   case BuiltinType::Short:
359   case BuiltinType::Int:
360   case BuiltinType::Int128:
361   case BuiltinType::Long:
362   case BuiltinType::WChar_S:
363   case BuiltinType::LongLong:  Encoding = llvm::dwarf::DW_ATE_signed; break;
364   case BuiltinType::Bool:      Encoding = llvm::dwarf::DW_ATE_boolean; break;
365   case BuiltinType::Float:
366   case BuiltinType::LongDouble:
367   case BuiltinType::Double:    Encoding = llvm::dwarf::DW_ATE_float; break;
368   }
369 
370   switch (BT->getKind()) {
371   case BuiltinType::Long:      BTName = "long int"; break;
372   case BuiltinType::LongLong:  BTName = "long long int"; break;
373   case BuiltinType::ULong:     BTName = "long unsigned int"; break;
374   case BuiltinType::ULongLong: BTName = "long long unsigned int"; break;
375   default:
376     BTName = BT->getName(CGM.getContext().getLangOptions());
377     break;
378   }
379   // Bit size, align and offset of the type.
380   uint64_t Size = CGM.getContext().getTypeSize(BT);
381   uint64_t Align = CGM.getContext().getTypeAlign(BT);
382   llvm::DIType DbgTy =
383     DBuilder.createBasicType(BTName, Size, Align, Encoding);
384   return DbgTy;
385 }
386 
387 llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty) {
388   // Bit size, align and offset of the type.
389   unsigned Encoding = llvm::dwarf::DW_ATE_complex_float;
390   if (Ty->isComplexIntegerType())
391     Encoding = llvm::dwarf::DW_ATE_lo_user;
392 
393   uint64_t Size = CGM.getContext().getTypeSize(Ty);
394   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
395   llvm::DIType DbgTy =
396     DBuilder.createBasicType("complex", Size, Align, Encoding);
397 
398   return DbgTy;
399 }
400 
401 /// CreateCVRType - Get the qualified type from the cache or create
402 /// a new one if necessary.
403 llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit) {
404   QualifierCollector Qc;
405   const Type *T = Qc.strip(Ty);
406 
407   // Ignore these qualifiers for now.
408   Qc.removeObjCGCAttr();
409   Qc.removeAddressSpace();
410   Qc.removeObjCLifetime();
411 
412   // We will create one Derived type for one qualifier and recurse to handle any
413   // additional ones.
414   unsigned Tag;
415   if (Qc.hasConst()) {
416     Tag = llvm::dwarf::DW_TAG_const_type;
417     Qc.removeConst();
418   } else if (Qc.hasVolatile()) {
419     Tag = llvm::dwarf::DW_TAG_volatile_type;
420     Qc.removeVolatile();
421   } else if (Qc.hasRestrict()) {
422     Tag = llvm::dwarf::DW_TAG_restrict_type;
423     Qc.removeRestrict();
424   } else {
425     assert(Qc.empty() && "Unknown type qualifier for debug info");
426     return getOrCreateType(QualType(T, 0), Unit);
427   }
428 
429   llvm::DIType FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
430 
431   // No need to fill in the Name, Line, Size, Alignment, Offset in case of
432   // CVR derived types.
433   llvm::DIType DbgTy = DBuilder.createQualifiedType(Tag, FromTy);
434 
435   return DbgTy;
436 }
437 
438 llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
439                                      llvm::DIFile Unit) {
440   llvm::DIType DbgTy =
441     CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
442                           Ty->getPointeeType(), Unit);
443   return DbgTy;
444 }
445 
446 llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
447                                      llvm::DIFile Unit) {
448   return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
449                                Ty->getPointeeType(), Unit);
450 }
451 
452 /// CreatePointeeType - Create Pointee type. If Pointee is a record
453 /// then emit record's fwd if debug info size reduction is enabled.
454 llvm::DIType CGDebugInfo::CreatePointeeType(QualType PointeeTy,
455                                             llvm::DIFile Unit) {
456   if (!CGM.getCodeGenOpts().LimitDebugInfo)
457     return getOrCreateType(PointeeTy, Unit);
458 
459   if (const RecordType *RTy = dyn_cast<RecordType>(PointeeTy)) {
460     RecordDecl *RD = RTy->getDecl();
461     llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
462     unsigned Line = getLineNumber(RD->getLocation());
463     llvm::DIDescriptor FDContext =
464       getContextDescriptor(cast<Decl>(RD->getDeclContext()));
465 
466     if (RD->isStruct())
467       return DBuilder.createStructType(FDContext, RD->getName(), DefUnit,
468                                        Line, 0, 0, llvm::DIType::FlagFwdDecl,
469                                        llvm::DIArray());
470     else if (RD->isUnion())
471       return DBuilder.createUnionType(FDContext, RD->getName(), DefUnit,
472                                       Line, 0, 0, llvm::DIType::FlagFwdDecl,
473                                       llvm::DIArray());
474     else {
475       assert(RD->isClass() && "Unknown RecordType!");
476       return DBuilder.createClassType(FDContext, RD->getName(), DefUnit,
477                                       Line, 0, 0, 0, llvm::DIType::FlagFwdDecl,
478                                       llvm::DIType(), llvm::DIArray());
479     }
480   }
481   return getOrCreateType(PointeeTy, Unit);
482 
483 }
484 
485 llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag,
486                                                 const Type *Ty,
487                                                 QualType PointeeTy,
488                                                 llvm::DIFile Unit) {
489 
490   if (Tag == llvm::dwarf::DW_TAG_reference_type)
491     return DBuilder.createReferenceType(CreatePointeeType(PointeeTy, Unit));
492 
493   // Bit size, align and offset of the type.
494   // Size is always the size of a pointer. We can't use getTypeSize here
495   // because that does not return the correct value for references.
496   unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
497   uint64_t Size = CGM.getContext().getTargetInfo().getPointerWidth(AS);
498   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
499 
500   return
501     DBuilder.createPointerType(CreatePointeeType(PointeeTy, Unit), Size, Align);
502 }
503 
504 llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
505                                      llvm::DIFile Unit) {
506   if (BlockLiteralGenericSet)
507     return BlockLiteralGeneric;
508 
509   SmallVector<llvm::Value *, 8> EltTys;
510   llvm::DIType FieldTy;
511   QualType FType;
512   uint64_t FieldSize, FieldOffset;
513   unsigned FieldAlign;
514   llvm::DIArray Elements;
515   llvm::DIType EltTy, DescTy;
516 
517   FieldOffset = 0;
518   FType = CGM.getContext().UnsignedLongTy;
519   EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
520   EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
521 
522   Elements = DBuilder.getOrCreateArray(EltTys);
523   EltTys.clear();
524 
525   unsigned Flags = llvm::DIDescriptor::FlagAppleBlock;
526   unsigned LineNo = getLineNumber(CurLoc);
527 
528   EltTy = DBuilder.createStructType(Unit, "__block_descriptor",
529                                     Unit, LineNo, FieldOffset, 0,
530                                     Flags, Elements);
531 
532   // Bit size, align and offset of the type.
533   uint64_t Size = CGM.getContext().getTypeSize(Ty);
534 
535   DescTy = DBuilder.createPointerType(EltTy, Size);
536 
537   FieldOffset = 0;
538   FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
539   EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
540   FType = CGM.getContext().IntTy;
541   EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
542   EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
543   FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
544   EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
545 
546   FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
547   FieldTy = DescTy;
548   FieldSize = CGM.getContext().getTypeSize(Ty);
549   FieldAlign = CGM.getContext().getTypeAlign(Ty);
550   FieldTy = DBuilder.createMemberType(Unit, "__descriptor", Unit,
551                                       LineNo, FieldSize, FieldAlign,
552                                       FieldOffset, 0, FieldTy);
553   EltTys.push_back(FieldTy);
554 
555   FieldOffset += FieldSize;
556   Elements = DBuilder.getOrCreateArray(EltTys);
557 
558   EltTy = DBuilder.createStructType(Unit, "__block_literal_generic",
559                                     Unit, LineNo, FieldOffset, 0,
560                                     Flags, Elements);
561 
562   BlockLiteralGenericSet = true;
563   BlockLiteralGeneric = DBuilder.createPointerType(EltTy, Size);
564   return BlockLiteralGeneric;
565 }
566 
567 llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty,
568                                      llvm::DIFile Unit) {
569   // Typedefs are derived from some other type.  If we have a typedef of a
570   // typedef, make sure to emit the whole chain.
571   llvm::DIType Src = getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
572   if (!Src.Verify())
573     return llvm::DIType();
574   // We don't set size information, but do specify where the typedef was
575   // declared.
576   unsigned Line = getLineNumber(Ty->getDecl()->getLocation());
577   const TypedefNameDecl *TyDecl = Ty->getDecl();
578   llvm::DIDescriptor TydefContext =
579     getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext()));
580 
581   return
582     DBuilder.createTypedef(Src, TyDecl->getName(), Unit, Line, TydefContext);
583 }
584 
585 llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
586                                      llvm::DIFile Unit) {
587   SmallVector<llvm::Value *, 16> EltTys;
588 
589   // Add the result type at least.
590   EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit));
591 
592   // Set up remainder of arguments if there is a prototype.
593   // FIXME: IF NOT, HOW IS THIS REPRESENTED?  llvm-gcc doesn't represent '...'!
594   if (isa<FunctionNoProtoType>(Ty))
595     EltTys.push_back(DBuilder.createUnspecifiedParameter());
596   else if (const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(Ty)) {
597     for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i)
598       EltTys.push_back(getOrCreateType(FTP->getArgType(i), Unit));
599   }
600 
601   llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
602 
603   llvm::DIType DbgTy = DBuilder.createSubroutineType(Unit, EltTypeArray);
604   return DbgTy;
605 }
606 
607 llvm::DIType CGDebugInfo::createFieldType(StringRef name,
608                                           QualType type,
609                                           uint64_t sizeInBitsOverride,
610                                           SourceLocation loc,
611                                           AccessSpecifier AS,
612                                           uint64_t offsetInBits,
613                                           llvm::DIFile tunit,
614                                           llvm::DIDescriptor scope) {
615   llvm::DIType debugType = getOrCreateType(type, tunit);
616 
617   // Get the location for the field.
618   llvm::DIFile file = getOrCreateFile(loc);
619   unsigned line = getLineNumber(loc);
620 
621   uint64_t sizeInBits = 0;
622   unsigned alignInBits = 0;
623   if (!type->isIncompleteArrayType()) {
624     llvm::tie(sizeInBits, alignInBits) = CGM.getContext().getTypeInfo(type);
625 
626     if (sizeInBitsOverride)
627       sizeInBits = sizeInBitsOverride;
628   }
629 
630   unsigned flags = 0;
631   if (AS == clang::AS_private)
632     flags |= llvm::DIDescriptor::FlagPrivate;
633   else if (AS == clang::AS_protected)
634     flags |= llvm::DIDescriptor::FlagProtected;
635 
636   return DBuilder.createMemberType(scope, name, file, line, sizeInBits,
637                                    alignInBits, offsetInBits, flags, debugType);
638 }
639 
640 /// CollectRecordFields - A helper function to collect debug info for
641 /// record fields. This is used while creating debug info entry for a Record.
642 void CGDebugInfo::
643 CollectRecordFields(const RecordDecl *record, llvm::DIFile tunit,
644                     SmallVectorImpl<llvm::Value *> &elements,
645                     llvm::DIType RecordTy) {
646   unsigned fieldNo = 0;
647   const FieldDecl *LastFD = 0;
648   bool IsMsStruct = record->hasAttr<MsStructAttr>();
649 
650   const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
651   for (RecordDecl::field_iterator I = record->field_begin(),
652                                   E = record->field_end();
653        I != E; ++I, ++fieldNo) {
654     FieldDecl *field = *I;
655     if (IsMsStruct) {
656       // Zero-length bitfields following non-bitfield members are ignored
657       if (CGM.getContext().ZeroBitfieldFollowsNonBitfield((field), LastFD)) {
658         --fieldNo;
659         continue;
660       }
661       LastFD = field;
662     }
663 
664     StringRef name = field->getName();
665     QualType type = field->getType();
666 
667     // Ignore unnamed fields unless they're anonymous structs/unions.
668     if (name.empty() && !type->isRecordType()) {
669       LastFD = field;
670       continue;
671     }
672 
673     uint64_t SizeInBitsOverride = 0;
674     if (field->isBitField()) {
675       SizeInBitsOverride = field->getBitWidthValue(CGM.getContext());
676       assert(SizeInBitsOverride && "found named 0-width bitfield");
677     }
678 
679     llvm::DIType fieldType
680       = createFieldType(name, type, SizeInBitsOverride,
681                         field->getLocation(), field->getAccess(),
682                         layout.getFieldOffset(fieldNo), tunit, RecordTy);
683 
684     elements.push_back(fieldType);
685   }
686 }
687 
688 /// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
689 /// function type is not updated to include implicit "this" pointer. Use this
690 /// routine to get a method type which includes "this" pointer.
691 llvm::DIType
692 CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
693                                    llvm::DIFile Unit) {
694   llvm::DIType FnTy
695     = getOrCreateType(QualType(Method->getType()->getAs<FunctionProtoType>(),
696                                0),
697                       Unit);
698 
699   // Add "this" pointer.
700   llvm::DIArray Args = llvm::DICompositeType(FnTy).getTypeArray();
701   assert (Args.getNumElements() && "Invalid number of arguments!");
702 
703   SmallVector<llvm::Value *, 16> Elts;
704 
705   // First element is always return type. For 'void' functions it is NULL.
706   Elts.push_back(Args.getElement(0));
707 
708   if (!Method->isStatic()) {
709     // "this" pointer is always first argument.
710     QualType ThisPtr = Method->getThisType(CGM.getContext());
711     llvm::DIType ThisPtrType =
712       DBuilder.createArtificialType(getOrCreateType(ThisPtr, Unit));
713 
714     TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
715     Elts.push_back(ThisPtrType);
716   }
717 
718   // Copy rest of the arguments.
719   for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
720     Elts.push_back(Args.getElement(i));
721 
722   llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
723 
724   return DBuilder.createSubroutineType(Unit, EltTypeArray);
725 }
726 
727 /// isFunctionLocalClass - Return true if CXXRecordDecl is defined
728 /// inside a function.
729 static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
730   if (const CXXRecordDecl *NRD =
731       dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
732     return isFunctionLocalClass(NRD);
733   else if (isa<FunctionDecl>(RD->getDeclContext()))
734     return true;
735   return false;
736 
737 }
738 /// CreateCXXMemberFunction - A helper function to create a DISubprogram for
739 /// a single member function GlobalDecl.
740 llvm::DISubprogram
741 CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
742                                      llvm::DIFile Unit,
743                                      llvm::DIType RecordTy) {
744   bool IsCtorOrDtor =
745     isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
746 
747   StringRef MethodName = getFunctionName(Method);
748   llvm::DIType MethodTy = getOrCreateMethodType(Method, Unit);
749 
750   // Since a single ctor/dtor corresponds to multiple functions, it doesn't
751   // make sense to give a single ctor/dtor a linkage name.
752   StringRef MethodLinkageName;
753   if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
754     MethodLinkageName = CGM.getMangledName(Method);
755 
756   // Get the location for the method.
757   llvm::DIFile MethodDefUnit = getOrCreateFile(Method->getLocation());
758   unsigned MethodLine = getLineNumber(Method->getLocation());
759 
760   // Collect virtual method info.
761   llvm::DIType ContainingType;
762   unsigned Virtuality = 0;
763   unsigned VIndex = 0;
764 
765   if (Method->isVirtual()) {
766     if (Method->isPure())
767       Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
768     else
769       Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
770 
771     // It doesn't make sense to give a virtual destructor a vtable index,
772     // since a single destructor has two entries in the vtable.
773     if (!isa<CXXDestructorDecl>(Method))
774       VIndex = CGM.getVTableContext().getMethodVTableIndex(Method);
775     ContainingType = RecordTy;
776   }
777 
778   unsigned Flags = 0;
779   if (Method->isImplicit())
780     Flags |= llvm::DIDescriptor::FlagArtificial;
781   AccessSpecifier Access = Method->getAccess();
782   if (Access == clang::AS_private)
783     Flags |= llvm::DIDescriptor::FlagPrivate;
784   else if (Access == clang::AS_protected)
785     Flags |= llvm::DIDescriptor::FlagProtected;
786   if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
787     if (CXXC->isExplicit())
788       Flags |= llvm::DIDescriptor::FlagExplicit;
789   } else if (const CXXConversionDecl *CXXC =
790              dyn_cast<CXXConversionDecl>(Method)) {
791     if (CXXC->isExplicit())
792       Flags |= llvm::DIDescriptor::FlagExplicit;
793   }
794   if (Method->hasPrototype())
795     Flags |= llvm::DIDescriptor::FlagPrototyped;
796 
797   llvm::DISubprogram SP =
798     DBuilder.createMethod(RecordTy, MethodName, MethodLinkageName,
799                           MethodDefUnit, MethodLine,
800                           MethodTy, /*isLocalToUnit=*/false,
801                           /* isDefinition=*/ false,
802                           Virtuality, VIndex, ContainingType,
803                           Flags, CGM.getLangOptions().Optimize);
804 
805   SPCache[Method] = llvm::WeakVH(SP);
806 
807   return SP;
808 }
809 
810 /// CollectCXXMemberFunctions - A helper function to collect debug info for
811 /// C++ member functions.This is used while creating debug info entry for
812 /// a Record.
813 void CGDebugInfo::
814 CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
815                           SmallVectorImpl<llvm::Value *> &EltTys,
816                           llvm::DIType RecordTy) {
817   for(CXXRecordDecl::method_iterator I = RD->method_begin(),
818         E = RD->method_end(); I != E; ++I) {
819     const CXXMethodDecl *Method = *I;
820 
821     if (Method->isImplicit() && !Method->isUsed())
822       continue;
823 
824     EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
825   }
826 }
827 
828 /// CollectCXXFriends - A helper function to collect debug info for
829 /// C++ base classes. This is used while creating debug info entry for
830 /// a Record.
831 void CGDebugInfo::
832 CollectCXXFriends(const CXXRecordDecl *RD, llvm::DIFile Unit,
833                 SmallVectorImpl<llvm::Value *> &EltTys,
834                 llvm::DIType RecordTy) {
835   for (CXXRecordDecl::friend_iterator BI =  RD->friend_begin(),
836          BE = RD->friend_end(); BI != BE; ++BI) {
837     if ((*BI)->isUnsupportedFriend())
838       continue;
839     if (TypeSourceInfo *TInfo = (*BI)->getFriendType())
840       EltTys.push_back(DBuilder.createFriend(RecordTy,
841                                              getOrCreateType(TInfo->getType(),
842                                                              Unit)));
843   }
844 }
845 
846 /// CollectCXXBases - A helper function to collect debug info for
847 /// C++ base classes. This is used while creating debug info entry for
848 /// a Record.
849 void CGDebugInfo::
850 CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
851                 SmallVectorImpl<llvm::Value *> &EltTys,
852                 llvm::DIType RecordTy) {
853 
854   const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
855   for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
856          BE = RD->bases_end(); BI != BE; ++BI) {
857     unsigned BFlags = 0;
858     uint64_t BaseOffset;
859 
860     const CXXRecordDecl *Base =
861       cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl());
862 
863     if (BI->isVirtual()) {
864       // virtual base offset offset is -ve. The code generator emits dwarf
865       // expression where it expects +ve number.
866       BaseOffset =
867         0 - CGM.getVTableContext()
868                .getVirtualBaseOffsetOffset(RD, Base).getQuantity();
869       BFlags = llvm::DIDescriptor::FlagVirtual;
870     } else
871       BaseOffset = RL.getBaseClassOffsetInBits(Base);
872     // FIXME: Inconsistent units for BaseOffset. It is in bytes when
873     // BI->isVirtual() and bits when not.
874 
875     AccessSpecifier Access = BI->getAccessSpecifier();
876     if (Access == clang::AS_private)
877       BFlags |= llvm::DIDescriptor::FlagPrivate;
878     else if (Access == clang::AS_protected)
879       BFlags |= llvm::DIDescriptor::FlagProtected;
880 
881     llvm::DIType DTy =
882       DBuilder.createInheritance(RecordTy,
883                                  getOrCreateType(BI->getType(), Unit),
884                                  BaseOffset, BFlags);
885     EltTys.push_back(DTy);
886   }
887 }
888 
889 /// CollectTemplateParams - A helper function to collect template parameters.
890 llvm::DIArray CGDebugInfo::
891 CollectTemplateParams(const TemplateParameterList *TPList,
892                       const TemplateArgumentList &TAList,
893                       llvm::DIFile Unit) {
894   SmallVector<llvm::Value *, 16> TemplateParams;
895   for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
896     const TemplateArgument &TA = TAList[i];
897     const NamedDecl *ND = TPList->getParam(i);
898     if (TA.getKind() == TemplateArgument::Type) {
899       llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit);
900       llvm::DITemplateTypeParameter TTP =
901         DBuilder.createTemplateTypeParameter(TheCU, ND->getName(), TTy);
902       TemplateParams.push_back(TTP);
903     } else if (TA.getKind() == TemplateArgument::Integral) {
904       llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit);
905       llvm::DITemplateValueParameter TVP =
906         DBuilder.createTemplateValueParameter(TheCU, ND->getName(), TTy,
907                                           TA.getAsIntegral()->getZExtValue());
908       TemplateParams.push_back(TVP);
909     }
910   }
911   return DBuilder.getOrCreateArray(TemplateParams);
912 }
913 
914 /// CollectFunctionTemplateParams - A helper function to collect debug
915 /// info for function template parameters.
916 llvm::DIArray CGDebugInfo::
917 CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) {
918   if (FD->getTemplatedKind() ==
919       FunctionDecl::TK_FunctionTemplateSpecialization) {
920     const TemplateParameterList *TList =
921       FD->getTemplateSpecializationInfo()->getTemplate()
922       ->getTemplateParameters();
923     return
924       CollectTemplateParams(TList, *FD->getTemplateSpecializationArgs(), Unit);
925   }
926   return llvm::DIArray();
927 }
928 
929 /// CollectCXXTemplateParams - A helper function to collect debug info for
930 /// template parameters.
931 llvm::DIArray CGDebugInfo::
932 CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial,
933                          llvm::DIFile Unit) {
934   llvm::PointerUnion<ClassTemplateDecl *,
935                      ClassTemplatePartialSpecializationDecl *>
936     PU = TSpecial->getSpecializedTemplateOrPartial();
937 
938   TemplateParameterList *TPList = PU.is<ClassTemplateDecl *>() ?
939     PU.get<ClassTemplateDecl *>()->getTemplateParameters() :
940     PU.get<ClassTemplatePartialSpecializationDecl *>()->getTemplateParameters();
941   const TemplateArgumentList &TAList = TSpecial->getTemplateInstantiationArgs();
942   return CollectTemplateParams(TPList, TAList, Unit);
943 }
944 
945 /// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
946 llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
947   if (VTablePtrType.isValid())
948     return VTablePtrType;
949 
950   ASTContext &Context = CGM.getContext();
951 
952   /* Function type */
953   llvm::Value *STy = getOrCreateType(Context.IntTy, Unit);
954   llvm::DIArray SElements = DBuilder.getOrCreateArray(STy);
955   llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements);
956   unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
957   llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0,
958                                                           "__vtbl_ptr_type");
959   VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
960   return VTablePtrType;
961 }
962 
963 /// getVTableName - Get vtable name for the given Class.
964 StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
965   // Otherwise construct gdb compatible name name.
966   std::string Name = "_vptr$" + RD->getNameAsString();
967 
968   // Copy this name on the side and use its reference.
969   char *StrPtr = DebugInfoNames.Allocate<char>(Name.length());
970   memcpy(StrPtr, Name.data(), Name.length());
971   return StringRef(StrPtr, Name.length());
972 }
973 
974 
975 /// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
976 /// debug info entry in EltTys vector.
977 void CGDebugInfo::
978 CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
979                   SmallVectorImpl<llvm::Value *> &EltTys) {
980   const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
981 
982   // If there is a primary base then it will hold vtable info.
983   if (RL.getPrimaryBase())
984     return;
985 
986   // If this class is not dynamic then there is not any vtable info to collect.
987   if (!RD->isDynamicClass())
988     return;
989 
990   unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
991   llvm::DIType VPTR
992     = DBuilder.createMemberType(Unit, getVTableName(RD), Unit,
993                                 0, Size, 0, 0, 0,
994                                 getOrCreateVTablePtrType(Unit));
995   EltTys.push_back(VPTR);
996 }
997 
998 /// getOrCreateRecordType - Emit record type's standalone debug info.
999 llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy,
1000                                                 SourceLocation Loc) {
1001   llvm::DIType T =  getOrCreateType(RTy, getOrCreateFile(Loc));
1002   DBuilder.retainType(T);
1003   return T;
1004 }
1005 
1006 /// CreateType - get structure or union type.
1007 llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty) {
1008   RecordDecl *RD = Ty->getDecl();
1009   llvm::DIFile Unit = getOrCreateFile(RD->getLocation());
1010 
1011   // Get overall information about the record type for the debug info.
1012   llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1013   unsigned Line = getLineNumber(RD->getLocation());
1014 
1015   // Records and classes and unions can all be recursive.  To handle them, we
1016   // first generate a debug descriptor for the struct as a forward declaration.
1017   // Then (if it is a definition) we go through and get debug info for all of
1018   // its members.  Finally, we create a descriptor for the complete type (which
1019   // may refer to the forward decl if the struct is recursive) and replace all
1020   // uses of the forward declaration with the final definition.
1021   llvm::DIDescriptor FDContext =
1022     getContextDescriptor(cast<Decl>(RD->getDeclContext()));
1023 
1024   // If this is just a forward declaration, construct an appropriately
1025   // marked node and just return it.
1026   if (!RD->getDefinition()) {
1027     llvm::DIType FwdDecl =
1028       DBuilder.createStructType(FDContext, RD->getName(),
1029                                 DefUnit, Line, 0, 0,
1030                                 llvm::DIDescriptor::FlagFwdDecl,
1031                                 llvm::DIArray());
1032 
1033       return FwdDecl;
1034   }
1035 
1036   llvm::DIType FwdDecl = DBuilder.createTemporaryType(DefUnit);
1037 
1038   llvm::MDNode *MN = FwdDecl;
1039   llvm::TrackingVH<llvm::MDNode> FwdDeclNode = MN;
1040   // Otherwise, insert it into the TypeCache so that recursive uses will find
1041   // it.
1042   TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1043   // Push the struct on region stack.
1044   LexicalBlockStack.push_back(FwdDeclNode);
1045   RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1046 
1047   // Convert all the elements.
1048   SmallVector<llvm::Value *, 16> EltTys;
1049 
1050   const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1051   if (CXXDecl) {
1052     CollectCXXBases(CXXDecl, Unit, EltTys, FwdDecl);
1053     CollectVTableInfo(CXXDecl, Unit, EltTys);
1054   }
1055 
1056   // Collect static variables with initializers.
1057   for (RecordDecl::decl_iterator I = RD->decls_begin(), E = RD->decls_end();
1058        I != E; ++I)
1059     if (const VarDecl *V = dyn_cast<VarDecl>(*I)) {
1060       if (const Expr *Init = V->getInit()) {
1061         Expr::EvalResult Result;
1062         if (Init->Evaluate(Result, CGM.getContext()) && Result.Val.isInt()) {
1063           llvm::ConstantInt *CI
1064             = llvm::ConstantInt::get(CGM.getLLVMContext(), Result.Val.getInt());
1065 
1066           // Create the descriptor for static variable.
1067           llvm::DIFile VUnit = getOrCreateFile(V->getLocation());
1068           StringRef VName = V->getName();
1069           llvm::DIType VTy = getOrCreateType(V->getType(), VUnit);
1070           // Do not use DIGlobalVariable for enums.
1071           if (VTy.getTag() != llvm::dwarf::DW_TAG_enumeration_type) {
1072             DBuilder.createStaticVariable(FwdDecl, VName, VName, VUnit,
1073                                           getLineNumber(V->getLocation()),
1074                                           VTy, true, CI);
1075           }
1076         }
1077       }
1078     }
1079 
1080   CollectRecordFields(RD, Unit, EltTys, FwdDecl);
1081   llvm::DIArray TParamsArray;
1082   if (CXXDecl) {
1083     CollectCXXMemberFunctions(CXXDecl, Unit, EltTys, FwdDecl);
1084     CollectCXXFriends(CXXDecl, Unit, EltTys, FwdDecl);
1085     if (const ClassTemplateSpecializationDecl *TSpecial
1086         = dyn_cast<ClassTemplateSpecializationDecl>(RD))
1087       TParamsArray = CollectCXXTemplateParams(TSpecial, Unit);
1088   }
1089 
1090   LexicalBlockStack.pop_back();
1091   llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator RI =
1092     RegionMap.find(Ty->getDecl());
1093   if (RI != RegionMap.end())
1094     RegionMap.erase(RI);
1095 
1096   llvm::DIDescriptor RDContext =
1097     getContextDescriptor(cast<Decl>(RD->getDeclContext()));
1098   StringRef RDName = RD->getName();
1099   uint64_t Size = CGM.getContext().getTypeSize(Ty);
1100   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1101   llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
1102   llvm::MDNode *RealDecl = NULL;
1103 
1104   if (RD->isUnion())
1105     RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
1106                                         Size, Align, 0, Elements);
1107   else if (CXXDecl) {
1108     RDName = getClassName(RD);
1109      // A class's primary base or the class itself contains the vtable.
1110     llvm::MDNode *ContainingType = NULL;
1111     const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1112     if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
1113       // Seek non virtual primary base root.
1114       while (1) {
1115         const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
1116         const CXXRecordDecl *PBT = BRL.getPrimaryBase();
1117         if (PBT && !BRL.isPrimaryBaseVirtual())
1118           PBase = PBT;
1119         else
1120           break;
1121       }
1122       ContainingType =
1123         getOrCreateType(QualType(PBase->getTypeForDecl(), 0), Unit);
1124     }
1125     else if (CXXDecl->isDynamicClass())
1126       ContainingType = FwdDecl;
1127 
1128    RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
1129                                        Size, Align, 0, 0, llvm::DIType(),
1130                                        Elements, ContainingType,
1131                                        TParamsArray);
1132   } else
1133     RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line,
1134                                          Size, Align, 0, Elements);
1135 
1136   // Now that we have a real decl for the struct, replace anything using the
1137   // old decl with the new one.  This will recursively update the debug info.
1138   llvm::DIType(FwdDeclNode).replaceAllUsesWith(RealDecl);
1139   RegionMap[RD] = llvm::WeakVH(RealDecl);
1140   return llvm::DIType(RealDecl);
1141 }
1142 
1143 /// CreateType - get objective-c object type.
1144 llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1145                                      llvm::DIFile Unit) {
1146   // Ignore protocols.
1147   return getOrCreateType(Ty->getBaseType(), Unit);
1148 }
1149 
1150 /// CreateType - get objective-c interface type.
1151 llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1152                                      llvm::DIFile Unit) {
1153   ObjCInterfaceDecl *ID = Ty->getDecl();
1154   if (!ID)
1155     return llvm::DIType();
1156 
1157   // Get overall information about the record type for the debug info.
1158   llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1159   unsigned Line = getLineNumber(ID->getLocation());
1160   unsigned RuntimeLang = TheCU.getLanguage();
1161 
1162   // If this is just a forward declaration return a special forward-declaration
1163   // debug type since we won't be able to lay out the entire type.
1164   if (ID->isForwardDecl()) {
1165     llvm::DIType FwdDecl =
1166       DBuilder.createStructType(Unit, ID->getName(),
1167                                 DefUnit, Line, 0, 0, 0,
1168                                 llvm::DIArray(), RuntimeLang);
1169     return FwdDecl;
1170   }
1171 
1172   // To handle a recursive interface, we first generate a debug descriptor
1173   // for the struct as a forward declaration. Then (if it is a definition)
1174   // we go through and get debug info for all of its members.  Finally, we
1175   // create a descriptor for the complete type (which may refer to the
1176   // forward decl if the struct is recursive) and replace all uses of the
1177   // forward declaration with the final definition.
1178   llvm::DIType FwdDecl = DBuilder.createTemporaryType(DefUnit);
1179 
1180   llvm::MDNode *MN = FwdDecl;
1181   llvm::TrackingVH<llvm::MDNode> FwdDeclNode = MN;
1182   // Otherwise, insert it into the TypeCache so that recursive uses will find
1183   // it.
1184   TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1185   // Push the struct on region stack.
1186   LexicalBlockStack.push_back(FwdDeclNode);
1187   RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1188 
1189   // Convert all the elements.
1190   SmallVector<llvm::Value *, 16> EltTys;
1191 
1192   ObjCInterfaceDecl *SClass = ID->getSuperClass();
1193   if (SClass) {
1194     llvm::DIType SClassTy =
1195       getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1196     if (!SClassTy.isValid())
1197       return llvm::DIType();
1198 
1199     llvm::DIType InhTag =
1200       DBuilder.createInheritance(FwdDecl, SClassTy, 0, 0);
1201     EltTys.push_back(InhTag);
1202   }
1203 
1204   const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1205   ObjCImplementationDecl *ImpD = ID->getImplementation();
1206   unsigned FieldNo = 0;
1207   for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1208        Field = Field->getNextIvar(), ++FieldNo) {
1209     llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1210     if (!FieldTy.isValid())
1211       return llvm::DIType();
1212 
1213     StringRef FieldName = Field->getName();
1214 
1215     // Ignore unnamed fields.
1216     if (FieldName.empty())
1217       continue;
1218 
1219     // Get the location for the field.
1220     llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1221     unsigned FieldLine = getLineNumber(Field->getLocation());
1222     QualType FType = Field->getType();
1223     uint64_t FieldSize = 0;
1224     unsigned FieldAlign = 0;
1225 
1226     if (!FType->isIncompleteArrayType()) {
1227 
1228       // Bit size, align and offset of the type.
1229       FieldSize = Field->isBitField()
1230         ? Field->getBitWidthValue(CGM.getContext())
1231         : CGM.getContext().getTypeSize(FType);
1232       FieldAlign = CGM.getContext().getTypeAlign(FType);
1233     }
1234 
1235     // We can't know the offset of our ivar in the structure if we're using
1236     // the non-fragile abi and the debugger should ignore the value anyways.
1237     // Call it the FieldNo+1 due to how debuggers use the information,
1238     // e.g. negating the value when it needs a lookup in the dynamic table.
1239     uint64_t FieldOffset = CGM.getLangOptions().ObjCNonFragileABI ? FieldNo+1
1240       : RL.getFieldOffset(FieldNo);
1241 
1242     unsigned Flags = 0;
1243     if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1244       Flags = llvm::DIDescriptor::FlagProtected;
1245     else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1246       Flags = llvm::DIDescriptor::FlagPrivate;
1247 
1248     StringRef PropertyName;
1249     StringRef PropertyGetter;
1250     StringRef PropertySetter;
1251     unsigned PropertyAttributes = 0;
1252     ObjCPropertyDecl *PD = NULL;
1253     if (ImpD)
1254       if (ObjCPropertyImplDecl *PImpD =
1255           ImpD->FindPropertyImplIvarDecl(Field->getIdentifier()))
1256         PD = PImpD->getPropertyDecl();
1257     if (PD) {
1258       PropertyName = PD->getName();
1259       PropertyGetter = getSelectorName(PD->getGetterName());
1260       PropertySetter = getSelectorName(PD->getSetterName());
1261       PropertyAttributes = PD->getPropertyAttributes();
1262     }
1263     FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit,
1264                                       FieldLine, FieldSize, FieldAlign,
1265                                       FieldOffset, Flags, FieldTy,
1266                                       PropertyName, PropertyGetter,
1267                                       PropertySetter, PropertyAttributes);
1268     EltTys.push_back(FieldTy);
1269   }
1270 
1271   llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
1272 
1273   LexicalBlockStack.pop_back();
1274   llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator RI =
1275     RegionMap.find(Ty->getDecl());
1276   if (RI != RegionMap.end())
1277     RegionMap.erase(RI);
1278 
1279   // Bit size, align and offset of the type.
1280   uint64_t Size = CGM.getContext().getTypeSize(Ty);
1281   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1282 
1283   unsigned Flags = 0;
1284   if (ID->getImplementation())
1285     Flags |= llvm::DIDescriptor::FlagObjcClassComplete;
1286 
1287   llvm::DIType RealDecl =
1288     DBuilder.createStructType(Unit, ID->getName(), DefUnit,
1289                                   Line, Size, Align, Flags,
1290                                   Elements, RuntimeLang);
1291 
1292   // Now that we have a real decl for the struct, replace anything using the
1293   // old decl with the new one.  This will recursively update the debug info.
1294   llvm::DIType(FwdDeclNode).replaceAllUsesWith(RealDecl);
1295   RegionMap[ID] = llvm::WeakVH(RealDecl);
1296 
1297   return RealDecl;
1298 }
1299 
1300 llvm::DIType CGDebugInfo::CreateType(const TagType *Ty) {
1301   if (const RecordType *RT = dyn_cast<RecordType>(Ty))
1302     return CreateType(RT);
1303   else if (const EnumType *ET = dyn_cast<EnumType>(Ty))
1304     return CreateEnumType(ET->getDecl());
1305 
1306   return llvm::DIType();
1307 }
1308 
1309 llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty,
1310                                      llvm::DIFile Unit) {
1311   llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1312   int64_t NumElems = Ty->getNumElements();
1313   int64_t LowerBound = 0;
1314   if (NumElems == 0)
1315     // If number of elements are not known then this is an unbounded array.
1316     // Use Low = 1, Hi = 0 to express such arrays.
1317     LowerBound = 1;
1318   else
1319     --NumElems;
1320 
1321   llvm::Value *Subscript = DBuilder.getOrCreateSubrange(LowerBound, NumElems);
1322   llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1323 
1324   uint64_t Size = CGM.getContext().getTypeSize(Ty);
1325   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1326 
1327   return
1328     DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1329 }
1330 
1331 llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1332                                      llvm::DIFile Unit) {
1333   uint64_t Size;
1334   uint64_t Align;
1335 
1336 
1337   // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1338   if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1339     Size = 0;
1340     Align =
1341       CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1342   } else if (Ty->isIncompleteArrayType()) {
1343     Size = 0;
1344     Align = CGM.getContext().getTypeAlign(Ty->getElementType());
1345   } else if (Ty->isDependentSizedArrayType() || Ty->isIncompleteType()) {
1346     Size = 0;
1347     Align = 0;
1348   } else {
1349     // Size and align of the whole array, not the element type.
1350     Size = CGM.getContext().getTypeSize(Ty);
1351     Align = CGM.getContext().getTypeAlign(Ty);
1352   }
1353 
1354   // Add the dimensions of the array.  FIXME: This loses CV qualifiers from
1355   // interior arrays, do we care?  Why aren't nested arrays represented the
1356   // obvious/recursive way?
1357   SmallVector<llvm::Value *, 8> Subscripts;
1358   QualType EltTy(Ty, 0);
1359   if (Ty->isIncompleteArrayType())
1360     EltTy = Ty->getElementType();
1361   else {
1362     while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1363       int64_t UpperBound = 0;
1364       int64_t LowerBound = 0;
1365       if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty)) {
1366         if (CAT->getSize().getZExtValue())
1367           UpperBound = CAT->getSize().getZExtValue() - 1;
1368       } else
1369         // This is an unbounded array. Use Low = 1, Hi = 0 to express such
1370         // arrays.
1371         LowerBound = 1;
1372 
1373       // FIXME: Verify this is right for VLAs.
1374       Subscripts.push_back(DBuilder.getOrCreateSubrange(LowerBound,
1375                                                         UpperBound));
1376       EltTy = Ty->getElementType();
1377     }
1378   }
1379 
1380   llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1381 
1382   llvm::DIType DbgTy =
1383     DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1384                              SubscriptArray);
1385   return DbgTy;
1386 }
1387 
1388 llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
1389                                      llvm::DIFile Unit) {
1390   return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
1391                                Ty, Ty->getPointeeType(), Unit);
1392 }
1393 
1394 llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
1395                                      llvm::DIFile Unit) {
1396   return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type,
1397                                Ty, Ty->getPointeeType(), Unit);
1398 }
1399 
1400 llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
1401                                      llvm::DIFile U) {
1402   QualType PointerDiffTy = CGM.getContext().getPointerDiffType();
1403   llvm::DIType PointerDiffDITy = getOrCreateType(PointerDiffTy, U);
1404 
1405   if (!Ty->getPointeeType()->isFunctionType()) {
1406     // We have a data member pointer type.
1407     return PointerDiffDITy;
1408   }
1409 
1410   // We have a member function pointer type. Treat it as a struct with two
1411   // ptrdiff_t members.
1412   std::pair<uint64_t, unsigned> Info = CGM.getContext().getTypeInfo(Ty);
1413 
1414   uint64_t FieldOffset = 0;
1415   llvm::Value *ElementTypes[2];
1416 
1417   // FIXME: This should probably be a function type instead.
1418   ElementTypes[0] =
1419     DBuilder.createMemberType(U, "ptr", U, 0,
1420                               Info.first, Info.second, FieldOffset, 0,
1421                               PointerDiffDITy);
1422   FieldOffset += Info.first;
1423 
1424   ElementTypes[1] =
1425     DBuilder.createMemberType(U, "ptr", U, 0,
1426                               Info.first, Info.second, FieldOffset, 0,
1427                               PointerDiffDITy);
1428 
1429   llvm::DIArray Elements = DBuilder.getOrCreateArray(ElementTypes);
1430 
1431   return DBuilder.createStructType(U, StringRef("test"),
1432                                    U, 0, FieldOffset,
1433                                    0, 0, Elements);
1434 }
1435 
1436 llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty,
1437                                      llvm::DIFile U) {
1438   // Ignore the atomic wrapping
1439   // FIXME: What is the correct representation?
1440   return getOrCreateType(Ty->getValueType(), U);
1441 }
1442 
1443 /// CreateEnumType - get enumeration type.
1444 llvm::DIType CGDebugInfo::CreateEnumType(const EnumDecl *ED) {
1445   llvm::DIFile Unit = getOrCreateFile(ED->getLocation());
1446   SmallVector<llvm::Value *, 16> Enumerators;
1447 
1448   // Create DIEnumerator elements for each enumerator.
1449   for (EnumDecl::enumerator_iterator
1450          Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
1451        Enum != EnumEnd; ++Enum) {
1452     Enumerators.push_back(
1453       DBuilder.createEnumerator(Enum->getName(),
1454                                 Enum->getInitVal().getZExtValue()));
1455   }
1456 
1457   // Return a CompositeType for the enum itself.
1458   llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1459 
1460   llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1461   unsigned Line = getLineNumber(ED->getLocation());
1462   uint64_t Size = 0;
1463   uint64_t Align = 0;
1464   if (!ED->getTypeForDecl()->isIncompleteType()) {
1465     Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1466     Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1467   }
1468   llvm::DIDescriptor EnumContext =
1469     getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1470   llvm::DIType DbgTy =
1471     DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1472                                    Size, Align, EltArray);
1473   return DbgTy;
1474 }
1475 
1476 static QualType UnwrapTypeForDebugInfo(QualType T) {
1477   do {
1478     QualType LastT = T;
1479     switch (T->getTypeClass()) {
1480     default:
1481       return T;
1482     case Type::TemplateSpecialization:
1483       T = cast<TemplateSpecializationType>(T)->desugar();
1484       break;
1485     case Type::TypeOfExpr:
1486       T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1487       break;
1488     case Type::TypeOf:
1489       T = cast<TypeOfType>(T)->getUnderlyingType();
1490       break;
1491     case Type::Decltype:
1492       T = cast<DecltypeType>(T)->getUnderlyingType();
1493       break;
1494     case Type::UnaryTransform:
1495       T = cast<UnaryTransformType>(T)->getUnderlyingType();
1496       break;
1497     case Type::Attributed:
1498       T = cast<AttributedType>(T)->getEquivalentType();
1499       break;
1500     case Type::Elaborated:
1501       T = cast<ElaboratedType>(T)->getNamedType();
1502       break;
1503     case Type::Paren:
1504       T = cast<ParenType>(T)->getInnerType();
1505       break;
1506     case Type::SubstTemplateTypeParm:
1507       T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
1508       break;
1509     case Type::Auto:
1510       T = cast<AutoType>(T)->getDeducedType();
1511       break;
1512     }
1513 
1514     assert(T != LastT && "Type unwrapping failed to unwrap!");
1515     if (T == LastT)
1516       return T;
1517   } while (true);
1518 
1519   return T;
1520 }
1521 
1522 /// getOrCreateType - Get the type from the cache or create a new
1523 /// one if necessary.
1524 llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty,
1525                                           llvm::DIFile Unit) {
1526   if (Ty.isNull())
1527     return llvm::DIType();
1528 
1529   // Unwrap the type as needed for debug information.
1530   Ty = UnwrapTypeForDebugInfo(Ty);
1531 
1532   // Check for existing entry.
1533   llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1534     TypeCache.find(Ty.getAsOpaquePtr());
1535   if (it != TypeCache.end()) {
1536     // Verify that the debug info still exists.
1537     if (&*it->second)
1538       return llvm::DIType(cast<llvm::MDNode>(it->second));
1539   }
1540 
1541   // Otherwise create the type.
1542   llvm::DIType Res = CreateTypeNode(Ty, Unit);
1543 
1544   // And update the type cache.
1545   TypeCache[Ty.getAsOpaquePtr()] = Res;
1546   return Res;
1547 }
1548 
1549 /// CreateTypeNode - Create a new debug type node.
1550 llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty,
1551                                          llvm::DIFile Unit) {
1552   // Handle qualifiers, which recursively handles what they refer to.
1553   if (Ty.hasLocalQualifiers())
1554     return CreateQualifiedType(Ty, Unit);
1555 
1556   const char *Diag = 0;
1557 
1558   // Work out details of type.
1559   switch (Ty->getTypeClass()) {
1560 #define TYPE(Class, Base)
1561 #define ABSTRACT_TYPE(Class, Base)
1562 #define NON_CANONICAL_TYPE(Class, Base)
1563 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1564 #include "clang/AST/TypeNodes.def"
1565     llvm_unreachable("Dependent types cannot show up in debug information");
1566 
1567   case Type::ExtVector:
1568   case Type::Vector:
1569     return CreateType(cast<VectorType>(Ty), Unit);
1570   case Type::ObjCObjectPointer:
1571     return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
1572   case Type::ObjCObject:
1573     return CreateType(cast<ObjCObjectType>(Ty), Unit);
1574   case Type::ObjCInterface:
1575     return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
1576   case Type::Builtin: return CreateType(cast<BuiltinType>(Ty));
1577   case Type::Complex: return CreateType(cast<ComplexType>(Ty));
1578   case Type::Pointer: return CreateType(cast<PointerType>(Ty), Unit);
1579   case Type::BlockPointer:
1580     return CreateType(cast<BlockPointerType>(Ty), Unit);
1581   case Type::Typedef: return CreateType(cast<TypedefType>(Ty), Unit);
1582   case Type::Record:
1583   case Type::Enum:
1584     return CreateType(cast<TagType>(Ty));
1585   case Type::FunctionProto:
1586   case Type::FunctionNoProto:
1587     return CreateType(cast<FunctionType>(Ty), Unit);
1588   case Type::ConstantArray:
1589   case Type::VariableArray:
1590   case Type::IncompleteArray:
1591     return CreateType(cast<ArrayType>(Ty), Unit);
1592 
1593   case Type::LValueReference:
1594     return CreateType(cast<LValueReferenceType>(Ty), Unit);
1595   case Type::RValueReference:
1596     return CreateType(cast<RValueReferenceType>(Ty), Unit);
1597 
1598   case Type::MemberPointer:
1599     return CreateType(cast<MemberPointerType>(Ty), Unit);
1600 
1601   case Type::Atomic:
1602     return CreateType(cast<AtomicType>(Ty), Unit);
1603 
1604   case Type::Attributed:
1605   case Type::TemplateSpecialization:
1606   case Type::Elaborated:
1607   case Type::Paren:
1608   case Type::SubstTemplateTypeParm:
1609   case Type::TypeOfExpr:
1610   case Type::TypeOf:
1611   case Type::Decltype:
1612   case Type::UnaryTransform:
1613   case Type::Auto:
1614     llvm_unreachable("type should have been unwrapped!");
1615     return llvm::DIType();
1616   }
1617 
1618   assert(Diag && "Fall through without a diagnostic?");
1619   unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error,
1620                                "debug information for %0 is not yet supported");
1621   CGM.getDiags().Report(DiagID)
1622     << Diag;
1623   return llvm::DIType();
1624 }
1625 
1626 /// CreateMemberType - Create new member and increase Offset by FType's size.
1627 llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
1628                                            StringRef Name,
1629                                            uint64_t *Offset) {
1630   llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1631   uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
1632   unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
1633   llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0,
1634                                               FieldSize, FieldAlign,
1635                                               *Offset, 0, FieldTy);
1636   *Offset += FieldSize;
1637   return Ty;
1638 }
1639 
1640 /// getFunctionDeclaration - Return debug info descriptor to describe method
1641 /// declaration for the given method definition.
1642 llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
1643   const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
1644   if (!FD) return llvm::DISubprogram();
1645 
1646   // Setup context.
1647   getContextDescriptor(cast<Decl>(D->getDeclContext()));
1648 
1649   llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
1650     MI = SPCache.find(FD);
1651   if (MI != SPCache.end()) {
1652     llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(&*MI->second));
1653     if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
1654       return SP;
1655   }
1656 
1657   for (FunctionDecl::redecl_iterator I = FD->redecls_begin(),
1658          E = FD->redecls_end(); I != E; ++I) {
1659     const FunctionDecl *NextFD = *I;
1660     llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
1661       MI = SPCache.find(NextFD);
1662     if (MI != SPCache.end()) {
1663       llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(&*MI->second));
1664       if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
1665         return SP;
1666     }
1667   }
1668   return llvm::DISubprogram();
1669 }
1670 
1671 // getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
1672 // implicit parameter "this".
1673 llvm::DIType CGDebugInfo::getOrCreateFunctionType(const Decl * D,
1674                                                   QualType FnType,
1675                                                   llvm::DIFile F) {
1676   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1677     return getOrCreateMethodType(Method, F);
1678   else if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
1679     // Add "self" and "_cmd"
1680     SmallVector<llvm::Value *, 16> Elts;
1681 
1682     // First element is always return type. For 'void' functions it is NULL.
1683     Elts.push_back(getOrCreateType(OMethod->getResultType(), F));
1684     // "self" pointer is always first argument.
1685     Elts.push_back(getOrCreateType(OMethod->getSelfDecl()->getType(), F));
1686     // "cmd" pointer is always second argument.
1687     Elts.push_back(getOrCreateType(OMethod->getCmdDecl()->getType(), F));
1688     // Get rest of the arguments.
1689     for (ObjCMethodDecl::param_const_iterator PI = OMethod->param_begin(),
1690            PE = OMethod->param_end(); PI != PE; ++PI)
1691       Elts.push_back(getOrCreateType((*PI)->getType(), F));
1692 
1693     llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
1694     return DBuilder.createSubroutineType(F, EltTypeArray);
1695   }
1696   return getOrCreateType(FnType, F);
1697 }
1698 
1699 /// EmitFunctionStart - Constructs the debug code for entering a function -
1700 /// "llvm.dbg.func.start.".
1701 void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
1702                                     llvm::Function *Fn,
1703                                     CGBuilderTy &Builder) {
1704 
1705   StringRef Name;
1706   StringRef LinkageName;
1707 
1708   FnBeginRegionCount.push_back(LexicalBlockStack.size());
1709 
1710   const Decl *D = GD.getDecl();
1711 
1712   unsigned Flags = 0;
1713   llvm::DIFile Unit = getOrCreateFile(CurLoc);
1714   llvm::DIDescriptor FDContext(Unit);
1715   llvm::DIArray TParamsArray;
1716   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1717     // If there is a DISubprogram for  this function available then use it.
1718     llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
1719       FI = SPCache.find(FD);
1720     if (FI != SPCache.end()) {
1721       llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(&*FI->second));
1722       if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
1723         llvm::MDNode *SPN = SP;
1724         LexicalBlockStack.push_back(SPN);
1725         RegionMap[D] = llvm::WeakVH(SP);
1726         return;
1727       }
1728     }
1729     Name = getFunctionName(FD);
1730     // Use mangled name as linkage name for c/c++ functions.
1731     if (!Fn->hasInternalLinkage())
1732       LinkageName = CGM.getMangledName(GD);
1733     if (LinkageName == Name)
1734       LinkageName = StringRef();
1735     if (FD->hasPrototype())
1736       Flags |= llvm::DIDescriptor::FlagPrototyped;
1737     if (const NamespaceDecl *NSDecl =
1738         dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
1739       FDContext = getOrCreateNameSpace(NSDecl);
1740     else if (const RecordDecl *RDecl =
1741              dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
1742       FDContext = getContextDescriptor(cast<Decl>(RDecl->getDeclContext()));
1743 
1744     // Collect template parameters.
1745     TParamsArray = CollectFunctionTemplateParams(FD, Unit);
1746   } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
1747     Name = getObjCMethodName(OMD);
1748     Flags |= llvm::DIDescriptor::FlagPrototyped;
1749   } else {
1750     // Use llvm function name.
1751     Name = Fn->getName();
1752     Flags |= llvm::DIDescriptor::FlagPrototyped;
1753   }
1754   if (!Name.empty() && Name[0] == '\01')
1755     Name = Name.substr(1);
1756 
1757   // It is expected that CurLoc is set before using EmitFunctionStart.
1758   // Usually, CurLoc points to the left bracket location of compound
1759   // statement representing function body.
1760   unsigned LineNo = getLineNumber(CurLoc);
1761   if (D->isImplicit())
1762     Flags |= llvm::DIDescriptor::FlagArtificial;
1763   llvm::DISubprogram SPDecl = getFunctionDeclaration(D);
1764   llvm::DISubprogram SP =
1765     DBuilder.createFunction(FDContext, Name, LinkageName, Unit,
1766                             LineNo, getOrCreateFunctionType(D, FnType, Unit),
1767                             Fn->hasInternalLinkage(), true/*definition*/,
1768                             Flags, CGM.getLangOptions().Optimize, Fn,
1769                             TParamsArray, SPDecl);
1770 
1771   // Push function on region stack.
1772   llvm::MDNode *SPN = SP;
1773   LexicalBlockStack.push_back(SPN);
1774   RegionMap[D] = llvm::WeakVH(SP);
1775 
1776   // Clear stack used to keep track of #line directives.
1777   LineDirectiveFiles.clear();
1778 }
1779 
1780 // UpdateLineDirectiveRegion - Update region stack only if #line directive
1781 // has introduced scope change.
1782 void CGDebugInfo::UpdateLineDirectiveRegion(CGBuilderTy &Builder) {
1783   if (CurLoc.isInvalid() || CurLoc.isMacroID() ||
1784       PrevLoc.isInvalid() || PrevLoc.isMacroID())
1785     return;
1786   SourceManager &SM = CGM.getContext().getSourceManager();
1787   PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
1788   PresumedLoc PPLoc = SM.getPresumedLoc(PrevLoc);
1789 
1790   if (PCLoc.isInvalid() || PPLoc.isInvalid() ||
1791       !strcmp(PPLoc.getFilename(), PCLoc.getFilename()))
1792     return;
1793 
1794   // If #line directive stack is empty then we are entering a new scope.
1795   if (LineDirectiveFiles.empty()) {
1796     EmitLexicalBlockStart(Builder);
1797     LineDirectiveFiles.push_back(PCLoc.getFilename());
1798     return;
1799   }
1800 
1801   assert (LexicalBlockStack.size() >= LineDirectiveFiles.size()
1802           && "error handling #line regions!");
1803 
1804   bool SeenThisFile = false;
1805   // Chek if current file is already seen earlier.
1806   for(std::vector<const char *>::iterator I = LineDirectiveFiles.begin(),
1807         E = LineDirectiveFiles.end(); I != E; ++I)
1808     if (!strcmp(PCLoc.getFilename(), *I)) {
1809       SeenThisFile = true;
1810       break;
1811     }
1812 
1813   // If #line for this file is seen earlier then pop out #line regions.
1814   if (SeenThisFile) {
1815     while (!LineDirectiveFiles.empty()) {
1816       const char *LastFile = LineDirectiveFiles.back();
1817       LexicalBlockStack.pop_back();
1818       LineDirectiveFiles.pop_back();
1819       if (!strcmp(PPLoc.getFilename(), LastFile))
1820         break;
1821     }
1822     return;
1823   }
1824 
1825   // .. otherwise insert new #line region.
1826   EmitLexicalBlockStart(Builder);
1827   LineDirectiveFiles.push_back(PCLoc.getFilename());
1828 
1829   return;
1830 }
1831 
1832 /// EmitLocation - Emit metadata to indicate a change in line/column
1833 /// information in the source file.
1834 void CGDebugInfo::EmitLocation(CGBuilderTy &Builder) {
1835   if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
1836 
1837   // Don't bother if things are the same as last time.
1838   SourceManager &SM = CGM.getContext().getSourceManager();
1839   if (CurLoc == PrevLoc ||
1840       SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc))
1841     // New Builder may not be in sync with CGDebugInfo.
1842     if (!Builder.getCurrentDebugLocation().isUnknown())
1843       return;
1844 
1845   // The file may have had a line directive change. Process any of
1846   // those before updating the state.
1847   UpdateLineDirectiveRegion(Builder);
1848 
1849   // Update last state.
1850   PrevLoc = CurLoc;
1851 
1852   llvm::MDNode *Scope = LexicalBlockStack.back();
1853   Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(CurLoc),
1854                                                       getColumnNumber(CurLoc),
1855                                                       Scope));
1856 }
1857 
1858 /// EmitLexicalBlockStart - Constructs the debug code for entering a declarative
1859 /// region - beginning of a DW_TAG_lexical_block.
1860 void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder) {
1861   llvm::DIDescriptor D =
1862     DBuilder.createLexicalBlock(LexicalBlockStack.empty() ?
1863                                 llvm::DIDescriptor() :
1864                                 llvm::DIDescriptor(LexicalBlockStack.back()),
1865                                 getOrCreateFile(CurLoc),
1866                                 getLineNumber(CurLoc),
1867                                 getColumnNumber(CurLoc));
1868   llvm::MDNode *DN = D;
1869   LexicalBlockStack.push_back(DN);
1870 }
1871 
1872 /// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative
1873 /// region - end of a DW_TAG_lexical_block.
1874 void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder) {
1875   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
1876 
1877   // Provide a region stop point.
1878   EmitLocation(Builder);
1879 
1880   LexicalBlockStack.pop_back();
1881 }
1882 
1883 /// EmitFunctionEnd - Constructs the debug code for exiting a function.
1884 void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
1885   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
1886   unsigned RCount = FnBeginRegionCount.back();
1887   assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
1888 
1889   // Pop all regions for this function.
1890   while (LexicalBlockStack.size() != RCount)
1891     EmitLexicalBlockEnd(Builder);
1892   FnBeginRegionCount.pop_back();
1893 }
1894 
1895 // EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
1896 // See BuildByRefType.
1897 llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const ValueDecl *VD,
1898                                                        uint64_t *XOffset) {
1899 
1900   SmallVector<llvm::Value *, 5> EltTys;
1901   QualType FType;
1902   uint64_t FieldSize, FieldOffset;
1903   unsigned FieldAlign;
1904 
1905   llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
1906   QualType Type = VD->getType();
1907 
1908   FieldOffset = 0;
1909   FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1910   EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
1911   EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
1912   FType = CGM.getContext().IntTy;
1913   EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
1914   EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
1915 
1916   bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type);
1917   if (HasCopyAndDispose) {
1918     FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1919     EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
1920                                       &FieldOffset));
1921     EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
1922                                       &FieldOffset));
1923   }
1924 
1925   CharUnits Align = CGM.getContext().getDeclAlign(VD);
1926   if (Align > CGM.getContext().toCharUnitsFromBits(
1927         CGM.getContext().getTargetInfo().getPointerAlign(0))) {
1928     CharUnits FieldOffsetInBytes
1929       = CGM.getContext().toCharUnitsFromBits(FieldOffset);
1930     CharUnits AlignedOffsetInBytes
1931       = FieldOffsetInBytes.RoundUpToAlignment(Align);
1932     CharUnits NumPaddingBytes
1933       = AlignedOffsetInBytes - FieldOffsetInBytes;
1934 
1935     if (NumPaddingBytes.isPositive()) {
1936       llvm::APInt pad(32, NumPaddingBytes.getQuantity());
1937       FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
1938                                                     pad, ArrayType::Normal, 0);
1939       EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
1940     }
1941   }
1942 
1943   FType = Type;
1944   llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1945   FieldSize = CGM.getContext().getTypeSize(FType);
1946   FieldAlign = CGM.getContext().toBits(Align);
1947 
1948   *XOffset = FieldOffset;
1949   FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit,
1950                                       0, FieldSize, FieldAlign,
1951                                       FieldOffset, 0, FieldTy);
1952   EltTys.push_back(FieldTy);
1953   FieldOffset += FieldSize;
1954 
1955   llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
1956 
1957   unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
1958 
1959   return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
1960                                    Elements);
1961 }
1962 
1963 /// EmitDeclare - Emit local variable declaration debug info.
1964 void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
1965                               llvm::Value *Storage,
1966                               unsigned ArgNo, CGBuilderTy &Builder) {
1967   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
1968 
1969   llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
1970   llvm::DIType Ty;
1971   uint64_t XOffset = 0;
1972   if (VD->hasAttr<BlocksAttr>())
1973     Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
1974   else
1975     Ty = getOrCreateType(VD->getType(), Unit);
1976 
1977   // If there is not any debug info for type then do not emit debug info
1978   // for this variable.
1979   if (!Ty)
1980     return;
1981 
1982   if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage)) {
1983     // If Storage is an aggregate returned as 'sret' then let debugger know
1984     // about this.
1985     if (Arg->hasStructRetAttr())
1986       Ty = DBuilder.createReferenceType(Ty);
1987     else if (CXXRecordDecl *Record = VD->getType()->getAsCXXRecordDecl()) {
1988       // If an aggregate variable has non trivial destructor or non trivial copy
1989       // constructor than it is pass indirectly. Let debug info know about this
1990       // by using reference of the aggregate type as a argument type.
1991       if (!Record->hasTrivialCopyConstructor() ||
1992           !Record->hasTrivialDestructor())
1993         Ty = DBuilder.createReferenceType(Ty);
1994     }
1995   }
1996 
1997   // Get location information.
1998   unsigned Line = getLineNumber(VD->getLocation());
1999   unsigned Column = getColumnNumber(VD->getLocation());
2000   unsigned Flags = 0;
2001   if (VD->isImplicit())
2002     Flags |= llvm::DIDescriptor::FlagArtificial;
2003   llvm::MDNode *Scope = LexicalBlockStack.back();
2004 
2005   StringRef Name = VD->getName();
2006   if (!Name.empty()) {
2007     if (VD->hasAttr<BlocksAttr>()) {
2008       CharUnits offset = CharUnits::fromQuantity(32);
2009       SmallVector<llvm::Value *, 9> addr;
2010       llvm::Type *Int64Ty = llvm::Type::getInt64Ty(CGM.getLLVMContext());
2011       addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2012       // offset of __forwarding field
2013       offset = CGM.getContext().toCharUnitsFromBits(
2014         CGM.getContext().getTargetInfo().getPointerWidth(0));
2015       addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2016       addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2017       addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2018       // offset of x field
2019       offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2020       addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2021 
2022       // Create the descriptor for the variable.
2023       llvm::DIVariable D =
2024         DBuilder.createComplexVariable(Tag,
2025                                        llvm::DIDescriptor(Scope),
2026                                        VD->getName(), Unit, Line, Ty,
2027                                        addr, ArgNo);
2028 
2029       // Insert an llvm.dbg.declare into the current block.
2030       llvm::Instruction *Call =
2031         DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2032 
2033       Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2034       return;
2035     }
2036       // Create the descriptor for the variable.
2037     llvm::DIVariable D =
2038       DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2039                                    Name, Unit, Line, Ty,
2040                                    CGM.getLangOptions().Optimize, Flags, ArgNo);
2041 
2042     // Insert an llvm.dbg.declare into the current block.
2043     llvm::Instruction *Call =
2044       DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2045 
2046     Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2047     return;
2048   }
2049 
2050   // If VD is an anonymous union then Storage represents value for
2051   // all union fields.
2052   if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2053     const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
2054     if (RD->isUnion()) {
2055       for (RecordDecl::field_iterator I = RD->field_begin(),
2056              E = RD->field_end();
2057            I != E; ++I) {
2058         FieldDecl *Field = *I;
2059         llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
2060         StringRef FieldName = Field->getName();
2061 
2062         // Ignore unnamed fields. Do not ignore unnamed records.
2063         if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2064           continue;
2065 
2066         // Use VarDecl's Tag, Scope and Line number.
2067         llvm::DIVariable D =
2068           DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2069                                        FieldName, Unit, Line, FieldTy,
2070                                        CGM.getLangOptions().Optimize, Flags,
2071                                        ArgNo);
2072 
2073         // Insert an llvm.dbg.declare into the current block.
2074         llvm::Instruction *Call =
2075           DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2076 
2077         Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2078       }
2079     }
2080   }
2081 }
2082 
2083 void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2084                                             llvm::Value *Storage,
2085                                             CGBuilderTy &Builder) {
2086   EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2087 }
2088 
2089 void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(
2090   const VarDecl *VD, llvm::Value *Storage, CGBuilderTy &Builder,
2091   const CGBlockInfo &blockInfo) {
2092   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2093 
2094   if (Builder.GetInsertBlock() == 0)
2095     return;
2096 
2097   bool isByRef = VD->hasAttr<BlocksAttr>();
2098 
2099   uint64_t XOffset = 0;
2100   llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2101   llvm::DIType Ty;
2102   if (isByRef)
2103     Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
2104   else
2105     Ty = getOrCreateType(VD->getType(), Unit);
2106 
2107   // Get location information.
2108   unsigned Line = getLineNumber(VD->getLocation());
2109   unsigned Column = getColumnNumber(VD->getLocation());
2110 
2111   const llvm::TargetData &target = CGM.getTargetData();
2112 
2113   CharUnits offset = CharUnits::fromQuantity(
2114     target.getStructLayout(blockInfo.StructureType)
2115           ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2116 
2117   SmallVector<llvm::Value *, 9> addr;
2118   llvm::Type *Int64Ty = llvm::Type::getInt64Ty(CGM.getLLVMContext());
2119   addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2120   addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2121   if (isByRef) {
2122     addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2123     addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2124     // offset of __forwarding field
2125     offset = CGM.getContext()
2126                 .toCharUnitsFromBits(target.getPointerSizeInBits());
2127     addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2128     addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2129     addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2130     // offset of x field
2131     offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2132     addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2133   }
2134 
2135   // Create the descriptor for the variable.
2136   llvm::DIVariable D =
2137     DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable,
2138                                    llvm::DIDescriptor(LexicalBlockStack.back()),
2139                                    VD->getName(), Unit, Line, Ty, addr);
2140   // Insert an llvm.dbg.declare into the current block.
2141   llvm::Instruction *Call =
2142     DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint());
2143 
2144   llvm::MDNode *Scope = LexicalBlockStack.back();
2145   Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2146 }
2147 
2148 /// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
2149 /// variable declaration.
2150 void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2151                                            unsigned ArgNo,
2152                                            CGBuilderTy &Builder) {
2153   EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2154 }
2155 
2156 namespace {
2157   struct BlockLayoutChunk {
2158     uint64_t OffsetInBits;
2159     const BlockDecl::Capture *Capture;
2160   };
2161   bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2162     return l.OffsetInBits < r.OffsetInBits;
2163   }
2164 }
2165 
2166 void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
2167                                                        llvm::Value *addr,
2168                                                        CGBuilderTy &Builder) {
2169   ASTContext &C = CGM.getContext();
2170   const BlockDecl *blockDecl = block.getBlockDecl();
2171 
2172   // Collect some general information about the block's location.
2173   SourceLocation loc = blockDecl->getCaretLocation();
2174   llvm::DIFile tunit = getOrCreateFile(loc);
2175   unsigned line = getLineNumber(loc);
2176   unsigned column = getColumnNumber(loc);
2177 
2178   // Build the debug-info type for the block literal.
2179   getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
2180 
2181   const llvm::StructLayout *blockLayout =
2182     CGM.getTargetData().getStructLayout(block.StructureType);
2183 
2184   SmallVector<llvm::Value*, 16> fields;
2185   fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
2186                                    blockLayout->getElementOffsetInBits(0),
2187                                    tunit, tunit));
2188   fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
2189                                    blockLayout->getElementOffsetInBits(1),
2190                                    tunit, tunit));
2191   fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
2192                                    blockLayout->getElementOffsetInBits(2),
2193                                    tunit, tunit));
2194   fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public,
2195                                    blockLayout->getElementOffsetInBits(3),
2196                                    tunit, tunit));
2197   fields.push_back(createFieldType("__descriptor",
2198                                    C.getPointerType(block.NeedsCopyDispose ?
2199                                         C.getBlockDescriptorExtendedType() :
2200                                         C.getBlockDescriptorType()),
2201                                    0, loc, AS_public,
2202                                    blockLayout->getElementOffsetInBits(4),
2203                                    tunit, tunit));
2204 
2205   // We want to sort the captures by offset, not because DWARF
2206   // requires this, but because we're paranoid about debuggers.
2207   SmallVector<BlockLayoutChunk, 8> chunks;
2208 
2209   // 'this' capture.
2210   if (blockDecl->capturesCXXThis()) {
2211     BlockLayoutChunk chunk;
2212     chunk.OffsetInBits =
2213       blockLayout->getElementOffsetInBits(block.CXXThisIndex);
2214     chunk.Capture = 0;
2215     chunks.push_back(chunk);
2216   }
2217 
2218   // Variable captures.
2219   for (BlockDecl::capture_const_iterator
2220          i = blockDecl->capture_begin(), e = blockDecl->capture_end();
2221        i != e; ++i) {
2222     const BlockDecl::Capture &capture = *i;
2223     const VarDecl *variable = capture.getVariable();
2224     const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
2225 
2226     // Ignore constant captures.
2227     if (captureInfo.isConstant())
2228       continue;
2229 
2230     BlockLayoutChunk chunk;
2231     chunk.OffsetInBits =
2232       blockLayout->getElementOffsetInBits(captureInfo.getIndex());
2233     chunk.Capture = &capture;
2234     chunks.push_back(chunk);
2235   }
2236 
2237   // Sort by offset.
2238   llvm::array_pod_sort(chunks.begin(), chunks.end());
2239 
2240   for (SmallVectorImpl<BlockLayoutChunk>::iterator
2241          i = chunks.begin(), e = chunks.end(); i != e; ++i) {
2242     uint64_t offsetInBits = i->OffsetInBits;
2243     const BlockDecl::Capture *capture = i->Capture;
2244 
2245     // If we have a null capture, this must be the C++ 'this' capture.
2246     if (!capture) {
2247       const CXXMethodDecl *method =
2248         cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
2249       QualType type = method->getThisType(C);
2250 
2251       fields.push_back(createFieldType("this", type, 0, loc, AS_public,
2252                                        offsetInBits, tunit, tunit));
2253       continue;
2254     }
2255 
2256     const VarDecl *variable = capture->getVariable();
2257     StringRef name = variable->getName();
2258 
2259     llvm::DIType fieldType;
2260     if (capture->isByRef()) {
2261       std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy);
2262 
2263       // FIXME: this creates a second copy of this type!
2264       uint64_t xoffset;
2265       fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
2266       fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first);
2267       fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
2268                                             ptrInfo.first, ptrInfo.second,
2269                                             offsetInBits, 0, fieldType);
2270     } else {
2271       fieldType = createFieldType(name, variable->getType(), 0,
2272                                   loc, AS_public, offsetInBits, tunit, tunit);
2273     }
2274     fields.push_back(fieldType);
2275   }
2276 
2277   llvm::SmallString<36> typeName;
2278   llvm::raw_svector_ostream(typeName)
2279     << "__block_literal_" << CGM.getUniqueBlockCount();
2280 
2281   llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
2282 
2283   llvm::DIType type =
2284     DBuilder.createStructType(tunit, typeName.str(), tunit, line,
2285                               CGM.getContext().toBits(block.BlockSize),
2286                               CGM.getContext().toBits(block.BlockAlign),
2287                               0, fieldsArray);
2288   type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
2289 
2290   // Get overall information about the block.
2291   unsigned flags = llvm::DIDescriptor::FlagArtificial;
2292   llvm::MDNode *scope = LexicalBlockStack.back();
2293   StringRef name = ".block_descriptor";
2294 
2295   // Create the descriptor for the parameter.
2296   llvm::DIVariable debugVar =
2297     DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
2298                                  llvm::DIDescriptor(scope),
2299                                  name, tunit, line, type,
2300                                  CGM.getLangOptions().Optimize, flags,
2301                                  cast<llvm::Argument>(addr)->getArgNo() + 1);
2302 
2303   // Insert an llvm.dbg.value into the current block.
2304   llvm::Instruction *declare =
2305     DBuilder.insertDbgValueIntrinsic(addr, 0, debugVar,
2306                                      Builder.GetInsertBlock());
2307   declare->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
2308 }
2309 
2310 /// EmitGlobalVariable - Emit information about a global variable.
2311 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
2312                                      const VarDecl *D) {
2313 
2314   // Create global variable debug descriptor.
2315   llvm::DIFile Unit = getOrCreateFile(D->getLocation());
2316   unsigned LineNo = getLineNumber(D->getLocation());
2317 
2318   QualType T = D->getType();
2319   if (T->isIncompleteArrayType()) {
2320 
2321     // CodeGen turns int[] into int[1] so we'll do the same here.
2322     llvm::APSInt ConstVal(32);
2323 
2324     ConstVal = 1;
2325     QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
2326 
2327     T = CGM.getContext().getConstantArrayType(ET, ConstVal,
2328                                            ArrayType::Normal, 0);
2329   }
2330   StringRef DeclName = D->getName();
2331   StringRef LinkageName;
2332   if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext())
2333       && !isa<ObjCMethodDecl>(D->getDeclContext()))
2334     LinkageName = Var->getName();
2335   if (LinkageName == DeclName)
2336     LinkageName = StringRef();
2337   llvm::DIDescriptor DContext =
2338     getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
2339   DBuilder.createStaticVariable(DContext, DeclName, LinkageName,
2340                                 Unit, LineNo, getOrCreateType(T, Unit),
2341                                 Var->hasInternalLinkage(), Var);
2342 }
2343 
2344 /// EmitGlobalVariable - Emit information about an objective-c interface.
2345 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
2346                                      ObjCInterfaceDecl *ID) {
2347   // Create global variable debug descriptor.
2348   llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
2349   unsigned LineNo = getLineNumber(ID->getLocation());
2350 
2351   StringRef Name = ID->getName();
2352 
2353   QualType T = CGM.getContext().getObjCInterfaceType(ID);
2354   if (T->isIncompleteArrayType()) {
2355 
2356     // CodeGen turns int[] into int[1] so we'll do the same here.
2357     llvm::APSInt ConstVal(32);
2358 
2359     ConstVal = 1;
2360     QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
2361 
2362     T = CGM.getContext().getConstantArrayType(ET, ConstVal,
2363                                            ArrayType::Normal, 0);
2364   }
2365 
2366   DBuilder.createGlobalVariable(Name, Unit, LineNo,
2367                                 getOrCreateType(T, Unit),
2368                                 Var->hasInternalLinkage(), Var);
2369 }
2370 
2371 /// EmitGlobalVariable - Emit global variable's debug info.
2372 void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
2373                                      llvm::Constant *Init) {
2374   // Create the descriptor for the variable.
2375   llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2376   StringRef Name = VD->getName();
2377   llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
2378   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
2379     if (const EnumDecl *ED = dyn_cast<EnumDecl>(ECD->getDeclContext()))
2380       Ty = CreateEnumType(ED);
2381   }
2382   // Do not use DIGlobalVariable for enums.
2383   if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
2384     return;
2385   DBuilder.createStaticVariable(Unit, Name, Name, Unit,
2386                                 getLineNumber(VD->getLocation()),
2387                                 Ty, true, Init);
2388 }
2389 
2390 /// getOrCreateNamesSpace - Return namespace descriptor for the given
2391 /// namespace decl.
2392 llvm::DINameSpace
2393 CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
2394   llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
2395     NameSpaceCache.find(NSDecl);
2396   if (I != NameSpaceCache.end())
2397     return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
2398 
2399   unsigned LineNo = getLineNumber(NSDecl->getLocation());
2400   llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
2401   llvm::DIDescriptor Context =
2402     getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
2403   llvm::DINameSpace NS =
2404     DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
2405   NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
2406   return NS;
2407 }
2408 
2409 /// UpdateCompletedType - Update type cache because the type is now
2410 /// translated.
2411 void CGDebugInfo::UpdateCompletedType(const TagDecl *TD) {
2412   QualType Ty = CGM.getContext().getTagDeclType(TD);
2413 
2414   // If the type exist in type cache then remove it from the cache.
2415   // There is no need to prepare debug info for the completed type
2416   // right now. It will be generated on demand lazily.
2417   llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
2418     TypeCache.find(Ty.getAsOpaquePtr());
2419   if (it != TypeCache.end())
2420     TypeCache.erase(it);
2421 }
2422