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