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