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