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