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