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