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