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