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