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