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