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