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