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