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