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