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