blob: 6965c4a1209c229f7da95fbfc09745621b446ede [file] [log] [blame]
Guy Benyei11169dd2012-12-18 14:30:41 +00001//===--- CGDebugInfo.cpp - Emit Debug Information for a Module ------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Guy Benyei11169dd2012-12-18 14:30:41 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This coordinates the debug information generation while generating code.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CGDebugInfo.h"
14#include "CGBlocks.h"
David Blaikie38079fd2013-05-10 21:53:14 +000015#include "CGCXXABI.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000016#include "CGObjCRuntime.h"
Bob Haarmandff36732016-10-25 22:19:32 +000017#include "CGRecordLayout.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000018#include "CodeGenFunction.h"
19#include "CodeGenModule.h"
John McCallde0fe072017-08-15 21:42:52 +000020#include "ConstantEmitter.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000021#include "clang/AST/ASTContext.h"
Reid Kleckner98031782019-12-09 16:11:56 -080022#include "clang/AST/Attr.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000023#include "clang/AST/DeclFriend.h"
24#include "clang/AST/DeclObjC.h"
25#include "clang/AST/DeclTemplate.h"
26#include "clang/AST/Expr.h"
27#include "clang/AST/RecordLayout.h"
Richard Trieu63688182018-12-11 03:18:39 +000028#include "clang/Basic/CodeGenOptions.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000029#include "clang/Basic/FileManager.h"
30#include "clang/Basic/SourceManager.h"
31#include "clang/Basic/Version.h"
Taewook Oh0fb5b782017-08-16 19:36:24 +000032#include "clang/Frontend/FrontendOptions.h"
Adrian Prantlc4bb47e2015-06-30 17:39:51 +000033#include "clang/Lex/HeaderSearchOptions.h"
Adrian Prantl9402cef2015-09-20 16:51:35 +000034#include "clang/Lex/ModuleMap.h"
Adrian Prantlc4bb47e2015-06-30 17:39:51 +000035#include "clang/Lex/PreprocessorOptions.h"
Bob Haarmandff36732016-10-25 22:19:32 +000036#include "llvm/ADT/DenseSet.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000037#include "llvm/ADT/SmallVector.h"
38#include "llvm/ADT/StringExtras.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000039#include "llvm/IR/Constants.h"
40#include "llvm/IR/DataLayout.h"
41#include "llvm/IR/DerivedTypes.h"
42#include "llvm/IR/Instructions.h"
43#include "llvm/IR/Intrinsics.h"
Matthew Voss20165362018-10-03 18:45:04 +000044#include "llvm/IR/Metadata.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000045#include "llvm/IR/Module.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000046#include "llvm/Support/FileSystem.h"
Amjad Aboude2aab8c2016-12-25 10:12:27 +000047#include "llvm/Support/MD5.h"
Adrian Prantl0630eb72013-12-18 21:48:18 +000048#include "llvm/Support/Path.h"
Luboš Luňák4f2104c2019-11-02 16:39:59 +010049#include "llvm/Support/TimeProfiler.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000050using namespace clang;
51using namespace clang::CodeGen;
52
Victor Leschuka7ece032016-10-20 00:13:19 +000053static uint32_t getTypeAlignIfRequired(const Type *Ty, const ASTContext &Ctx) {
54 auto TI = Ctx.getTypeInfo(Ty);
55 return TI.AlignIsRequired ? TI.Align : 0;
56}
57
58static uint32_t getTypeAlignIfRequired(QualType Ty, const ASTContext &Ctx) {
59 return getTypeAlignIfRequired(Ty.getTypePtr(), Ctx);
60}
61
62static uint32_t getDeclAlignIfRequired(const Decl *D, const ASTContext &Ctx) {
63 return D->hasAttr<AlignedAttr>() ? D->getMaxAlignment() : 0;
64}
65
Guy Benyei11169dd2012-12-18 14:30:41 +000066CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
Eric Christopher324bbbd2013-07-14 21:12:44 +000067 : CGM(CGM), DebugKind(CGM.getCodeGenOpts().getDebugInfo()),
Adrian Prantl6b21ab22015-08-27 19:46:20 +000068 DebugTypeExtRefs(CGM.getCodeGenOpts().DebugTypeExtRefs),
Eric Christopher324bbbd2013-07-14 21:12:44 +000069 DBuilder(CGM.getModule()) {
Saleem Abdulrasool436256a2015-10-12 20:21:08 +000070 for (const auto &KV : CGM.getCodeGenOpts().DebugPrefixMap)
71 DebugPrefixMap[KV.first] = KV.second;
Guy Benyei11169dd2012-12-18 14:30:41 +000072 CreateCompileUnit();
73}
74
75CGDebugInfo::~CGDebugInfo() {
76 assert(LexicalBlockStack.empty() &&
77 "Region stack mismatch, stack not empty!");
78}
79
David Blaikie66e41972015-01-14 07:38:27 +000080ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF,
Calixte Denizetfcd661d2018-09-24 18:24:18 +000081 SourceLocation TemporaryLocation)
David Blaikied7057d92015-08-12 23:49:57 +000082 : CGF(&CGF) {
Calixte Denizetfcd661d2018-09-24 18:24:18 +000083 init(TemporaryLocation);
David Blaikie9b479662015-01-25 01:19:10 +000084}
85
Adrian Prantl39428e72015-02-03 18:40:42 +000086ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF,
Adrian Prantl95b24e92015-02-03 20:00:54 +000087 bool DefaultToEmpty,
Calixte Denizetfcd661d2018-09-24 18:24:18 +000088 SourceLocation TemporaryLocation)
David Blaikied7057d92015-08-12 23:49:57 +000089 : CGF(&CGF) {
Calixte Denizetfcd661d2018-09-24 18:24:18 +000090 init(TemporaryLocation, DefaultToEmpty);
Adrian Prantl39428e72015-02-03 18:40:42 +000091}
92
93void ApplyDebugLocation::init(SourceLocation TemporaryLocation,
Calixte Denizetfcd661d2018-09-24 18:24:18 +000094 bool DefaultToEmpty) {
David Blaikied7057d92015-08-12 23:49:57 +000095 auto *DI = CGF->getDebugInfo();
96 if (!DI) {
97 CGF = nullptr;
98 return;
David Blaikie66e41972015-01-14 07:38:27 +000099 }
David Blaikied7057d92015-08-12 23:49:57 +0000100
101 OriginalLocation = CGF->Builder.getCurrentDebugLocation();
Bob Haarmanc6c9b8f2017-09-11 22:11:57 +0000102
103 if (OriginalLocation && !DI->CGM.getExpressionLocationsEnabled())
104 return;
105
David Blaikied7057d92015-08-12 23:49:57 +0000106 if (TemporaryLocation.isValid()) {
Calixte Denizetfcd661d2018-09-24 18:24:18 +0000107 DI->EmitLocation(CGF->Builder, TemporaryLocation);
David Blaikied7057d92015-08-12 23:49:57 +0000108 return;
109 }
110
111 if (DefaultToEmpty) {
112 CGF->Builder.SetCurrentDebugLocation(llvm::DebugLoc());
113 return;
114 }
115
116 // Construct a location that has a valid scope, but no line info.
117 assert(!DI->LexicalBlockStack.empty());
Adrian Prantlb7acfc02017-02-27 21:30:05 +0000118 CGF->Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(
119 0, 0, DI->LexicalBlockStack.back(), DI->getInlinedAt()));
Adrian Prantl2e0637f2013-07-18 00:28:02 +0000120}
121
David Blaikie9b479662015-01-25 01:19:10 +0000122ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, const Expr *E)
David Blaikied7057d92015-08-12 23:49:57 +0000123 : CGF(&CGF) {
David Blaikie9b479662015-01-25 01:19:10 +0000124 init(E->getExprLoc());
125}
126
David Blaikie66e41972015-01-14 07:38:27 +0000127ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, llvm::DebugLoc Loc)
David Blaikied7057d92015-08-12 23:49:57 +0000128 : CGF(&CGF) {
129 if (!CGF.getDebugInfo()) {
130 this->CGF = nullptr;
131 return;
David Blaikie66e41972015-01-14 07:38:27 +0000132 }
David Blaikied7057d92015-08-12 23:49:57 +0000133 OriginalLocation = CGF.Builder.getCurrentDebugLocation();
134 if (Loc)
135 CGF.Builder.SetCurrentDebugLocation(std::move(Loc));
David Blaikie66e41972015-01-14 07:38:27 +0000136}
137
138ApplyDebugLocation::~ApplyDebugLocation() {
139 // Query CGF so the location isn't overwritten when location updates are
140 // temporarily disabled (for C++ default function arguments)
David Blaikied7057d92015-08-12 23:49:57 +0000141 if (CGF)
142 CGF->Builder.SetCurrentDebugLocation(std::move(OriginalLocation));
David Blaikie66e41972015-01-14 07:38:27 +0000143}
144
Adrian Prantlb7acfc02017-02-27 21:30:05 +0000145ApplyInlineDebugLocation::ApplyInlineDebugLocation(CodeGenFunction &CGF,
146 GlobalDecl InlinedFn)
147 : CGF(&CGF) {
148 if (!CGF.getDebugInfo()) {
149 this->CGF = nullptr;
150 return;
151 }
152 auto &DI = *CGF.getDebugInfo();
153 SavedLocation = DI.getLocation();
154 assert((DI.getInlinedAt() ==
155 CGF.Builder.getCurrentDebugLocation()->getInlinedAt()) &&
156 "CGDebugInfo and IRBuilder are out of sync");
157
158 DI.EmitInlineFunctionStart(CGF.Builder, InlinedFn);
159}
160
161ApplyInlineDebugLocation::~ApplyInlineDebugLocation() {
162 if (!CGF)
163 return;
164 auto &DI = *CGF->getDebugInfo();
165 DI.EmitInlineFunctionEnd(CGF->Builder);
166 DI.EmitLocation(CGF->Builder, SavedLocation);
167}
168
Guy Benyei11169dd2012-12-18 14:30:41 +0000169void CGDebugInfo::setLocation(SourceLocation Loc) {
170 // If the new location isn't valid return.
Eric Christophere7b87e52014-10-26 23:40:33 +0000171 if (Loc.isInvalid())
172 return;
Guy Benyei11169dd2012-12-18 14:30:41 +0000173
174 CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc);
175
176 // If we've changed files in the middle of a lexical scope go ahead
177 // and create a new lexical scope with file node if it's different
178 // from the one in the scope.
Eric Christophere7b87e52014-10-26 23:40:33 +0000179 if (LexicalBlockStack.empty())
180 return;
Guy Benyei11169dd2012-12-18 14:30:41 +0000181
182 SourceManager &SM = CGM.getContext().getSourceManager();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +0000183 auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
Guy Benyei11169dd2012-12-18 14:30:41 +0000184 PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
Adrian Prantl212c1042018-12-06 18:44:50 +0000185 if (PCLoc.isInvalid() || Scope->getFile() == getOrCreateFile(CurLoc))
Guy Benyei11169dd2012-12-18 14:30:41 +0000186 return;
187
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +0000188 if (auto *LBF = dyn_cast<llvm::DILexicalBlockFile>(Scope)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000189 LexicalBlockStack.pop_back();
Duncan P. N. Exon Smithd899f6e2015-04-18 00:07:30 +0000190 LexicalBlockStack.emplace_back(DBuilder.createLexicalBlockFile(
191 LBF->getScope(), getOrCreateFile(CurLoc)));
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +0000192 } else if (isa<llvm::DILexicalBlock>(Scope) ||
193 isa<llvm::DISubprogram>(Scope)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000194 LexicalBlockStack.pop_back();
Duncan P. N. Exon Smithd899f6e2015-04-18 00:07:30 +0000195 LexicalBlockStack.emplace_back(
196 DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000197 }
198}
199
Adrian Prantl6ec370a2015-09-10 18:39:45 +0000200llvm::DIScope *CGDebugInfo::getDeclContextDescriptor(const Decl *D) {
Adrian Prantl5c8bd882015-09-11 17:23:08 +0000201 llvm::DIScope *Mod = getParentModuleOrNull(D);
202 return getContextDescriptor(cast<Decl>(D->getDeclContext()),
203 Mod ? Mod : TheCU);
Adrian Prantl6ec370a2015-09-10 18:39:45 +0000204}
205
206llvm::DIScope *CGDebugInfo::getContextDescriptor(const Decl *Context,
207 llvm::DIScope *Default) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000208 if (!Context)
Adrian Prantl6ec370a2015-09-10 18:39:45 +0000209 return Default;
Guy Benyei11169dd2012-12-18 14:30:41 +0000210
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +0000211 auto I = RegionMap.find(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +0000212 if (I != RegionMap.end()) {
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +0000213 llvm::Metadata *V = I->second;
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +0000214 return dyn_cast_or_null<llvm::DIScope>(V);
Guy Benyei11169dd2012-12-18 14:30:41 +0000215 }
216
217 // Check namespace.
Adrian Prantlddb8e062017-05-12 16:23:53 +0000218 if (const auto *NSDecl = dyn_cast<NamespaceDecl>(Context))
219 return getOrCreateNamespace(NSDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +0000220
David Majnemer58ed0f32016-07-17 00:39:12 +0000221 if (const auto *RDecl = dyn_cast<RecordDecl>(Context))
David Blaikiebfa52742013-04-19 06:56:38 +0000222 if (!RDecl->isDependentType())
223 return getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
Adrian Prantlc2a44ec2018-12-11 16:58:46 +0000224 TheCU->getFile());
Adrian Prantl6ec370a2015-09-10 18:39:45 +0000225 return Default;
Guy Benyei11169dd2012-12-18 14:30:41 +0000226}
227
Reid Kleckner59d12202017-08-08 01:33:53 +0000228PrintingPolicy CGDebugInfo::getPrintingPolicy() const {
229 PrintingPolicy PP = CGM.getContext().getPrintingPolicy();
230
231 // If we're emitting codeview, it's important to try to match MSVC's naming so
232 // that visualizers written for MSVC will trigger for our class names. In
233 // particular, we can't have spaces between arguments of standard templates
Adrian McCarthya549c0d2020-05-01 15:51:02 -0700234 // like basic_string and vector, but we must have spaces between consecutive
235 // angle brackets that close nested template argument lists.
236 if (CGM.getCodeGenOpts().EmitCodeView) {
Reid Kleckner59d12202017-08-08 01:33:53 +0000237 PP.MSVCFormatting = true;
Adrian McCarthya549c0d2020-05-01 15:51:02 -0700238 PP.SplitTemplateClosers = true;
Sam McCalld283fc42020-05-26 15:43:52 +0200239 } else {
240 // For DWARF, printing rules are underspecified.
241 // SplitTemplateClosers yields better interop with GCC and GDB (PR46052).
242 PP.SplitTemplateClosers = true;
Adrian McCarthya549c0d2020-05-01 15:51:02 -0700243 }
Reid Kleckner59d12202017-08-08 01:33:53 +0000244
Adrian Prantl56acd5a2018-12-05 18:37:44 +0000245 // Apply -fdebug-prefix-map.
Richard Smithdbcb6902019-10-15 17:51:08 -0700246 PP.Callbacks = &PrintCB;
Reid Kleckner59d12202017-08-08 01:33:53 +0000247 return PP;
248}
249
Guy Benyei11169dd2012-12-18 14:30:41 +0000250StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
Eric Christophere7b87e52014-10-26 23:40:33 +0000251 assert(FD && "Invalid FunctionDecl!");
Guy Benyei11169dd2012-12-18 14:30:41 +0000252 IdentifierInfo *FII = FD->getIdentifier();
Eric Christophere7b87e52014-10-26 23:40:33 +0000253 FunctionTemplateSpecializationInfo *Info =
254 FD->getTemplateSpecializationInfo();
Reid Kleckner60103382015-12-16 02:04:40 +0000255
Reid Kleckner31abd802016-06-30 17:41:31 +0000256 // Emit the unqualified name in normal operation. LLVM and the debugger can
257 // compute the fully qualified name from the scope chain. If we're only
258 // emitting line table info, there won't be any scope chains, so emit the
259 // fully qualified name here so that stack traces are more accurate.
260 // FIXME: Do this when emitting DWARF as well as when emitting CodeView after
261 // evaluating the size impact.
262 bool UseQualifiedName = DebugKind == codegenoptions::DebugLineTablesOnly &&
263 CGM.getCodeGenOpts().EmitCodeView;
264
265 if (!Info && FII && !UseQualifiedName)
Guy Benyei11169dd2012-12-18 14:30:41 +0000266 return FII->getName();
267
Benjamin Kramer9170e912013-02-22 15:46:01 +0000268 SmallString<128> NS;
269 llvm::raw_svector_ostream OS(NS);
Reid Kleckner31abd802016-06-30 17:41:31 +0000270 if (!UseQualifiedName)
271 FD->printName(OS);
272 else
Reid Kleckner59d12202017-08-08 01:33:53 +0000273 FD->printQualifiedName(OS, getPrintingPolicy());
Guy Benyei11169dd2012-12-18 14:30:41 +0000274
Reid Kleckner829398e2016-06-17 16:11:20 +0000275 // Add any template specialization args.
276 if (Info) {
277 const TemplateArgumentList *TArgs = Info->TemplateArguments;
Serge Pavlov03e672c2017-11-28 16:14:14 +0000278 printTemplateArgumentList(OS, TArgs->asArray(), getPrintingPolicy());
Guy Benyei11169dd2012-12-18 14:30:41 +0000279 }
280
281 // Copy this name on the side and use its reference.
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +0000282 return internString(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +0000283}
284
285StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
286 SmallString<256> MethodName;
287 llvm::raw_svector_ostream OS(MethodName);
288 OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
289 const DeclContext *DC = OMD->getDeclContext();
David Majnemer58ed0f32016-07-17 00:39:12 +0000290 if (const auto *OID = dyn_cast<ObjCImplementationDecl>(DC)) {
Eric Christophere7b87e52014-10-26 23:40:33 +0000291 OS << OID->getName();
David Majnemer58ed0f32016-07-17 00:39:12 +0000292 } else if (const auto *OID = dyn_cast<ObjCInterfaceDecl>(DC)) {
Eric Christophere7b87e52014-10-26 23:40:33 +0000293 OS << OID->getName();
David Majnemer58ed0f32016-07-17 00:39:12 +0000294 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(DC)) {
Douglas Gregoracf4fd32015-11-03 01:15:46 +0000295 if (OC->IsClassExtension()) {
296 OS << OC->getClassInterface()->getName();
297 } else {
David Majnemer58ed0f32016-07-17 00:39:12 +0000298 OS << OC->getIdentifier()->getNameStart() << '('
Douglas Gregoracf4fd32015-11-03 01:15:46 +0000299 << OC->getIdentifier()->getNameStart() << ')';
300 }
David Majnemer58ed0f32016-07-17 00:39:12 +0000301 } else if (const auto *OCD = dyn_cast<ObjCCategoryImplDecl>(DC)) {
Jonas Devlieghere9ef49652018-06-28 10:56:40 +0000302 OS << OCD->getClassInterface()->getName() << '(' << OCD->getName() << ')';
Guy Benyei11169dd2012-12-18 14:30:41 +0000303 }
304 OS << ' ' << OMD->getSelector().getAsString() << ']';
305
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +0000306 return internString(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +0000307}
308
Guy Benyei11169dd2012-12-18 14:30:41 +0000309StringRef CGDebugInfo::getSelectorName(Selector S) {
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +0000310 return internString(S.getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +0000311}
312
Eric Christophere7b87e52014-10-26 23:40:33 +0000313StringRef CGDebugInfo::getClassName(const RecordDecl *RD) {
David Majnemerbc5976a2016-07-01 23:12:54 +0000314 if (isa<ClassTemplateSpecializationDecl>(RD)) {
315 SmallString<128> Name;
David Blaikie65813a32014-04-02 18:21:09 +0000316 llvm::raw_svector_ostream OS(Name);
David Blaikie9fdd09a2019-10-18 23:58:34 +0000317 PrintingPolicy PP = getPrintingPolicy();
318 PP.PrintCanonicalTypes = true;
319 RD->getNameForDiagnostic(OS, PP,
David Blaikie65813a32014-04-02 18:21:09 +0000320 /*Qualified*/ false);
David Majnemerbc5976a2016-07-01 23:12:54 +0000321
322 // Copy this name on the side and use its reference.
323 return internString(Name);
Benjamin Kramer9170e912013-02-22 15:46:01 +0000324 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000325
David Majnemerbc5976a2016-07-01 23:12:54 +0000326 // quick optimization to avoid having to intern strings that are already
327 // stored reliably elsewhere
328 if (const IdentifierInfo *II = RD->getIdentifier())
329 return II->getName();
330
331 // The CodeView printer in LLVM wants to see the names of unnamed types: it is
332 // used to reconstruct the fully qualified type names.
333 if (CGM.getCodeGenOpts().EmitCodeView) {
334 if (const TypedefNameDecl *D = RD->getTypedefNameForAnonDecl()) {
335 assert(RD->getDeclContext() == D->getDeclContext() &&
336 "Typedef should not be in another decl context!");
337 assert(D->getDeclName().getAsIdentifierInfo() &&
338 "Typedef was not named!");
339 return D->getDeclName().getAsIdentifierInfo()->getName();
340 }
341
342 if (CGM.getLangOpts().CPlusPlus) {
343 StringRef Name;
344
345 ASTContext &Context = CGM.getContext();
346 if (const DeclaratorDecl *DD = Context.getDeclaratorForUnnamedTagDecl(RD))
347 // Anonymous types without a name for linkage purposes have their
348 // declarator mangled in if they have one.
349 Name = DD->getName();
350 else if (const TypedefNameDecl *TND =
351 Context.getTypedefNameForUnnamedTagDecl(RD))
352 // Anonymous types without a name for linkage purposes have their
353 // associate typedef mangled in if they have one.
354 Name = TND->getName();
355
356 if (!Name.empty()) {
357 SmallString<256> UnnamedType("<unnamed-type-");
358 UnnamedType += Name;
359 UnnamedType += '>';
360 return internString(UnnamedType);
361 }
362 }
363 }
364
365 return StringRef();
Guy Benyei11169dd2012-12-18 14:30:41 +0000366}
367
Scott Linder94834f12018-02-12 19:47:05 +0000368Optional<llvm::DIFile::ChecksumKind>
Amjad Aboude2aab8c2016-12-25 10:12:27 +0000369CGDebugInfo::computeChecksum(FileID FID, SmallString<32> &Checksum) const {
370 Checksum.clear();
371
Paul Robinson76178632018-05-25 22:35:59 +0000372 if (!CGM.getCodeGenOpts().EmitCodeView &&
373 CGM.getCodeGenOpts().DwarfVersion < 5)
Scott Linder94834f12018-02-12 19:47:05 +0000374 return None;
Amjad Aboude2aab8c2016-12-25 10:12:27 +0000375
376 SourceManager &SM = CGM.getContext().getSourceManager();
377 bool Invalid;
Nico Weber04347d82019-04-04 21:06:41 +0000378 const llvm::MemoryBuffer *MemBuffer = SM.getBuffer(FID, &Invalid);
Paul Robinson76178632018-05-25 22:35:59 +0000379 if (Invalid)
Scott Linder94834f12018-02-12 19:47:05 +0000380 return None;
Amjad Aboude2aab8c2016-12-25 10:12:27 +0000381
382 llvm::MD5 Hash;
383 llvm::MD5::MD5Result Result;
384
385 Hash.update(MemBuffer->getBuffer());
386 Hash.final(Result);
387
388 Hash.stringifyResult(Result, Checksum);
389 return llvm::DIFile::CSK_MD5;
390}
391
Jonas Devlieghere9ef49652018-06-28 10:56:40 +0000392Optional<StringRef> CGDebugInfo::getSource(const SourceManager &SM,
393 FileID FID) {
Scott Lindera2fbcef2018-02-26 17:32:31 +0000394 if (!CGM.getCodeGenOpts().EmbedSource)
395 return None;
396
397 bool SourceInvalid = false;
398 StringRef Source = SM.getBufferData(FID, &SourceInvalid);
399
400 if (SourceInvalid)
401 return None;
402
403 return Source;
404}
405
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +0000406llvm::DIFile *CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000407 if (!Loc.isValid())
408 // If Location is not valid then use main input file.
Adrian Prantlc2a44ec2018-12-11 16:58:46 +0000409 return TheCU->getFile();
Guy Benyei11169dd2012-12-18 14:30:41 +0000410
411 SourceManager &SM = CGM.getContext().getSourceManager();
412 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
413
Adrian Prantl212c1042018-12-06 18:44:50 +0000414 StringRef FileName = PLoc.getFilename();
415 if (PLoc.isInvalid() || FileName.empty())
Guy Benyei11169dd2012-12-18 14:30:41 +0000416 // If the location is not valid then use main input file.
Adrian Prantlc2a44ec2018-12-11 16:58:46 +0000417 return TheCU->getFile();
Guy Benyei11169dd2012-12-18 14:30:41 +0000418
419 // Cache the results.
Adrian Prantl212c1042018-12-06 18:44:50 +0000420 auto It = DIFileCache.find(FileName.data());
Jonas Devlieghere9ef49652018-06-28 10:56:40 +0000421 if (It != DIFileCache.end()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000422 // Verify that the information still exists.
Jonas Devlieghere9ef49652018-06-28 10:56:40 +0000423 if (llvm::Metadata *V = It->second)
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +0000424 return cast<llvm::DIFile>(V);
Guy Benyei11169dd2012-12-18 14:30:41 +0000425 }
426
Amjad Aboude2aab8c2016-12-25 10:12:27 +0000427 SmallString<32> Checksum;
Alexandre Ganea047e65d2019-05-21 19:40:28 +0000428
429 // Compute the checksum if possible. If the location is affected by a #line
430 // directive that refers to a file, PLoc will have an invalid FileID, and we
431 // will correctly get no checksum.
Scott Linder94834f12018-02-12 19:47:05 +0000432 Optional<llvm::DIFile::ChecksumKind> CSKind =
Alexandre Ganea047e65d2019-05-21 19:40:28 +0000433 computeChecksum(PLoc.getFileID(), Checksum);
Scott Linder94834f12018-02-12 19:47:05 +0000434 Optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo;
435 if (CSKind)
436 CSInfo.emplace(*CSKind, Checksum);
Adrian Prantlaa5bad42018-12-11 16:58:43 +0000437 return createFile(FileName, CSInfo, getSource(SM, SM.getFileID(Loc)));
438}
Amjad Aboude2aab8c2016-12-25 10:12:27 +0000439
Adrian Prantlaa5bad42018-12-11 16:58:43 +0000440llvm::DIFile *
441CGDebugInfo::createFile(StringRef FileName,
442 Optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo,
443 Optional<StringRef> Source) {
Adrian Prantl212c1042018-12-06 18:44:50 +0000444 StringRef Dir;
445 StringRef File;
446 std::string RemappedFile = remapDIPath(FileName);
447 std::string CurDir = remapDIPath(getCurrentDirname());
448 SmallString<128> DirBuf;
449 SmallString<128> FileBuf;
450 if (llvm::sys::path::is_absolute(RemappedFile)) {
451 // Strip the common prefix (if it is more than just "/") from current
452 // directory and FileName for a more space-efficient encoding.
453 auto FileIt = llvm::sys::path::begin(RemappedFile);
454 auto FileE = llvm::sys::path::end(RemappedFile);
455 auto CurDirIt = llvm::sys::path::begin(CurDir);
456 auto CurDirE = llvm::sys::path::end(CurDir);
457 for (; CurDirIt != CurDirE && *CurDirIt == *FileIt; ++CurDirIt, ++FileIt)
458 llvm::sys::path::append(DirBuf, *CurDirIt);
459 if (std::distance(llvm::sys::path::begin(CurDir), CurDirIt) == 1) {
Adrian Prantl0feb7b72019-02-05 21:21:01 +0000460 // Don't strip the common prefix if it is only the root "/"
461 // since that would make LLVM diagnostic locations confusing.
Adrian Prantl212c1042018-12-06 18:44:50 +0000462 Dir = {};
463 File = RemappedFile;
464 } else {
465 for (; FileIt != FileE; ++FileIt)
466 llvm::sys::path::append(FileBuf, *FileIt);
467 Dir = DirBuf;
468 File = FileBuf;
469 }
470 } else {
471 Dir = CurDir;
472 File = RemappedFile;
473 }
Adrian Prantlaa5bad42018-12-11 16:58:43 +0000474 llvm::DIFile *F = DBuilder.createFile(File, Dir, CSInfo, Source);
Adrian Prantl212c1042018-12-06 18:44:50 +0000475 DIFileCache[FileName.data()].reset(F);
Guy Benyei11169dd2012-12-18 14:30:41 +0000476 return F;
477}
478
Saleem Abdulrasool436256a2015-10-12 20:21:08 +0000479std::string CGDebugInfo::remapDIPath(StringRef Path) const {
Sylvain Audi7a8edcb2020-04-29 12:50:37 -0400480 if (DebugPrefixMap.empty())
481 return Path.str();
482
483 SmallString<256> P = Path;
Saleem Abdulrasool436256a2015-10-12 20:21:08 +0000484 for (const auto &Entry : DebugPrefixMap)
Sylvain Audi7a8edcb2020-04-29 12:50:37 -0400485 if (llvm::sys::path::replace_path_prefix(P, Entry.first, Entry.second))
486 break;
487 return P.str().str();
Guy Benyei11169dd2012-12-18 14:30:41 +0000488}
489
Guy Benyei11169dd2012-12-18 14:30:41 +0000490unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
491 if (Loc.isInvalid() && CurLoc.isInvalid())
492 return 0;
493 SourceManager &SM = CGM.getContext().getSourceManager();
494 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
Eric Christophere7b87e52014-10-26 23:40:33 +0000495 return PLoc.isValid() ? PLoc.getLine() : 0;
Guy Benyei11169dd2012-12-18 14:30:41 +0000496}
497
Adrian Prantlc7822422013-03-12 20:43:25 +0000498unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000499 // We may not want column information at all.
Adrian Prantlc7822422013-03-12 20:43:25 +0000500 if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo)
Guy Benyei11169dd2012-12-18 14:30:41 +0000501 return 0;
502
503 // If the location is invalid then use the current column.
504 if (Loc.isInvalid() && CurLoc.isInvalid())
505 return 0;
506 SourceManager &SM = CGM.getContext().getSourceManager();
507 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
Eric Christophere7b87e52014-10-26 23:40:33 +0000508 return PLoc.isValid() ? PLoc.getColumn() : 0;
Guy Benyei11169dd2012-12-18 14:30:41 +0000509}
510
511StringRef CGDebugInfo::getCurrentDirname() {
512 if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
513 return CGM.getCodeGenOpts().DebugCompilationDir;
514
515 if (!CWDName.empty())
516 return CWDName;
517 SmallString<256> CWD;
518 llvm::sys::fs::current_path(CWD);
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +0000519 return CWDName = internString(CWD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000520}
521
Guy Benyei11169dd2012-12-18 14:30:41 +0000522void CGDebugInfo::CreateCompileUnit() {
Amjad Aboude2aab8c2016-12-25 10:12:27 +0000523 SmallString<32> Checksum;
Scott Linder94834f12018-02-12 19:47:05 +0000524 Optional<llvm::DIFile::ChecksumKind> CSKind;
525 Optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo;
Guy Benyei11169dd2012-12-18 14:30:41 +0000526
David Blaikieaabde052014-05-14 00:29:00 +0000527 // Should we be asking the SourceManager for the main file name, instead of
528 // accepting it as an argument? This just causes the main file name to
529 // mismatch with source locations and create extra lexical scopes or
530 // mismatched debug info (a CU with a DW_AT_file of "-", because that's what
531 // the driver passed, but functions/other things have DW_AT_file of "<stdin>"
532 // because that's what the SourceManager says)
533
Guy Benyei11169dd2012-12-18 14:30:41 +0000534 // Get absolute path name.
535 SourceManager &SM = CGM.getContext().getSourceManager();
536 std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
537 if (MainFileName.empty())
David Blaikieaabde052014-05-14 00:29:00 +0000538 MainFileName = "<stdin>";
Guy Benyei11169dd2012-12-18 14:30:41 +0000539
540 // The main file name provided via the "-main-file-name" option contains just
541 // the file name itself with no path information. This file name may have had
542 // a relative path, so we look into the actual file entry for the main
543 // file to determine the real absolute path for the file.
544 std::string MainFileDir;
545 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
Benjamin Krameradcd0262020-01-28 20:23:46 +0100546 MainFileDir = std::string(MainFile->getDir()->getName());
Adrian Prantl122e7af2019-10-21 16:44:37 +0000547 if (!llvm::sys::path::is_absolute(MainFileName)) {
Eric Christopher0a1301f2014-02-26 02:49:36 +0000548 llvm::SmallString<1024> MainFileDirSS(MainFileDir);
549 llvm::sys::path::append(MainFileDirSS, MainFileName);
Benjamin Krameradcd0262020-01-28 20:23:46 +0100550 MainFileName =
551 std::string(llvm::sys::path::remove_leading_dotslash(MainFileDirSS));
Yaron Keren9fb7e902013-10-21 20:07:37 +0000552 }
Taewook Oh0fb5b782017-08-16 19:36:24 +0000553 // If the main file name provided is identical to the input file name, and
554 // if the input file is a preprocessed source, use the module name for
555 // debug info. The module name comes from the name specified in the first
556 // linemarker if the input is a preprocessed source.
557 if (MainFile->getName() == MainFileName &&
558 FrontendOptions::getInputKindForExtension(
559 MainFile->getName().rsplit('.').second)
560 .isPreprocessed())
561 MainFileName = CGM.getModule().getName().str();
562
Amjad Aboude2aab8c2016-12-25 10:12:27 +0000563 CSKind = computeChecksum(SM.getMainFileID(), Checksum);
Guy Benyei11169dd2012-12-18 14:30:41 +0000564 }
565
Ed Masteda706022014-05-07 12:49:30 +0000566 llvm::dwarf::SourceLanguage LangTag;
Guy Benyei11169dd2012-12-18 14:30:41 +0000567 const LangOptions &LO = CGM.getLangOpts();
568 if (LO.CPlusPlus) {
Erik Pilkingtonfa983902018-10-30 20:31:30 +0000569 if (LO.ObjC)
Guy Benyei11169dd2012-12-18 14:30:41 +0000570 LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
Adrian Prantl350de4f2019-09-24 00:38:49 +0000571 else if (LO.CPlusPlus14)
572 LangTag = llvm::dwarf::DW_LANG_C_plus_plus_14;
573 else if (LO.CPlusPlus11)
574 LangTag = llvm::dwarf::DW_LANG_C_plus_plus_11;
Guy Benyei11169dd2012-12-18 14:30:41 +0000575 else
576 LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
Erik Pilkingtonfa983902018-10-30 20:31:30 +0000577 } else if (LO.ObjC) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000578 LangTag = llvm::dwarf::DW_LANG_ObjC;
Pirama Arumuga Nainara7484c92016-06-21 21:35:11 +0000579 } else if (LO.RenderScript) {
580 LangTag = llvm::dwarf::DW_LANG_GOOGLE_RenderScript;
Guy Benyei11169dd2012-12-18 14:30:41 +0000581 } else if (LO.C99) {
582 LangTag = llvm::dwarf::DW_LANG_C99;
583 } else {
584 LangTag = llvm::dwarf::DW_LANG_C89;
585 }
586
587 std::string Producer = getClangFullVersion();
588
589 // Figure out which version of the ObjC runtime we have.
590 unsigned RuntimeVers = 0;
Erik Pilkingtonfa983902018-10-30 20:31:30 +0000591 if (LO.ObjC)
Guy Benyei11169dd2012-12-18 14:30:41 +0000592 RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
593
Adrian Prantl826824e2016-04-08 22:43:06 +0000594 llvm::DICompileUnit::DebugEmissionKind EmissionKind;
595 switch (DebugKind) {
596 case codegenoptions::NoDebugInfo:
597 case codegenoptions::LocTrackingOnly:
598 EmissionKind = llvm::DICompileUnit::NoDebug;
599 break;
600 case codegenoptions::DebugLineTablesOnly:
601 EmissionKind = llvm::DICompileUnit::LineTablesOnly;
602 break;
Alexey Bataev80e1b5e2018-08-31 13:56:14 +0000603 case codegenoptions::DebugDirectivesOnly:
604 EmissionKind = llvm::DICompileUnit::DebugDirectivesOnly;
605 break;
Amy Huang53539bb2020-01-13 15:54:54 -0800606 case codegenoptions::DebugInfoConstructor:
Adrian Prantl826824e2016-04-08 22:43:06 +0000607 case codegenoptions::LimitedDebugInfo:
608 case codegenoptions::FullDebugInfo:
609 EmissionKind = llvm::DICompileUnit::FullDebug;
610 break;
611 }
612
Adrian Prantl046d1002018-12-13 17:53:29 +0000613 uint64_t DwoId = 0;
614 auto &CGOpts = CGM.getCodeGenOpts();
615 // The DIFile used by the CU is distinct from the main source
616 // file. Its directory part specifies what becomes the
617 // DW_AT_comp_dir (the compilation directory), even if the source
618 // file was specified with an absolute path.
Scott Linder94834f12018-02-12 19:47:05 +0000619 if (CSKind)
620 CSInfo.emplace(*CSKind, Checksum);
Adrian Prantl046d1002018-12-13 17:53:29 +0000621 llvm::DIFile *CUFile = DBuilder.createFile(
622 remapDIPath(MainFileName), remapDIPath(getCurrentDirname()), CSInfo,
623 getSource(SM, SM.getMainFileID()));
Scott Linder94834f12018-02-12 19:47:05 +0000624
Adrian Prantl842ea702020-03-12 14:19:04 -0700625 StringRef Sysroot, SDK;
626 if (CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB) {
Adrian Prantl7b303702020-01-14 13:37:04 -0800627 Sysroot = CGM.getHeaderSearchOpts().Sysroot;
Adrian Prantl842ea702020-03-12 14:19:04 -0700628 auto B = llvm::sys::path::rbegin(Sysroot);
629 auto E = llvm::sys::path::rend(Sysroot);
630 auto It = std::find_if(B, E, [](auto SDK) { return SDK.endswith(".sdk"); });
631 if (It != E)
632 SDK = *It;
633 }
Adrian Prantl7b303702020-01-14 13:37:04 -0800634
Guy Benyei11169dd2012-12-18 14:30:41 +0000635 // Create new compile unit.
Eric Christophere4200a22014-02-27 01:25:08 +0000636 TheCU = DBuilder.createCompileUnit(
Adrian Prantl046d1002018-12-13 17:53:29 +0000637 LangTag, CUFile, CGOpts.EmitVersionIdentMetadata ? Producer : "",
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +0000638 LO.Optimize || CGOpts.PrepareForLTO || CGOpts.PrepareForThinLTO,
Aaron Puchert45611612019-06-26 21:39:19 +0000639 CGOpts.DwarfDebugFlags, RuntimeVers, CGOpts.SplitDwarfFile, EmissionKind,
640 DwoId, CGOpts.SplitDwarfInlining, CGOpts.DebugInfoForProfiling,
David Blaikie9982bb82018-08-16 23:56:32 +0000641 CGM.getTarget().getTriple().isNVPTX()
642 ? llvm::DICompileUnit::DebugNameTableKind::None
David Blaikie65864522018-08-20 20:14:08 +0000643 : static_cast<llvm::DICompileUnit::DebugNameTableKind>(
David Blaikie27692de2018-11-13 20:08:13 +0000644 CGOpts.DebugNameTable),
Adrian Prantlceae4712020-03-18 15:48:23 -0700645 CGOpts.DebugRangesBaseAddress, remapDIPath(Sysroot), SDK);
Guy Benyei11169dd2012-12-18 14:30:41 +0000646}
647
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +0000648llvm::DIType *CGDebugInfo::CreateType(const BuiltinType *BT) {
Ed Masteda706022014-05-07 12:49:30 +0000649 llvm::dwarf::TypeKind Encoding;
Guy Benyei11169dd2012-12-18 14:30:41 +0000650 StringRef BTName;
651 switch (BT->getKind()) {
652#define BUILTIN_TYPE(Id, SingletonId)
Eric Christophere7b87e52014-10-26 23:40:33 +0000653#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
Guy Benyei11169dd2012-12-18 14:30:41 +0000654#include "clang/AST/BuiltinTypes.def"
655 case BuiltinType::Dependent:
656 llvm_unreachable("Unexpected builtin type");
657 case BuiltinType::NullPtr:
Peter Collingbourne5c5e6172013-06-27 22:51:01 +0000658 return DBuilder.createNullPtrType();
Guy Benyei11169dd2012-12-18 14:30:41 +0000659 case BuiltinType::Void:
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +0000660 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000661 case BuiltinType::ObjCClass:
David Blaikief427b002014-05-06 03:42:01 +0000662 if (!ClassTy)
Adrian Prantlc2a44ec2018-12-11 16:58:46 +0000663 ClassTy =
664 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
665 "objc_class", TheCU, TheCU->getFile(), 0);
Guy Benyei11169dd2012-12-18 14:30:41 +0000666 return ClassTy;
667 case BuiltinType::ObjCId: {
668 // typedef struct objc_class *Class;
669 // typedef struct objc_object {
670 // Class isa;
671 // } *id;
672
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000673 if (ObjTy)
Guy Benyei11169dd2012-12-18 14:30:41 +0000674 return ObjTy;
675
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000676 if (!ClassTy)
Adrian Prantlc2a44ec2018-12-11 16:58:46 +0000677 ClassTy =
678 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
679 "objc_class", TheCU, TheCU->getFile(), 0);
Guy Benyei11169dd2012-12-18 14:30:41 +0000680
681 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
Eric Christopherb2a008c2013-05-16 00:45:12 +0000682
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +0000683 auto *ISATy = DBuilder.createPointerType(ClassTy, Size);
Guy Benyei11169dd2012-12-18 14:30:41 +0000684
Adrian Prantlc2a44ec2018-12-11 16:58:46 +0000685 ObjTy = DBuilder.createStructType(TheCU, "objc_object", TheCU->getFile(), 0,
686 0, 0, llvm::DINode::FlagZero, nullptr,
687 llvm::DINodeArray());
Guy Benyei11169dd2012-12-18 14:30:41 +0000688
Duncan P. N. Exon Smithc8ee63e2014-12-18 00:48:56 +0000689 DBuilder.replaceArrays(
Leny Kholodovdf050fd2016-09-06 17:06:14 +0000690 ObjTy, DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
Adrian Prantlc2a44ec2018-12-11 16:58:46 +0000691 ObjTy, "isa", TheCU->getFile(), 0, Size, 0, 0,
Leny Kholodovdf050fd2016-09-06 17:06:14 +0000692 llvm::DINode::FlagZero, ISATy)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000693 return ObjTy;
694 }
695 case BuiltinType::ObjCSel: {
David Blaikief427b002014-05-06 03:42:01 +0000696 if (!SelTy)
697 SelTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
698 "objc_selector", TheCU,
Adrian Prantlc2a44ec2018-12-11 16:58:46 +0000699 TheCU->getFile(), 0);
Guy Benyei11169dd2012-12-18 14:30:41 +0000700 return SelTy;
701 }
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000702
Jonas Devlieghere9ef49652018-06-28 10:56:40 +0000703#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
704 case BuiltinType::Id: \
705 return getOrCreateStructPtrType("opencl_" #ImgType "_" #Suffix "_t", \
Alexey Bader954ba212016-04-08 13:40:33 +0000706 SingletonId);
Alexey Baderb62f1442016-04-13 08:33:41 +0000707#include "clang/Basic/OpenCLImageTypes.def"
Guy Benyei61054192013-02-07 10:55:47 +0000708 case BuiltinType::OCLSampler:
Jonas Devlieghere9ef49652018-06-28 10:56:40 +0000709 return getOrCreateStructPtrType("opencl_sampler_t", OCLSamplerDITy);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +0000710 case BuiltinType::OCLEvent:
Eric Christophere7b87e52014-10-26 23:40:33 +0000711 return getOrCreateStructPtrType("opencl_event_t", OCLEventDITy);
Alexey Bader9c8453f2015-09-15 11:18:52 +0000712 case BuiltinType::OCLClkEvent:
713 return getOrCreateStructPtrType("opencl_clk_event_t", OCLClkEventDITy);
714 case BuiltinType::OCLQueue:
715 return getOrCreateStructPtrType("opencl_queue_t", OCLQueueDITy);
Alexey Bader9c8453f2015-09-15 11:18:52 +0000716 case BuiltinType::OCLReserveID:
717 return getOrCreateStructPtrType("opencl_reserve_id_t", OCLReserveIDDITy);
Andrew Savonichev3fee3512018-11-08 11:25:41 +0000718#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
719 case BuiltinType::Id: \
720 return getOrCreateStructPtrType("opencl_" #ExtType, Id##Ty);
721#include "clang/Basic/OpenCLExtensionTypes.def"
Richard Sandifordeb485fb2019-08-09 08:52:54 +0000722 // TODO: real support for SVE types requires more infrastructure
723 // to be added first. The types have a variable length and are
724 // represented in debug info as types whose length depends on a
725 // target-specific pseudo register.
726#define SVE_TYPE(Name, Id, SingletonId) \
727 case BuiltinType::Id:
728#include "clang/Basic/AArch64SVEACLETypes.def"
729 {
730 unsigned DiagID = CGM.getDiags().getCustomDiagID(
731 DiagnosticsEngine::Error,
732 "cannot yet generate debug info for SVE type '%0'");
733 auto Name = BT->getName(CGM.getContext().getPrintingPolicy());
734 CGM.getDiags().Report(DiagID) << Name;
735 // Return something safe.
736 return CreateType(cast<const BuiltinType>(CGM.getContext().IntTy));
737 }
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000738
Guy Benyei11169dd2012-12-18 14:30:41 +0000739 case BuiltinType::UChar:
Eric Christophere7b87e52014-10-26 23:40:33 +0000740 case BuiltinType::Char_U:
741 Encoding = llvm::dwarf::DW_ATE_unsigned_char;
742 break;
Guy Benyei11169dd2012-12-18 14:30:41 +0000743 case BuiltinType::Char_S:
Eric Christophere7b87e52014-10-26 23:40:33 +0000744 case BuiltinType::SChar:
745 Encoding = llvm::dwarf::DW_ATE_signed_char;
746 break;
Richard Smith3a8244d2018-05-01 05:02:45 +0000747 case BuiltinType::Char8:
Guy Benyei11169dd2012-12-18 14:30:41 +0000748 case BuiltinType::Char16:
Eric Christophere7b87e52014-10-26 23:40:33 +0000749 case BuiltinType::Char32:
750 Encoding = llvm::dwarf::DW_ATE_UTF;
751 break;
Guy Benyei11169dd2012-12-18 14:30:41 +0000752 case BuiltinType::UShort:
753 case BuiltinType::UInt:
754 case BuiltinType::UInt128:
755 case BuiltinType::ULong:
756 case BuiltinType::WChar_U:
Eric Christophere7b87e52014-10-26 23:40:33 +0000757 case BuiltinType::ULongLong:
758 Encoding = llvm::dwarf::DW_ATE_unsigned;
759 break;
Guy Benyei11169dd2012-12-18 14:30:41 +0000760 case BuiltinType::Short:
761 case BuiltinType::Int:
762 case BuiltinType::Int128:
763 case BuiltinType::Long:
764 case BuiltinType::WChar_S:
Eric Christophere7b87e52014-10-26 23:40:33 +0000765 case BuiltinType::LongLong:
766 Encoding = llvm::dwarf::DW_ATE_signed;
767 break;
768 case BuiltinType::Bool:
769 Encoding = llvm::dwarf::DW_ATE_boolean;
770 break;
Guy Benyei11169dd2012-12-18 14:30:41 +0000771 case BuiltinType::Half:
772 case BuiltinType::Float:
773 case BuiltinType::LongDouble:
Sjoerd Meijercc623ad2017-09-08 15:15:00 +0000774 case BuiltinType::Float16:
Ties Stuijecd682b2020-06-05 00:20:02 +0100775 case BuiltinType::BFloat16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +0000776 case BuiltinType::Float128:
Eric Christophere7b87e52014-10-26 23:40:33 +0000777 case BuiltinType::Double:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +0000778 // FIXME: For targets where long double and __float128 have the same size,
779 // they are currently indistinguishable in the debugger without some
780 // special treatment. However, there is currently no consensus on encoding
781 // and this should be updated once a DWARF encoding exists for distinct
782 // floating point types of the same size.
Eric Christophere7b87e52014-10-26 23:40:33 +0000783 Encoding = llvm::dwarf::DW_ATE_float;
784 break;
Leonard Chanf921d852018-06-04 16:07:52 +0000785 case BuiltinType::ShortAccum:
786 case BuiltinType::Accum:
787 case BuiltinType::LongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +0000788 case BuiltinType::ShortFract:
789 case BuiltinType::Fract:
790 case BuiltinType::LongFract:
791 case BuiltinType::SatShortFract:
792 case BuiltinType::SatFract:
793 case BuiltinType::SatLongFract:
794 case BuiltinType::SatShortAccum:
795 case BuiltinType::SatAccum:
796 case BuiltinType::SatLongAccum:
Leonard Chanf921d852018-06-04 16:07:52 +0000797 Encoding = llvm::dwarf::DW_ATE_signed_fixed;
798 break;
799 case BuiltinType::UShortAccum:
800 case BuiltinType::UAccum:
801 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +0000802 case BuiltinType::UShortFract:
803 case BuiltinType::UFract:
804 case BuiltinType::ULongFract:
805 case BuiltinType::SatUShortAccum:
806 case BuiltinType::SatUAccum:
807 case BuiltinType::SatULongAccum:
808 case BuiltinType::SatUShortFract:
809 case BuiltinType::SatUFract:
810 case BuiltinType::SatULongFract:
Leonard Chanf921d852018-06-04 16:07:52 +0000811 Encoding = llvm::dwarf::DW_ATE_unsigned_fixed;
812 break;
Guy Benyei11169dd2012-12-18 14:30:41 +0000813 }
814
815 switch (BT->getKind()) {
Eric Christophere7b87e52014-10-26 23:40:33 +0000816 case BuiltinType::Long:
817 BTName = "long int";
818 break;
819 case BuiltinType::LongLong:
820 BTName = "long long int";
821 break;
822 case BuiltinType::ULong:
823 BTName = "long unsigned int";
824 break;
825 case BuiltinType::ULongLong:
826 BTName = "long long unsigned int";
827 break;
Guy Benyei11169dd2012-12-18 14:30:41 +0000828 default:
829 BTName = BT->getName(CGM.getLangOpts());
830 break;
831 }
Victor Leschuka7ece032016-10-20 00:13:19 +0000832 // Bit size and offset of the type.
Guy Benyei11169dd2012-12-18 14:30:41 +0000833 uint64_t Size = CGM.getContext().getTypeSize(BT);
Victor Leschuka7ece032016-10-20 00:13:19 +0000834 return DBuilder.createBasicType(BTName, Size, Encoding);
Guy Benyei11169dd2012-12-18 14:30:41 +0000835}
836
Awanish Pandeyc83602f2020-01-23 16:06:52 +0530837llvm::DIType *CGDebugInfo::CreateType(const AutoType *Ty) {
838 return DBuilder.createUnspecifiedType("auto");
839}
840
Erich Keane5f0903e2020-04-17 10:44:19 -0700841llvm::DIType *CGDebugInfo::CreateType(const ExtIntType *Ty) {
842
843 StringRef Name = Ty->isUnsigned() ? "unsigned _ExtInt" : "_ExtInt";
844 llvm::dwarf::TypeKind Encoding = Ty->isUnsigned()
845 ? llvm::dwarf::DW_ATE_unsigned
846 : llvm::dwarf::DW_ATE_signed;
847
848 return DBuilder.createBasicType(Name, CGM.getContext().getTypeSize(Ty),
849 Encoding);
850}
851
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +0000852llvm::DIType *CGDebugInfo::CreateType(const ComplexType *Ty) {
Victor Leschuka7ece032016-10-20 00:13:19 +0000853 // Bit size and offset of the type.
Ed Masteda706022014-05-07 12:49:30 +0000854 llvm::dwarf::TypeKind Encoding = llvm::dwarf::DW_ATE_complex_float;
Guy Benyei11169dd2012-12-18 14:30:41 +0000855 if (Ty->isComplexIntegerType())
856 Encoding = llvm::dwarf::DW_ATE_lo_user;
857
858 uint64_t Size = CGM.getContext().getTypeSize(Ty);
Victor Leschuka7ece032016-10-20 00:13:19 +0000859 return DBuilder.createBasicType("complex", Size, Encoding);
Guy Benyei11169dd2012-12-18 14:30:41 +0000860}
861
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +0000862llvm::DIType *CGDebugInfo::CreateQualifiedType(QualType Ty,
863 llvm::DIFile *Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000864 QualifierCollector Qc;
865 const Type *T = Qc.strip(Ty);
866
867 // Ignore these qualifiers for now.
868 Qc.removeObjCGCAttr();
869 Qc.removeAddressSpace();
870 Qc.removeObjCLifetime();
871
872 // We will create one Derived type for one qualifier and recurse to handle any
873 // additional ones.
Ed Masteda706022014-05-07 12:49:30 +0000874 llvm::dwarf::Tag Tag;
Guy Benyei11169dd2012-12-18 14:30:41 +0000875 if (Qc.hasConst()) {
876 Tag = llvm::dwarf::DW_TAG_const_type;
877 Qc.removeConst();
878 } else if (Qc.hasVolatile()) {
879 Tag = llvm::dwarf::DW_TAG_volatile_type;
880 Qc.removeVolatile();
881 } else if (Qc.hasRestrict()) {
882 Tag = llvm::dwarf::DW_TAG_restrict_type;
883 Qc.removeRestrict();
884 } else {
885 assert(Qc.empty() && "Unknown type qualifier for debug info");
886 return getOrCreateType(QualType(T, 0), Unit);
887 }
888
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +0000889 auto *FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +0000890
891 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
892 // CVR derived types.
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +0000893 return DBuilder.createQualifiedType(Tag, FromTy);
Guy Benyei11169dd2012-12-18 14:30:41 +0000894}
895
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +0000896llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
897 llvm::DIFile *Unit) {
Fariborz Jahanian65f1fa12013-02-21 20:42:11 +0000898
899 // The frontend treats 'id' as a typedef to an ObjCObjectType,
900 // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
901 // debug info, we want to emit 'id' in both cases.
902 if (Ty->isObjCQualifiedIdType())
Eric Christophere7b87e52014-10-26 23:40:33 +0000903 return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
Fariborz Jahanian65f1fa12013-02-21 20:42:11 +0000904
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +0000905 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
906 Ty->getPointeeType(), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +0000907}
908
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +0000909llvm::DIType *CGDebugInfo::CreateType(const PointerType *Ty,
910 llvm::DIFile *Unit) {
Eric Christopherb2a008c2013-05-16 00:45:12 +0000911 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +0000912 Ty->getPointeeType(), Unit);
913}
914
Adrian Prantlc6f91a22015-06-15 23:18:16 +0000915/// \return whether a C++ mangling exists for the type defined by TD.
916static bool hasCXXMangling(const TagDecl *TD, llvm::DICompileUnit *TheCU) {
917 switch (TheCU->getSourceLanguage()) {
918 case llvm::dwarf::DW_LANG_C_plus_plus:
Adrian Prantl350de4f2019-09-24 00:38:49 +0000919 case llvm::dwarf::DW_LANG_C_plus_plus_11:
920 case llvm::dwarf::DW_LANG_C_plus_plus_14:
Adrian Prantlc6f91a22015-06-15 23:18:16 +0000921 return true;
922 case llvm::dwarf::DW_LANG_ObjC_plus_plus:
923 return isa<CXXRecordDecl>(TD) || isa<EnumDecl>(TD);
924 default:
925 return false;
926 }
927}
928
Reid Kleckner59320fc2018-08-17 20:59:52 +0000929// Determines if the debug info for this tag declaration needs a type
930// identifier. The purpose of the unique identifier is to deduplicate type
931// information for identical types across TUs. Because of the C++ one definition
932// rule (ODR), it is valid to assume that the type is defined the same way in
933// every TU and its debug info is equivalent.
934//
935// C does not have the ODR, and it is common for codebases to contain multiple
936// different definitions of a struct with the same name in different TUs.
937// Therefore, if the type doesn't have a C++ mangling, don't give it an
938// identifer. Type information in C is smaller and simpler than C++ type
939// information, so the increase in debug info size is negligible.
940//
941// If the type is not externally visible, it should be unique to the current TU,
942// and should not need an identifier to participate in type deduplication.
943// However, when emitting CodeView, the format internally uses these
944// unique type name identifers for references between debug info. For example,
945// the method of a class in an anonymous namespace uses the identifer to refer
946// to its parent class. The Microsoft C++ ABI attempts to provide unique names
947// for such types, so when emitting CodeView, always use identifiers for C++
948// types. This may create problems when attempting to emit CodeView when the MS
949// C++ ABI is not in use.
Jonas Devlieghere9ef49652018-06-28 10:56:40 +0000950static bool needsTypeIdentifier(const TagDecl *TD, CodeGenModule &CGM,
Brock Wyma8557ec52018-05-22 12:41:19 +0000951 llvm::DICompileUnit *TheCU) {
952 // We only add a type identifier for types with C++ name mangling.
953 if (!hasCXXMangling(TD, TheCU))
954 return false;
955
Brock Wyma8557ec52018-05-22 12:41:19 +0000956 // Externally visible types with C++ mangling need a type identifier.
957 if (TD->isExternallyVisible())
958 return true;
959
Reid Kleckner59320fc2018-08-17 20:59:52 +0000960 // CodeView types with C++ mangling need a type identifier.
961 if (CGM.getCodeGenOpts().EmitCodeView)
962 return true;
963
Brock Wyma8557ec52018-05-22 12:41:19 +0000964 return false;
965}
966
Reid Kleckner59320fc2018-08-17 20:59:52 +0000967// Returns a unique type identifier string if one exists, or an empty string.
Jonas Devlieghere9ef49652018-06-28 10:56:40 +0000968static SmallString<256> getTypeIdentifier(const TagType *Ty, CodeGenModule &CGM,
Brock Wyma8557ec52018-05-22 12:41:19 +0000969 llvm::DICompileUnit *TheCU) {
970 SmallString<256> Identifier;
Manman Rene0064d82013-08-29 23:19:58 +0000971 const TagDecl *TD = Ty->getDecl();
Adrian Prantlc6f91a22015-06-15 23:18:16 +0000972
Brock Wyma8557ec52018-05-22 12:41:19 +0000973 if (!needsTypeIdentifier(TD, CGM, TheCU))
974 return Identifier;
David Blaikief0d66552019-04-25 20:05:47 +0000975 if (const auto *RD = dyn_cast<CXXRecordDecl>(TD))
976 if (RD->getDefinition())
977 if (RD->isDynamicClass() &&
978 CGM.getVTableLinkage(RD) == llvm::GlobalValue::ExternalLinkage)
979 return Identifier;
Adrian Prantlc6f91a22015-06-15 23:18:16 +0000980
Manman Rene0064d82013-08-29 23:19:58 +0000981 // TODO: This is using the RTTI name. Is there a better way to get
982 // a unique string for a type?
Brock Wyma8557ec52018-05-22 12:41:19 +0000983 llvm::raw_svector_ostream Out(Identifier);
Manman Rene0064d82013-08-29 23:19:58 +0000984 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(QualType(Ty, 0), Out);
Brock Wyma8557ec52018-05-22 12:41:19 +0000985 return Identifier;
Manman Rene0064d82013-08-29 23:19:58 +0000986}
987
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +0000988/// \return the appropriate DWARF tag for a composite type.
Adrian Prantl5f66bae2015-02-11 17:45:15 +0000989static llvm::dwarf::Tag getTagForRecord(const RecordDecl *RD) {
Jonas Devlieghere9ef49652018-06-28 10:56:40 +0000990 llvm::dwarf::Tag Tag;
Adrian Prantl5f66bae2015-02-11 17:45:15 +0000991 if (RD->isStruct() || RD->isInterface())
992 Tag = llvm::dwarf::DW_TAG_structure_type;
993 else if (RD->isUnion())
994 Tag = llvm::dwarf::DW_TAG_union_type;
995 else {
996 // FIXME: This could be a struct type giving a default visibility different
997 // than C++ class type, but needs llvm metadata changes first.
998 assert(RD->isClass());
999 Tag = llvm::dwarf::DW_TAG_class_type;
1000 }
1001 return Tag;
1002}
1003
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001004llvm::DICompositeType *
Manman Ren1b457022013-08-28 21:20:28 +00001005CGDebugInfo::getOrCreateRecordFwdDecl(const RecordType *Ty,
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001006 llvm::DIScope *Ctx) {
Manman Ren1b457022013-08-28 21:20:28 +00001007 const RecordDecl *RD = Ty->getDecl();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001008 if (llvm::DIType *T = getTypeOrNull(CGM.getContext().getRecordType(RD)))
1009 return cast<llvm::DICompositeType>(T);
1010 llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00001011 unsigned Line = getLineNumber(RD->getLocation());
1012 StringRef RDName = getClassName(RD);
1013
Peter Collingbourned251b0a2015-03-01 22:07:04 +00001014 uint64_t Size = 0;
Victor Leschuk802e4a52016-10-19 22:11:07 +00001015 uint32_t Align = 0;
Peter Collingbourned251b0a2015-03-01 22:07:04 +00001016
Amy Huangbcf66082020-02-04 13:20:13 -08001017 llvm::DINode::DIFlags Flags = llvm::DINode::FlagFwdDecl;
1018
1019 // Add flag to nontrivial forward declarations. To be consistent with MSVC,
1020 // add the flag if a record has no definition because we don't know whether
1021 // it will be trivial or not.
1022 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1023 if (!CXXRD->hasDefinition() ||
1024 (CXXRD->hasDefinition() && !CXXRD->isTrivial()))
1025 Flags |= llvm::DINode::FlagNonTrivial;
1026
Guy Benyei11169dd2012-12-18 14:30:41 +00001027 // Create the type.
Brock Wyma8557ec52018-05-22 12:41:19 +00001028 SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001029 llvm::DICompositeType *RetTy = DBuilder.createReplaceableCompositeType(
Amy Huangbcf66082020-02-04 13:20:13 -08001030 getTagForRecord(RD), RDName, Ctx, DefUnit, Line, 0, Size, Align, Flags,
1031 Identifier);
Paul Robinson1787f812017-09-28 18:37:02 +00001032 if (CGM.getCodeGenOpts().DebugFwdTemplateParams)
1033 if (auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD))
1034 DBuilder.replaceArrays(RetTy, llvm::DINodeArray(),
1035 CollectCXXTemplateParams(TSpecial, DefUnit));
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001036 ReplaceMap.emplace_back(
1037 std::piecewise_construct, std::make_tuple(Ty),
1038 std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
David Blaikief427b002014-05-06 03:42:01 +00001039 return RetTy;
Guy Benyei11169dd2012-12-18 14:30:41 +00001040}
1041
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001042llvm::DIType *CGDebugInfo::CreatePointerLikeType(llvm::dwarf::Tag Tag,
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00001043 const Type *Ty,
1044 QualType PointeeTy,
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001045 llvm::DIFile *Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001046 // Bit size, align and offset of the type.
1047 // Size is always the size of a pointer. We can't use getTypeSize here
1048 // because that does not return the correct value for references.
Konstantin Zhuravlyovd1ba16e2017-03-08 23:56:48 +00001049 unsigned AddressSpace = CGM.getContext().getTargetAddressSpace(PointeeTy);
1050 uint64_t Size = CGM.getTarget().getPointerWidth(AddressSpace);
Victor Leschuka7ece032016-10-20 00:13:19 +00001051 auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
Konstantin Zhuravlyovd1ba16e2017-03-08 23:56:48 +00001052 Optional<unsigned> DWARFAddressSpace =
1053 CGM.getTarget().getDWARFAddressSpace(AddressSpace);
Guy Benyei11169dd2012-12-18 14:30:41 +00001054
Keno Fischer87842f32015-11-16 09:04:13 +00001055 if (Tag == llvm::dwarf::DW_TAG_reference_type ||
1056 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
1057 return DBuilder.createReferenceType(Tag, getOrCreateType(PointeeTy, Unit),
Konstantin Zhuravlyovd1ba16e2017-03-08 23:56:48 +00001058 Size, Align, DWARFAddressSpace);
Keno Fischer87842f32015-11-16 09:04:13 +00001059 else
1060 return DBuilder.createPointerType(getOrCreateType(PointeeTy, Unit), Size,
Konstantin Zhuravlyovd1ba16e2017-03-08 23:56:48 +00001061 Align, DWARFAddressSpace);
Guy Benyei11169dd2012-12-18 14:30:41 +00001062}
1063
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001064llvm::DIType *CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
1065 llvm::DIType *&Cache) {
Eric Christopherf8bc4d82013-07-18 00:52:50 +00001066 if (Cache)
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001067 return Cache;
David Blaikiefefc7f72013-05-21 17:58:54 +00001068 Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
Adrian Prantlc2a44ec2018-12-11 16:58:46 +00001069 TheCU, TheCU->getFile(), 0);
David Blaikiefefc7f72013-05-21 17:58:54 +00001070 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1071 Cache = DBuilder.createPointerType(Cache, Size);
1072 return Cache;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001073}
1074
Scott Linder58df0e42018-08-08 15:56:12 +00001075uint64_t CGDebugInfo::collectDefaultElementTypesForBlockPointer(
1076 const BlockPointerType *Ty, llvm::DIFile *Unit, llvm::DIDerivedType *DescTy,
1077 unsigned LineNo, SmallVectorImpl<llvm::Metadata *> &EltTys) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001078 QualType FType;
Guy Benyei11169dd2012-12-18 14:30:41 +00001079
Scott Linder58df0e42018-08-08 15:56:12 +00001080 // Advanced by calls to CreateMemberType in increments of FType, then
1081 // returned as the overall size of the default elements.
1082 uint64_t FieldOffset = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00001083
Scott Linder58df0e42018-08-08 15:56:12 +00001084 // Blocks in OpenCL have unique constraints which make the standard fields
1085 // redundant while requiring size and align fields for enqueue_kernel. See
1086 // initializeForBlockHeader in CGBlocks.cpp
Scott Linder2b5cf042018-07-30 20:31:11 +00001087 if (CGM.getLangOpts().OpenCL) {
1088 FType = CGM.getContext().IntTy;
1089 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
1090 EltTys.push_back(CreateMemberType(Unit, FType, "__align", &FieldOffset));
1091 } else {
1092 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1093 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
1094 FType = CGM.getContext().IntTy;
1095 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
1096 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
1097 FType = CGM.getContext().getPointerType(Ty->getPointeeType());
1098 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
1099 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
Scott Linder58df0e42018-08-08 15:56:12 +00001100 uint64_t FieldSize = CGM.getContext().getTypeSize(Ty);
1101 uint32_t FieldAlign = CGM.getContext().getTypeAlign(Ty);
Scott Linder2b5cf042018-07-30 20:31:11 +00001102 EltTys.push_back(DBuilder.createMemberType(
Scott Linder58df0e42018-08-08 15:56:12 +00001103 Unit, "__descriptor", nullptr, LineNo, FieldSize, FieldAlign,
1104 FieldOffset, llvm::DINode::FlagZero, DescTy));
Scott Lindera7c45682018-07-30 22:52:07 +00001105 FieldOffset += FieldSize;
Scott Linder2b5cf042018-07-30 20:31:11 +00001106 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001107
Scott Linder58df0e42018-08-08 15:56:12 +00001108 return FieldOffset;
1109}
1110
1111llvm::DIType *CGDebugInfo::CreateType(const BlockPointerType *Ty,
1112 llvm::DIFile *Unit) {
1113 SmallVector<llvm::Metadata *, 8> EltTys;
1114 QualType FType;
1115 uint64_t FieldOffset;
1116 llvm::DINodeArray Elements;
1117
1118 FieldOffset = 0;
1119 FType = CGM.getContext().UnsignedLongTy;
1120 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
1121 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
1122
1123 Elements = DBuilder.getOrCreateArray(EltTys);
1124 EltTys.clear();
1125
1126 llvm::DINode::DIFlags Flags = llvm::DINode::FlagAppleBlock;
1127
1128 auto *EltTy =
1129 DBuilder.createStructType(Unit, "__block_descriptor", nullptr, 0,
1130 FieldOffset, 0, Flags, nullptr, Elements);
1131
1132 // Bit size, align and offset of the type.
1133 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1134
1135 auto *DescTy = DBuilder.createPointerType(EltTy, Size);
1136
1137 FieldOffset = collectDefaultElementTypesForBlockPointer(Ty, Unit, DescTy,
1138 0, EltTys);
1139
Guy Benyei11169dd2012-12-18 14:30:41 +00001140 Elements = DBuilder.getOrCreateArray(EltTys);
1141
Adrian Prantl3d2c0512015-07-07 00:49:35 +00001142 // The __block_literal_generic structs are marked with a special
1143 // DW_AT_APPLE_BLOCK attribute and are an implementation detail only
1144 // the debugger needs to know about. To allow type uniquing, emit
1145 // them without a name or a location.
Scott Linder58df0e42018-08-08 15:56:12 +00001146 EltTy = DBuilder.createStructType(Unit, "", nullptr, 0, FieldOffset, 0,
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00001147 Flags, nullptr, Elements);
Guy Benyei11169dd2012-12-18 14:30:41 +00001148
Adrian Prantl3d2c0512015-07-07 00:49:35 +00001149 return DBuilder.createPointerType(EltTy, Size);
Guy Benyei11169dd2012-12-18 14:30:41 +00001150}
1151
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001152llvm::DIType *CGDebugInfo::CreateType(const TemplateSpecializationType *Ty,
1153 llvm::DIFile *Unit) {
David Blaikief1b382e2014-04-06 17:14:06 +00001154 assert(Ty->isTypeAlias());
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001155 llvm::DIType *Src = getOrCreateType(Ty->getAliasedType(), Unit);
David Blaikief1b382e2014-04-06 17:14:06 +00001156
David Blaikie8472fa62019-06-08 00:01:21 +00001157 auto *AliasDecl =
1158 cast<TypeAliasTemplateDecl>(Ty->getTemplateName().getAsTemplateDecl())
1159 ->getTemplatedDecl();
1160
1161 if (AliasDecl->hasAttr<NoDebugAttr>())
1162 return Src;
1163
David Blaikief1b382e2014-04-06 17:14:06 +00001164 SmallString<128> NS;
1165 llvm::raw_svector_ostream OS(NS);
Serge Pavlov03e672c2017-11-28 16:14:14 +00001166 Ty->getTemplateName().print(OS, getPrintingPolicy(), /*qualified*/ false);
1167 printTemplateArgumentList(OS, Ty->template_arguments(), getPrintingPolicy());
David Blaikief1b382e2014-04-06 17:14:06 +00001168
David Blaikief1b382e2014-04-06 17:14:06 +00001169 SourceLocation Loc = AliasDecl->getLocation();
Adrian Prantlb67dbce2015-09-11 18:45:02 +00001170 return DBuilder.createTypedef(Src, OS.str(), getOrCreateFile(Loc),
1171 getLineNumber(Loc),
Sam McCalld27a16e2019-11-18 15:53:22 +01001172 getDeclContextDescriptor(AliasDecl));
David Blaikief1b382e2014-04-06 17:14:06 +00001173}
1174
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001175llvm::DIType *CGDebugInfo::CreateType(const TypedefType *Ty,
1176 llvm::DIFile *Unit) {
David Blaikie8472fa62019-06-08 00:01:21 +00001177 llvm::DIType *Underlying =
1178 getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
1179
1180 if (Ty->getDecl()->hasAttr<NoDebugAttr>())
1181 return Underlying;
1182
Guy Benyei11169dd2012-12-18 14:30:41 +00001183 // We don't set size information, but do specify where the typedef was
1184 // declared.
Amjad Abouddc4531e2016-04-30 01:44:38 +00001185 SourceLocation Loc = Ty->getDecl()->getLocation();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001186
Sourabh Singh Tomarf1e39882019-12-03 09:29:54 +05301187 uint32_t Align = getDeclAlignIfRequired(Ty->getDecl(), CGM.getContext());
Duncan P. N. Exon Smith4078ad42015-04-16 16:36:45 +00001188 // Typedefs are derived from some other type.
Sam McCalld27a16e2019-11-18 15:53:22 +01001189 return DBuilder.createTypedef(Underlying, Ty->getDecl()->getName(),
1190 getOrCreateFile(Loc), getLineNumber(Loc),
Sourabh Singh Tomarf1e39882019-12-03 09:29:54 +05301191 getDeclContextDescriptor(Ty->getDecl()), Align);
Guy Benyei11169dd2012-12-18 14:30:41 +00001192}
1193
Reid Klecknerf00f8032016-06-08 20:41:54 +00001194static unsigned getDwarfCC(CallingConv CC) {
1195 switch (CC) {
1196 case CC_C:
1197 // Avoid emitting DW_AT_calling_convention if the C convention was used.
1198 return 0;
1199
1200 case CC_X86StdCall:
1201 return llvm::dwarf::DW_CC_BORLAND_stdcall;
1202 case CC_X86FastCall:
1203 return llvm::dwarf::DW_CC_BORLAND_msfastcall;
1204 case CC_X86ThisCall:
1205 return llvm::dwarf::DW_CC_BORLAND_thiscall;
1206 case CC_X86VectorCall:
1207 return llvm::dwarf::DW_CC_LLVM_vectorcall;
1208 case CC_X86Pascal:
1209 return llvm::dwarf::DW_CC_BORLAND_pascal;
Martin Storsjo022e7822017-07-17 20:49:45 +00001210 case CC_Win64:
Jonas Devliegheref0702682018-03-22 13:53:30 +00001211 return llvm::dwarf::DW_CC_LLVM_Win64;
Reid Klecknerf00f8032016-06-08 20:41:54 +00001212 case CC_X86_64SysV:
Jonas Devliegheref0702682018-03-22 13:53:30 +00001213 return llvm::dwarf::DW_CC_LLVM_X86_64SysV;
Reid Klecknerf00f8032016-06-08 20:41:54 +00001214 case CC_AAPCS:
Sander de Smalen44a22532018-11-26 16:38:37 +00001215 case CC_AArch64VectorCall:
Jonas Devliegheref0702682018-03-22 13:53:30 +00001216 return llvm::dwarf::DW_CC_LLVM_AAPCS;
Reid Klecknerf00f8032016-06-08 20:41:54 +00001217 case CC_AAPCS_VFP:
Jonas Devliegheref0702682018-03-22 13:53:30 +00001218 return llvm::dwarf::DW_CC_LLVM_AAPCS_VFP;
Reid Klecknerf00f8032016-06-08 20:41:54 +00001219 case CC_IntelOclBicc:
Jonas Devliegheref0702682018-03-22 13:53:30 +00001220 return llvm::dwarf::DW_CC_LLVM_IntelOclBicc;
Reid Klecknerf00f8032016-06-08 20:41:54 +00001221 case CC_SpirFunction:
Jonas Devliegheref0702682018-03-22 13:53:30 +00001222 return llvm::dwarf::DW_CC_LLVM_SpirFunction;
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00001223 case CC_OpenCLKernel:
Jonas Devliegheref0702682018-03-22 13:53:30 +00001224 return llvm::dwarf::DW_CC_LLVM_OpenCLKernel;
Reid Klecknerf00f8032016-06-08 20:41:54 +00001225 case CC_Swift:
Jonas Devliegheref0702682018-03-22 13:53:30 +00001226 return llvm::dwarf::DW_CC_LLVM_Swift;
Reid Klecknerf00f8032016-06-08 20:41:54 +00001227 case CC_PreserveMost:
Jonas Devliegheref0702682018-03-22 13:53:30 +00001228 return llvm::dwarf::DW_CC_LLVM_PreserveMost;
Reid Klecknerf00f8032016-06-08 20:41:54 +00001229 case CC_PreserveAll:
Jonas Devliegheref0702682018-03-22 13:53:30 +00001230 return llvm::dwarf::DW_CC_LLVM_PreserveAll;
Erich Keane757d3172016-11-02 18:29:35 +00001231 case CC_X86RegCall:
Jonas Devliegheref0702682018-03-22 13:53:30 +00001232 return llvm::dwarf::DW_CC_LLVM_X86RegCall;
Reid Klecknerf00f8032016-06-08 20:41:54 +00001233 }
1234 return 0;
1235}
1236
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001237llvm::DIType *CGDebugInfo::CreateType(const FunctionType *Ty,
1238 llvm::DIFile *Unit) {
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001239 SmallVector<llvm::Metadata *, 16> EltTys;
Guy Benyei11169dd2012-12-18 14:30:41 +00001240
1241 // Add the result type at least.
Alp Toker314cc812014-01-25 16:55:45 +00001242 EltTys.push_back(getOrCreateType(Ty->getReturnType(), Unit));
Guy Benyei11169dd2012-12-18 14:30:41 +00001243
1244 // Set up remainder of arguments if there is a prototype.
Adrian Prantl800faef2014-02-25 23:42:18 +00001245 // otherwise emit it as a variadic function.
Guy Benyei11169dd2012-12-18 14:30:41 +00001246 if (isa<FunctionNoProtoType>(Ty))
1247 EltTys.push_back(DBuilder.createUnspecifiedParameter());
David Majnemer58ed0f32016-07-17 00:39:12 +00001248 else if (const auto *FPT = dyn_cast<FunctionProtoType>(Ty)) {
1249 for (const QualType &ParamType : FPT->param_types())
1250 EltTys.push_back(getOrCreateType(ParamType, Unit));
Adrian Prantld45ba252014-02-25 19:38:11 +00001251 if (FPT->isVariadic())
1252 EltTys.push_back(DBuilder.createUnspecifiedParameter());
Guy Benyei11169dd2012-12-18 14:30:41 +00001253 }
1254
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001255 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
Leny Kholodov80c047d2016-09-06 10:48:04 +00001256 return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
Reid Klecknerf00f8032016-06-08 20:41:54 +00001257 getDwarfCC(Ty->getCallConv()));
Guy Benyei11169dd2012-12-18 14:30:41 +00001258}
1259
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001260/// Convert an AccessSpecifier into the corresponding DINode flag.
Adrian Prantl21361fb2014-08-29 22:44:27 +00001261/// As an optimization, return 0 if the access specifier equals the
1262/// default for the containing type.
Leny Kholodovdf050fd2016-09-06 17:06:14 +00001263static llvm::DINode::DIFlags getAccessFlag(AccessSpecifier Access,
1264 const RecordDecl *RD) {
Adrian Prantl21361fb2014-08-29 22:44:27 +00001265 AccessSpecifier Default = clang::AS_none;
1266 if (RD && RD->isClass())
1267 Default = clang::AS_private;
1268 else if (RD && (RD->isStruct() || RD->isUnion()))
1269 Default = clang::AS_public;
1270
1271 if (Access == Default)
Leny Kholodov80c047d2016-09-06 10:48:04 +00001272 return llvm::DINode::FlagZero;
Adrian Prantl21361fb2014-08-29 22:44:27 +00001273
Eric Christophere7b87e52014-10-26 23:40:33 +00001274 switch (Access) {
1275 case clang::AS_private:
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001276 return llvm::DINode::FlagPrivate;
Eric Christophere7b87e52014-10-26 23:40:33 +00001277 case clang::AS_protected:
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001278 return llvm::DINode::FlagProtected;
Eric Christophere7b87e52014-10-26 23:40:33 +00001279 case clang::AS_public:
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001280 return llvm::DINode::FlagPublic;
Eric Christophere7b87e52014-10-26 23:40:33 +00001281 case clang::AS_none:
Leny Kholodov80c047d2016-09-06 10:48:04 +00001282 return llvm::DINode::FlagZero;
Adrian Prantl21361fb2014-08-29 22:44:27 +00001283 }
1284 llvm_unreachable("unexpected access enumerator");
1285}
Guy Benyei11169dd2012-12-18 14:30:41 +00001286
David Majnemerb4b671e2016-06-30 03:01:59 +00001287llvm::DIType *CGDebugInfo::createBitFieldType(const FieldDecl *BitFieldDecl,
1288 llvm::DIScope *RecordTy,
1289 const RecordDecl *RD) {
1290 StringRef Name = BitFieldDecl->getName();
1291 QualType Ty = BitFieldDecl->getType();
1292 SourceLocation Loc = BitFieldDecl->getLocation();
1293 llvm::DIFile *VUnit = getOrCreateFile(Loc);
1294 llvm::DIType *DebugType = getOrCreateType(Ty, VUnit);
1295
1296 // Get the location for the field.
1297 llvm::DIFile *File = getOrCreateFile(Loc);
1298 unsigned Line = getLineNumber(Loc);
1299
1300 const CGBitFieldInfo &BitFieldInfo =
1301 CGM.getTypes().getCGRecordLayout(RD).getBitFieldInfo(BitFieldDecl);
1302 uint64_t SizeInBits = BitFieldInfo.Size;
1303 assert(SizeInBits > 0 && "found named 0-width bitfield");
David Majnemerb4b671e2016-06-30 03:01:59 +00001304 uint64_t StorageOffsetInBits =
1305 CGM.getContext().toBits(BitFieldInfo.StorageOffset);
Reid Kleckner06a4b2a2017-06-12 19:57:56 +00001306 uint64_t Offset = BitFieldInfo.Offset;
1307 // The bit offsets for big endian machines are reversed for big
1308 // endian target, compensate for that as the DIDerivedType requires
1309 // un-reversed offsets.
1310 if (CGM.getDataLayout().isBigEndian())
1311 Offset = BitFieldInfo.StorageSize - BitFieldInfo.Size - Offset;
1312 uint64_t OffsetInBits = StorageOffsetInBits + Offset;
Leny Kholodov80c047d2016-09-06 10:48:04 +00001313 llvm::DINode::DIFlags Flags = getAccessFlag(BitFieldDecl->getAccess(), RD);
David Majnemerb4b671e2016-06-30 03:01:59 +00001314 return DBuilder.createBitFieldMemberType(
Victor Leschuka7ece032016-10-20 00:13:19 +00001315 RecordTy, Name, File, Line, SizeInBits, OffsetInBits, StorageOffsetInBits,
1316 Flags, DebugType);
David Majnemerb4b671e2016-06-30 03:01:59 +00001317}
1318
1319llvm::DIType *
1320CGDebugInfo::createFieldType(StringRef name, QualType type, SourceLocation loc,
1321 AccessSpecifier AS, uint64_t offsetInBits,
Victor Leschuka7ece032016-10-20 00:13:19 +00001322 uint32_t AlignInBits, llvm::DIFile *tunit,
1323 llvm::DIScope *scope, const RecordDecl *RD) {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001324 llvm::DIType *debugType = getOrCreateType(type, tunit);
Guy Benyei11169dd2012-12-18 14:30:41 +00001325
1326 // Get the location for the field.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001327 llvm::DIFile *file = getOrCreateFile(loc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001328 unsigned line = getLineNumber(loc);
1329
David Majnemer34b57492014-07-30 01:30:47 +00001330 uint64_t SizeInBits = 0;
Victor Leschuka7ece032016-10-20 00:13:19 +00001331 auto Align = AlignInBits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001332 if (!type->isIncompleteArrayType()) {
David Majnemer34b57492014-07-30 01:30:47 +00001333 TypeInfo TI = CGM.getContext().getTypeInfo(type);
1334 SizeInBits = TI.Width;
Victor Leschuka7ece032016-10-20 00:13:19 +00001335 if (!Align)
1336 Align = getTypeAlignIfRequired(type, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00001337 }
1338
Leny Kholodov80c047d2016-09-06 10:48:04 +00001339 llvm::DINode::DIFlags flags = getAccessFlag(AS, RD);
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00001340 return DBuilder.createMemberType(scope, name, file, line, SizeInBits, Align,
1341 offsetInBits, flags, debugType);
Guy Benyei11169dd2012-12-18 14:30:41 +00001342}
1343
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001344void CGDebugInfo::CollectRecordLambdaFields(
1345 const CXXRecordDecl *CXXDecl, SmallVectorImpl<llvm::Metadata *> &elements,
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001346 llvm::DIType *RecordTy) {
Eric Christopher91a31902013-01-16 01:22:32 +00001347 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
1348 // has the name and the location of the variable so we should iterate over
1349 // both concurrently.
1350 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
1351 RecordDecl::field_iterator Field = CXXDecl->field_begin();
1352 unsigned fieldno = 0;
1353 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
Eric Christophere7b87e52014-10-26 23:40:33 +00001354 E = CXXDecl->captures_end();
1355 I != E; ++I, ++Field, ++fieldno) {
Benjamin Kramerf3ca26982014-05-10 16:31:55 +00001356 const LambdaCapture &C = *I;
Eric Christopher91a31902013-01-16 01:22:32 +00001357 if (C.capturesVariable()) {
David Majnemerb4b671e2016-06-30 03:01:59 +00001358 SourceLocation Loc = C.getLocation();
1359 assert(!Field->isBitField() && "lambdas don't have bitfield members!");
Eric Christopher91a31902013-01-16 01:22:32 +00001360 VarDecl *V = C.getCapturedVar();
Eric Christopher91a31902013-01-16 01:22:32 +00001361 StringRef VName = V->getName();
David Majnemerb4b671e2016-06-30 03:01:59 +00001362 llvm::DIFile *VUnit = getOrCreateFile(Loc);
Victor Leschuka7ece032016-10-20 00:13:19 +00001363 auto Align = getDeclAlignIfRequired(V, CGM.getContext());
David Majnemerb4b671e2016-06-30 03:01:59 +00001364 llvm::DIType *FieldType = createFieldType(
1365 VName, Field->getType(), Loc, Field->getAccess(),
Victor Leschuka7ece032016-10-20 00:13:19 +00001366 layout.getFieldOffset(fieldno), Align, VUnit, RecordTy, CXXDecl);
David Majnemerb4b671e2016-06-30 03:01:59 +00001367 elements.push_back(FieldType);
Alexey Bataev39c81e22014-08-28 04:28:19 +00001368 } else if (C.capturesThis()) {
Eric Christopher91a31902013-01-16 01:22:32 +00001369 // TODO: Need to handle 'this' in some way by probably renaming the
1370 // this of the lambda class and having a field member of 'this' or
1371 // by using AT_object_pointer for the function and having that be
1372 // used as 'this' for semantic references.
Eric Christopher91a31902013-01-16 01:22:32 +00001373 FieldDecl *f = *Field;
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001374 llvm::DIFile *VUnit = getOrCreateFile(f->getLocation());
Eric Christopher91a31902013-01-16 01:22:32 +00001375 QualType type = f->getType();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001376 llvm::DIType *fieldType = createFieldType(
David Majnemerb4b671e2016-06-30 03:01:59 +00001377 "this", type, f->getLocation(), f->getAccess(),
Eric Christophere7b87e52014-10-26 23:40:33 +00001378 layout.getFieldOffset(fieldno), VUnit, RecordTy, CXXDecl);
Eric Christopher91a31902013-01-16 01:22:32 +00001379
1380 elements.push_back(fieldType);
1381 }
1382 }
1383}
1384
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001385llvm::DIDerivedType *
1386CGDebugInfo::CreateRecordStaticField(const VarDecl *Var, llvm::DIType *RecordTy,
Duncan P. N. Exon Smithc09c5482015-04-20 21:17:26 +00001387 const RecordDecl *RD) {
Eric Christopher91a31902013-01-16 01:22:32 +00001388 // Create the descriptor for the static variable, with or without
1389 // constant initializers.
David Blaikie8e707bb2014-10-14 22:22:17 +00001390 Var = Var->getCanonicalDecl();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001391 llvm::DIFile *VUnit = getOrCreateFile(Var->getLocation());
1392 llvm::DIType *VTy = getOrCreateType(Var->getType(), VUnit);
Eric Christopher91a31902013-01-16 01:22:32 +00001393
Eric Christopher91a31902013-01-16 01:22:32 +00001394 unsigned LineNumber = getLineNumber(Var->getLocation());
1395 StringRef VName = Var->getName();
Craig Topper8a13c412014-05-21 05:09:00 +00001396 llvm::Constant *C = nullptr;
Eric Christopher91a31902013-01-16 01:22:32 +00001397 if (Var->getInit()) {
1398 const APValue *Value = Var->evaluateValue();
David Blaikied42917f2013-01-20 01:19:17 +00001399 if (Value) {
1400 if (Value->isInt())
1401 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
1402 if (Value->isFloat())
1403 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
1404 }
Eric Christopher91a31902013-01-16 01:22:32 +00001405 }
1406
Leny Kholodov80c047d2016-09-06 10:48:04 +00001407 llvm::DINode::DIFlags Flags = getAccessFlag(Var->getAccess(), RD);
Victor Leschuka7ece032016-10-20 00:13:19 +00001408 auto Align = getDeclAlignIfRequired(Var, CGM.getContext());
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001409 llvm::DIDerivedType *GV = DBuilder.createStaticMemberType(
Victor Leschuka7ece032016-10-20 00:13:19 +00001410 RecordTy, VName, VUnit, LineNumber, VTy, Flags, C, Align);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001411 StaticDataMemberCache[Var->getCanonicalDecl()].reset(GV);
David Blaikieae019462013-08-15 22:50:29 +00001412 return GV;
Eric Christopher91a31902013-01-16 01:22:32 +00001413}
1414
Eric Christophere7b87e52014-10-26 23:40:33 +00001415void CGDebugInfo::CollectRecordNormalField(
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001416 const FieldDecl *field, uint64_t OffsetInBits, llvm::DIFile *tunit,
1417 SmallVectorImpl<llvm::Metadata *> &elements, llvm::DIType *RecordTy,
Eric Christophere7b87e52014-10-26 23:40:33 +00001418 const RecordDecl *RD) {
Eric Christopher91a31902013-01-16 01:22:32 +00001419 StringRef name = field->getName();
1420 QualType type = field->getType();
1421
1422 // Ignore unnamed fields unless they're anonymous structs/unions.
1423 if (name.empty() && !type->isRecordType())
1424 return;
1425
David Majnemerb4b671e2016-06-30 03:01:59 +00001426 llvm::DIType *FieldType;
Eric Christopher91a31902013-01-16 01:22:32 +00001427 if (field->isBitField()) {
David Majnemerb4b671e2016-06-30 03:01:59 +00001428 FieldType = createBitFieldType(field, RecordTy, RD);
1429 } else {
Victor Leschuka7ece032016-10-20 00:13:19 +00001430 auto Align = getDeclAlignIfRequired(field, CGM.getContext());
David Majnemerb4b671e2016-06-30 03:01:59 +00001431 FieldType =
1432 createFieldType(name, type, field->getLocation(), field->getAccess(),
Victor Leschuka7ece032016-10-20 00:13:19 +00001433 OffsetInBits, Align, tunit, RecordTy, RD);
Eric Christopher91a31902013-01-16 01:22:32 +00001434 }
1435
David Majnemerb4b671e2016-06-30 03:01:59 +00001436 elements.push_back(FieldType);
Eric Christopher91a31902013-01-16 01:22:32 +00001437}
1438
Reid Klecknere2e82062017-08-08 20:30:14 +00001439void CGDebugInfo::CollectRecordNestedType(
1440 const TypeDecl *TD, SmallVectorImpl<llvm::Metadata *> &elements) {
1441 QualType Ty = CGM.getContext().getTypeDeclType(TD);
Reid Kleckner755220b2016-08-01 18:56:13 +00001442 // Injected class names are not considered nested records.
1443 if (isa<InjectedClassNameType>(Ty))
1444 return;
Reid Klecknere2e82062017-08-08 20:30:14 +00001445 SourceLocation Loc = TD->getLocation();
Adrian McCarthyab1e7862016-07-21 18:43:20 +00001446 llvm::DIType *nestedType = getOrCreateType(Ty, getOrCreateFile(Loc));
1447 elements.push_back(nestedType);
1448}
1449
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001450void CGDebugInfo::CollectRecordFields(
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001451 const RecordDecl *record, llvm::DIFile *tunit,
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001452 SmallVectorImpl<llvm::Metadata *> &elements,
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001453 llvm::DICompositeType *RecordTy) {
David Majnemer58ed0f32016-07-17 00:39:12 +00001454 const auto *CXXDecl = dyn_cast<CXXRecordDecl>(record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001455
Eric Christopher91a31902013-01-16 01:22:32 +00001456 if (CXXDecl && CXXDecl->isLambda())
1457 CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
1458 else {
1459 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001460
Eric Christopher91a31902013-01-16 01:22:32 +00001461 // Field number for non-static fields.
Eric Christopher0f7594372013-01-04 17:59:07 +00001462 unsigned fieldNo = 0;
Eric Christopher91a31902013-01-16 01:22:32 +00001463
Eric Christopher91a31902013-01-16 01:22:32 +00001464 // Static and non-static members should appear in the same order as
1465 // the corresponding declarations in the source program.
Aaron Ballman629afae2014-03-07 19:56:05 +00001466 for (const auto *I : record->decls())
1467 if (const auto *V = dyn_cast<VarDecl>(I)) {
Paul Robinsonb17327d2016-04-27 17:37:12 +00001468 if (V->hasAttr<NoDebugAttr>())
1469 continue;
Reid Kleckner891b2712018-07-20 20:55:00 +00001470
1471 // Skip variable template specializations when emitting CodeView. MSVC
1472 // doesn't emit them.
1473 if (CGM.getCodeGenOpts().EmitCodeView &&
1474 isa<VarTemplateSpecializationDecl>(V))
1475 continue;
1476
David Blaikie4f3b7362019-06-17 19:40:52 +00001477 if (isa<VarTemplatePartialSpecializationDecl>(V))
1478 continue;
1479
David Blaikiece763042013-08-20 21:49:21 +00001480 // Reuse the existing static member declaration if one exists
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001481 auto MI = StaticDataMemberCache.find(V->getCanonicalDecl());
David Blaikiece763042013-08-20 21:49:21 +00001482 if (MI != StaticDataMemberCache.end()) {
1483 assert(MI->second &&
1484 "Static data member declaration should still exist");
Duncan P. N. Exon Smithac346ba2015-07-24 18:05:58 +00001485 elements.push_back(MI->second);
Adrian Prantl21361fb2014-08-29 22:44:27 +00001486 } else {
1487 auto Field = CreateRecordStaticField(V, RecordTy, record);
1488 elements.push_back(Field);
1489 }
Aaron Ballman629afae2014-03-07 19:56:05 +00001490 } else if (const auto *field = dyn_cast<FieldDecl>(I)) {
Eric Christophere7b87e52014-10-26 23:40:33 +00001491 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo), tunit,
1492 elements, RecordTy, record);
Eric Christopher91a31902013-01-16 01:22:32 +00001493
1494 // Bump field number for next field.
1495 ++fieldNo;
Reid Kleckner891b2712018-07-20 20:55:00 +00001496 } else if (CGM.getCodeGenOpts().EmitCodeView) {
1497 // Debug info for nested types is included in the member list only for
1498 // CodeView.
Reid Klecknere2e82062017-08-08 20:30:14 +00001499 if (const auto *nestedType = dyn_cast<TypeDecl>(I))
1500 if (!nestedType->isImplicit() &&
1501 nestedType->getDeclContext() == record)
1502 CollectRecordNestedType(nestedType, elements);
1503 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001504 }
1505}
1506
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001507llvm::DISubroutineType *
Guy Benyei11169dd2012-12-18 14:30:41 +00001508CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
Awanish Pandeyc83602f2020-01-23 16:06:52 +05301509 llvm::DIFile *Unit, bool decl) {
David Blaikie7eb06852013-01-07 23:06:35 +00001510 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
David Blaikie2aaf0652013-01-07 22:24:59 +00001511 if (Method->isStatic())
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001512 return cast_or_null<llvm::DISubroutineType>(
Duncan P. N. Exon Smithc7551282015-04-06 23:21:33 +00001513 getOrCreateType(QualType(Func, 0), Unit));
Awanish Pandeyc83602f2020-01-23 16:06:52 +05301514 return getOrCreateInstanceMethodType(Method->getThisType(), Func, Unit, decl);
David Blaikie7eb06852013-01-07 23:06:35 +00001515}
David Blaikie2aaf0652013-01-07 22:24:59 +00001516
Awanish Pandeyc83602f2020-01-23 16:06:52 +05301517llvm::DISubroutineType *
1518CGDebugInfo::getOrCreateInstanceMethodType(QualType ThisPtr,
1519 const FunctionProtoType *Func,
1520 llvm::DIFile *Unit, bool decl) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001521 // Add "this" pointer.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001522 llvm::DITypeRefArray Args(
1523 cast<llvm::DISubroutineType>(getOrCreateType(QualType(Func, 0), Unit))
Duncan P. N. Exon Smithc7551282015-04-06 23:21:33 +00001524 ->getTypeArray());
Duncan P. N. Exon Smitha98fac62015-04-07 04:14:45 +00001525 assert(Args.size() && "Invalid number of arguments!");
Guy Benyei11169dd2012-12-18 14:30:41 +00001526
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001527 SmallVector<llvm::Metadata *, 16> Elts;
Guy Benyei11169dd2012-12-18 14:30:41 +00001528 // First element is always return type. For 'void' functions it is NULL.
Awanish Pandeyc83602f2020-01-23 16:06:52 +05301529 QualType temp = Func->getReturnType();
1530 if (temp->getTypeClass() == Type::Auto && decl)
1531 Elts.push_back(CreateType(cast<AutoType>(temp)));
1532 else
1533 Elts.push_back(Args[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001534
David Blaikie2aaf0652013-01-07 22:24:59 +00001535 // "this" pointer is always first argument.
David Blaikie7eb06852013-01-07 23:06:35 +00001536 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
David Blaikie2aaf0652013-01-07 22:24:59 +00001537 if (isa<ClassTemplateSpecializationDecl>(RD)) {
1538 // Create pointer type directly in this case.
1539 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
1540 QualType PointeeTy = ThisPtrTy->getPointeeType();
1541 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCallc8e01702013-04-16 22:48:15 +00001542 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
Victor Leschuka7ece032016-10-20 00:13:19 +00001543 auto Align = getTypeAlignIfRequired(ThisPtrTy, CGM.getContext());
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001544 llvm::DIType *PointeeType = getOrCreateType(PointeeTy, Unit);
1545 llvm::DIType *ThisPtrType =
Eric Christophere7b87e52014-10-26 23:40:33 +00001546 DBuilder.createPointerType(PointeeType, Size, Align);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001547 TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);
David Blaikie2aaf0652013-01-07 22:24:59 +00001548 // TODO: This and the artificial type below are misleading, the
1549 // types aren't artificial the argument is, but the current
1550 // metadata doesn't represent that.
1551 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1552 Elts.push_back(ThisPtrType);
1553 } else {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001554 llvm::DIType *ThisPtrType = getOrCreateType(ThisPtr, Unit);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001555 TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);
David Blaikie2aaf0652013-01-07 22:24:59 +00001556 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1557 Elts.push_back(ThisPtrType);
Guy Benyei11169dd2012-12-18 14:30:41 +00001558 }
1559
1560 // Copy rest of the arguments.
Duncan P. N. Exon Smitha98fac62015-04-07 04:14:45 +00001561 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1562 Elts.push_back(Args[i]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001563
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001564 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
Guy Benyei11169dd2012-12-18 14:30:41 +00001565
Leny Kholodov80c047d2016-09-06 10:48:04 +00001566 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
Adrian Prantl0630eb72013-12-18 21:48:18 +00001567 if (Func->getExtProtoInfo().RefQualifier == RQ_LValue)
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001568 Flags |= llvm::DINode::FlagLValueReference;
Adrian Prantl0630eb72013-12-18 21:48:18 +00001569 if (Func->getExtProtoInfo().RefQualifier == RQ_RValue)
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001570 Flags |= llvm::DINode::FlagRValueReference;
Adrian Prantl0630eb72013-12-18 21:48:18 +00001571
Reid Klecknerf00f8032016-06-08 20:41:54 +00001572 return DBuilder.createSubroutineType(EltTypeArray, Flags,
1573 getDwarfCC(Func->getCallConv()));
Guy Benyei11169dd2012-12-18 14:30:41 +00001574}
1575
Eric Christopherb2a008c2013-05-16 00:45:12 +00001576/// isFunctionLocalClass - Return true if CXXRecordDecl is defined
Guy Benyei11169dd2012-12-18 14:30:41 +00001577/// inside a function.
1578static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
David Majnemer58ed0f32016-07-17 00:39:12 +00001579 if (const auto *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
Guy Benyei11169dd2012-12-18 14:30:41 +00001580 return isFunctionLocalClass(NRD);
1581 if (isa<FunctionDecl>(RD->getDeclContext()))
1582 return true;
1583 return false;
1584}
1585
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001586llvm::DISubprogram *CGDebugInfo::CreateCXXMemberFunction(
1587 const CXXMethodDecl *Method, llvm::DIFile *Unit, llvm::DIType *RecordTy) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001588 bool IsCtorOrDtor =
Eric Christophere7b87e52014-10-26 23:40:33 +00001589 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
Eric Christopherb2a008c2013-05-16 00:45:12 +00001590
Guy Benyei11169dd2012-12-18 14:30:41 +00001591 StringRef MethodName = getFunctionName(Method);
Awanish Pandeyc83602f2020-01-23 16:06:52 +05301592 llvm::DISubroutineType *MethodTy = getOrCreateMethodType(Method, Unit, true);
Guy Benyei11169dd2012-12-18 14:30:41 +00001593
1594 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1595 // make sense to give a single ctor/dtor a linkage name.
1596 StringRef MethodLinkageName;
David Blaikie71647672016-04-12 21:22:48 +00001597 // FIXME: 'isFunctionLocalClass' seems like an arbitrary/unintentional
1598 // property to use here. It may've been intended to model "is non-external
1599 // type" but misses cases of non-function-local but non-external classes such
1600 // as those in anonymous namespaces as well as the reverse - external types
1601 // that are function local, such as those in (non-local) inline functions.
Guy Benyei11169dd2012-12-18 14:30:41 +00001602 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1603 MethodLinkageName = CGM.getMangledName(Method);
1604
1605 // Get the location for the method.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001606 llvm::DIFile *MethodDefUnit = nullptr;
David Blaikie7fceebf2013-08-19 03:37:48 +00001607 unsigned MethodLine = 0;
1608 if (!Method->isImplicit()) {
1609 MethodDefUnit = getOrCreateFile(Method->getLocation());
1610 MethodLine = getLineNumber(Method->getLocation());
1611 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001612
1613 // Collect virtual method info.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001614 llvm::DIType *ContainingType = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001615 unsigned VIndex = 0;
Leny Kholodov80c047d2016-09-06 10:48:04 +00001616 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
Paul Robinsoncda54212018-11-19 18:29:28 +00001617 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
Reid Kleckner0358cbf2016-07-01 02:41:25 +00001618 int ThisAdjustment = 0;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001619
Guy Benyei11169dd2012-12-18 14:30:41 +00001620 if (Method->isVirtual()) {
1621 if (Method->isPure())
Paul Robinsoncda54212018-11-19 18:29:28 +00001622 SPFlags |= llvm::DISubprogram::SPFlagPureVirtual;
Guy Benyei11169dd2012-12-18 14:30:41 +00001623 else
Paul Robinsoncda54212018-11-19 18:29:28 +00001624 SPFlags |= llvm::DISubprogram::SPFlagVirtual;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001625
Reid Kleckner216d0a12016-06-16 20:08:51 +00001626 if (CGM.getTarget().getCXXABI().isItaniumFamily()) {
1627 // It doesn't make sense to give a virtual destructor a vtable index,
1628 // since a single destructor has two entries in the vtable.
1629 if (!isa<CXXDestructorDecl>(Method))
1630 VIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(Method);
1631 } else {
1632 // Emit MS ABI vftable information. There is only one entry for the
1633 // deleting dtor.
1634 const auto *DD = dyn_cast<CXXDestructorDecl>(Method);
1635 GlobalDecl GD = DD ? GlobalDecl(DD, Dtor_Deleting) : GlobalDecl(Method);
Reid Klecknercbec0262018-04-02 20:00:39 +00001636 MethodVFTableLocation ML =
Reid Kleckner216d0a12016-06-16 20:08:51 +00001637 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD);
1638 VIndex = ML.Index;
Reid Klecknerc4871ed2016-06-22 18:34:45 +00001639
1640 // CodeView only records the vftable offset in the class that introduces
1641 // the virtual method. This is possible because, unlike Itanium, the MS
1642 // C++ ABI does not include all virtual methods from non-primary bases in
1643 // the vtable for the most derived class. For example, if C inherits from
1644 // A and B, C's primary vftable will not include B's virtual methods.
Benjamin Krameracfa3392017-12-17 23:52:45 +00001645 if (Method->size_overridden_methods() == 0)
Reid Klecknerc4871ed2016-06-22 18:34:45 +00001646 Flags |= llvm::DINode::FlagIntroducedVirtual;
1647
Reid Kleckner0358cbf2016-07-01 02:41:25 +00001648 // The 'this' adjustment accounts for both the virtual and non-virtual
1649 // portions of the adjustment. Presumably the debugger only uses it when
1650 // it knows the dynamic type of an object.
1651 ThisAdjustment = CGM.getCXXABI()
1652 .getVirtualFunctionPrologueThisAdjustment(GD)
1653 .getQuantity();
Reid Kleckner216d0a12016-06-16 20:08:51 +00001654 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001655 ContainingType = RecordTy;
1656 }
1657
Adrian Prantlf919be32019-10-29 09:20:14 -07001658 // We're checking for deleted C++ special member functions
1659 // [Ctors,Dtors, Copy/Move]
Sourabh Singh Tomar52ea3082019-11-02 01:28:40 +05301660 auto checkAttrDeleted = [&](const auto *Method) {
Adrian Prantlf919be32019-10-29 09:20:14 -07001661 if (Method->getCanonicalDecl()->isDeleted())
1662 SPFlags |= llvm::DISubprogram::SPFlagDeleted;
1663 };
1664
1665 switch (Method->getKind()) {
1666
1667 case Decl::CXXConstructor:
1668 case Decl::CXXDestructor:
1669 checkAttrDeleted(Method);
1670 break;
1671 case Decl::CXXMethod:
1672 if (Method->isCopyAssignmentOperator() ||
1673 Method->isMoveAssignmentOperator())
1674 checkAttrDeleted(Method);
1675 break;
1676 default:
1677 break;
1678 }
1679
Adrian Prantla9cfde12019-10-16 16:30:38 +00001680 if (Method->isNoReturn())
1681 Flags |= llvm::DINode::FlagNoReturn;
Adrian Prantlf919be32019-10-29 09:20:14 -07001682
Adrian McCarthyd91bf392017-09-13 20:53:55 +00001683 if (Method->isStatic())
1684 Flags |= llvm::DINode::FlagStaticMember;
Guy Benyei11169dd2012-12-18 14:30:41 +00001685 if (Method->isImplicit())
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001686 Flags |= llvm::DINode::FlagArtificial;
Adrian Prantl21361fb2014-08-29 22:44:27 +00001687 Flags |= getAccessFlag(Method->getAccess(), Method->getParent());
David Majnemer58ed0f32016-07-17 00:39:12 +00001688 if (const auto *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001689 if (CXXC->isExplicit())
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001690 Flags |= llvm::DINode::FlagExplicit;
David Majnemer58ed0f32016-07-17 00:39:12 +00001691 } else if (const auto *CXXC = dyn_cast<CXXConversionDecl>(Method)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001692 if (CXXC->isExplicit())
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001693 Flags |= llvm::DINode::FlagExplicit;
Guy Benyei11169dd2012-12-18 14:30:41 +00001694 }
1695 if (Method->hasPrototype())
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001696 Flags |= llvm::DINode::FlagPrototyped;
Adrian Prantl0630eb72013-12-18 21:48:18 +00001697 if (Method->getRefQualifier() == RQ_LValue)
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001698 Flags |= llvm::DINode::FlagLValueReference;
Adrian Prantl0630eb72013-12-18 21:48:18 +00001699 if (Method->getRefQualifier() == RQ_RValue)
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001700 Flags |= llvm::DINode::FlagRValueReference;
Paul Robinsoncda54212018-11-19 18:29:28 +00001701 if (CGM.getLangOpts().Optimize)
1702 SPFlags |= llvm::DISubprogram::SPFlagOptimized;
Guy Benyei11169dd2012-12-18 14:30:41 +00001703
Amy Huang651128f2020-01-03 16:28:48 -08001704 // In this debug mode, emit type info for a class when its constructor type
1705 // info is emitted.
1706 if (DebugKind == codegenoptions::DebugInfoConstructor)
1707 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
1708 completeClass(CD->getParent());
1709
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001710 llvm::DINodeArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1711 llvm::DISubprogram *SP = DBuilder.createMethod(
Eric Christophere7b87e52014-10-26 23:40:33 +00001712 RecordTy, MethodName, MethodLinkageName, MethodDefUnit, MethodLine,
Paul Robinsoncda54212018-11-19 18:29:28 +00001713 MethodTy, VIndex, ThisAdjustment, ContainingType, Flags, SPFlags,
Reid Kleckner0358cbf2016-07-01 02:41:25 +00001714 TParamsArray.get());
Eric Christopherb2a008c2013-05-16 00:45:12 +00001715
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001716 SPCache[Method->getCanonicalDecl()].reset(SP);
Guy Benyei11169dd2012-12-18 14:30:41 +00001717
1718 return SP;
1719}
1720
Eric Christophere7b87e52014-10-26 23:40:33 +00001721void CGDebugInfo::CollectCXXMemberFunctions(
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001722 const CXXRecordDecl *RD, llvm::DIFile *Unit,
1723 SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001724
1725 // Since we want more than just the individual member decls if we
1726 // have templated functions iterate over every declaration to gather
1727 // the functions.
Eric Christophere7b87e52014-10-26 23:40:33 +00001728 for (const auto *I : RD->decls()) {
David Blaikiefd580722014-10-06 05:18:55 +00001729 const auto *Method = dyn_cast<CXXMethodDecl>(I);
1730 // If the member is implicit, don't add it to the member list. This avoids
1731 // the member being added to type units by LLVM, while still allowing it
1732 // to be emitted into the type declaration/reference inside the compile
1733 // unit.
Paul Robinson6a7511b2015-06-25 17:50:43 +00001734 // Ditto 'nodebug' methods, for consistency with CodeGenFunction.cpp.
David Blaikie6dddfe32014-10-06 05:52:27 +00001735 // FIXME: Handle Using(Shadow?)Decls here to create
1736 // DW_TAG_imported_declarations inside the class for base decls brought into
1737 // derived classes. GDB doesn't seem to notice/leverage these when I tried
1738 // it, so I'm not rushing to fix this. (GCC seems to produce them, if
1739 // referenced)
Paul Robinson6a7511b2015-06-25 17:50:43 +00001740 if (!Method || Method->isImplicit() || Method->hasAttr<NoDebugAttr>())
David Blaikiefd580722014-10-06 05:18:55 +00001741 continue;
David Blaikie42edade2014-11-11 20:44:45 +00001742
Simon Pilgrim7e38f0c2019-10-07 16:42:25 +00001743 if (Method->getType()->castAs<FunctionProtoType>()->getContainedAutoType())
David Blaikie42edade2014-11-11 20:44:45 +00001744 continue;
1745
David Blaikiefd580722014-10-06 05:18:55 +00001746 // Reuse the existing member function declaration if it exists.
1747 // It may be associated with the declaration of the type & should be
1748 // reused as we're building the definition.
1749 //
1750 // This situation can arise in the vtable-based debug info reduction where
1751 // implicit members are emitted in a non-vtable TU.
1752 auto MI = SPCache.find(Method->getCanonicalDecl());
1753 EltTys.push_back(MI == SPCache.end()
1754 ? CreateCXXMemberFunction(Method, Unit, RecordTy)
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001755 : static_cast<llvm::Metadata *>(MI->second));
Guy Benyei11169dd2012-12-18 14:30:41 +00001756 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00001757}
Guy Benyei11169dd2012-12-18 14:30:41 +00001758
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001759void CGDebugInfo::CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile *Unit,
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001760 SmallVectorImpl<llvm::Metadata *> &EltTys,
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001761 llvm::DIType *RecordTy) {
Bob Haarmandff36732016-10-25 22:19:32 +00001762 llvm::DenseSet<CanonicalDeclPtr<const CXXRecordDecl>> SeenTypes;
1763 CollectCXXBasesAux(RD, Unit, EltTys, RecordTy, RD->bases(), SeenTypes,
1764 llvm::DINode::FlagZero);
Eric Christopherb2a008c2013-05-16 00:45:12 +00001765
Bob Haarmandff36732016-10-25 22:19:32 +00001766 // If we are generating CodeView debug info, we also need to emit records for
1767 // indirect virtual base classes.
1768 if (CGM.getCodeGenOpts().EmitCodeView) {
1769 CollectCXXBasesAux(RD, Unit, EltTys, RecordTy, RD->vbases(), SeenTypes,
1770 llvm::DINode::FlagIndirectVirtualBase);
1771 }
1772}
1773
1774void CGDebugInfo::CollectCXXBasesAux(
1775 const CXXRecordDecl *RD, llvm::DIFile *Unit,
1776 SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy,
1777 const CXXRecordDecl::base_class_const_range &Bases,
1778 llvm::DenseSet<CanonicalDeclPtr<const CXXRecordDecl>> &SeenTypes,
1779 llvm::DINode::DIFlags StartingFlags) {
1780 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1781 for (const auto &BI : Bases) {
David Majnemer58ed0f32016-07-17 00:39:12 +00001782 const auto *Base =
Simon Pilgrim1cd399c2019-10-03 11:22:48 +00001783 cast<CXXRecordDecl>(BI.getType()->castAs<RecordType>()->getDecl());
Bob Haarmandff36732016-10-25 22:19:32 +00001784 if (!SeenTypes.insert(Base).second)
1785 continue;
1786 auto *BaseTy = getOrCreateType(BI.getType(), Unit);
1787 llvm::DINode::DIFlags BFlags = StartingFlags;
1788 uint64_t BaseOffset;
Brock Wyma3db2b102018-05-14 21:21:22 +00001789 uint32_t VBPtrOffset = 0;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001790
Aaron Ballman574705e2014-03-13 15:41:46 +00001791 if (BI.isVirtual()) {
Reid Klecknerd3b23d62014-08-07 21:29:25 +00001792 if (CGM.getTarget().getCXXABI().isItaniumFamily()) {
1793 // virtual base offset offset is -ve. The code generator emits dwarf
1794 // expression where it expects +ve number.
Eric Christophere7b87e52014-10-26 23:40:33 +00001795 BaseOffset = 0 - CGM.getItaniumVTableContext()
1796 .getVirtualBaseOffsetOffset(RD, Base)
1797 .getQuantity();
Reid Klecknerd3b23d62014-08-07 21:29:25 +00001798 } else {
1799 // In the MS ABI, store the vbtable offset, which is analogous to the
1800 // vbase offset offset in Itanium.
1801 BaseOffset =
1802 4 * CGM.getMicrosoftVTableContext().getVBTableIndex(RD, Base);
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00001803 VBPtrOffset = CGM.getContext()
1804 .getASTRecordLayout(RD)
1805 .getVBPtrOffset()
1806 .getQuantity();
Reid Klecknerd3b23d62014-08-07 21:29:25 +00001807 }
Bob Haarmandff36732016-10-25 22:19:32 +00001808 BFlags |= llvm::DINode::FlagVirtual;
Guy Benyei11169dd2012-12-18 14:30:41 +00001809 } else
1810 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1811 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1812 // BI->isVirtual() and bits when not.
Eric Christopherb2a008c2013-05-16 00:45:12 +00001813
Adrian Prantl21361fb2014-08-29 22:44:27 +00001814 BFlags |= getAccessFlag(BI.getAccessSpecifier(), RD);
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00001815 llvm::DIType *DTy = DBuilder.createInheritance(RecordTy, BaseTy, BaseOffset,
1816 VBPtrOffset, BFlags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001817 EltTys.push_back(DTy);
1818 }
1819}
1820
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001821llvm::DINodeArray
Eric Christophere7b87e52014-10-26 23:40:33 +00001822CGDebugInfo::CollectTemplateParams(const TemplateParameterList *TPList,
1823 ArrayRef<TemplateArgument> TAList,
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001824 llvm::DIFile *Unit) {
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001825 SmallVector<llvm::Metadata *, 16> TemplateParams;
Guy Benyei11169dd2012-12-18 14:30:41 +00001826 for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1827 const TemplateArgument &TA = TAList[i];
David Blaikie47c11502013-06-22 18:59:18 +00001828 StringRef Name;
Awanish Pandey7a42bab2020-03-02 10:52:12 +05301829 bool defaultParameter = false;
David Blaikie47c11502013-06-22 18:59:18 +00001830 if (TPList)
1831 Name = TPList->getParam(i)->getName();
David Blaikie38079fd2013-05-10 21:53:14 +00001832 switch (TA.getKind()) {
1833 case TemplateArgument::Type: {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001834 llvm::DIType *TTy = getOrCreateType(TA.getAsType(), Unit);
Awanish Pandey7a42bab2020-03-02 10:52:12 +05301835
1836 if (TPList)
1837 if (auto *templateType =
1838 dyn_cast_or_null<TemplateTypeParmDecl>(TPList->getParam(i)))
1839 if (templateType->hasDefaultArgument())
1840 defaultParameter =
1841 templateType->getDefaultArgument() == TA.getAsType();
1842
1843 TemplateParams.push_back(DBuilder.createTemplateTypeParameter(
1844 TheCU, Name, TTy, defaultParameter));
1845
David Blaikie38079fd2013-05-10 21:53:14 +00001846 } break;
1847 case TemplateArgument::Integral: {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001848 llvm::DIType *TTy = getOrCreateType(TA.getIntegralType(), Unit);
Awanish Pandey7a42bab2020-03-02 10:52:12 +05301849 if (TPList && CGM.getCodeGenOpts().DwarfVersion >= 5)
1850 if (auto *templateType =
1851 dyn_cast_or_null<NonTypeTemplateParmDecl>(TPList->getParam(i)))
David Blaikiee9644e62020-04-05 12:49:02 -07001852 if (templateType->hasDefaultArgument() &&
1853 !templateType->getDefaultArgument()->isValueDependent())
David Blaikiedb927192020-04-01 13:00:12 -07001854 defaultParameter = llvm::APSInt::isSameValue(
Awanish Pandey7a42bab2020-03-02 10:52:12 +05301855 templateType->getDefaultArgument()->EvaluateKnownConstInt(
David Blaikiedb927192020-04-01 13:00:12 -07001856 CGM.getContext()),
1857 TA.getAsIntegral());
Awanish Pandey7a42bab2020-03-02 10:52:12 +05301858
Duncan P. N. Exon Smithdadc2b62015-04-21 18:43:54 +00001859 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
Awanish Pandey7a42bab2020-03-02 10:52:12 +05301860 TheCU, Name, TTy, defaultParameter,
Duncan P. N. Exon Smithdadc2b62015-04-21 18:43:54 +00001861 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral())));
David Blaikie38079fd2013-05-10 21:53:14 +00001862 } break;
1863 case TemplateArgument::Declaration: {
1864 const ValueDecl *D = TA.getAsDecl();
David Blaikieb5c7e6a2014-10-18 02:21:26 +00001865 QualType T = TA.getParamTypeForDecl().getDesugaredType(CGM.getContext());
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001866 llvm::DIType *TTy = getOrCreateType(T, Unit);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001867 llvm::Constant *V = nullptr;
Michael Liao982cbb62019-03-06 21:16:27 +00001868 // Skip retrieve the value if that template parameter has cuda device
1869 // attribute, i.e. that value is not available at the host side.
1870 if (!CGM.getLangOpts().CUDA || CGM.getLangOpts().CUDAIsDevice ||
1871 !D->hasAttr<CUDADeviceAttr>()) {
1872 const CXXMethodDecl *MD;
1873 // Variable pointer template parameters have a value that is the address
1874 // of the variable.
1875 if (const auto *VD = dyn_cast<VarDecl>(D))
1876 V = CGM.GetAddrOfGlobalVar(VD);
1877 // Member function pointers have special support for building them,
1878 // though this is currently unsupported in LLVM CodeGen.
1879 else if ((MD = dyn_cast<CXXMethodDecl>(D)) && MD->isInstance())
1880 V = CGM.getCXXABI().EmitMemberFunctionPointer(MD);
1881 else if (const auto *FD = dyn_cast<FunctionDecl>(D))
1882 V = CGM.GetAddrOfFunction(FD);
1883 // Member data pointers have special handling too to compute the fixed
1884 // offset within the object.
1885 else if (const auto *MPT =
1886 dyn_cast<MemberPointerType>(T.getTypePtr())) {
1887 // These five lines (& possibly the above member function pointer
1888 // handling) might be able to be refactored to use similar code in
1889 // CodeGenModule::getMemberPointerConstant
1890 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
1891 CharUnits chars =
1892 CGM.getContext().toCharUnitsFromBits((int64_t)fieldOffset);
1893 V = CGM.getCXXABI().EmitMemberDataPointer(MPT, chars);
Richard Smithbab6df82020-04-11 22:15:29 -07001894 } else if (const auto *GD = dyn_cast<MSGuidDecl>(D)) {
1895 V = CGM.GetAddrOfMSGuidDecl(GD).getPointer();
Michael Liao982cbb62019-03-06 21:16:27 +00001896 }
Simon Pilgrimcfee2ef2019-10-16 10:38:49 +00001897 assert(V && "Failed to find template parameter pointer");
Michael Liao982cbb62019-03-06 21:16:27 +00001898 V = V->stripPointerCasts();
David Blaikie38079fd2013-05-10 21:53:14 +00001899 }
Duncan P. N. Exon Smithdadc2b62015-04-21 18:43:54 +00001900 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
Awanish Pandey7a42bab2020-03-02 10:52:12 +05301901 TheCU, Name, TTy, defaultParameter, cast_or_null<llvm::Constant>(V)));
David Blaikie38079fd2013-05-10 21:53:14 +00001902 } break;
1903 case TemplateArgument::NullPtr: {
1904 QualType T = TA.getNullPtrType();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001905 llvm::DIType *TTy = getOrCreateType(T, Unit);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001906 llvm::Constant *V = nullptr;
David Blaikie38079fd2013-05-10 21:53:14 +00001907 // Special case member data pointer null values since they're actually -1
1908 // instead of zero.
David Majnemer58ed0f32016-07-17 00:39:12 +00001909 if (const auto *MPT = dyn_cast<MemberPointerType>(T.getTypePtr()))
David Blaikie38079fd2013-05-10 21:53:14 +00001910 // But treat member function pointers as simple zero integers because
1911 // it's easier than having a special case in LLVM's CodeGen. If LLVM
1912 // CodeGen grows handling for values of non-null member function
1913 // pointers then perhaps we could remove this special case and rely on
1914 // EmitNullMemberPointer for member function pointers.
1915 if (MPT->isMemberDataPointer())
1916 V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
1917 if (!V)
1918 V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
Awanish Pandey7a42bab2020-03-02 10:52:12 +05301919 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
1920 TheCU, Name, TTy, defaultParameter, V));
David Blaikie38079fd2013-05-10 21:53:14 +00001921 } break;
Duncan P. N. Exon Smithdadc2b62015-04-21 18:43:54 +00001922 case TemplateArgument::Template:
1923 TemplateParams.push_back(DBuilder.createTemplateTemplateParameter(
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00001924 TheCU, Name, nullptr,
Duncan P. N. Exon Smithdadc2b62015-04-21 18:43:54 +00001925 TA.getAsTemplate().getAsTemplateDecl()->getQualifiedNameAsString()));
1926 break;
1927 case TemplateArgument::Pack:
1928 TemplateParams.push_back(DBuilder.createTemplateParameterPack(
1929 TheCU, Name, nullptr,
1930 CollectTemplateParams(nullptr, TA.getPackAsArray(), Unit)));
1931 break;
David Majnemer5559d472013-08-24 08:21:10 +00001932 case TemplateArgument::Expression: {
1933 const Expr *E = TA.getAsExpr();
1934 QualType T = E->getType();
David Majnemer922ad9f2014-10-24 19:49:04 +00001935 if (E->isGLValue())
1936 T = CGM.getContext().getLValueReferenceType(T);
John McCallde0fe072017-08-15 21:42:52 +00001937 llvm::Constant *V = ConstantEmitter(CGM).emitAbstract(E, T);
David Majnemer5559d472013-08-24 08:21:10 +00001938 assert(V && "Expression in template argument isn't constant");
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001939 llvm::DIType *TTy = getOrCreateType(T, Unit);
Duncan P. N. Exon Smithdadc2b62015-04-21 18:43:54 +00001940 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
Awanish Pandey7a42bab2020-03-02 10:52:12 +05301941 TheCU, Name, TTy, defaultParameter, V->stripPointerCasts()));
David Majnemer5559d472013-08-24 08:21:10 +00001942 } break;
David Blaikie2b93c542013-05-10 23:36:06 +00001943 // And the following should never occur:
David Blaikie38079fd2013-05-10 21:53:14 +00001944 case TemplateArgument::TemplateExpansion:
David Blaikie38079fd2013-05-10 21:53:14 +00001945 case TemplateArgument::Null:
1946 llvm_unreachable(
1947 "These argument types shouldn't exist in concrete types");
Guy Benyei11169dd2012-12-18 14:30:41 +00001948 }
1949 }
1950 return DBuilder.getOrCreateArray(TemplateParams);
1951}
1952
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001953llvm::DINodeArray
Duncan P. N. Exon Smith8e47da42015-04-21 20:07:29 +00001954CGDebugInfo::CollectFunctionTemplateParams(const FunctionDecl *FD,
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001955 llvm::DIFile *Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001956 if (FD->getTemplatedKind() ==
1957 FunctionDecl::TK_FunctionTemplateSpecialization) {
Eric Christophere7b87e52014-10-26 23:40:33 +00001958 const TemplateParameterList *TList = FD->getTemplateSpecializationInfo()
1959 ->getTemplate()
1960 ->getTemplateParameters();
David Blaikie47c11502013-06-22 18:59:18 +00001961 return CollectTemplateParams(
1962 TList, FD->getTemplateSpecializationArgs()->asArray(), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00001963 }
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001964 return llvm::DINodeArray();
Guy Benyei11169dd2012-12-18 14:30:41 +00001965}
1966
Matthew Voss20165362018-10-03 18:45:04 +00001967llvm::DINodeArray CGDebugInfo::CollectVarTemplateParams(const VarDecl *VL,
Reid Kleckner2dbd5d82019-05-02 17:45:54 +00001968 llvm::DIFile *Unit) {
1969 // Always get the full list of parameters, not just the ones from the
1970 // specialization. A partial specialization may have fewer parameters than
1971 // there are arguments.
1972 auto *TS = dyn_cast<VarTemplateSpecializationDecl>(VL);
1973 if (!TS)
1974 return llvm::DINodeArray();
1975 VarTemplateDecl *T = TS->getSpecializedTemplate();
1976 const TemplateParameterList *TList = T->getTemplateParameters();
1977 auto TA = TS->getTemplateArgs().asArray();
1978 return CollectTemplateParams(TList, TA, Unit);
Matthew Voss20165362018-10-03 18:45:04 +00001979}
1980
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001981llvm::DINodeArray CGDebugInfo::CollectCXXTemplateParams(
1982 const ClassTemplateSpecializationDecl *TSpecial, llvm::DIFile *Unit) {
Reid Kleckner2dbd5d82019-05-02 17:45:54 +00001983 // Always get the full list of parameters, not just the ones from the
1984 // specialization. A partial specialization may have fewer parameters than
1985 // there are arguments.
Adrian Prantl649f0302014-04-17 01:04:01 +00001986 TemplateParameterList *TPList =
Eric Christophere7b87e52014-10-26 23:40:33 +00001987 TSpecial->getSpecializedTemplate()->getTemplateParameters();
Adrian Prantl2c92e9c2014-04-17 00:30:48 +00001988 const TemplateArgumentList &TAList = TSpecial->getTemplateArgs();
David Blaikie47c11502013-06-22 18:59:18 +00001989 return CollectTemplateParams(TPList, TAList.asArray(), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00001990}
1991
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001992llvm::DIType *CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile *Unit) {
Duncan P. N. Exon Smithb7470232015-04-15 23:48:50 +00001993 if (VTablePtrType)
Guy Benyei11169dd2012-12-18 14:30:41 +00001994 return VTablePtrType;
1995
1996 ASTContext &Context = CGM.getContext();
1997
1998 /* Function type */
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001999 llvm::Metadata *STy = getOrCreateType(Context.IntTy, Unit);
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002000 llvm::DITypeRefArray SElements = DBuilder.getOrCreateTypeArray(STy);
Eric Christopher28a6db52015-10-15 06:56:08 +00002001 llvm::DIType *SubTy = DBuilder.createSubroutineType(SElements);
Guy Benyei11169dd2012-12-18 14:30:41 +00002002 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
Konstantin Zhuravlyovd1ba16e2017-03-08 23:56:48 +00002003 unsigned VtblPtrAddressSpace = CGM.getTarget().getVtblPtrAddressSpace();
2004 Optional<unsigned> DWARFAddressSpace =
2005 CGM.getTarget().getDWARFAddressSpace(VtblPtrAddressSpace);
2006
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00002007 llvm::DIType *vtbl_ptr_type = DBuilder.createPointerType(
2008 SubTy, Size, 0, DWARFAddressSpace, "__vtbl_ptr_type");
Guy Benyei11169dd2012-12-18 14:30:41 +00002009 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
2010 return VTablePtrType;
2011}
2012
Guy Benyei11169dd2012-12-18 14:30:41 +00002013StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +00002014 // Copy the gdb compatible name on the side and use its reference.
2015 return internString("_vptr$", RD->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00002016}
2017
Reid Kleckner105c5652019-04-24 22:45:44 +00002018StringRef CGDebugInfo::getDynamicInitializerName(const VarDecl *VD,
2019 DynamicInitKind StubKind,
2020 llvm::Function *InitFn) {
2021 // If we're not emitting codeview, use the mangled name. For Itanium, this is
2022 // arbitrary.
Alexandre Ganeacaf31662019-11-15 16:21:17 -05002023 if (!CGM.getCodeGenOpts().EmitCodeView)
Reid Kleckner105c5652019-04-24 22:45:44 +00002024 return InitFn->getName();
2025
2026 // Print the normal qualified name for the variable, then break off the last
2027 // NNS, and add the appropriate other text. Clang always prints the global
2028 // variable name without template arguments, so we can use rsplit("::") and
2029 // then recombine the pieces.
2030 SmallString<128> QualifiedGV;
2031 StringRef Quals;
2032 StringRef GVName;
2033 {
2034 llvm::raw_svector_ostream OS(QualifiedGV);
2035 VD->printQualifiedName(OS, getPrintingPolicy());
2036 std::tie(Quals, GVName) = OS.str().rsplit("::");
2037 if (GVName.empty())
2038 std::swap(Quals, GVName);
2039 }
2040
2041 SmallString<128> InitName;
2042 llvm::raw_svector_ostream OS(InitName);
2043 if (!Quals.empty())
2044 OS << Quals << "::";
2045
2046 switch (StubKind) {
2047 case DynamicInitKind::NoStub:
2048 llvm_unreachable("not an initializer");
2049 case DynamicInitKind::Initializer:
2050 OS << "`dynamic initializer for '";
2051 break;
2052 case DynamicInitKind::AtExit:
2053 OS << "`dynamic atexit destructor for '";
2054 break;
2055 }
2056
2057 OS << GVName;
2058
2059 // Add any template specialization args.
2060 if (const auto *VTpl = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
2061 printTemplateArgumentList(OS, VTpl->getTemplateArgs().asArray(),
2062 getPrintingPolicy());
2063 }
2064
2065 OS << '\'';
2066
2067 return internString(OS.str());
2068}
2069
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002070void CGDebugInfo::CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile *Unit,
Reid Klecknerdc124992016-08-31 16:11:43 +00002071 SmallVectorImpl<llvm::Metadata *> &EltTys,
2072 llvm::DICompositeType *RecordTy) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002073 // If this class is not dynamic then there is not any vtable info to collect.
2074 if (!RD->isDynamicClass())
2075 return;
2076
Reid Kleckner59812422016-08-31 20:35:01 +00002077 // Don't emit any vtable shape or vptr info if this class doesn't have an
2078 // extendable vfptr. This can happen if the class doesn't have virtual
2079 // methods, or in the MS ABI if those virtual methods only come from virtually
2080 // inherited bases.
2081 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2082 if (!RL.hasExtendableVFPtr())
2083 return;
2084
Reid Klecknerdc124992016-08-31 16:11:43 +00002085 // CodeView needs to know how large the vtable of every dynamic class is, so
2086 // emit a special named pointer type into the element list. The vptr type
2087 // points to this type as well.
2088 llvm::DIType *VPtrTy = nullptr;
2089 bool NeedVTableShape = CGM.getCodeGenOpts().EmitCodeView &&
2090 CGM.getTarget().getCXXABI().isMicrosoft();
2091 if (NeedVTableShape) {
2092 uint64_t PtrWidth =
2093 CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
2094 const VTableLayout &VFTLayout =
2095 CGM.getMicrosoftVTableContext().getVFTableLayout(RD, CharUnits::Zero());
2096 unsigned VSlotCount =
Peter Collingbournee53683f2016-09-08 01:14:39 +00002097 VFTLayout.vtable_components().size() - CGM.getLangOpts().RTTIData;
Reid Klecknerdc124992016-08-31 16:11:43 +00002098 unsigned VTableWidth = PtrWidth * VSlotCount;
Konstantin Zhuravlyovd1ba16e2017-03-08 23:56:48 +00002099 unsigned VtblPtrAddressSpace = CGM.getTarget().getVtblPtrAddressSpace();
2100 Optional<unsigned> DWARFAddressSpace =
2101 CGM.getTarget().getDWARFAddressSpace(VtblPtrAddressSpace);
Reid Klecknerdc124992016-08-31 16:11:43 +00002102
2103 // Create a very wide void* type and insert it directly in the element list.
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00002104 llvm::DIType *VTableType = DBuilder.createPointerType(
2105 nullptr, VTableWidth, 0, DWARFAddressSpace, "__vtbl_ptr_type");
Reid Klecknerdc124992016-08-31 16:11:43 +00002106 EltTys.push_back(VTableType);
2107
2108 // The vptr is a pointer to this special vtable type.
2109 VPtrTy = DBuilder.createPointerType(VTableType, PtrWidth);
2110 }
2111
2112 // If there is a primary base then the artificial vptr member lives there.
Reid Klecknerdc124992016-08-31 16:11:43 +00002113 if (RL.getPrimaryBase())
2114 return;
2115
2116 if (!VPtrTy)
2117 VPtrTy = getOrCreateVTablePtrType(Unit);
2118
Guy Benyei11169dd2012-12-18 14:30:41 +00002119 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00002120 llvm::DIType *VPtrMember =
2121 DBuilder.createMemberType(Unit, getVTableName(RD), Unit, 0, Size, 0, 0,
2122 llvm::DINode::FlagArtificial, VPtrTy);
Reid Klecknerdc124992016-08-31 16:11:43 +00002123 EltTys.push_back(VPtrMember);
Guy Benyei11169dd2012-12-18 14:30:41 +00002124}
2125
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002126llvm::DIType *CGDebugInfo::getOrCreateRecordType(QualType RTy,
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00002127 SourceLocation Loc) {
Amy Huang53539bb2020-01-13 15:54:54 -08002128 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002129 llvm::DIType *T = getOrCreateType(RTy, getOrCreateFile(Loc));
Guy Benyei11169dd2012-12-18 14:30:41 +00002130 return T;
2131}
2132
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002133llvm::DIType *CGDebugInfo::getOrCreateInterfaceType(QualType D,
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00002134 SourceLocation Loc) {
Adrian Prantlad9a195e2015-08-27 21:21:19 +00002135 return getOrCreateStandaloneType(D, Loc);
2136}
2137
2138llvm::DIType *CGDebugInfo::getOrCreateStandaloneType(QualType D,
2139 SourceLocation Loc) {
Amy Huang53539bb2020-01-13 15:54:54 -08002140 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
Adrian Prantlad9a195e2015-08-27 21:21:19 +00002141 assert(!D.isNull() && "null type");
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002142 llvm::DIType *T = getOrCreateType(D, getOrCreateFile(Loc));
Adrian Prantlad9a195e2015-08-27 21:21:19 +00002143 assert(T && "could not create debug info for type");
Adrian Prantl3a884fa2015-08-27 22:56:46 +00002144
Adrian Prantl73409ce2013-03-11 18:33:46 +00002145 RetainedTypes.push_back(D.getAsOpaquePtr());
Guy Benyei11169dd2012-12-18 14:30:41 +00002146 return T;
2147}
2148
Arthur Eubanksce7d3e12020-06-08 19:07:59 -07002149void CGDebugInfo::addHeapAllocSiteMetadata(llvm::CallBase *CI,
2150 QualType AllocatedTy,
Amy Huang0d0334f2019-04-12 20:25:30 +00002151 SourceLocation Loc) {
Arthur Eubanksbc387932020-06-09 09:55:25 -07002152 if (CGM.getCodeGenOpts().getDebugInfo() <=
2153 codegenoptions::DebugLineTablesOnly)
2154 return;
Amy Huang0d0334f2019-04-12 20:25:30 +00002155 llvm::MDNode *node;
Arthur Eubanksce7d3e12020-06-08 19:07:59 -07002156 if (AllocatedTy->isVoidType())
Amy Huang0d0334f2019-04-12 20:25:30 +00002157 node = llvm::MDNode::get(CGM.getLLVMContext(), None);
Arthur Eubanksce7d3e12020-06-08 19:07:59 -07002158 else
2159 node = getOrCreateType(AllocatedTy, getOrCreateFile(Loc));
Amy Huangfc79ab92019-04-23 21:12:58 +00002160
Amy Huang0d0334f2019-04-12 20:25:30 +00002161 CI->setMetadata("heapallocsite", node);
2162}
2163
David Blaikie483a9da2014-05-06 18:35:21 +00002164void CGDebugInfo::completeType(const EnumDecl *ED) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00002165 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
David Blaikie483a9da2014-05-06 18:35:21 +00002166 return;
2167 QualType Ty = CGM.getContext().getEnumType(ED);
Eric Christophere7b87e52014-10-26 23:40:33 +00002168 void *TyPtr = Ty.getAsOpaquePtr();
David Blaikie483a9da2014-05-06 18:35:21 +00002169 auto I = TypeCache.find(TyPtr);
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002170 if (I == TypeCache.end() || !cast<llvm::DIType>(I->second)->isForwardDecl())
David Blaikie483a9da2014-05-06 18:35:21 +00002171 return;
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002172 llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<EnumType>());
Duncan P. N. Exon Smith4caa7f22015-04-16 01:00:56 +00002173 assert(!Res->isForwardDecl());
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002174 TypeCache[TyPtr].reset(Res);
David Blaikie483a9da2014-05-06 18:35:21 +00002175}
2176
David Blaikieb2e86eb2013-08-15 20:49:17 +00002177void CGDebugInfo::completeType(const RecordDecl *RD) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00002178 if (DebugKind > codegenoptions::LimitedDebugInfo ||
David Blaikieb2e86eb2013-08-15 20:49:17 +00002179 !CGM.getLangOpts().CPlusPlus)
2180 completeRequiredType(RD);
2181}
2182
David Blaikieb11c8732017-01-30 06:36:08 +00002183/// Return true if the class or any of its methods are marked dllimport.
2184static bool isClassOrMethodDLLImport(const CXXRecordDecl *RD) {
2185 if (RD->hasAttr<DLLImportAttr>())
2186 return true;
2187 for (const CXXMethodDecl *MD : RD->methods())
2188 if (MD->hasAttr<DLLImportAttr>())
2189 return true;
2190 return false;
2191}
2192
Adrian Prantla43acdc2017-07-24 23:48:51 +00002193/// Does a type definition exist in an imported clang module?
2194static bool isDefinedInClangModule(const RecordDecl *RD) {
2195 // Only definitions that where imported from an AST file come from a module.
2196 if (!RD || !RD->isFromASTFile())
2197 return false;
2198 // Anonymous entities cannot be addressed. Treat them as not from module.
2199 if (!RD->isExternallyVisible() && RD->getName().empty())
2200 return false;
2201 if (auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD)) {
2202 if (!CXXDecl->isCompleteDefinition())
2203 return false;
Adrian Prantlba6fdc52018-10-24 00:06:02 +00002204 // Check wether RD is a template.
Adrian Prantla43acdc2017-07-24 23:48:51 +00002205 auto TemplateKind = CXXDecl->getTemplateSpecializationKind();
2206 if (TemplateKind != TSK_Undeclared) {
Adrian Prantlba6fdc52018-10-24 00:06:02 +00002207 // Unfortunately getOwningModule() isn't accurate enough to find the
2208 // owning module of a ClassTemplateSpecializationDecl that is inside a
2209 // namespace spanning multiple modules.
2210 bool Explicit = false;
2211 if (auto *TD = dyn_cast<ClassTemplateSpecializationDecl>(CXXDecl))
2212 Explicit = TD->isExplicitInstantiationOrSpecialization();
2213 if (!Explicit && CXXDecl->getEnclosingNamespaceContext())
2214 return false;
Adrian Prantla43acdc2017-07-24 23:48:51 +00002215 // This is a template, check the origin of the first member.
2216 if (CXXDecl->field_begin() == CXXDecl->field_end())
2217 return TemplateKind == TSK_ExplicitInstantiationDeclaration;
2218 if (!CXXDecl->field_begin()->isFromASTFile())
2219 return false;
2220 }
2221 }
2222 return true;
2223}
2224
David Blaikie6943dea2013-08-20 01:28:15 +00002225void CGDebugInfo::completeClassData(const RecordDecl *RD) {
David Blaikieb11c8732017-01-30 06:36:08 +00002226 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
2227 if (CXXRD->isDynamicClass() &&
2228 CGM.getVTableLinkage(CXXRD) ==
2229 llvm::GlobalValue::AvailableExternallyLinkage &&
2230 !isClassOrMethodDLLImport(CXXRD))
2231 return;
Adrian Prantla43acdc2017-07-24 23:48:51 +00002232
2233 if (DebugTypeExtRefs && isDefinedInClangModule(RD->getDefinition()))
2234 return;
2235
David Blaikieb11c8732017-01-30 06:36:08 +00002236 completeClass(RD);
2237}
2238
2239void CGDebugInfo::completeClass(const RecordDecl *RD) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00002240 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
Michael Gottesman349542b2013-08-19 18:46:16 +00002241 return;
David Blaikie6943dea2013-08-20 01:28:15 +00002242 QualType Ty = CGM.getContext().getRecordType(RD);
Eric Christophere7b87e52014-10-26 23:40:33 +00002243 void *TyPtr = Ty.getAsOpaquePtr();
David Blaikieef8a9512014-05-05 23:23:53 +00002244 auto I = TypeCache.find(TyPtr);
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002245 if (I != TypeCache.end() && !cast<llvm::DIType>(I->second)->isForwardDecl())
David Blaikieb2e86eb2013-08-15 20:49:17 +00002246 return;
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002247 llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<RecordType>());
Duncan P. N. Exon Smith4caa7f22015-04-16 01:00:56 +00002248 assert(!Res->isForwardDecl());
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002249 TypeCache[TyPtr].reset(Res);
David Blaikieb2e86eb2013-08-15 20:49:17 +00002250}
2251
David Blaikie0e716b42014-03-03 23:48:23 +00002252static bool hasExplicitMemberDefinition(CXXRecordDecl::method_iterator I,
2253 CXXRecordDecl::method_iterator End) {
David Majnemer58ed0f32016-07-17 00:39:12 +00002254 for (CXXMethodDecl *MD : llvm::make_range(I, End))
2255 if (FunctionDecl *Tmpl = MD->getInstantiatedFromMemberFunction())
David Blaikief7f21852014-03-04 03:08:14 +00002256 if (!Tmpl->isImplicit() && Tmpl->isThisDeclarationADefinition() &&
David Majnemer58ed0f32016-07-17 00:39:12 +00002257 !MD->getMemberSpecializationInfo()->isExplicitSpecialization())
David Blaikie0e716b42014-03-03 23:48:23 +00002258 return true;
2259 return false;
2260}
2261
Benjamin Kramer8c305922016-02-02 11:06:51 +00002262static bool shouldOmitDefinition(codegenoptions::DebugInfoKind DebugKind,
2263 bool DebugTypeExtRefs, const RecordDecl *RD,
David Blaikie0e716b42014-03-03 23:48:23 +00002264 const LangOptions &LangOpts) {
Adrian Prantl88d79172016-04-26 21:58:18 +00002265 if (DebugTypeExtRefs && isDefinedInClangModule(RD->getDefinition()))
Adrian Prantl43e00812016-01-19 23:42:53 +00002266 return true;
Adrian Prantl5c8bd882015-09-11 17:23:08 +00002267
David Blaikie1ac9c982017-04-11 21:13:37 +00002268 if (auto *ES = RD->getASTContext().getExternalSource())
2269 if (ES->hasExternalDefinitions(RD) == ExternalASTSource::EK_Always)
2270 return true;
2271
Benjamin Kramer8c305922016-02-02 11:06:51 +00002272 if (DebugKind > codegenoptions::LimitedDebugInfo)
David Blaikie0e716b42014-03-03 23:48:23 +00002273 return false;
2274
2275 if (!LangOpts.CPlusPlus)
2276 return false;
2277
2278 if (!RD->isCompleteDefinitionRequired())
2279 return true;
2280
David Majnemer58ed0f32016-07-17 00:39:12 +00002281 const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
David Blaikie0e716b42014-03-03 23:48:23 +00002282
2283 if (!CXXDecl)
2284 return false;
2285
Adrian McCarthy99242982016-08-16 22:11:18 +00002286 // Only emit complete debug info for a dynamic class when its vtable is
2287 // emitted. However, Microsoft debuggers don't resolve type information
Reid Klecknerc9404e12016-09-09 16:27:04 +00002288 // across DLL boundaries, so skip this optimization if the class or any of its
2289 // methods are marked dllimport. This isn't a complete solution, since objects
2290 // without any dllimport methods can be used in one DLL and constructed in
2291 // another, but it is the current behavior of LimitedDebugInfo.
Adrian McCarthy99242982016-08-16 22:11:18 +00002292 if (CXXDecl->hasDefinition() && CXXDecl->isDynamicClass() &&
Reid Klecknerc9404e12016-09-09 16:27:04 +00002293 !isClassOrMethodDLLImport(CXXDecl))
David Blaikie0e716b42014-03-03 23:48:23 +00002294 return true;
2295
Amy Huang651128f2020-01-03 16:28:48 -08002296 // In constructor debug mode, only emit debug info for a class when its
2297 // constructor is emitted. Skip this optimization if the class or any of
2298 // its methods are marked dllimport.
2299 if (DebugKind == codegenoptions::DebugInfoConstructor &&
Amy Huang11a04a62020-03-31 13:31:42 -07002300 !CXXDecl->isLambda() && !CXXDecl->hasConstexprNonCopyMoveConstructor() &&
2301 !isClassOrMethodDLLImport(CXXDecl))
2302 for (const auto *Ctor : CXXDecl->ctors())
Amy Huang651128f2020-01-03 16:28:48 -08002303 if (Ctor->isUserProvided())
2304 return true;
Amy Huang651128f2020-01-03 16:28:48 -08002305
David Blaikie0e716b42014-03-03 23:48:23 +00002306 TemplateSpecializationKind Spec = TSK_Undeclared;
David Majnemer58ed0f32016-07-17 00:39:12 +00002307 if (const auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD))
David Blaikie0e716b42014-03-03 23:48:23 +00002308 Spec = SD->getSpecializationKind();
2309
2310 if (Spec == TSK_ExplicitInstantiationDeclaration &&
2311 hasExplicitMemberDefinition(CXXDecl->method_begin(),
2312 CXXDecl->method_end()))
2313 return true;
2314
2315 return false;
2316}
2317
Reid Kleckner6c7b1c62016-09-13 00:01:23 +00002318void CGDebugInfo::completeRequiredType(const RecordDecl *RD) {
2319 if (shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD, CGM.getLangOpts()))
2320 return;
2321
2322 QualType Ty = CGM.getContext().getRecordType(RD);
2323 llvm::DIType *T = getTypeOrNull(Ty);
2324 if (T && T->isForwardDecl())
2325 completeClassData(RD);
2326}
2327
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002328llvm::DIType *CGDebugInfo::CreateType(const RecordType *Ty) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002329 RecordDecl *RD = Ty->getDecl();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002330 llvm::DIType *T = cast_or_null<llvm::DIType>(getTypeOrNull(QualType(Ty, 0)));
Adrian Prantl5c8bd882015-09-11 17:23:08 +00002331 if (T || shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD,
2332 CGM.getLangOpts())) {
David Blaikie3b1cc9b2013-09-06 06:45:04 +00002333 if (!T)
Adrian Prantl6ec370a2015-09-10 18:39:45 +00002334 T = getOrCreateRecordFwdDecl(Ty, getDeclContextDescriptor(RD));
David Blaikie3b1cc9b2013-09-06 06:45:04 +00002335 return T;
David Blaikiee36464c2013-06-05 05:32:23 +00002336 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002337
David Blaikieb2e86eb2013-08-15 20:49:17 +00002338 return CreateTypeDefinition(Ty);
2339}
2340
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002341llvm::DIType *CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) {
David Blaikieb2e86eb2013-08-15 20:49:17 +00002342 RecordDecl *RD = Ty->getDecl();
2343
Guy Benyei11169dd2012-12-18 14:30:41 +00002344 // Get overall information about the record type for the debug info.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002345 llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00002346
2347 // Records and classes and unions can all be recursive. To handle them, we
2348 // first generate a debug descriptor for the struct as a forward declaration.
2349 // Then (if it is a definition) we go through and get debug info for all of
2350 // its members. Finally, we create a descriptor for the complete type (which
2351 // may refer to the forward decl if the struct is recursive) and replace all
2352 // uses of the forward declaration with the final definition.
Duncan P. N. Exon Smithbd210e62015-07-24 20:34:41 +00002353 llvm::DICompositeType *FwdDecl = getOrCreateLimitedType(Ty, DefUnit);
Guy Benyei11169dd2012-12-18 14:30:41 +00002354
Adrian Prantl5f66bae2015-02-11 17:45:15 +00002355 const RecordDecl *D = RD->getDefinition();
2356 if (!D || !D->isCompleteDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00002357 return FwdDecl;
2358
David Majnemer58ed0f32016-07-17 00:39:12 +00002359 if (const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
David Blaikieadfbf992013-08-18 16:55:33 +00002360 CollectContainingType(CXXDecl, FwdDecl);
2361
Guy Benyei11169dd2012-12-18 14:30:41 +00002362 // Push the struct on region stack.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002363 LexicalBlockStack.emplace_back(&*FwdDecl);
2364 RegionMap[Ty->getDecl()].reset(FwdDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00002365
Guy Benyei11169dd2012-12-18 14:30:41 +00002366 // Convert all the elements.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002367 SmallVector<llvm::Metadata *, 16> EltTys;
David Blaikie6943dea2013-08-20 01:28:15 +00002368 // what about nested types?
Guy Benyei11169dd2012-12-18 14:30:41 +00002369
2370 // Note: The split of CXXDecl information here is intentional, the
2371 // gdb tests will depend on a certain ordering at printout. The debug
2372 // information offsets are still correct if we merge them all together
2373 // though.
David Majnemer58ed0f32016-07-17 00:39:12 +00002374 const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
Guy Benyei11169dd2012-12-18 14:30:41 +00002375 if (CXXDecl) {
2376 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
Reid Klecknerdc124992016-08-31 16:11:43 +00002377 CollectVTableInfo(CXXDecl, DefUnit, EltTys, FwdDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00002378 }
2379
Eric Christopher91a31902013-01-16 01:22:32 +00002380 // Collect data fields (including static variables and any initializers).
Guy Benyei11169dd2012-12-18 14:30:41 +00002381 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
Eric Christopher2df080e2013-10-11 18:16:51 +00002382 if (CXXDecl)
Guy Benyei11169dd2012-12-18 14:30:41 +00002383 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00002384
2385 LexicalBlockStack.pop_back();
2386 RegionMap.erase(Ty->getDecl());
2387
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002388 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
Duncan P. N. Exon Smithc8ee63e2014-12-18 00:48:56 +00002389 DBuilder.replaceArrays(FwdDecl, Elements);
Guy Benyei11169dd2012-12-18 14:30:41 +00002390
Adrian Prantl5f66bae2015-02-11 17:45:15 +00002391 if (FwdDecl->isTemporary())
Duncan P. N. Exon Smith4078ad42015-04-16 16:36:45 +00002392 FwdDecl =
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002393 llvm::MDNode::replaceWithPermanent(llvm::TempDICompositeType(FwdDecl));
Adrian Prantl5f66bae2015-02-11 17:45:15 +00002394
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002395 RegionMap[Ty->getDecl()].reset(FwdDecl);
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00002396 return FwdDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00002397}
2398
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002399llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectType *Ty,
2400 llvm::DIFile *Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002401 // Ignore protocols.
2402 return getOrCreateType(Ty->getBaseType(), Unit);
2403}
2404
Manman Rene6be26c2016-09-13 17:25:08 +00002405llvm::DIType *CGDebugInfo::CreateType(const ObjCTypeParamType *Ty,
2406 llvm::DIFile *Unit) {
2407 // Ignore protocols.
2408 SourceLocation Loc = Ty->getDecl()->getLocation();
2409
2410 // Use Typedefs to represent ObjCTypeParamType.
2411 return DBuilder.createTypedef(
2412 getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit),
2413 Ty->getDecl()->getName(), getOrCreateFile(Loc), getLineNumber(Loc),
Sam McCalld27a16e2019-11-18 15:53:22 +01002414 getDeclContextDescriptor(Ty->getDecl()));
Manman Rene6be26c2016-09-13 17:25:08 +00002415}
2416
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00002417/// \return true if Getter has the default name for the property PD.
2418static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,
2419 const ObjCMethodDecl *Getter) {
2420 assert(PD);
2421 if (!Getter)
2422 return true;
2423
2424 assert(Getter->getDeclName().isObjCZeroArgSelector());
2425 return PD->getName() ==
Eric Christophere7b87e52014-10-26 23:40:33 +00002426 Getter->getDeclName().getObjCSelector().getNameForSlot(0);
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00002427}
2428
2429/// \return true if Setter has the default name for the property PD.
2430static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,
2431 const ObjCMethodDecl *Setter) {
2432 assert(PD);
2433 if (!Setter)
2434 return true;
2435
2436 assert(Setter->getDeclName().isObjCOneArgSelector());
Adrian Prantla4ce9062013-06-07 22:29:12 +00002437 return SelectorTable::constructSetterName(PD->getName()) ==
Eric Christophere7b87e52014-10-26 23:40:33 +00002438 Setter->getDeclName().getObjCSelector().getNameForSlot(0);
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00002439}
2440
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002441llvm::DIType *CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
2442 llvm::DIFile *Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002443 ObjCInterfaceDecl *ID = Ty->getDecl();
2444 if (!ID)
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00002445 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00002446
Adrian Prantl50fd1a82016-04-20 23:59:32 +00002447 // Return a forward declaration if this type was imported from a clang module,
2448 // and this is not the compile unit with the implementation of the type (which
2449 // may contain hidden ivars).
2450 if (DebugTypeExtRefs && ID->isFromASTFile() && ID->getDefinition() &&
2451 !ID->getImplementation())
Adrian Prantl5c8bd882015-09-11 17:23:08 +00002452 return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
2453 ID->getName(),
2454 getDeclContextDescriptor(ID), Unit, 0);
2455
Guy Benyei11169dd2012-12-18 14:30:41 +00002456 // Get overall information about the record type for the debug info.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002457 llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00002458 unsigned Line = getLineNumber(ID->getLocation());
Duncan P. N. Exon Smith798d5652015-04-15 23:19:15 +00002459 auto RuntimeLang =
2460 static_cast<llvm::dwarf::SourceLanguage>(TheCU->getSourceLanguage());
Guy Benyei11169dd2012-12-18 14:30:41 +00002461
2462 // If this is just a forward declaration return a special forward-declaration
2463 // debug type since we won't be able to lay out the entire type.
2464 ObjCInterfaceDecl *Def = ID->getDefinition();
David Blaikieef8a9512014-05-05 23:23:53 +00002465 if (!Def || !Def->getImplementation()) {
Adrian Prantl42ce2d32015-10-01 16:57:02 +00002466 llvm::DIScope *Mod = getParentModuleOrNull(ID);
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002467 llvm::DIType *FwdDecl = DBuilder.createReplaceableCompositeType(
Adrian Prantl42ce2d32015-10-01 16:57:02 +00002468 llvm::dwarf::DW_TAG_structure_type, ID->getName(), Mod ? Mod : TheCU,
2469 DefUnit, Line, RuntimeLang);
David Blaikieef8a9512014-05-05 23:23:53 +00002470 ObjCInterfaceCache.push_back(ObjCInterfaceCacheEntry(Ty, FwdDecl, Unit));
Guy Benyei11169dd2012-12-18 14:30:41 +00002471 return FwdDecl;
2472 }
2473
David Blaikieef8a9512014-05-05 23:23:53 +00002474 return CreateTypeDefinition(Ty, Unit);
2475}
2476
Reid Klecknerc915cb92020-02-27 18:13:54 -08002477llvm::DIModule *CGDebugInfo::getOrCreateModuleRef(ASTSourceDescriptor Mod,
2478 bool CreateSkeletonCU) {
Adrian Prantleb66a262015-09-24 16:10:04 +00002479 // Use the Module pointer as the key into the cache. This is a
2480 // nullptr if the "Module" is a PCH, which is safe because we don't
2481 // support chained PCH debug info, so there can only be a single PCH.
2482 const Module *M = Mod.getModuleOrNull();
Adrian Prantl9e8ea352015-09-29 20:44:46 +00002483 auto ModRef = ModuleCache.find(M);
2484 if (ModRef != ModuleCache.end())
2485 return cast<llvm::DIModule>(ModRef->second);
Adrian Prantl2388ead2015-06-30 18:01:05 +00002486
2487 // Macro definitions that were defined with "-D" on the command line.
2488 SmallString<128> ConfigMacros;
2489 {
2490 llvm::raw_svector_ostream OS(ConfigMacros);
2491 const auto &PPOpts = CGM.getPreprocessorOpts();
2492 unsigned I = 0;
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002493 // Translate the macro definitions back into a command line.
Adrian Prantl2388ead2015-06-30 18:01:05 +00002494 for (auto &M : PPOpts.Macros) {
2495 if (++I > 1)
2496 OS << " ";
2497 const std::string &Macro = M.first;
2498 bool Undef = M.second;
2499 OS << "\"-" << (Undef ? 'U' : 'D');
2500 for (char c : Macro)
2501 switch (c) {
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00002502 case '\\':
2503 OS << "\\\\";
2504 break;
2505 case '"':
2506 OS << "\\\"";
2507 break;
2508 default:
2509 OS << c;
Adrian Prantl2388ead2015-06-30 18:01:05 +00002510 }
2511 OS << '\"';
Adrian Prantlc4bb47e2015-06-30 17:39:51 +00002512 }
Adrian Prantlc4bb47e2015-06-30 17:39:51 +00002513 }
Adrian Prantl66689202015-09-18 23:01:45 +00002514
Adrian Prantl835e6632015-09-24 16:10:10 +00002515 bool IsRootModule = M ? !M->Parent : true;
Adrian Prantl7b6b9a12019-02-08 23:15:42 +00002516 // When a module name is specified as -fmodule-name, that module gets a
2517 // clang::Module object, but it won't actually be built or imported; it will
2518 // be textual.
Adrian Prantle308e422019-02-15 20:24:26 +00002519 if (CreateSkeletonCU && IsRootModule && Mod.getASTFile().empty() && M)
2520 assert(StringRef(M->Name).startswith(CGM.getLangOpts().ModuleName) &&
Adrian Prantl7b6b9a12019-02-08 23:15:42 +00002521 "clang module without ASTFile must be specified by -fmodule-name");
2522
Adrian Prantl22d5bd02020-03-18 15:30:20 -07002523 // Return a StringRef to the remapped Path.
2524 auto RemapPath = [this](StringRef Path) -> std::string {
2525 std::string Remapped = remapDIPath(Path);
2526 StringRef Relative(Remapped);
2527 StringRef CompDir = TheCU->getDirectory();
2528 if (Relative.consume_front(CompDir))
2529 Relative.consume_front(llvm::sys::path::get_separator());
2530
2531 return Relative.str();
2532 };
2533
Adrian Prantl7b6b9a12019-02-08 23:15:42 +00002534 if (CreateSkeletonCU && IsRootModule && !Mod.getASTFile().empty()) {
Adrian Prantlc96da8f2016-01-22 17:43:43 +00002535 // PCH files don't have a signature field in the control block,
2536 // but LLVM detects skeleton CUs by looking for a non-zero DWO id.
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002537 // We use the lower 64 bits for debug info.
Daniel Grumberge87e55ed2020-06-07 20:05:25 +01002538
2539 uint64_t Signature = 0;
2540 if (const auto &ModSig = Mod.getSignature()) {
2541 for (unsigned I = 0; I != sizeof(Signature); ++I)
2542 Signature |= (uint64_t)ModSig[I] << (I * 8);
2543 } else {
2544 Signature = ~1ULL;
2545 }
Adrian Prantl66689202015-09-18 23:01:45 +00002546 llvm::DIBuilder DIB(CGM.getModule());
Adrian Prantl079c6dd2020-03-18 13:14:07 -07002547 SmallString<0> PCM;
Adrian Prantl43580a52020-03-18 13:15:14 -07002548 if (!llvm::sys::path::is_absolute(Mod.getASTFile()))
Adrian Prantl079c6dd2020-03-18 13:14:07 -07002549 PCM = Mod.getPath();
2550 llvm::sys::path::append(PCM, Mod.getASTFile());
Adrian Prantl22d5bd02020-03-18 15:30:20 -07002551 DIB.createCompileUnit(
2552 TheCU->getSourceLanguage(),
2553 // TODO: Support "Source" from external AST providers?
2554 DIB.createFile(Mod.getModuleName(), TheCU->getDirectory()),
2555 TheCU->getProducer(), false, StringRef(), 0, RemapPath(PCM),
2556 llvm::DICompileUnit::FullDebug, Signature);
Adrian Prantl66689202015-09-18 23:01:45 +00002557 DIB.finalize();
Adrian Prantl2f957ac2015-09-19 00:59:22 +00002558 }
Adrian Prantl7b6b9a12019-02-08 23:15:42 +00002559
Adrian Prantl835e6632015-09-24 16:10:10 +00002560 llvm::DIModule *Parent =
2561 IsRootModule ? nullptr
Reid Klecknerc915cb92020-02-27 18:13:54 -08002562 : getOrCreateModuleRef(ASTSourceDescriptor(*M->Parent),
2563 CreateSkeletonCU);
Adrian Prantl22d5bd02020-03-18 15:30:20 -07002564 std::string IncludePath = Mod.getPath().str();
Adrian Prantleb66a262015-09-24 16:10:04 +00002565 llvm::DIModule *DIMod =
Adrian Prantl835e6632015-09-24 16:10:10 +00002566 DBuilder.createModule(Parent, Mod.getModuleName(), ConfigMacros,
Adrian Prantl22d5bd02020-03-18 15:30:20 -07002567 RemapPath(IncludePath));
Adrian Prantl9e8ea352015-09-29 20:44:46 +00002568 ModuleCache[M].reset(DIMod);
Adrian Prantleb66a262015-09-24 16:10:04 +00002569 return DIMod;
Adrian Prantlc4bb47e2015-06-30 17:39:51 +00002570}
2571
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002572llvm::DIType *CGDebugInfo::CreateTypeDefinition(const ObjCInterfaceType *Ty,
2573 llvm::DIFile *Unit) {
David Blaikieef8a9512014-05-05 23:23:53 +00002574 ObjCInterfaceDecl *ID = Ty->getDecl();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002575 llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
David Blaikieef8a9512014-05-05 23:23:53 +00002576 unsigned Line = getLineNumber(ID->getLocation());
Duncan P. N. Exon Smith798d5652015-04-15 23:19:15 +00002577 unsigned RuntimeLang = TheCU->getSourceLanguage();
Guy Benyei11169dd2012-12-18 14:30:41 +00002578
2579 // Bit size, align and offset of the type.
2580 uint64_t Size = CGM.getContext().getTypeSize(Ty);
Victor Leschuka7ece032016-10-20 00:13:19 +00002581 auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00002582
Leny Kholodov80c047d2016-09-06 10:48:04 +00002583 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
Guy Benyei11169dd2012-12-18 14:30:41 +00002584 if (ID->getImplementation())
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002585 Flags |= llvm::DINode::FlagObjcClassComplete;
Guy Benyei11169dd2012-12-18 14:30:41 +00002586
Adrian Prantlfd696112015-10-01 00:48:51 +00002587 llvm::DIScope *Mod = getParentModuleOrNull(ID);
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002588 llvm::DICompositeType *RealDecl = DBuilder.createStructType(
Adrian Prantlfd696112015-10-01 00:48:51 +00002589 Mod ? Mod : Unit, ID->getName(), DefUnit, Line, Size, Align, Flags,
2590 nullptr, llvm::DINodeArray(), RuntimeLang);
Guy Benyei11169dd2012-12-18 14:30:41 +00002591
David Blaikieef8a9512014-05-05 23:23:53 +00002592 QualType QTy(Ty, 0);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002593 TypeCache[QTy.getAsOpaquePtr()].reset(RealDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00002594
Eric Christopher35f1f9f2013-07-14 21:00:07 +00002595 // Push the struct on region stack.
Duncan P. N. Exon Smith4078ad42015-04-16 16:36:45 +00002596 LexicalBlockStack.emplace_back(RealDecl);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002597 RegionMap[Ty->getDecl()].reset(RealDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00002598
2599 // Convert all the elements.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002600 SmallVector<llvm::Metadata *, 16> EltTys;
Guy Benyei11169dd2012-12-18 14:30:41 +00002601
2602 ObjCInterfaceDecl *SClass = ID->getSuperClass();
2603 if (SClass) {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002604 llvm::DIType *SClassTy =
Eric Christophere7b87e52014-10-26 23:40:33 +00002605 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
Duncan P. N. Exon Smithb7470232015-04-15 23:48:50 +00002606 if (!SClassTy)
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00002607 return nullptr;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002608
Brock Wyma3db2b102018-05-14 21:21:22 +00002609 llvm::DIType *InhTag = DBuilder.createInheritance(RealDecl, SClassTy, 0, 0,
Leny Kholodovdf050fd2016-09-06 17:06:14 +00002610 llvm::DINode::FlagZero);
Guy Benyei11169dd2012-12-18 14:30:41 +00002611 EltTys.push_back(InhTag);
2612 }
2613
Eric Christopher35f1f9f2013-07-14 21:00:07 +00002614 // Create entries for all of the properties.
Nico Weber7123bca2015-12-04 19:14:14 +00002615 auto AddProperty = [&](const ObjCPropertyDecl *PD) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002616 SourceLocation Loc = PD->getLocation();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002617 llvm::DIFile *PUnit = getOrCreateFile(Loc);
Guy Benyei11169dd2012-12-18 14:30:41 +00002618 unsigned PLine = getLineNumber(Loc);
2619 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
2620 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
Eric Christophere7b87e52014-10-26 23:40:33 +00002621 llvm::MDNode *PropertyNode = DBuilder.createObjCProperty(
2622 PD->getName(), PUnit, PLine,
2623 hasDefaultGetterName(PD, Getter) ? ""
2624 : getSelectorName(PD->getGetterName()),
2625 hasDefaultSetterName(PD, Setter) ? ""
2626 : getSelectorName(PD->getSetterName()),
2627 PD->getPropertyAttributes(), getOrCreateType(PD->getType(), PUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00002628 EltTys.push_back(PropertyNode);
Nico Weber7123bca2015-12-04 19:14:14 +00002629 };
2630 {
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00002631 llvm::SmallPtrSet<const IdentifierInfo *, 16> PropertySet;
Nico Weberde059e12015-12-04 19:35:45 +00002632 for (const ObjCCategoryDecl *ClassExt : ID->known_extensions())
Manman Renefe1bac2016-01-27 20:00:32 +00002633 for (auto *PD : ClassExt->properties()) {
Nico Weberde059e12015-12-04 19:35:45 +00002634 PropertySet.insert(PD->getIdentifier());
2635 AddProperty(PD);
2636 }
Manman Renefe1bac2016-01-27 20:00:32 +00002637 for (const auto *PD : ID->properties()) {
Nico Weber7123bca2015-12-04 19:14:14 +00002638 // Don't emit duplicate metadata for properties that were already in a
2639 // class extension.
2640 if (!PropertySet.insert(PD->getIdentifier()).second)
2641 continue;
2642 AddProperty(PD);
2643 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002644 }
2645
2646 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
2647 unsigned FieldNo = 0;
2648 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
2649 Field = Field->getNextIvar(), ++FieldNo) {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002650 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
Duncan P. N. Exon Smithb7470232015-04-15 23:48:50 +00002651 if (!FieldTy)
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00002652 return nullptr;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002653
Guy Benyei11169dd2012-12-18 14:30:41 +00002654 StringRef FieldName = Field->getName();
2655
2656 // Ignore unnamed fields.
2657 if (FieldName.empty())
2658 continue;
2659
2660 // Get the location for the field.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002661 llvm::DIFile *FieldDefUnit = getOrCreateFile(Field->getLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00002662 unsigned FieldLine = getLineNumber(Field->getLocation());
2663 QualType FType = Field->getType();
2664 uint64_t FieldSize = 0;
Victor Leschuk802e4a52016-10-19 22:11:07 +00002665 uint32_t FieldAlign = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00002666
2667 if (!FType->isIncompleteArrayType()) {
2668
2669 // Bit size, align and offset of the type.
2670 FieldSize = Field->isBitField()
Eric Christopher35f1f9f2013-07-14 21:00:07 +00002671 ? Field->getBitWidthValue(CGM.getContext())
2672 : CGM.getContext().getTypeSize(FType);
Victor Leschuka7ece032016-10-20 00:13:19 +00002673 FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00002674 }
2675
2676 uint64_t FieldOffset;
2677 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
2678 // We don't know the runtime offset of an ivar if we're using the
2679 // non-fragile ABI. For bitfields, use the bit offset into the first
2680 // byte of storage of the bitfield. For other fields, use zero.
2681 if (Field->isBitField()) {
Eric Christophere7b87e52014-10-26 23:40:33 +00002682 FieldOffset =
2683 CGM.getObjCRuntime().ComputeBitfieldBitOffset(CGM, ID, Field);
Guy Benyei11169dd2012-12-18 14:30:41 +00002684 FieldOffset %= CGM.getContext().getCharWidth();
2685 } else {
2686 FieldOffset = 0;
2687 }
2688 } else {
2689 FieldOffset = RL.getFieldOffset(FieldNo);
2690 }
2691
Leny Kholodov80c047d2016-09-06 10:48:04 +00002692 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
Guy Benyei11169dd2012-12-18 14:30:41 +00002693 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002694 Flags = llvm::DINode::FlagProtected;
Guy Benyei11169dd2012-12-18 14:30:41 +00002695 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002696 Flags = llvm::DINode::FlagPrivate;
Adrian Prantl21361fb2014-08-29 22:44:27 +00002697 else if (Field->getAccessControl() == ObjCIvarDecl::Public)
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002698 Flags = llvm::DINode::FlagPublic;
Guy Benyei11169dd2012-12-18 14:30:41 +00002699
Craig Topper8a13c412014-05-21 05:09:00 +00002700 llvm::MDNode *PropertyNode = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00002701 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00002702 if (ObjCPropertyImplDecl *PImpD =
Eric Christophere7b87e52014-10-26 23:40:33 +00002703 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002704 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
Eric Christopherc0c5d462013-02-21 22:35:08 +00002705 SourceLocation Loc = PD->getLocation();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002706 llvm::DIFile *PUnit = getOrCreateFile(Loc);
Eric Christopherc0c5d462013-02-21 22:35:08 +00002707 unsigned PLine = getLineNumber(Loc);
Adrian Prantl901cc4a2019-11-08 09:24:31 -08002708 ObjCMethodDecl *Getter = PImpD->getGetterMethodDecl();
2709 ObjCMethodDecl *Setter = PImpD->getSetterMethodDecl();
Eric Christophere7b87e52014-10-26 23:40:33 +00002710 PropertyNode = DBuilder.createObjCProperty(
2711 PD->getName(), PUnit, PLine,
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00002712 hasDefaultGetterName(PD, Getter)
2713 ? ""
2714 : getSelectorName(PD->getGetterName()),
2715 hasDefaultSetterName(PD, Setter)
2716 ? ""
2717 : getSelectorName(PD->getSetterName()),
Eric Christophere7b87e52014-10-26 23:40:33 +00002718 PD->getPropertyAttributes(),
2719 getOrCreateType(PD->getType(), PUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00002720 }
2721 }
2722 }
Eric Christophere7b87e52014-10-26 23:40:33 +00002723 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit, FieldLine,
2724 FieldSize, FieldAlign, FieldOffset, Flags,
2725 FieldTy, PropertyNode);
Guy Benyei11169dd2012-12-18 14:30:41 +00002726 EltTys.push_back(FieldTy);
2727 }
2728
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002729 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
Duncan P. N. Exon Smithc8ee63e2014-12-18 00:48:56 +00002730 DBuilder.replaceArrays(RealDecl, Elements);
Adrian Prantla03a85a2013-03-06 22:03:30 +00002731
Guy Benyei11169dd2012-12-18 14:30:41 +00002732 LexicalBlockStack.pop_back();
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00002733 return RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00002734}
2735
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002736llvm::DIType *CGDebugInfo::CreateType(const VectorType *Ty,
2737 llvm::DIFile *Unit) {
2738 llvm::DIType *ElementTy = getOrCreateType(Ty->getElementType(), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00002739 int64_t Count = Ty->getNumElements();
Guy Benyei11169dd2012-12-18 14:30:41 +00002740
Sander de Smalen891af03a2018-02-03 13:55:59 +00002741 llvm::Metadata *Subscript;
2742 QualType QTy(Ty, 0);
2743 auto SizeExpr = SizeExprCache.find(QTy);
2744 if (SizeExpr != SizeExprCache.end())
Alok Kumar Sharmad20bf5a2020-05-28 13:31:22 +05302745 Subscript = DBuilder.getOrCreateSubrange(
2746 SizeExpr->getSecond() /*count*/, nullptr /*lowerBound*/,
2747 nullptr /*upperBound*/, nullptr /*stride*/);
2748 else {
2749 auto *CountNode =
2750 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
2751 llvm::Type::getInt64Ty(CGM.getLLVMContext()), Count ? Count : -1));
2752 Subscript = DBuilder.getOrCreateSubrange(
2753 CountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
2754 nullptr /*stride*/);
2755 }
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002756 llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
Guy Benyei11169dd2012-12-18 14:30:41 +00002757
2758 uint64_t Size = CGM.getContext().getTypeSize(Ty);
Victor Leschuka7ece032016-10-20 00:13:19 +00002759 auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00002760
2761 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
2762}
2763
Florian Hahn10658692020-05-11 17:45:51 +01002764llvm::DIType *CGDebugInfo::CreateType(const ConstantMatrixType *Ty,
2765 llvm::DIFile *Unit) {
2766 // FIXME: Create another debug type for matrices
2767 // For the time being, it treats it like a nested ArrayType.
2768
2769 llvm::DIType *ElementTy = getOrCreateType(Ty->getElementType(), Unit);
2770 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2771 uint32_t Align = getTypeAlignIfRequired(Ty, CGM.getContext());
2772
2773 // Create ranges for both dimensions.
2774 llvm::SmallVector<llvm::Metadata *, 2> Subscripts;
Alok Kumar Sharmad20bf5a2020-05-28 13:31:22 +05302775 auto *ColumnCountNode =
2776 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
2777 llvm::Type::getInt64Ty(CGM.getLLVMContext()), Ty->getNumColumns()));
2778 auto *RowCountNode =
2779 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
2780 llvm::Type::getInt64Ty(CGM.getLLVMContext()), Ty->getNumRows()));
2781 Subscripts.push_back(DBuilder.getOrCreateSubrange(
2782 ColumnCountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
2783 nullptr /*stride*/));
2784 Subscripts.push_back(DBuilder.getOrCreateSubrange(
2785 RowCountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
2786 nullptr /*stride*/));
Florian Hahn10658692020-05-11 17:45:51 +01002787 llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
2788 return DBuilder.createArrayType(Size, Align, ElementTy, SubscriptArray);
2789}
2790
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002791llvm::DIType *CGDebugInfo::CreateType(const ArrayType *Ty, llvm::DIFile *Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002792 uint64_t Size;
Victor Leschuk802e4a52016-10-19 22:11:07 +00002793 uint32_t Align;
Guy Benyei11169dd2012-12-18 14:30:41 +00002794
2795 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
David Majnemer58ed0f32016-07-17 00:39:12 +00002796 if (const auto *VAT = dyn_cast<VariableArrayType>(Ty)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002797 Size = 0;
Victor Leschuka7ece032016-10-20 00:13:19 +00002798 Align = getTypeAlignIfRequired(CGM.getContext().getBaseElementType(VAT),
2799 CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00002800 } else if (Ty->isIncompleteArrayType()) {
2801 Size = 0;
2802 if (Ty->getElementType()->isIncompleteType())
2803 Align = 0;
2804 else
Victor Leschuka7ece032016-10-20 00:13:19 +00002805 Align = getTypeAlignIfRequired(Ty->getElementType(), CGM.getContext());
David Blaikief03b2e82013-05-09 20:48:12 +00002806 } else if (Ty->isIncompleteType()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002807 Size = 0;
2808 Align = 0;
2809 } else {
2810 // Size and align of the whole array, not the element type.
2811 Size = CGM.getContext().getTypeSize(Ty);
Victor Leschuka7ece032016-10-20 00:13:19 +00002812 Align = getTypeAlignIfRequired(Ty, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00002813 }
2814
2815 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
2816 // interior arrays, do we care? Why aren't nested arrays represented the
2817 // obvious/recursive way?
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002818 SmallVector<llvm::Metadata *, 8> Subscripts;
Guy Benyei11169dd2012-12-18 14:30:41 +00002819 QualType EltTy(Ty, 0);
2820 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
2821 // If the number of elements is known, then count is that number. Otherwise,
2822 // it's -1. This allows us to represent a subrange with an array of 0
2823 // elements, like this:
2824 //
2825 // struct foo {
2826 // int x[0];
2827 // };
Eric Christophere7b87e52014-10-26 23:40:33 +00002828 int64_t Count = -1; // Count == -1 is an unbounded array.
David Majnemer58ed0f32016-07-17 00:39:12 +00002829 if (const auto *CAT = dyn_cast<ConstantArrayType>(Ty))
Guy Benyei11169dd2012-12-18 14:30:41 +00002830 Count = CAT->getSize().getZExtValue();
David Blaikie87173f12016-08-22 17:49:56 +00002831 else if (const auto *VAT = dyn_cast<VariableArrayType>(Ty)) {
Eli Friedman01d6b962016-10-19 22:16:32 +00002832 if (Expr *Size = VAT->getSizeExpr()) {
Fangrui Song407659a2018-11-30 23:41:18 +00002833 Expr::EvalResult Result;
2834 if (Size->EvaluateAsInt(Result, CGM.getContext()))
2835 Count = Result.Val.getInt().getExtValue();
Eli Friedman01d6b962016-10-19 22:16:32 +00002836 }
David Blaikie87173f12016-08-22 17:49:56 +00002837 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00002838
Sander de Smalen891af03a2018-02-03 13:55:59 +00002839 auto SizeNode = SizeExprCache.find(EltTy);
2840 if (SizeNode != SizeExprCache.end())
Alok Kumar Sharmad20bf5a2020-05-28 13:31:22 +05302841 Subscripts.push_back(DBuilder.getOrCreateSubrange(
2842 SizeNode->getSecond() /*count*/, nullptr /*lowerBound*/,
2843 nullptr /*upperBound*/, nullptr /*stride*/));
2844 else {
2845 auto *CountNode =
2846 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
2847 llvm::Type::getInt64Ty(CGM.getLLVMContext()), Count));
2848 Subscripts.push_back(DBuilder.getOrCreateSubrange(
2849 CountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
2850 nullptr /*stride*/));
2851 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002852 EltTy = Ty->getElementType();
2853 }
2854
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002855 llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
Guy Benyei11169dd2012-12-18 14:30:41 +00002856
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00002857 return DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
2858 SubscriptArray);
Guy Benyei11169dd2012-12-18 14:30:41 +00002859}
2860
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002861llvm::DIType *CGDebugInfo::CreateType(const LValueReferenceType *Ty,
2862 llvm::DIFile *Unit) {
Eric Christophere7b87e52014-10-26 23:40:33 +00002863 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type, Ty,
2864 Ty->getPointeeType(), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00002865}
2866
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002867llvm::DIType *CGDebugInfo::CreateType(const RValueReferenceType *Ty,
2868 llvm::DIFile *Unit) {
Eric Christophere7b87e52014-10-26 23:40:33 +00002869 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type, Ty,
2870 Ty->getPointeeType(), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00002871}
2872
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002873llvm::DIType *CGDebugInfo::CreateType(const MemberPointerType *Ty,
2874 llvm::DIFile *U) {
Leny Kholodov80c047d2016-09-06 10:48:04 +00002875 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
Reid Klecknerfb727182016-06-17 22:27:59 +00002876 uint64_t Size = 0;
2877
2878 if (!Ty->isIncompleteType()) {
2879 Size = CGM.getContext().getTypeSize(Ty);
2880
2881 // Set the MS inheritance model. There is no flag for the unspecified model.
2882 if (CGM.getTarget().getCXXABI().isMicrosoft()) {
2883 switch (Ty->getMostRecentCXXRecordDecl()->getMSInheritanceModel()) {
Reid Klecknera9cc64e2019-11-15 18:49:32 -08002884 case MSInheritanceModel::Single:
Reid Klecknerfb727182016-06-17 22:27:59 +00002885 Flags |= llvm::DINode::FlagSingleInheritance;
2886 break;
Reid Klecknera9cc64e2019-11-15 18:49:32 -08002887 case MSInheritanceModel::Multiple:
Reid Klecknerfb727182016-06-17 22:27:59 +00002888 Flags |= llvm::DINode::FlagMultipleInheritance;
2889 break;
Reid Klecknera9cc64e2019-11-15 18:49:32 -08002890 case MSInheritanceModel::Virtual:
Reid Klecknerfb727182016-06-17 22:27:59 +00002891 Flags |= llvm::DINode::FlagVirtualInheritance;
2892 break;
Reid Klecknera9cc64e2019-11-15 18:49:32 -08002893 case MSInheritanceModel::Unspecified:
Reid Klecknerfb727182016-06-17 22:27:59 +00002894 break;
2895 }
2896 }
2897 }
2898
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002899 llvm::DIType *ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
David Majnemer5fd33e02015-04-24 01:25:08 +00002900 if (Ty->isMemberDataPointerType())
David Blaikie2c705ca2013-01-19 19:20:56 +00002901 return DBuilder.createMemberPointerType(
Reid Klecknerfb727182016-06-17 22:27:59 +00002902 getOrCreateType(Ty->getPointeeType(), U), ClassType, Size, /*Align=*/0,
2903 Flags);
Adrian Prantl0866acd2013-12-19 01:38:47 +00002904
2905 const FunctionProtoType *FPT =
Eric Christophere7b87e52014-10-26 23:40:33 +00002906 Ty->getPointeeType()->getAs<FunctionProtoType>();
2907 return DBuilder.createMemberPointerType(
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00002908 getOrCreateInstanceMethodType(
2909 CXXMethodDecl::getThisType(FPT, Ty->getMostRecentCXXRecordDecl()),
Awanish Pandeyc83602f2020-01-23 16:06:52 +05302910 FPT, U, false),
Reid Klecknerfb727182016-06-17 22:27:59 +00002911 ClassType, Size, /*Align=*/0, Flags);
Guy Benyei11169dd2012-12-18 14:30:41 +00002912}
2913
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002914llvm::DIType *CGDebugInfo::CreateType(const AtomicType *Ty, llvm::DIFile *U) {
Victor Leschuk0df190372016-10-31 19:09:47 +00002915 auto *FromTy = getOrCreateType(Ty->getValueType(), U);
2916 return DBuilder.createQualifiedType(llvm::dwarf::DW_TAG_atomic_type, FromTy);
Guy Benyei11169dd2012-12-18 14:30:41 +00002917}
2918
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00002919llvm::DIType *CGDebugInfo::CreateType(const PipeType *Ty, llvm::DIFile *U) {
Xiuli Pan9c14e282016-01-09 12:53:17 +00002920 return getOrCreateType(Ty->getElementType(), U);
2921}
2922
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002923llvm::DIType *CGDebugInfo::CreateEnumType(const EnumType *Ty) {
Manman Ren1b457022013-08-28 21:20:28 +00002924 const EnumDecl *ED = Ty->getDecl();
Adrian Prantl5c8bd882015-09-11 17:23:08 +00002925
Guy Benyei11169dd2012-12-18 14:30:41 +00002926 uint64_t Size = 0;
Victor Leschuk802e4a52016-10-19 22:11:07 +00002927 uint32_t Align = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00002928 if (!ED->getTypeForDecl()->isIncompleteType()) {
2929 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
Victor Leschuka7ece032016-10-20 00:13:19 +00002930 Align = getDeclAlignIfRequired(ED, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00002931 }
2932
Brock Wyma8557ec52018-05-22 12:41:19 +00002933 SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
Manman Rene0064d82013-08-29 23:19:58 +00002934
Adrian Prantl5c8bd882015-09-11 17:23:08 +00002935 bool isImportedFromModule =
2936 DebugTypeExtRefs && ED->isFromASTFile() && ED->getDefinition();
2937
Guy Benyei11169dd2012-12-18 14:30:41 +00002938 // If this is just a forward declaration, construct an appropriately
2939 // marked node and just return it.
Adrian Prantl5c8bd882015-09-11 17:23:08 +00002940 if (isImportedFromModule || !ED->getDefinition()) {
Adrian Prantl45946062016-02-23 19:30:08 +00002941 // Note that it is possible for enums to be created as part of
2942 // their own declcontext. In this case a FwdDecl will be created
2943 // twice. This doesn't cause a problem because both FwdDecls are
2944 // entered into the ReplaceMap: finalize() will replace the first
2945 // FwdDecl with the second and then replace the second with
2946 // complete type.
Amjad Abouddc4531e2016-04-30 01:44:38 +00002947 llvm::DIScope *EDContext = getDeclContextDescriptor(ED);
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002948 llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
Adrian Prantlff9d83c2016-02-08 17:03:28 +00002949 llvm::TempDIScope TmpContext(DBuilder.createReplaceableCompositeType(
2950 llvm::dwarf::DW_TAG_enumeration_type, "", TheCU, DefUnit, 0));
Adrian Prantla40030f2016-02-06 01:59:09 +00002951
Guy Benyei11169dd2012-12-18 14:30:41 +00002952 unsigned Line = getLineNumber(ED->getLocation());
2953 StringRef EDName = ED->getName();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002954 llvm::DIType *RetTy = DBuilder.createReplaceableCompositeType(
Adrian Prantl45946062016-02-23 19:30:08 +00002955 llvm::dwarf::DW_TAG_enumeration_type, EDName, EDContext, DefUnit, Line,
Brock Wyma8557ec52018-05-22 12:41:19 +00002956 0, Size, Align, llvm::DINode::FlagFwdDecl, Identifier);
Adrian Prantla40030f2016-02-06 01:59:09 +00002957
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002958 ReplaceMap.emplace_back(
2959 std::piecewise_construct, std::make_tuple(Ty),
2960 std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
David Blaikief427b002014-05-06 03:42:01 +00002961 return RetTy;
Guy Benyei11169dd2012-12-18 14:30:41 +00002962 }
2963
David Blaikie483a9da2014-05-06 18:35:21 +00002964 return CreateTypeDefinition(Ty);
2965}
2966
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002967llvm::DIType *CGDebugInfo::CreateTypeDefinition(const EnumType *Ty) {
David Blaikie483a9da2014-05-06 18:35:21 +00002968 const EnumDecl *ED = Ty->getDecl();
2969 uint64_t Size = 0;
Victor Leschuk802e4a52016-10-19 22:11:07 +00002970 uint32_t Align = 0;
David Blaikie483a9da2014-05-06 18:35:21 +00002971 if (!ED->getTypeForDecl()->isIncompleteType()) {
2972 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
Victor Leschuka7ece032016-10-20 00:13:19 +00002973 Align = getDeclAlignIfRequired(ED, CGM.getContext());
David Blaikie483a9da2014-05-06 18:35:21 +00002974 }
2975
Brock Wyma8557ec52018-05-22 12:41:19 +00002976 SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
David Blaikie483a9da2014-05-06 18:35:21 +00002977
Duncan P. N. Exon Smithdadc2b62015-04-21 18:43:54 +00002978 // Create elements for each enumerator.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002979 SmallVector<llvm::Metadata *, 16> Enumerators;
Guy Benyei11169dd2012-12-18 14:30:41 +00002980 ED = ED->getDefinition();
Momchil Velikov25f6be52018-02-12 16:12:52 +00002981 bool IsSigned = ED->getIntegerType()->isSignedIntegerType();
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00002982 for (const auto *Enum : ED->enumerators()) {
Momchil Velikov25f6be52018-02-12 16:12:52 +00002983 const auto &InitVal = Enum->getInitVal();
2984 auto Value = IsSigned ? InitVal.getSExtValue() : InitVal.getZExtValue();
2985 Enumerators.push_back(
2986 DBuilder.createEnumerator(Enum->getName(), Value, !IsSigned));
Guy Benyei11169dd2012-12-18 14:30:41 +00002987 }
2988
2989 // Return a CompositeType for the enum itself.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002990 llvm::DINodeArray EltArray = DBuilder.getOrCreateArray(Enumerators);
Guy Benyei11169dd2012-12-18 14:30:41 +00002991
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002992 llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00002993 unsigned Line = getLineNumber(ED->getLocation());
Amjad Abouddc4531e2016-04-30 01:44:38 +00002994 llvm::DIScope *EnumContext = getDeclContextDescriptor(ED);
Momchil Velikov25f6be52018-02-12 16:12:52 +00002995 llvm::DIType *ClassTy = getOrCreateType(ED->getIntegerType(), DefUnit);
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00002996 return DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit,
2997 Line, Size, Align, EltArray, ClassTy,
Paul Robinsonb1ce7c82019-01-08 16:28:11 +00002998 Identifier, ED->isScoped());
Guy Benyei11169dd2012-12-18 14:30:41 +00002999}
3000
Amjad Aboud546bc112017-02-09 22:07:24 +00003001llvm::DIMacro *CGDebugInfo::CreateMacro(llvm::DIMacroFile *Parent,
3002 unsigned MType, SourceLocation LineLoc,
3003 StringRef Name, StringRef Value) {
3004 unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(LineLoc);
3005 return DBuilder.createMacro(Parent, Line, MType, Name, Value);
3006}
3007
3008llvm::DIMacroFile *CGDebugInfo::CreateTempMacroFile(llvm::DIMacroFile *Parent,
3009 SourceLocation LineLoc,
3010 SourceLocation FileLoc) {
3011 llvm::DIFile *FName = getOrCreateFile(FileLoc);
3012 unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(LineLoc);
3013 return DBuilder.createTempMacroFile(Parent, Line, FName);
3014}
3015
David Blaikie05491062013-01-21 04:37:12 +00003016static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
3017 Qualifiers Quals;
Guy Benyei11169dd2012-12-18 14:30:41 +00003018 do {
Adrian Prantl179af902013-09-26 21:35:50 +00003019 Qualifiers InnerQuals = T.getLocalQualifiers();
3020 // Qualifiers::operator+() doesn't like it if you add a Qualifier
3021 // that is already there.
3022 Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals);
3023 Quals += InnerQuals;
Guy Benyei11169dd2012-12-18 14:30:41 +00003024 QualType LastT = T;
3025 switch (T->getTypeClass()) {
3026 default:
David Blaikie05491062013-01-21 04:37:12 +00003027 return C.getQualifiedType(T.getTypePtr(), Quals);
David Blaikief1b382e2014-04-06 17:14:06 +00003028 case Type::TemplateSpecialization: {
3029 const auto *Spec = cast<TemplateSpecializationType>(T);
3030 if (Spec->isTypeAlias())
3031 return C.getQualifiedType(T.getTypePtr(), Quals);
3032 T = Spec->desugar();
Eric Christophere7b87e52014-10-26 23:40:33 +00003033 break;
3034 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003035 case Type::TypeOfExpr:
3036 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
3037 break;
3038 case Type::TypeOf:
3039 T = cast<TypeOfType>(T)->getUnderlyingType();
3040 break;
3041 case Type::Decltype:
3042 T = cast<DecltypeType>(T)->getUnderlyingType();
3043 break;
3044 case Type::UnaryTransform:
3045 T = cast<UnaryTransformType>(T)->getUnderlyingType();
3046 break;
3047 case Type::Attributed:
3048 T = cast<AttributedType>(T)->getEquivalentType();
3049 break;
3050 case Type::Elaborated:
3051 T = cast<ElaboratedType>(T)->getNamedType();
3052 break;
3053 case Type::Paren:
3054 T = cast<ParenType>(T)->getInnerType();
3055 break;
Leonard Chanc72aaf62019-05-07 03:20:17 +00003056 case Type::MacroQualified:
3057 T = cast<MacroQualifiedType>(T)->getUnderlyingType();
3058 break;
David Blaikie05491062013-01-21 04:37:12 +00003059 case Type::SubstTemplateTypeParm:
Guy Benyei11169dd2012-12-18 14:30:41 +00003060 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
Guy Benyei11169dd2012-12-18 14:30:41 +00003061 break;
Richard Smitha0abc422017-02-22 00:13:14 +00003062 case Type::Auto:
3063 case Type::DeducedTemplateSpecialization: {
3064 QualType DT = cast<DeducedType>(T)->getDeducedType();
David Blaikie42edade2014-11-11 20:44:45 +00003065 assert(!DT.isNull() && "Undeduced types shouldn't reach here.");
David Blaikie22c460a02013-05-24 21:24:35 +00003066 T = DT;
Guy Benyei11169dd2012-12-18 14:30:41 +00003067 break;
3068 }
Jordan Rose303e2f12016-11-10 23:28:17 +00003069 case Type::Adjusted:
3070 case Type::Decayed:
3071 // Decayed and adjusted types use the adjusted type in LLVM and DWARF.
3072 T = cast<AdjustedType>(T)->getAdjustedType();
3073 break;
3074 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00003075
Guy Benyei11169dd2012-12-18 14:30:41 +00003076 assert(T != LastT && "Type unwrapping failed to unwrap!");
NAKAMURA Takumi3e0a3632013-01-21 10:51:28 +00003077 (void)LastT;
Guy Benyei11169dd2012-12-18 14:30:41 +00003078 } while (true);
3079}
3080
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003081llvm::DIType *CGDebugInfo::getTypeOrNull(QualType Ty) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003082
3083 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00003084 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Eric Christopherb2a008c2013-05-16 00:45:12 +00003085
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00003086 auto It = TypeCache.find(Ty.getAsOpaquePtr());
3087 if (It != TypeCache.end()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003088 // Verify that the debug info still exists.
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00003089 if (llvm::Metadata *V = It->second)
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003090 return cast<llvm::DIType>(V);
Guy Benyei11169dd2012-12-18 14:30:41 +00003091 }
3092
Duncan P. N. Exon Smithc7551282015-04-06 23:21:33 +00003093 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003094}
3095
David Blaikie0e716b42014-03-03 23:48:23 +00003096void CGDebugInfo::completeTemplateDefinition(
3097 const ClassTemplateSpecializationDecl &SD) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00003098 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
David Blaikie0856f662014-03-04 22:01:08 +00003099 return;
David Blaikie1ac9c982017-04-11 21:13:37 +00003100 completeUnusedClass(SD);
3101}
David Blaikie0856f662014-03-04 22:01:08 +00003102
David Blaikie1ac9c982017-04-11 21:13:37 +00003103void CGDebugInfo::completeUnusedClass(const CXXRecordDecl &D) {
3104 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
3105 return;
3106
3107 completeClassData(&D);
David Blaikie0e716b42014-03-03 23:48:23 +00003108 // In case this type has no member function definitions being emitted, ensure
3109 // it is retained
David Blaikie1ac9c982017-04-11 21:13:37 +00003110 RetainedTypes.push_back(CGM.getContext().getRecordType(&D).getAsOpaquePtr());
David Blaikie0e716b42014-03-03 23:48:23 +00003111}
3112
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003113llvm::DIType *CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile *Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003114 if (Ty.isNull())
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00003115 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003116
Luboš Luňák4f2104c2019-11-02 16:39:59 +01003117 llvm::TimeTraceScope TimeScope("DebugType", [&]() {
3118 std::string Name;
3119 llvm::raw_string_ostream OS(Name);
3120 Ty.print(OS, getPrintingPolicy());
3121 return Name;
3122 });
3123
Guy Benyei11169dd2012-12-18 14:30:41 +00003124 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00003125 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00003126
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00003127 if (auto *T = getTypeOrNull(Ty))
Guy Benyei11169dd2012-12-18 14:30:41 +00003128 return T;
3129
Adrian Prantlca844182015-09-11 17:23:03 +00003130 llvm::DIType *Res = CreateTypeNode(Ty, Unit);
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00003131 void *TyPtr = Ty.getAsOpaquePtr();
Adrian Prantl73409ce2013-03-11 18:33:46 +00003132
3133 // And update the type cache.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003134 TypeCache[TyPtr].reset(Res);
Guy Benyei11169dd2012-12-18 14:30:41 +00003135
Guy Benyei11169dd2012-12-18 14:30:41 +00003136 return Res;
3137}
3138
Adrian Prantl5c8bd882015-09-11 17:23:08 +00003139llvm::DIModule *CGDebugInfo::getParentModuleOrNull(const Decl *D) {
Adrian Prantl335f5c72015-10-02 17:36:14 +00003140 // A forward declaration inside a module header does not belong to the module.
3141 if (isa<RecordDecl>(D) && !cast<RecordDecl>(D)->getDefinition())
3142 return nullptr;
Adrian Prantl85d938a2015-09-21 17:48:37 +00003143 if (DebugTypeExtRefs && D->isFromASTFile()) {
3144 // Record a reference to an imported clang module or precompiled header.
3145 auto *Reader = CGM.getContext().getExternalSource();
3146 auto Idx = D->getOwningModuleID();
3147 auto Info = Reader->getSourceDescriptor(Idx);
3148 if (Info)
3149 return getOrCreateModuleRef(*Info, /*SkeletonCU=*/true);
3150 } else if (ClangModuleMap) {
Adrian Prantl9402cef2015-09-20 16:51:35 +00003151 // We are building a clang module or a precompiled header.
3152 //
3153 // TODO: When D is a CXXRecordDecl or a C++ Enum, the ODR applies
3154 // and it wouldn't be necessary to specify the parent scope
3155 // because the type is already unique by definition (it would look
3156 // like the output of -fno-standalone-debug). On the other hand,
3157 // the parent scope helps a consumer to quickly locate the object
3158 // file where the type's definition is located, so it might be
3159 // best to make this behavior a command line or debugger tuning
3160 // option.
Richard Smith54f04402017-05-18 02:29:20 +00003161 if (Module *M = D->getOwningModule()) {
Adrian Prantlaa5d08d2016-01-22 21:14:41 +00003162 // This is a (sub-)module.
Reid Klecknerc915cb92020-02-27 18:13:54 -08003163 auto Info = ASTSourceDescriptor(*M);
Adrian Prantl9402cef2015-09-20 16:51:35 +00003164 return getOrCreateModuleRef(Info, /*SkeletonCU=*/false);
Adrian Prantlaa5d08d2016-01-22 21:14:41 +00003165 } else {
3166 // This the precompiled header being built.
3167 return getOrCreateModuleRef(PCHDescriptor, /*SkeletonCU=*/false);
Adrian Prantl9402cef2015-09-20 16:51:35 +00003168 }
3169 }
Adrian Prantl5c8bd882015-09-11 17:23:08 +00003170
Adrian Prantl9402cef2015-09-20 16:51:35 +00003171 return nullptr;
Adrian Prantl5c8bd882015-09-11 17:23:08 +00003172}
3173
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003174llvm::DIType *CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile *Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003175 // Handle qualifiers, which recursively handles what they refer to.
3176 if (Ty.hasLocalQualifiers())
David Blaikie99dab3b2013-09-04 22:03:57 +00003177 return CreateQualifiedType(Ty, Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00003178
Guy Benyei11169dd2012-12-18 14:30:41 +00003179 // Work out details of type.
3180 switch (Ty->getTypeClass()) {
3181#define TYPE(Class, Base)
3182#define ABSTRACT_TYPE(Class, Base)
3183#define NON_CANONICAL_TYPE(Class, Base)
3184#define DEPENDENT_TYPE(Class, Base) case Type::Class:
John McCall36b12a82019-10-02 06:35:23 +00003185#include "clang/AST/TypeNodes.inc"
Guy Benyei11169dd2012-12-18 14:30:41 +00003186 llvm_unreachable("Dependent types cannot show up in debug information");
3187
3188 case Type::ExtVector:
3189 case Type::Vector:
3190 return CreateType(cast<VectorType>(Ty), Unit);
Florian Hahn10658692020-05-11 17:45:51 +01003191 case Type::ConstantMatrix:
3192 return CreateType(cast<ConstantMatrixType>(Ty), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00003193 case Type::ObjCObjectPointer:
3194 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
3195 case Type::ObjCObject:
3196 return CreateType(cast<ObjCObjectType>(Ty), Unit);
Manman Rene6be26c2016-09-13 17:25:08 +00003197 case Type::ObjCTypeParam:
3198 return CreateType(cast<ObjCTypeParamType>(Ty), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00003199 case Type::ObjCInterface:
3200 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
3201 case Type::Builtin:
3202 return CreateType(cast<BuiltinType>(Ty));
3203 case Type::Complex:
3204 return CreateType(cast<ComplexType>(Ty));
3205 case Type::Pointer:
3206 return CreateType(cast<PointerType>(Ty), Unit);
3207 case Type::BlockPointer:
3208 return CreateType(cast<BlockPointerType>(Ty), Unit);
3209 case Type::Typedef:
David Blaikie99dab3b2013-09-04 22:03:57 +00003210 return CreateType(cast<TypedefType>(Ty), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00003211 case Type::Record:
David Blaikie99dab3b2013-09-04 22:03:57 +00003212 return CreateType(cast<RecordType>(Ty));
Guy Benyei11169dd2012-12-18 14:30:41 +00003213 case Type::Enum:
Manman Ren1b457022013-08-28 21:20:28 +00003214 return CreateEnumType(cast<EnumType>(Ty));
Guy Benyei11169dd2012-12-18 14:30:41 +00003215 case Type::FunctionProto:
3216 case Type::FunctionNoProto:
3217 return CreateType(cast<FunctionType>(Ty), Unit);
3218 case Type::ConstantArray:
3219 case Type::VariableArray:
3220 case Type::IncompleteArray:
3221 return CreateType(cast<ArrayType>(Ty), Unit);
3222
3223 case Type::LValueReference:
3224 return CreateType(cast<LValueReferenceType>(Ty), Unit);
3225 case Type::RValueReference:
3226 return CreateType(cast<RValueReferenceType>(Ty), Unit);
3227
3228 case Type::MemberPointer:
3229 return CreateType(cast<MemberPointerType>(Ty), Unit);
3230
3231 case Type::Atomic:
3232 return CreateType(cast<AtomicType>(Ty), Unit);
3233
Erich Keane5f0903e2020-04-17 10:44:19 -07003234 case Type::ExtInt:
3235 return CreateType(cast<ExtIntType>(Ty));
Xiuli Pan9c14e282016-01-09 12:53:17 +00003236 case Type::Pipe:
3237 return CreateType(cast<PipeType>(Ty), Unit);
3238
Guy Benyei11169dd2012-12-18 14:30:41 +00003239 case Type::TemplateSpecialization:
David Blaikief1b382e2014-04-06 17:14:06 +00003240 return CreateType(cast<TemplateSpecializationType>(Ty), Unit);
3241
David Blaikie42edade2014-11-11 20:44:45 +00003242 case Type::Auto:
David Blaikief1b382e2014-04-06 17:14:06 +00003243 case Type::Attributed:
Jordan Rose303e2f12016-11-10 23:28:17 +00003244 case Type::Adjusted:
3245 case Type::Decayed:
Richard Smith600b5262017-01-26 20:40:47 +00003246 case Type::DeducedTemplateSpecialization:
Guy Benyei11169dd2012-12-18 14:30:41 +00003247 case Type::Elaborated:
3248 case Type::Paren:
Leonard Chanc72aaf62019-05-07 03:20:17 +00003249 case Type::MacroQualified:
Guy Benyei11169dd2012-12-18 14:30:41 +00003250 case Type::SubstTemplateTypeParm:
3251 case Type::TypeOfExpr:
3252 case Type::TypeOf:
3253 case Type::Decltype:
3254 case Type::UnaryTransform:
David Blaikie66ed89d2013-07-13 21:08:08 +00003255 case Type::PackExpansion:
David Blaikie22c460a02013-05-24 21:24:35 +00003256 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003257 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00003258
David Blaikie42edade2014-11-11 20:44:45 +00003259 llvm_unreachable("type should have been unwrapped!");
Guy Benyei11169dd2012-12-18 14:30:41 +00003260}
3261
Duncan P. N. Exon Smithbd210e62015-07-24 20:34:41 +00003262llvm::DICompositeType *CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty,
3263 llvm::DIFile *Unit) {
David Blaikie4a2b5ef2013-08-12 22:24:20 +00003264 QualType QTy(Ty, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00003265
Duncan P. N. Exon Smithbd210e62015-07-24 20:34:41 +00003266 auto *T = cast_or_null<llvm::DICompositeType>(getTypeOrNull(QTy));
Guy Benyei11169dd2012-12-18 14:30:41 +00003267
3268 // We may have cached a forward decl when we could have created
3269 // a non-forward decl. Go ahead and create a non-forward decl
3270 // now.
Duncan P. N. Exon Smith4caa7f22015-04-16 01:00:56 +00003271 if (T && !T->isForwardDecl())
Eric Christophere7b87e52014-10-26 23:40:33 +00003272 return T;
Guy Benyei11169dd2012-12-18 14:30:41 +00003273
3274 // Otherwise create the type.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003275 llvm::DICompositeType *Res = CreateLimitedType(Ty);
David Blaikie8d5e1282013-08-20 21:03:29 +00003276
3277 // Propagate members from the declaration to the definition
3278 // CreateType(const RecordType*) will overwrite this with the members in the
3279 // correct order if the full type is needed.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003280 DBuilder.replaceArrays(Res, T ? T->getElements() : llvm::DINodeArray());
Guy Benyei11169dd2012-12-18 14:30:41 +00003281
Guy Benyei11169dd2012-12-18 14:30:41 +00003282 // And update the type cache.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003283 TypeCache[QTy.getAsOpaquePtr()].reset(Res);
Guy Benyei11169dd2012-12-18 14:30:41 +00003284 return Res;
3285}
3286
3287// TODO: Currently used for context chains when limiting debug info.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003288llvm::DICompositeType *CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003289 RecordDecl *RD = Ty->getDecl();
Eric Christopherb2a008c2013-05-16 00:45:12 +00003290
Guy Benyei11169dd2012-12-18 14:30:41 +00003291 // Get overall information about the record type for the debug info.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003292 llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00003293 unsigned Line = getLineNumber(RD->getLocation());
3294 StringRef RDName = getClassName(RD);
3295
Amjad Abouddc4531e2016-04-30 01:44:38 +00003296 llvm::DIScope *RDContext = getDeclContextDescriptor(RD);
Guy Benyei11169dd2012-12-18 14:30:41 +00003297
David Blaikied2785892013-08-18 17:36:19 +00003298 // If we ended up creating the type during the context chain construction,
3299 // just return that.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003300 auto *T = cast_or_null<llvm::DICompositeType>(
Duncan P. N. Exon Smithc7551282015-04-06 23:21:33 +00003301 getTypeOrNull(CGM.getContext().getRecordType(RD)));
Duncan P. N. Exon Smith4caa7f22015-04-16 01:00:56 +00003302 if (T && (!T->isForwardDecl() || !RD->getDefinition()))
Eric Christophere7b87e52014-10-26 23:40:33 +00003303 return T;
David Blaikied2785892013-08-18 17:36:19 +00003304
Adrian Prantl381e7552014-02-04 21:29:50 +00003305 // If this is just a forward or incomplete declaration, construct an
3306 // appropriately marked node and just return it.
3307 const RecordDecl *D = RD->getDefinition();
3308 if (!D || !D->isCompleteDefinition())
Manman Ren1b457022013-08-28 21:20:28 +00003309 return getOrCreateRecordFwdDecl(Ty, RDContext);
Guy Benyei11169dd2012-12-18 14:30:41 +00003310
3311 uint64_t Size = CGM.getContext().getTypeSize(Ty);
Victor Leschuka7ece032016-10-20 00:13:19 +00003312 auto Align = getDeclAlignIfRequired(D, CGM.getContext());
Eric Christopherb2a008c2013-05-16 00:45:12 +00003313
Brock Wyma8557ec52018-05-22 12:41:19 +00003314 SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
Manman Rene0064d82013-08-29 23:19:58 +00003315
Shafik Yaghmour528f5da2019-08-27 20:17:35 +00003316 // Explicitly record the calling convention and export symbols for C++
3317 // records.
Adrian Prantl6c5f03a2018-01-05 01:13:52 +00003318 auto Flags = llvm::DINode::FlagZero;
3319 if (auto CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3320 if (CGM.getCXXABI().getRecordArgABI(CXXRD) == CGCXXABI::RAA_Indirect)
3321 Flags |= llvm::DINode::FlagTypePassByReference;
3322 else
3323 Flags |= llvm::DINode::FlagTypePassByValue;
Aaron Smith044326c2018-07-23 20:49:07 +00003324
Aaron Smithfa7745b2019-04-11 20:24:54 +00003325 // Record if a C++ record is non-trivial type.
3326 if (!CXXRD->isTrivial())
Aaron Smithf0d27332019-02-26 03:49:05 +00003327 Flags |= llvm::DINode::FlagNonTrivial;
Shafik Yaghmour528f5da2019-08-27 20:17:35 +00003328
3329 // Record exports it symbols to the containing structure.
3330 if (CXXRD->isAnonymousStructOrUnion())
3331 Flags |= llvm::DINode::FlagExportSymbols;
Adrian Prantl6c5f03a2018-01-05 01:13:52 +00003332 }
3333
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003334 llvm::DICompositeType *RealDecl = DBuilder.createReplaceableCompositeType(
Leny Kholodov80c047d2016-09-06 10:48:04 +00003335 getTagForRecord(RD), RDName, RDContext, DefUnit, Line, 0, Size, Align,
Brock Wyma8557ec52018-05-22 12:41:19 +00003336 Flags, Identifier);
Guy Benyei11169dd2012-12-18 14:30:41 +00003337
Duncan P. N. Exon Smithf9521b02016-04-17 07:45:08 +00003338 // Elements of composite types usually have back to the type, creating
3339 // uniquing cycles. Distinct nodes are more efficient.
3340 switch (RealDecl->getTag()) {
3341 default:
3342 llvm_unreachable("invalid composite type tag");
3343
3344 case llvm::dwarf::DW_TAG_array_type:
3345 case llvm::dwarf::DW_TAG_enumeration_type:
3346 // Array elements and most enumeration elements don't have back references,
3347 // so they don't tend to be involved in uniquing cycles and there is some
3348 // chance of merging them when linking together two modules. Only make
3349 // them distinct if they are ODR-uniqued.
Brock Wyma8557ec52018-05-22 12:41:19 +00003350 if (Identifier.empty())
Duncan P. N. Exon Smithf9521b02016-04-17 07:45:08 +00003351 break;
Galina Kistanova0872d6c2017-06-03 06:30:46 +00003352 LLVM_FALLTHROUGH;
Duncan P. N. Exon Smithf9521b02016-04-17 07:45:08 +00003353
3354 case llvm::dwarf::DW_TAG_structure_type:
3355 case llvm::dwarf::DW_TAG_union_type:
3356 case llvm::dwarf::DW_TAG_class_type:
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00003357 // Immediately resolve to a distinct node.
Duncan P. N. Exon Smithf9521b02016-04-17 07:45:08 +00003358 RealDecl =
3359 llvm::MDNode::replaceWithDistinct(llvm::TempDICompositeType(RealDecl));
3360 break;
3361 }
3362
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003363 RegionMap[Ty->getDecl()].reset(RealDecl);
3364 TypeCache[QualType(Ty, 0).getAsOpaquePtr()].reset(RealDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00003365
David Majnemer58ed0f32016-07-17 00:39:12 +00003366 if (const auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD))
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003367 DBuilder.replaceArrays(RealDecl, llvm::DINodeArray(),
Duncan P. N. Exon Smithc8ee63e2014-12-18 00:48:56 +00003368 CollectCXXTemplateParams(TSpecial, DefUnit));
David Blaikie952dac32013-08-15 22:42:12 +00003369 return RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00003370}
3371
David Blaikieadfbf992013-08-18 16:55:33 +00003372void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD,
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003373 llvm::DICompositeType *RealDecl) {
David Blaikieadfbf992013-08-18 16:55:33 +00003374 // A class's primary base or the class itself contains the vtable.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003375 llvm::DICompositeType *ContainingType = nullptr;
David Blaikieadfbf992013-08-18 16:55:33 +00003376 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
3377 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
Alp Tokerd4733632013-12-05 04:47:09 +00003378 // Seek non-virtual primary base root.
David Blaikieadfbf992013-08-18 16:55:33 +00003379 while (1) {
3380 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
3381 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
3382 if (PBT && !BRL.isPrimaryBaseVirtual())
3383 PBase = PBT;
3384 else
3385 break;
3386 }
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003387 ContainingType = cast<llvm::DICompositeType>(
David Blaikieadfbf992013-08-18 16:55:33 +00003388 getOrCreateType(QualType(PBase->getTypeForDecl(), 0),
3389 getOrCreateFile(RD->getLocation())));
3390 } else if (RD->isDynamicClass())
3391 ContainingType = RealDecl;
3392
Duncan P. N. Exon Smithc8ee63e2014-12-18 00:48:56 +00003393 DBuilder.replaceVTableHolder(RealDecl, ContainingType);
David Blaikieadfbf992013-08-18 16:55:33 +00003394}
3395
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003396llvm::DIType *CGDebugInfo::CreateMemberType(llvm::DIFile *Unit, QualType FType,
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00003397 StringRef Name, uint64_t *Offset) {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003398 llvm::DIType *FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00003399 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
Victor Leschuka7ece032016-10-20 00:13:19 +00003400 auto FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext());
Leny Kholodovdf050fd2016-09-06 17:06:14 +00003401 llvm::DIType *Ty =
3402 DBuilder.createMemberType(Unit, Name, Unit, 0, FieldSize, FieldAlign,
3403 *Offset, llvm::DINode::FlagZero, FieldTy);
Guy Benyei11169dd2012-12-18 14:30:41 +00003404 *Offset += FieldSize;
3405 return Ty;
3406}
3407
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003408void CGDebugInfo::collectFunctionDeclProps(GlobalDecl GD, llvm::DIFile *Unit,
Duncan P. N. Exon Smith8e47da42015-04-21 20:07:29 +00003409 StringRef &Name,
3410 StringRef &LinkageName,
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003411 llvm::DIScope *&FDContext,
3412 llvm::DINodeArray &TParamsArray,
Leny Kholodov80c047d2016-09-06 10:48:04 +00003413 llvm::DINode::DIFlags &Flags) {
David Majnemer58ed0f32016-07-17 00:39:12 +00003414 const auto *FD = cast<FunctionDecl>(GD.getDecl());
Frederic Riss9db79f12014-11-18 03:40:46 +00003415 Name = getFunctionName(FD);
3416 // Use mangled name as linkage name for C/C++ functions.
3417 if (FD->hasPrototype()) {
3418 LinkageName = CGM.getMangledName(GD);
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003419 Flags |= llvm::DINode::FlagPrototyped;
Frederic Riss9db79f12014-11-18 03:40:46 +00003420 }
3421 // No need to replicate the linkage name if it isn't different from the
3422 // subprogram name, no need to have it at all unless coverage is enabled or
Dehao Chenb3a70de2017-01-19 00:44:21 +00003423 // debug is set to more than just line tables or extra debug info is needed.
Benjamin Kramer8c305922016-02-02 11:06:51 +00003424 if (LinkageName == Name || (!CGM.getCodeGenOpts().EmitGcovArcs &&
3425 !CGM.getCodeGenOpts().EmitGcovNotes &&
Dehao Chenb3a70de2017-01-19 00:44:21 +00003426 !CGM.getCodeGenOpts().DebugInfoForProfiling &&
Benjamin Kramer8c305922016-02-02 11:06:51 +00003427 DebugKind <= codegenoptions::DebugLineTablesOnly))
Frederic Riss9db79f12014-11-18 03:40:46 +00003428 LinkageName = StringRef();
3429
Amy Huang53539bb2020-01-13 15:54:54 -08003430 if (CGM.getCodeGenOpts().hasReducedDebugInfo()) {
Frederic Riss9db79f12014-11-18 03:40:46 +00003431 if (const NamespaceDecl *NSDecl =
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00003432 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
Adrian Prantlddb8e062017-05-12 16:23:53 +00003433 FDContext = getOrCreateNamespace(NSDecl);
Frederic Riss9db79f12014-11-18 03:40:46 +00003434 else if (const RecordDecl *RDecl =
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00003435 dyn_cast_or_null<RecordDecl>(FD->getDeclContext())) {
Adrian Prantl5c8bd882015-09-11 17:23:08 +00003436 llvm::DIScope *Mod = getParentModuleOrNull(RDecl);
3437 FDContext = getContextDescriptor(RDecl, Mod ? Mod : TheCU);
3438 }
Adrian Prantlfd5ac8a2016-08-17 16:20:32 +00003439 // Check if it is a noreturn-marked function
3440 if (FD->isNoReturn())
3441 Flags |= llvm::DINode::FlagNoReturn;
Frederic Riss9db79f12014-11-18 03:40:46 +00003442 // Collect template parameters.
3443 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
3444 }
3445}
3446
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003447void CGDebugInfo::collectVarDeclProps(const VarDecl *VD, llvm::DIFile *&Unit,
Frederic Riss9db79f12014-11-18 03:40:46 +00003448 unsigned &LineNo, QualType &T,
3449 StringRef &Name, StringRef &LinkageName,
Matthew Voss20165362018-10-03 18:45:04 +00003450 llvm::MDTuple *&TemplateParameters,
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003451 llvm::DIScope *&VDContext) {
Frederic Riss9db79f12014-11-18 03:40:46 +00003452 Unit = getOrCreateFile(VD->getLocation());
3453 LineNo = getLineNumber(VD->getLocation());
3454
3455 setLocation(VD->getLocation());
3456
3457 T = VD->getType();
3458 if (T->isIncompleteArrayType()) {
3459 // CodeGen turns int[] into int[1] so we'll do the same here.
3460 llvm::APInt ConstVal(32, 1);
3461 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3462
Richard Smith772e2662019-10-04 01:25:59 +00003463 T = CGM.getContext().getConstantArrayType(ET, ConstVal, nullptr,
3464 ArrayType::Normal, 0);
Frederic Riss9db79f12014-11-18 03:40:46 +00003465 }
3466
3467 Name = VD->getName();
3468 if (VD->getDeclContext() && !isa<FunctionDecl>(VD->getDeclContext()) &&
3469 !isa<ObjCMethodDecl>(VD->getDeclContext()))
3470 LinkageName = CGM.getMangledName(VD);
3471 if (LinkageName == Name)
3472 LinkageName = StringRef();
3473
Matthew Voss20165362018-10-03 18:45:04 +00003474 if (isa<VarTemplateSpecializationDecl>(VD)) {
3475 llvm::DINodeArray parameterNodes = CollectVarTemplateParams(VD, &*Unit);
3476 TemplateParameters = parameterNodes.get();
3477 } else {
3478 TemplateParameters = nullptr;
3479 }
3480
Frederic Riss9db79f12014-11-18 03:40:46 +00003481 // Since we emit declarations (DW_AT_members) for static members, place the
3482 // definition of those static members in the namespace they were declared in
3483 // in the source code (the lexical decl context).
3484 // FIXME: Generalize this for even non-member global variables where the
3485 // declaration and definition may have different lexical decl contexts, once
3486 // we have support for emitting declarations of (non-member) global variables.
Saleem Abdulrasoolcd187f02015-02-28 00:13:13 +00003487 const DeclContext *DC = VD->isStaticDataMember() ? VD->getLexicalDeclContext()
3488 : VD->getDeclContext();
3489 // When a record type contains an in-line initialization of a static data
3490 // member, and the record type is marked as __declspec(dllexport), an implicit
3491 // definition of the member will be created in the record context. DWARF
3492 // doesn't seem to have a nice way to describe this in a form that consumers
3493 // are likely to understand, so fake the "normal" situation of a definition
3494 // outside the class by putting it in the global scope.
3495 if (DC->isRecord())
3496 DC = CGM.getContext().getTranslationUnitDecl();
Adrian Prantl5c8bd882015-09-11 17:23:08 +00003497
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00003498 llvm::DIScope *Mod = getParentModuleOrNull(VD);
3499 VDContext = getContextDescriptor(cast<Decl>(DC), Mod ? Mod : TheCU);
Frederic Riss9db79f12014-11-18 03:40:46 +00003500}
3501
Adrian Prantlb7acfc02017-02-27 21:30:05 +00003502llvm::DISubprogram *CGDebugInfo::getFunctionFwdDeclOrStub(GlobalDecl GD,
3503 bool Stub) {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003504 llvm::DINodeArray TParamsArray;
Frederic Rissd253ed62014-11-18 03:40:51 +00003505 StringRef Name, LinkageName;
Leny Kholodov80c047d2016-09-06 10:48:04 +00003506 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
Paul Robinsoncda54212018-11-19 18:29:28 +00003507 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
Adrian Prantlb7acfc02017-02-27 21:30:05 +00003508 SourceLocation Loc = GD.getDecl()->getLocation();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003509 llvm::DIFile *Unit = getOrCreateFile(Loc);
3510 llvm::DIScope *DContext = Unit;
Frederic Rissd253ed62014-11-18 03:40:51 +00003511 unsigned Line = getLineNumber(Loc);
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00003512 collectFunctionDeclProps(GD, Unit, Name, LinkageName, DContext, TParamsArray,
3513 Flags);
Simon Pilgrimcfee2ef2019-10-16 10:38:49 +00003514 auto *FD = cast<FunctionDecl>(GD.getDecl());
Adrian Prantlb7acfc02017-02-27 21:30:05 +00003515
Frederic Rissd253ed62014-11-18 03:40:51 +00003516 // Build function type.
3517 SmallVector<QualType, 16> ArgTypes;
Simon Pilgrimcfee2ef2019-10-16 10:38:49 +00003518 for (const ParmVarDecl *Parm : FD->parameters())
3519 ArgTypes.push_back(Parm->getType());
3520
Reid Klecknerf00f8032016-06-08 20:41:54 +00003521 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
3522 QualType FnType = CGM.getContext().getFunctionType(
3523 FD->getReturnType(), ArgTypes, FunctionProtoType::ExtProtoInfo(CC));
Paul Robinsoncda54212018-11-19 18:29:28 +00003524 if (!FD->isExternallyVisible())
3525 SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;
3526 if (CGM.getLangOpts().Optimize)
3527 SPFlags |= llvm::DISubprogram::SPFlagOptimized;
3528
Adrian Prantlb7acfc02017-02-27 21:30:05 +00003529 if (Stub) {
Vedant Kumar5931b4e2018-10-05 20:37:17 +00003530 Flags |= getCallSiteRelatedAttrs();
Paul Robinsoncda54212018-11-19 18:29:28 +00003531 SPFlags |= llvm::DISubprogram::SPFlagDefinition;
Adrian Prantlb7acfc02017-02-27 21:30:05 +00003532 return DBuilder.createFunction(
3533 DContext, Name, LinkageName, Unit, Line,
Paul Robinsoncda54212018-11-19 18:29:28 +00003534 getOrCreateFunctionType(GD.getDecl(), FnType, Unit), 0, Flags, SPFlags,
Adrian Prantlb7acfc02017-02-27 21:30:05 +00003535 TParamsArray.get(), getFunctionDeclaration(FD));
3536 }
3537
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003538 llvm::DISubprogram *SP = DBuilder.createTempFunctionFwdDecl(
Duncan P. N. Exon Smithebad0aa2015-04-07 16:50:49 +00003539 DContext, Name, LinkageName, Unit, Line,
Paul Robinsoncda54212018-11-19 18:29:28 +00003540 getOrCreateFunctionType(GD.getDecl(), FnType, Unit), 0, Flags, SPFlags,
Duncan P. N. Exon Smithebad0aa2015-04-07 16:50:49 +00003541 TParamsArray.get(), getFunctionDeclaration(FD));
George Burgess IV00f70bd2018-03-01 05:43:23 +00003542 const FunctionDecl *CanonDecl = FD->getCanonicalDecl();
Duncan P. N. Exon Smith4078ad42015-04-16 16:36:45 +00003543 FwdDeclReplaceMap.emplace_back(std::piecewise_construct,
3544 std::make_tuple(CanonDecl),
3545 std::make_tuple(SP));
Frederic Rissd253ed62014-11-18 03:40:51 +00003546 return SP;
3547}
3548
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00003549llvm::DISubprogram *CGDebugInfo::getFunctionForwardDeclaration(GlobalDecl GD) {
Adrian Prantlb7acfc02017-02-27 21:30:05 +00003550 return getFunctionFwdDeclOrStub(GD, /* Stub = */ false);
3551}
3552
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00003553llvm::DISubprogram *CGDebugInfo::getFunctionStub(GlobalDecl GD) {
Adrian Prantlb7acfc02017-02-27 21:30:05 +00003554 return getFunctionFwdDeclOrStub(GD, /* Stub = */ true);
3555}
3556
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003557llvm::DIGlobalVariable *
Frederic Rissd253ed62014-11-18 03:40:51 +00003558CGDebugInfo::getGlobalVariableForwardDeclaration(const VarDecl *VD) {
3559 QualType T;
3560 StringRef Name, LinkageName;
3561 SourceLocation Loc = VD->getLocation();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003562 llvm::DIFile *Unit = getOrCreateFile(Loc);
3563 llvm::DIScope *DContext = Unit;
Frederic Rissd253ed62014-11-18 03:40:51 +00003564 unsigned Line = getLineNumber(Loc);
Matthew Voss20165362018-10-03 18:45:04 +00003565 llvm::MDTuple *TemplateParameters = nullptr;
Frederic Rissd253ed62014-11-18 03:40:51 +00003566
Matthew Voss20165362018-10-03 18:45:04 +00003567 collectVarDeclProps(VD, Unit, Line, T, Name, LinkageName, TemplateParameters,
3568 DContext);
Victor Leschuka7ece032016-10-20 00:13:19 +00003569 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
Duncan P. N. Exon Smithdadc2b62015-04-21 18:43:54 +00003570 auto *GV = DBuilder.createTempGlobalVariableFwdDecl(
3571 DContext, Name, LinkageName, Unit, Line, getOrCreateType(T, Unit),
Matthew Voss20165362018-10-03 18:45:04 +00003572 !VD->isExternallyVisible(), nullptr, TemplateParameters, Align);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003573 FwdDeclReplaceMap.emplace_back(
3574 std::piecewise_construct,
3575 std::make_tuple(cast<VarDecl>(VD->getCanonicalDecl())),
3576 std::make_tuple(static_cast<llvm::Metadata *>(GV)));
Frederic Rissd253ed62014-11-18 03:40:51 +00003577 return GV;
3578}
3579
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003580llvm::DINode *CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
David Blaikiebd483762013-05-20 04:58:53 +00003581 // We only need a declaration (not a definition) of the type - so use whatever
3582 // we would otherwise do to get a type for a pointee. (forward declarations in
3583 // limited debug info, full definitions (if the type definition is available)
3584 // in unlimited debug info)
David Majnemer58ed0f32016-07-17 00:39:12 +00003585 if (const auto *TD = dyn_cast<TypeDecl>(D))
David Blaikie6b7d060c2013-08-12 23:14:36 +00003586 return getOrCreateType(CGM.getContext().getTypeDeclType(TD),
David Blaikie99dab3b2013-09-04 22:03:57 +00003587 getOrCreateFile(TD->getLocation()));
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003588 auto I = DeclCache.find(D->getCanonicalDecl());
Frederic Rissd253ed62014-11-18 03:40:51 +00003589
Adrian Prantl5f4740d2016-12-20 02:10:02 +00003590 if (I != DeclCache.end()) {
3591 auto N = I->second;
3592 if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(N))
3593 return GVE->getVariable();
3594 return dyn_cast_or_null<llvm::DINode>(N);
3595 }
Frederic Rissd253ed62014-11-18 03:40:51 +00003596
3597 // No definition for now. Emit a forward definition that might be
3598 // merged with a potential upcoming definition.
David Majnemer58ed0f32016-07-17 00:39:12 +00003599 if (const auto *FD = dyn_cast<FunctionDecl>(D))
Frederic Rissd253ed62014-11-18 03:40:51 +00003600 return getFunctionForwardDeclaration(FD);
3601 else if (const auto *VD = dyn_cast<VarDecl>(D))
3602 return getGlobalVariableForwardDeclaration(VD);
3603
Duncan P. N. Exon Smith4078ad42015-04-16 16:36:45 +00003604 return nullptr;
David Blaikiebd483762013-05-20 04:58:53 +00003605}
3606
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003607llvm::DISubprogram *CGDebugInfo::getFunctionDeclaration(const Decl *D) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00003608 if (!D || DebugKind <= codegenoptions::DebugLineTablesOnly)
Duncan P. N. Exon Smitha7fbcbf2015-04-20 22:09:57 +00003609 return nullptr;
David Blaikie18cfbc52013-06-22 00:09:36 +00003610
David Majnemer58ed0f32016-07-17 00:39:12 +00003611 const auto *FD = dyn_cast<FunctionDecl>(D);
Eric Christophere7b87e52014-10-26 23:40:33 +00003612 if (!FD)
Duncan P. N. Exon Smitha7fbcbf2015-04-20 22:09:57 +00003613 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003614
3615 // Setup context.
Adrian Prantl6ec370a2015-09-10 18:39:45 +00003616 auto *S = getDeclContextDescriptor(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00003617
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003618 auto MI = SPCache.find(FD->getCanonicalDecl());
David Blaikiefd07c602013-08-09 17:20:05 +00003619 if (MI == SPCache.end()) {
David Majnemer58ed0f32016-07-17 00:39:12 +00003620 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {
Duncan P. N. Exon Smithc09c5482015-04-20 21:17:26 +00003621 return CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()),
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003622 cast<llvm::DICompositeType>(S));
David Blaikiefd07c602013-08-09 17:20:05 +00003623 }
3624 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003625 if (MI != SPCache.end()) {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003626 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
Duncan P. N. Exon Smith87afdeb2015-04-14 03:24:14 +00003627 if (SP && !SP->isDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00003628 return SP;
3629 }
3630
Aaron Ballman86c93902014-03-06 23:45:36 +00003631 for (auto NextFD : FD->redecls()) {
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003632 auto MI = SPCache.find(NextFD->getCanonicalDecl());
Guy Benyei11169dd2012-12-18 14:30:41 +00003633 if (MI != SPCache.end()) {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003634 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
Duncan P. N. Exon Smith87afdeb2015-04-14 03:24:14 +00003635 if (SP && !SP->isDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00003636 return SP;
3637 }
3638 }
Duncan P. N. Exon Smitha7fbcbf2015-04-20 22:09:57 +00003639 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003640}
3641
Adrian Prantl901cc4a2019-11-08 09:24:31 -08003642llvm::DISubprogram *CGDebugInfo::getObjCMethodDeclaration(
3643 const Decl *D, llvm::DISubroutineType *FnType, unsigned LineNo,
3644 llvm::DINode::DIFlags Flags, llvm::DISubprogram::DISPFlags SPFlags) {
3645 if (!D || DebugKind <= codegenoptions::DebugLineTablesOnly)
3646 return nullptr;
3647
Adrian Prantle0cabe22019-11-21 09:56:01 -08003648 const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
3649 if (!OMD)
3650 return nullptr;
3651
3652 if (CGM.getCodeGenOpts().DwarfVersion < 5 && !OMD->isDirectMethod())
Adrian Prantl901cc4a2019-11-08 09:24:31 -08003653 return nullptr;
3654
Raphael Isemannccfab8e2019-12-17 09:36:57 +01003655 if (OMD->isDirectMethod())
3656 SPFlags |= llvm::DISubprogram::SPFlagObjCDirect;
3657
Adrian Prantl901cc4a2019-11-08 09:24:31 -08003658 // Starting with DWARF V5 method declarations are emitted as children of
3659 // the interface type.
Adrian Prantl901cc4a2019-11-08 09:24:31 -08003660 auto *ID = dyn_cast_or_null<ObjCInterfaceDecl>(D->getDeclContext());
3661 if (!ID)
3662 ID = OMD->getClassInterface();
3663 if (!ID)
3664 return nullptr;
3665 QualType QTy(ID->getTypeForDecl(), 0);
3666 auto It = TypeCache.find(QTy.getAsOpaquePtr());
3667 if (It == TypeCache.end())
3668 return nullptr;
3669 auto *InterfaceType = cast<llvm::DICompositeType>(It->second);
3670 llvm::DISubprogram *FD = DBuilder.createFunction(
3671 InterfaceType, getObjCMethodName(OMD), StringRef(),
3672 InterfaceType->getFile(), LineNo, FnType, LineNo, Flags, SPFlags);
3673 DBuilder.finalizeSubprogram(FD);
Adrian Prantle0cabe22019-11-21 09:56:01 -08003674 ObjCMethodCache[ID].push_back({FD, OMD->isDirectMethod()});
Adrian Prantl901cc4a2019-11-08 09:24:31 -08003675 return FD;
3676}
3677
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00003678// getOrCreateFunctionType - Construct type. If it is a c++ method, include
Guy Benyei11169dd2012-12-18 14:30:41 +00003679// implicit parameter "this".
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003680llvm::DISubroutineType *CGDebugInfo::getOrCreateFunctionType(const Decl *D,
Duncan P. N. Exon Smith4078ad42015-04-16 16:36:45 +00003681 QualType FnType,
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003682 llvm::DIFile *F) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00003683 if (!D || DebugKind <= codegenoptions::DebugLineTablesOnly)
Duncan P. N. Exon Smitha7fbcbf2015-04-20 22:09:57 +00003684 // Create fake but valid subroutine type. Otherwise -verify would fail, and
3685 // subprogram DIE will miss DW_AT_decl_file and DW_AT_decl_line fields.
Eric Christopher28a6db52015-10-15 06:56:08 +00003686 return DBuilder.createSubroutineType(DBuilder.getOrCreateTypeArray(None));
Guy Benyei11169dd2012-12-18 14:30:41 +00003687
David Majnemer58ed0f32016-07-17 00:39:12 +00003688 if (const auto *Method = dyn_cast<CXXMethodDecl>(D))
Awanish Pandeyc83602f2020-01-23 16:06:52 +05303689 return getOrCreateMethodType(Method, F, false);
Reid Klecknerf00f8032016-06-08 20:41:54 +00003690
3691 const auto *FTy = FnType->getAs<FunctionType>();
3692 CallingConv CC = FTy ? FTy->getCallConv() : CallingConv::CC_C;
3693
David Majnemer58ed0f32016-07-17 00:39:12 +00003694 if (const auto *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003695 // Add "self" and "_cmd"
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003696 SmallVector<llvm::Metadata *, 16> Elts;
Guy Benyei11169dd2012-12-18 14:30:41 +00003697
3698 // First element is always return type. For 'void' functions it is NULL.
Alp Toker314cc812014-01-25 16:55:45 +00003699 QualType ResultTy = OMethod->getReturnType();
Adrian Prantl5f360102013-05-22 21:37:49 +00003700
3701 // Replace the instancetype keyword with the actual type.
3702 if (ResultTy == CGM.getContext().getObjCInstanceType())
3703 ResultTy = CGM.getContext().getPointerType(
Eric Christophere7b87e52014-10-26 23:40:33 +00003704 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
Adrian Prantl5f360102013-05-22 21:37:49 +00003705
Adrian Prantl7bec9032013-05-10 21:08:31 +00003706 Elts.push_back(getOrCreateType(ResultTy, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00003707 // "self" pointer is always first argument.
Adrian Prantl748a6cd2015-09-08 20:41:52 +00003708 QualType SelfDeclTy;
3709 if (auto *SelfDecl = OMethod->getSelfDecl())
3710 SelfDeclTy = SelfDecl->getType();
3711 else if (auto *FPT = dyn_cast<FunctionProtoType>(FnType))
3712 if (FPT->getNumParams() > 1)
3713 SelfDeclTy = FPT->getParamType(0);
3714 if (!SelfDeclTy.isNull())
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00003715 Elts.push_back(
3716 CreateSelfType(SelfDeclTy, getOrCreateType(SelfDeclTy, F)));
Guy Benyei11169dd2012-12-18 14:30:41 +00003717 // "_cmd" pointer is always second argument.
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00003718 Elts.push_back(DBuilder.createArtificialType(
Adrian Prantl748a6cd2015-09-08 20:41:52 +00003719 getOrCreateType(CGM.getContext().getObjCSelType(), F)));
Guy Benyei11169dd2012-12-18 14:30:41 +00003720 // Get rest of the arguments.
David Majnemer59f77922016-06-24 04:05:48 +00003721 for (const auto *PI : OMethod->parameters())
Aaron Ballman43b68be2014-03-07 17:50:17 +00003722 Elts.push_back(getOrCreateType(PI->getType(), F));
Frederic Riss787d9d62014-08-12 04:42:23 +00003723 // Variadic methods need a special marker at the end of the type list.
3724 if (OMethod->isVariadic())
3725 Elts.push_back(DBuilder.createUnspecifiedParameter());
Guy Benyei11169dd2012-12-18 14:30:41 +00003726
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003727 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
Leny Kholodov80c047d2016-09-06 10:48:04 +00003728 return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
3729 getDwarfCC(CC));
Guy Benyei11169dd2012-12-18 14:30:41 +00003730 }
Adrian Prantld45ba252014-02-25 19:38:11 +00003731
Adrian Prantl800faef2014-02-25 23:42:18 +00003732 // Handle variadic function types; they need an additional
3733 // unspecified parameter.
David Majnemer58ed0f32016-07-17 00:39:12 +00003734 if (const auto *FD = dyn_cast<FunctionDecl>(D))
Adrian Prantld45ba252014-02-25 19:38:11 +00003735 if (FD->isVariadic()) {
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003736 SmallVector<llvm::Metadata *, 16> EltTys;
Adrian Prantld45ba252014-02-25 19:38:11 +00003737 EltTys.push_back(getOrCreateType(FD->getReturnType(), F));
David Majnemer58ed0f32016-07-17 00:39:12 +00003738 if (const auto *FPT = dyn_cast<FunctionProtoType>(FnType))
3739 for (QualType ParamType : FPT->param_types())
3740 EltTys.push_back(getOrCreateType(ParamType, F));
Adrian Prantld45ba252014-02-25 19:38:11 +00003741 EltTys.push_back(DBuilder.createUnspecifiedParameter());
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003742 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
Leny Kholodov80c047d2016-09-06 10:48:04 +00003743 return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
3744 getDwarfCC(CC));
Adrian Prantld45ba252014-02-25 19:38:11 +00003745 }
3746
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003747 return cast<llvm::DISubroutineType>(getOrCreateType(FnType, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00003748}
3749
Eric Christophere7b87e52014-10-26 23:40:33 +00003750void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, SourceLocation Loc,
3751 SourceLocation ScopeLoc, QualType FnType,
Brock Wyma94ece8f2018-04-16 16:53:57 +00003752 llvm::Function *Fn, bool CurFuncIsThunk,
3753 CGBuilderTy &Builder) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003754
3755 StringRef Name;
3756 StringRef LinkageName;
3757
3758 FnBeginRegionCount.push_back(LexicalBlockStack.size());
3759
3760 const Decl *D = GD.getDecl();
Craig Topper8a13c412014-05-21 05:09:00 +00003761 bool HasDecl = (D != nullptr);
Eric Christopher885c41b2014-04-01 22:25:28 +00003762
Leny Kholodov80c047d2016-09-06 10:48:04 +00003763 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
Paul Robinsoncda54212018-11-19 18:29:28 +00003764 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003765 llvm::DIFile *Unit = getOrCreateFile(Loc);
3766 llvm::DIScope *FDContext = Unit;
3767 llvm::DINodeArray TParamsArray;
Guy Benyei11169dd2012-12-18 14:30:41 +00003768 if (!HasDecl) {
3769 // Use llvm function name.
David Blaikieebe87e12013-08-27 23:57:18 +00003770 LinkageName = Fn->getName();
David Majnemer58ed0f32016-07-17 00:39:12 +00003771 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Duncan P. N. Exon Smitha7fbcbf2015-04-20 22:09:57 +00003772 // If there is a subprogram for this function available then use it.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003773 auto FI = SPCache.find(FD->getCanonicalDecl());
Guy Benyei11169dd2012-12-18 14:30:41 +00003774 if (FI != SPCache.end()) {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003775 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
Duncan P. N. Exon Smith87afdeb2015-04-14 03:24:14 +00003776 if (SP && SP->isDefinition()) {
Duncan P. N. Exon Smithd899f6e2015-04-18 00:07:30 +00003777 LexicalBlockStack.emplace_back(SP);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003778 RegionMap[D].reset(SP);
Guy Benyei11169dd2012-12-18 14:30:41 +00003779 return;
3780 }
3781 }
Frederic Riss9db79f12014-11-18 03:40:46 +00003782 collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
3783 TParamsArray, Flags);
David Majnemer58ed0f32016-07-17 00:39:12 +00003784 } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003785 Name = getObjCMethodName(OMD);
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003786 Flags |= llvm::DINode::FlagPrototyped;
Reid Kleckner105c5652019-04-24 22:45:44 +00003787 } else if (isa<VarDecl>(D) &&
3788 GD.getDynamicInitKind() != DynamicInitKind::NoStub) {
3789 // This is a global initializer or atexit destructor for a global variable.
3790 Name = getDynamicInitializerName(cast<VarDecl>(D), GD.getDynamicInitKind(),
3791 Fn);
Guy Benyei11169dd2012-12-18 14:30:41 +00003792 } else {
Guy Benyei11169dd2012-12-18 14:30:41 +00003793 Name = Fn->getName();
shafik428583d2020-02-05 10:39:35 -08003794
Michael Liao318d0ed2020-02-06 12:19:55 -05003795 if (isa<BlockDecl>(D))
shafik428583d2020-02-05 10:39:35 -08003796 LinkageName = Name;
3797
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003798 Flags |= llvm::DINode::FlagPrototyped;
Guy Benyei11169dd2012-12-18 14:30:41 +00003799 }
David Majnemer58ed0f32016-07-17 00:39:12 +00003800 if (Name.startswith("\01"))
Guy Benyei11169dd2012-12-18 14:30:41 +00003801 Name = Name.substr(1);
3802
Alexandre Ganeacaf31662019-11-15 16:21:17 -05003803 if (!HasDecl || D->isImplicit() || D->hasAttr<ArtificialAttr>()) {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003804 Flags |= llvm::DINode::FlagArtificial;
Adrian Prantldb763572016-11-09 21:43:51 +00003805 // Artificial functions should not silently reuse CurLoc.
3806 CurLoc = SourceLocation();
Adrian Prantl42d71b92014-04-10 23:21:53 +00003807 }
Brock Wyma94ece8f2018-04-16 16:53:57 +00003808
3809 if (CurFuncIsThunk)
3810 Flags |= llvm::DINode::FlagThunk;
3811
Paul Robinsoncda54212018-11-19 18:29:28 +00003812 if (Fn->hasLocalLinkage())
3813 SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;
3814 if (CGM.getLangOpts().Optimize)
3815 SPFlags |= llvm::DISubprogram::SPFlagOptimized;
3816
Vedant Kumar5931b4e2018-10-05 20:37:17 +00003817 llvm::DINode::DIFlags FlagsForDef = Flags | getCallSiteRelatedAttrs();
Paul Robinsoncda54212018-11-19 18:29:28 +00003818 llvm::DISubprogram::DISPFlags SPFlagsForDef =
3819 SPFlags | llvm::DISubprogram::SPFlagDefinition;
Vedant Kumar5931b4e2018-10-05 20:37:17 +00003820
Adrian Prantl42d71b92014-04-10 23:21:53 +00003821 unsigned LineNo = getLineNumber(Loc);
3822 unsigned ScopeLine = getLineNumber(ScopeLoc);
Adrian Prantl901cc4a2019-11-08 09:24:31 -08003823 llvm::DISubroutineType *DIFnType = getOrCreateFunctionType(D, FnType, Unit);
3824 llvm::DISubprogram *Decl = nullptr;
3825 if (D)
3826 Decl = isa<ObjCMethodDecl>(D)
3827 ? getObjCMethodDeclaration(D, DIFnType, LineNo, Flags, SPFlags)
3828 : getFunctionDeclaration(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00003829
Eric Christopher8018e412014-03-27 18:50:35 +00003830 // FIXME: The function declaration we're constructing here is mostly reusing
3831 // declarations from CXXMethodDecl and not constructing new ones for arbitrary
3832 // FunctionDecls. When/if we fix this we can have FDContext be TheCU/null for
3833 // all subprograms instead of the actual context since subprogram definitions
3834 // are emitted as CU level entities by the backend.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003835 llvm::DISubprogram *SP = DBuilder.createFunction(
Adrian Prantl901cc4a2019-11-08 09:24:31 -08003836 FDContext, Name, LinkageName, Unit, LineNo, DIFnType, ScopeLine,
3837 FlagsForDef, SPFlagsForDef, TParamsArray.get(), Decl);
Peter Collingbourne0900fe02015-11-05 22:04:14 +00003838 Fn->setSubprogram(SP);
Frederic Rissb1ab28c2014-11-05 19:19:04 +00003839 // We might get here with a VarDecl in the case we're generating
3840 // code for the initialization of globals. Do not record these decls
3841 // as they will overwrite the actual VarDecl Decl in the cache.
3842 if (HasDecl && isa<FunctionDecl>(D))
David Majnemer58ed0f32016-07-17 00:39:12 +00003843 DeclCache[D->getCanonicalDecl()].reset(SP);
Guy Benyei11169dd2012-12-18 14:30:41 +00003844
Adrian Prantlbebb8932014-03-21 21:01:58 +00003845 // Push the function onto the lexical block stack.
Duncan P. N. Exon Smithd899f6e2015-04-18 00:07:30 +00003846 LexicalBlockStack.emplace_back(SP);
Adrian Prantlbebb8932014-03-21 21:01:58 +00003847
Guy Benyei11169dd2012-12-18 14:30:41 +00003848 if (HasDecl)
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003849 RegionMap[D].reset(SP);
Guy Benyei11169dd2012-12-18 14:30:41 +00003850}
3851
Vedant Kumar8bd52142019-07-11 19:28:07 +00003852void CGDebugInfo::EmitFunctionDecl(GlobalDecl GD, SourceLocation Loc,
3853 QualType FnType, llvm::Function *Fn) {
Adrian Prantl748a6cd2015-09-08 20:41:52 +00003854 StringRef Name;
3855 StringRef LinkageName;
3856
3857 const Decl *D = GD.getDecl();
3858 if (!D)
Vedant Kumar8bd52142019-07-11 19:28:07 +00003859 return;
Adrian Prantl748a6cd2015-09-08 20:41:52 +00003860
Luboš Luňák4f2104c2019-11-02 16:39:59 +01003861 llvm::TimeTraceScope TimeScope("DebugFunction", [&]() {
3862 std::string Name;
3863 llvm::raw_string_ostream OS(Name);
3864 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
3865 ND->getNameForDiagnostic(OS, getPrintingPolicy(),
3866 /*Qualified=*/true);
3867 return Name;
3868 });
3869
Leny Kholodov80c047d2016-09-06 10:48:04 +00003870 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
Adrian Prantl748a6cd2015-09-08 20:41:52 +00003871 llvm::DIFile *Unit = getOrCreateFile(Loc);
Vedant Kumar8bd52142019-07-11 19:28:07 +00003872 bool IsDeclForCallSite = Fn ? true : false;
Djordje Todorovic0f651682019-06-27 06:44:44 +00003873 llvm::DIScope *FDContext =
3874 IsDeclForCallSite ? Unit : getDeclContextDescriptor(D);
Adrian Prantl748a6cd2015-09-08 20:41:52 +00003875 llvm::DINodeArray TParamsArray;
3876 if (isa<FunctionDecl>(D)) {
3877 // If there is a DISubprogram for this function available then use it.
3878 collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
3879 TParamsArray, Flags);
David Majnemer58ed0f32016-07-17 00:39:12 +00003880 } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) {
Adrian Prantl748a6cd2015-09-08 20:41:52 +00003881 Name = getObjCMethodName(OMD);
3882 Flags |= llvm::DINode::FlagPrototyped;
3883 } else {
3884 llvm_unreachable("not a function or ObjC method");
3885 }
3886 if (!Name.empty() && Name[0] == '\01')
3887 Name = Name.substr(1);
3888
3889 if (D->isImplicit()) {
3890 Flags |= llvm::DINode::FlagArtificial;
3891 // Artificial functions without a location should not silently reuse CurLoc.
3892 if (Loc.isInvalid())
3893 CurLoc = SourceLocation();
3894 }
3895 unsigned LineNo = getLineNumber(Loc);
3896 unsigned ScopeLine = 0;
Paul Robinsoncda54212018-11-19 18:29:28 +00003897 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
3898 if (CGM.getLangOpts().Optimize)
3899 SPFlags |= llvm::DISubprogram::SPFlagOptimized;
Adrian Prantl748a6cd2015-09-08 20:41:52 +00003900
Djordje Todorovic0f651682019-06-27 06:44:44 +00003901 llvm::DISubprogram *SP = DBuilder.createFunction(
Adrian Prantle76bda52016-04-15 15:55:45 +00003902 FDContext, Name, LinkageName, Unit, LineNo,
Paul Robinsoncda54212018-11-19 18:29:28 +00003903 getOrCreateFunctionType(D, FnType, Unit), ScopeLine, Flags, SPFlags,
Djordje Todorovic0f651682019-06-27 06:44:44 +00003904 TParamsArray.get(), getFunctionDeclaration(D));
Vedant Kumar8bd52142019-07-11 19:28:07 +00003905
3906 if (IsDeclForCallSite)
3907 Fn->setSubprogram(SP);
3908
Djordje Todorovic40a3fcb2020-05-27 13:58:21 +02003909 DBuilder.finalizeSubprogram(SP);
Djordje Todorovic0f651682019-06-27 06:44:44 +00003910}
3911
3912void CGDebugInfo::EmitFuncDeclForCallSite(llvm::CallBase *CallOrInvoke,
3913 QualType CalleeType,
3914 const FunctionDecl *CalleeDecl) {
Vedant Kumar568db782019-11-13 18:19:32 -08003915 if (!CallOrInvoke)
Djordje Todorovic0f651682019-06-27 06:44:44 +00003916 return;
Djordje Todorovic0f651682019-06-27 06:44:44 +00003917 auto *Func = CallOrInvoke->getCalledFunction();
3918 if (!Func)
3919 return;
Vedant Kumar568db782019-11-13 18:19:32 -08003920 if (Func->getSubprogram())
3921 return;
3922
Yaxun (Sam) Liu361e4f12020-05-14 23:09:30 -04003923 // Do not emit a declaration subprogram for a builtin, a function with nodebug
3924 // attribute, or if call site info isn't required. Also, elide declarations
3925 // for functions with reserved names, as call site-related features aren't
3926 // interesting in this case (& also, the compiler may emit calls to these
3927 // functions without debug locations, which makes the verifier complain).
3928 if (CalleeDecl->getBuiltinID() != 0 || CalleeDecl->hasAttr<NoDebugAttr>() ||
Vedant Kumar568db782019-11-13 18:19:32 -08003929 getCallSiteRelatedAttrs() == llvm::DINode::FlagZero)
3930 return;
3931 if (const auto *Id = CalleeDecl->getIdentifier())
3932 if (Id->isReservedName())
3933 return;
Djordje Todorovic0f651682019-06-27 06:44:44 +00003934
3935 // If there is no DISubprogram attached to the function being called,
3936 // create the one describing the function in order to have complete
3937 // call site debug info.
Vedant Kumar8bd52142019-07-11 19:28:07 +00003938 if (!CalleeDecl->isStatic() && !CalleeDecl->isInlined())
Michael Liao4cf01ed2020-03-18 01:43:20 -04003939 EmitFunctionDecl(CalleeDecl, CalleeDecl->getLocation(), CalleeType, Func);
Adrian Prantl748a6cd2015-09-08 20:41:52 +00003940}
3941
Adrian Prantlb7acfc02017-02-27 21:30:05 +00003942void CGDebugInfo::EmitInlineFunctionStart(CGBuilderTy &Builder, GlobalDecl GD) {
3943 const auto *FD = cast<FunctionDecl>(GD.getDecl());
3944 // If there is a subprogram for this function available then use it.
3945 auto FI = SPCache.find(FD->getCanonicalDecl());
3946 llvm::DISubprogram *SP = nullptr;
3947 if (FI != SPCache.end())
3948 SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
Adrian Prantl8040a212017-08-23 21:24:12 +00003949 if (!SP || !SP->isDefinition())
Adrian Prantlb7acfc02017-02-27 21:30:05 +00003950 SP = getFunctionStub(GD);
3951 FnBeginRegionCount.push_back(LexicalBlockStack.size());
3952 LexicalBlockStack.emplace_back(SP);
3953 setInlinedAt(Builder.getCurrentDebugLocation());
3954 EmitLocation(Builder, FD->getLocation());
3955}
3956
3957void CGDebugInfo::EmitInlineFunctionEnd(CGBuilderTy &Builder) {
3958 assert(CurInlinedAt && "unbalanced inline scope stack");
Keno Fischer41d4b4e2017-06-01 21:14:03 +00003959 EmitFunctionEnd(Builder, nullptr);
Adrian Prantlb7acfc02017-02-27 21:30:05 +00003960 setInlinedAt(llvm::DebugLoc(CurInlinedAt).getInlinedAt());
3961}
3962
Calixte Denizetfcd661d2018-09-24 18:24:18 +00003963void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003964 // Update our current location
3965 setLocation(Loc);
3966
Adrian Prantl42ab39f2018-11-09 21:17:38 +00003967 if (CurLoc.isInvalid() || CurLoc.isMacroID() || LexicalBlockStack.empty())
Eric Christophere7b87e52014-10-26 23:40:33 +00003968 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00003969
Adrian Prantle83b1302014-01-07 22:05:52 +00003970 llvm::MDNode *Scope = LexicalBlockStack.back();
Calixte Denizetfcd661d2018-09-24 18:24:18 +00003971 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(
3972 getLineNumber(CurLoc), getColumnNumber(CurLoc), Scope, CurInlinedAt));
Guy Benyei11169dd2012-12-18 14:30:41 +00003973}
3974
Guy Benyei11169dd2012-12-18 14:30:41 +00003975void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
Duncan P. N. Exon Smitha66e3052014-12-09 19:22:40 +00003976 llvm::MDNode *Back = nullptr;
3977 if (!LexicalBlockStack.empty())
3978 Back = LexicalBlockStack.back().get();
Duncan P. N. Exon Smithd899f6e2015-04-18 00:07:30 +00003979 LexicalBlockStack.emplace_back(DBuilder.createLexicalBlock(
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003980 cast<llvm::DIScope>(Back), getOrCreateFile(CurLoc), getLineNumber(CurLoc),
Duncan P. N. Exon Smithd899f6e2015-04-18 00:07:30 +00003981 getColumnNumber(CurLoc)));
Guy Benyei11169dd2012-12-18 14:30:41 +00003982}
3983
Konstantin Zhuravlyov2b4917f2017-03-09 18:06:23 +00003984void CGDebugInfo::AppendAddressSpaceXDeref(
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00003985 unsigned AddressSpace, SmallVectorImpl<int64_t> &Expr) const {
Konstantin Zhuravlyov2b4917f2017-03-09 18:06:23 +00003986 Optional<unsigned> DWARFAddressSpace =
3987 CGM.getTarget().getDWARFAddressSpace(AddressSpace);
3988 if (!DWARFAddressSpace)
3989 return;
3990
3991 Expr.push_back(llvm::dwarf::DW_OP_constu);
3992 Expr.push_back(DWARFAddressSpace.getValue());
3993 Expr.push_back(llvm::dwarf::DW_OP_swap);
3994 Expr.push_back(llvm::dwarf::DW_OP_xderef);
3995}
3996
Eric Christopher0fdcb312013-05-16 00:52:20 +00003997void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
3998 SourceLocation Loc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003999 // Set our current location.
4000 setLocation(Loc);
4001
Guy Benyei11169dd2012-12-18 14:30:41 +00004002 // Emit a line table change for the current location inside the new scope.
Adrian Prantlb7acfc02017-02-27 21:30:05 +00004003 Builder.SetCurrentDebugLocation(
4004 llvm::DebugLoc::get(getLineNumber(Loc), getColumnNumber(Loc),
4005 LexicalBlockStack.back(), CurInlinedAt));
David Blaikie60a877b2014-10-22 19:34:33 +00004006
Benjamin Kramer8c305922016-02-02 11:06:51 +00004007 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
David Blaikie60a877b2014-10-22 19:34:33 +00004008 return;
4009
4010 // Create a new lexical block and push it on the stack.
4011 CreateLexicalBlock(Loc);
Guy Benyei11169dd2012-12-18 14:30:41 +00004012}
4013
Eric Christopher0fdcb312013-05-16 00:52:20 +00004014void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
4015 SourceLocation Loc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004016 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4017
4018 // Provide an entry in the line table for the end of the block.
Calixte Denizetfcd661d2018-09-24 18:24:18 +00004019 EmitLocation(Builder, Loc);
Guy Benyei11169dd2012-12-18 14:30:41 +00004020
Benjamin Kramer8c305922016-02-02 11:06:51 +00004021 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
David Blaikie60a877b2014-10-22 19:34:33 +00004022 return;
4023
Guy Benyei11169dd2012-12-18 14:30:41 +00004024 LexicalBlockStack.pop_back();
4025}
4026
Keno Fischer41d4b4e2017-06-01 21:14:03 +00004027void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder, llvm::Function *Fn) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004028 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4029 unsigned RCount = FnBeginRegionCount.back();
4030 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
4031
4032 // Pop all regions for this function.
David Blaikie60a877b2014-10-22 19:34:33 +00004033 while (LexicalBlockStack.size() != RCount) {
4034 // Provide an entry in the line table for the end of the block.
Calixte Denizetfcd661d2018-09-24 18:24:18 +00004035 EmitLocation(Builder, CurLoc);
David Blaikie60a877b2014-10-22 19:34:33 +00004036 LexicalBlockStack.pop_back();
4037 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004038 FnBeginRegionCount.pop_back();
Keno Fischer41d4b4e2017-06-01 21:14:03 +00004039
4040 if (Fn && Fn->getSubprogram())
4041 DBuilder.finalizeSubprogram(Fn->getSubprogram());
Guy Benyei11169dd2012-12-18 14:30:41 +00004042}
4043
Adrian Prantl05a623e2018-09-10 16:14:28 +00004044CGDebugInfo::BlockByRefType
4045CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
4046 uint64_t *XOffset) {
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00004047 SmallVector<llvm::Metadata *, 5> EltTys;
Guy Benyei11169dd2012-12-18 14:30:41 +00004048 QualType FType;
4049 uint64_t FieldSize, FieldOffset;
Victor Leschuk802e4a52016-10-19 22:11:07 +00004050 uint32_t FieldAlign;
Eric Christopherb2a008c2013-05-16 00:45:12 +00004051
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004052 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
Eric Christopherb2a008c2013-05-16 00:45:12 +00004053 QualType Type = VD->getType();
Guy Benyei11169dd2012-12-18 14:30:41 +00004054
4055 FieldOffset = 0;
4056 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
4057 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
4058 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
4059 FType = CGM.getContext().IntTy;
4060 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
4061 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
4062
4063 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
4064 if (HasCopyAndDispose) {
4065 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
Eric Christophere7b87e52014-10-26 23:40:33 +00004066 EltTys.push_back(
4067 CreateMemberType(Unit, FType, "__copy_helper", &FieldOffset));
4068 EltTys.push_back(
4069 CreateMemberType(Unit, FType, "__destroy_helper", &FieldOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00004070 }
4071 bool HasByrefExtendedLayout;
4072 Qualifiers::ObjCLifetime Lifetime;
Eric Christophere7b87e52014-10-26 23:40:33 +00004073 if (CGM.getContext().getByrefLifetime(Type, Lifetime,
4074 HasByrefExtendedLayout) &&
4075 HasByrefExtendedLayout) {
Adrian Prantlead2ba42013-07-23 00:12:14 +00004076 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
Eric Christophere7b87e52014-10-26 23:40:33 +00004077 EltTys.push_back(
4078 CreateMemberType(Unit, FType, "__byref_variable_layout", &FieldOffset));
Adrian Prantlead2ba42013-07-23 00:12:14 +00004079 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00004080
Guy Benyei11169dd2012-12-18 14:30:41 +00004081 CharUnits Align = CGM.getContext().getDeclAlign(VD);
4082 if (Align > CGM.getContext().toCharUnitsFromBits(
Eric Christophere7b87e52014-10-26 23:40:33 +00004083 CGM.getTarget().getPointerAlign(0))) {
4084 CharUnits FieldOffsetInBytes =
4085 CGM.getContext().toCharUnitsFromBits(FieldOffset);
Rui Ueyama83aa9792016-01-14 21:00:27 +00004086 CharUnits AlignedOffsetInBytes = FieldOffsetInBytes.alignTo(Align);
Eric Christophere7b87e52014-10-26 23:40:33 +00004087 CharUnits NumPaddingBytes = AlignedOffsetInBytes - FieldOffsetInBytes;
Eric Christopherb2a008c2013-05-16 00:45:12 +00004088
Guy Benyei11169dd2012-12-18 14:30:41 +00004089 if (NumPaddingBytes.isPositive()) {
4090 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
Richard Smith772e2662019-10-04 01:25:59 +00004091 FType = CGM.getContext().getConstantArrayType(
4092 CGM.getContext().CharTy, pad, nullptr, ArrayType::Normal, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00004093 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
4094 }
4095 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00004096
Guy Benyei11169dd2012-12-18 14:30:41 +00004097 FType = Type;
Adrian Prantl05a623e2018-09-10 16:14:28 +00004098 llvm::DIType *WrappedTy = getOrCreateType(FType, Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00004099 FieldSize = CGM.getContext().getTypeSize(FType);
4100 FieldAlign = CGM.getContext().toBits(Align);
4101
Eric Christopherb2a008c2013-05-16 00:45:12 +00004102 *XOffset = FieldOffset;
Adrian Prantl05a623e2018-09-10 16:14:28 +00004103 llvm::DIType *FieldTy = DBuilder.createMemberType(
4104 Unit, VD->getName(), Unit, 0, FieldSize, FieldAlign, FieldOffset,
4105 llvm::DINode::FlagZero, WrappedTy);
Guy Benyei11169dd2012-12-18 14:30:41 +00004106 EltTys.push_back(FieldTy);
4107 FieldOffset += FieldSize;
Eric Christopherb2a008c2013-05-16 00:45:12 +00004108
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004109 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
Adrian Prantl05a623e2018-09-10 16:14:28 +00004110 return {DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0,
4111 llvm::DINode::FlagZero, nullptr, Elements),
4112 WrappedTy};
Guy Benyei11169dd2012-12-18 14:30:41 +00004113}
4114
Sander de Smalen891af03a2018-02-03 13:55:59 +00004115llvm::DILocalVariable *CGDebugInfo::EmitDeclare(const VarDecl *VD,
4116 llvm::Value *Storage,
4117 llvm::Optional<unsigned> ArgNo,
Amy Huang7fac5c82019-06-20 17:15:21 +00004118 CGBuilderTy &Builder,
4119 const bool UsePointerValue) {
Amy Huang53539bb2020-01-13 15:54:54 -08004120 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00004121 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
Paul Robinsonafd2dde2016-06-16 00:42:36 +00004122 if (VD->hasAttr<NoDebugAttr>())
Sander de Smalen891af03a2018-02-03 13:55:59 +00004123 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004124
David Blaikie7fceebf2013-08-19 03:37:48 +00004125 bool Unwritten =
4126 VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) &&
4127 cast<Decl>(VD->getDeclContext())->isImplicit());
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004128 llvm::DIFile *Unit = nullptr;
David Blaikie7fceebf2013-08-19 03:37:48 +00004129 if (!Unwritten)
4130 Unit = getOrCreateFile(VD->getLocation());
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004131 llvm::DIType *Ty;
Guy Benyei11169dd2012-12-18 14:30:41 +00004132 uint64_t XOffset = 0;
4133 if (VD->hasAttr<BlocksAttr>())
Adrian Prantl05a623e2018-09-10 16:14:28 +00004134 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset).WrappedType;
Eric Christopherb2a008c2013-05-16 00:45:12 +00004135 else
Guy Benyei11169dd2012-12-18 14:30:41 +00004136 Ty = getOrCreateType(VD->getType(), Unit);
4137
4138 // If there is no debug info for this type then do not emit debug info
4139 // for this variable.
4140 if (!Ty)
Sander de Smalen891af03a2018-02-03 13:55:59 +00004141 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004142
Guy Benyei11169dd2012-12-18 14:30:41 +00004143 // Get location information.
David Blaikie7fceebf2013-08-19 03:37:48 +00004144 unsigned Line = 0;
4145 unsigned Column = 0;
4146 if (!Unwritten) {
4147 Line = getLineNumber(VD->getLocation());
4148 Column = getColumnNumber(VD->getLocation());
4149 }
Konstantin Zhuravlyov2b4917f2017-03-09 18:06:23 +00004150 SmallVector<int64_t, 13> Expr;
Leny Kholodov80c047d2016-09-06 10:48:04 +00004151 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
Guy Benyei11169dd2012-12-18 14:30:41 +00004152 if (VD->isImplicit())
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004153 Flags |= llvm::DINode::FlagArtificial;
Victor Leschuka7ece032016-10-20 00:13:19 +00004154
4155 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
4156
Konstantin Zhuravlyov2b4917f2017-03-09 18:06:23 +00004157 unsigned AddressSpace = CGM.getContext().getTargetAddressSpace(VD->getType());
4158 AppendAddressSpaceXDeref(AddressSpace, Expr);
4159
Alexey Bataev24f710182017-06-09 13:55:08 +00004160 // If this is implicit parameter of CXXThis or ObjCSelf kind, then give it an
4161 // object pointer flag.
Alexey Bataev56223232017-06-09 13:40:18 +00004162 if (const auto *IPD = dyn_cast<ImplicitParamDecl>(VD)) {
4163 if (IPD->getParameterKind() == ImplicitParamDecl::CXXThis ||
4164 IPD->getParameterKind() == ImplicitParamDecl::ObjCSelf)
4165 Flags |= llvm::DINode::FlagObjectPointer;
4166 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004167
Adrian Prantlc3782a12017-04-18 01:22:01 +00004168 // Note: Older versions of clang used to emit byval references with an extra
4169 // DW_OP_deref, because they referenced the IR arg directly instead of
4170 // referencing an alloca. Newer versions of LLVM don't treat allocas
4171 // differently from other function arguments when used in a dbg.declare.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004172 auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
Guy Benyei11169dd2012-12-18 14:30:41 +00004173 StringRef Name = VD->getName();
4174 if (!Name.empty()) {
4175 if (VD->hasAttr<BlocksAttr>()) {
Adrian Prantlc3782a12017-04-18 01:22:01 +00004176 // Here, we need an offset *into* the alloca.
Guy Benyei11169dd2012-12-18 14:30:41 +00004177 CharUnits offset = CharUnits::fromQuantity(32);
Florian Hahn3dbcced2017-06-13 18:06:15 +00004178 Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
Guy Benyei11169dd2012-12-18 14:30:41 +00004179 // offset of __forwarding field
4180 offset = CGM.getContext().toCharUnitsFromBits(
Eric Christophere7b87e52014-10-26 23:40:33 +00004181 CGM.getTarget().getPointerWidth(0));
Adrian Prantl7c6f9442015-01-19 17:51:58 +00004182 Expr.push_back(offset.getQuantity());
4183 Expr.push_back(llvm::dwarf::DW_OP_deref);
Florian Hahn3dbcced2017-06-13 18:06:15 +00004184 Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
Guy Benyei11169dd2012-12-18 14:30:41 +00004185 // offset of x field
4186 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
Adrian Prantl7c6f9442015-01-19 17:51:58 +00004187 Expr.push_back(offset.getQuantity());
Adrian Prantlc3782a12017-04-18 01:22:01 +00004188 }
David Majnemer58ed0f32016-07-17 00:39:12 +00004189 } else if (const auto *RT = dyn_cast<RecordType>(VD->getType())) {
Adrian Prantl0d820892015-04-29 15:05:50 +00004190 // If VD is an anonymous union then Storage represents value for
4191 // all union fields.
George Burgess IV00f70bd2018-03-01 05:43:23 +00004192 const RecordDecl *RD = RT->getDecl();
Adrian Prantl0d820892015-04-29 15:05:50 +00004193 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
Adrian Prantl00820ab2015-04-29 16:52:31 +00004194 // GDB has trouble finding local variables in anonymous unions, so we emit
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004195 // artificial local variables for each of the members.
Adrian Prantl00820ab2015-04-29 16:52:31 +00004196 //
4197 // FIXME: Remove this code as soon as GDB supports this.
4198 // The debug info verifier in LLVM operates based on the assumption that a
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004199 // variable has the same size as its storage and we had to disable the
4200 // check for artificial variables.
Adrian Prantl0d820892015-04-29 15:05:50 +00004201 for (const auto *Field : RD->fields()) {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004202 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
Adrian Prantl0d820892015-04-29 15:05:50 +00004203 StringRef FieldName = Field->getName();
4204
4205 // Ignore unnamed fields. Do not ignore unnamed records.
4206 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
4207 continue;
4208
4209 // Use VarDecl's Tag, Scope and Line number.
Victor Leschuka7ece032016-10-20 00:13:19 +00004210 auto FieldAlign = getDeclAlignIfRequired(Field, CGM.getContext());
Duncan P. N. Exon Smithe4306542015-07-31 17:56:14 +00004211 auto *D = DBuilder.createAutoVariable(
4212 Scope, FieldName, Unit, Line, FieldTy, CGM.getLangOpts().Optimize,
Victor Leschuka7ece032016-10-20 00:13:19 +00004213 Flags | llvm::DINode::FlagArtificial, FieldAlign);
Adrian Prantl0d820892015-04-29 15:05:50 +00004214
4215 // Insert an llvm.dbg.declare into the current block.
Adrian Prantlb7acfc02017-02-27 21:30:05 +00004216 DBuilder.insertDeclare(
4217 Storage, D, DBuilder.createExpression(Expr),
4218 llvm::DebugLoc::get(Line, Column, Scope, CurInlinedAt),
4219 Builder.GetInsertBlock());
Adrian Prantl0d820892015-04-29 15:05:50 +00004220 }
Adrian Prantl0d820892015-04-29 15:05:50 +00004221 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004222 }
David Blaikiea76a7c92013-01-05 05:58:35 +00004223
Amy Huang7fac5c82019-06-20 17:15:21 +00004224 // Clang stores the sret pointer provided by the caller in a static alloca.
4225 // Use DW_OP_deref to tell the debugger to load the pointer and treat it as
4226 // the address of the variable.
4227 if (UsePointerValue) {
4228 assert(std::find(Expr.begin(), Expr.end(), llvm::dwarf::DW_OP_deref) ==
4229 Expr.end() &&
4230 "Debug info already contains DW_OP_deref.");
4231 Expr.push_back(llvm::dwarf::DW_OP_deref);
4232 }
4233
David Blaikiea76a7c92013-01-05 05:58:35 +00004234 // Create the descriptor for the variable.
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004235 auto *D = ArgNo ? DBuilder.createParameterVariable(
4236 Scope, Name, *ArgNo, Unit, Line, Ty,
4237 CGM.getLangOpts().Optimize, Flags)
4238 : DBuilder.createAutoVariable(Scope, Name, Unit, Line, Ty,
4239 CGM.getLangOpts().Optimize,
4240 Flags, Align);
David Blaikiea76a7c92013-01-05 05:58:35 +00004241
4242 // Insert an llvm.dbg.declare into the current block.
Duncan P. N. Exon Smithfe88b482015-04-15 21:18:30 +00004243 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
Adrian Prantlb7acfc02017-02-27 21:30:05 +00004244 llvm::DebugLoc::get(Line, Column, Scope, CurInlinedAt),
Duncan P. N. Exon Smithfe88b482015-04-15 21:18:30 +00004245 Builder.GetInsertBlock());
Sander de Smalen891af03a2018-02-03 13:55:59 +00004246
4247 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00004248}
4249
Sander de Smalen891af03a2018-02-03 13:55:59 +00004250llvm::DILocalVariable *
4251CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD, llvm::Value *Storage,
Amy Huang7fac5c82019-06-20 17:15:21 +00004252 CGBuilderTy &Builder,
4253 const bool UsePointerValue) {
Amy Huang53539bb2020-01-13 15:54:54 -08004254 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
Amy Huang7fac5c82019-06-20 17:15:21 +00004255 return EmitDeclare(VD, Storage, llvm::None, Builder, UsePointerValue);
Guy Benyei11169dd2012-12-18 14:30:41 +00004256}
4257
Hsiangkai Wang35751492019-01-24 05:34:29 +00004258void CGDebugInfo::EmitLabel(const LabelDecl *D, CGBuilderTy &Builder) {
Amy Huang53539bb2020-01-13 15:54:54 -08004259 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
Hsiangkai Wang35751492019-01-24 05:34:29 +00004260 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4261
4262 if (D->hasAttr<NoDebugAttr>())
4263 return;
4264
4265 auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
4266 llvm::DIFile *Unit = getOrCreateFile(D->getLocation());
4267
4268 // Get location information.
4269 unsigned Line = getLineNumber(D->getLocation());
4270 unsigned Column = getColumnNumber(D->getLocation());
4271
4272 StringRef Name = D->getName();
4273
4274 // Create the descriptor for the label.
4275 auto *L =
4276 DBuilder.createLabel(Scope, Name, Unit, Line, CGM.getLangOpts().Optimize);
4277
4278 // Insert an llvm.dbg.label into the current block.
4279 DBuilder.insertLabel(L,
4280 llvm::DebugLoc::get(Line, Column, Scope, CurInlinedAt),
4281 Builder.GetInsertBlock());
4282}
4283
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004284llvm::DIType *CGDebugInfo::CreateSelfType(const QualType &QualTy,
4285 llvm::DIType *Ty) {
4286 llvm::DIType *CachedTy = getTypeOrNull(QualTy);
Eric Christophere7b87e52014-10-26 23:40:33 +00004287 if (CachedTy)
4288 Ty = CachedTy;
Adrian Prantlde17db32013-03-29 19:20:29 +00004289 return DBuilder.createObjectPointerType(Ty);
4290}
4291
Eric Christophere7b87e52014-10-26 23:40:33 +00004292void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(
4293 const VarDecl *VD, llvm::Value *Storage, CGBuilderTy &Builder,
Adrian Prantl88eec392014-11-21 00:35:25 +00004294 const CGBlockInfo &blockInfo, llvm::Instruction *InsertPoint) {
Amy Huang53539bb2020-01-13 15:54:54 -08004295 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00004296 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
Eric Christopherb2a008c2013-05-16 00:45:12 +00004297
Craig Topper8a13c412014-05-21 05:09:00 +00004298 if (Builder.GetInsertBlock() == nullptr)
Guy Benyei11169dd2012-12-18 14:30:41 +00004299 return;
Paul Robinsonafd2dde2016-06-16 00:42:36 +00004300 if (VD->hasAttr<NoDebugAttr>())
4301 return;
Eric Christopherb2a008c2013-05-16 00:45:12 +00004302
Guy Benyei11169dd2012-12-18 14:30:41 +00004303 bool isByRef = VD->hasAttr<BlocksAttr>();
Eric Christopherb2a008c2013-05-16 00:45:12 +00004304
Guy Benyei11169dd2012-12-18 14:30:41 +00004305 uint64_t XOffset = 0;
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004306 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
4307 llvm::DIType *Ty;
Guy Benyei11169dd2012-12-18 14:30:41 +00004308 if (isByRef)
Adrian Prantl05a623e2018-09-10 16:14:28 +00004309 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset).WrappedType;
Eric Christopherb2a008c2013-05-16 00:45:12 +00004310 else
Guy Benyei11169dd2012-12-18 14:30:41 +00004311 Ty = getOrCreateType(VD->getType(), Unit);
4312
4313 // Self is passed along as an implicit non-arg variable in a
4314 // block. Mark it as the object pointer.
Alexey Bataev56223232017-06-09 13:40:18 +00004315 if (const auto *IPD = dyn_cast<ImplicitParamDecl>(VD))
4316 if (IPD->getParameterKind() == ImplicitParamDecl::ObjCSelf)
4317 Ty = CreateSelfType(VD->getType(), Ty);
Guy Benyei11169dd2012-12-18 14:30:41 +00004318
4319 // Get location information.
4320 unsigned Line = getLineNumber(VD->getLocation());
4321 unsigned Column = getColumnNumber(VD->getLocation());
4322
4323 const llvm::DataLayout &target = CGM.getDataLayout();
4324
4325 CharUnits offset = CharUnits::fromQuantity(
Eric Christophere7b87e52014-10-26 23:40:33 +00004326 target.getStructLayout(blockInfo.StructureType)
Guy Benyei11169dd2012-12-18 14:30:41 +00004327 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
4328
Duncan P. N. Exon Smithf3dc4292014-10-01 20:26:18 +00004329 SmallVector<int64_t, 9> addr;
Adrian Prantlc3782a12017-04-18 01:22:01 +00004330 addr.push_back(llvm::dwarf::DW_OP_deref);
Florian Hahn3dbcced2017-06-13 18:06:15 +00004331 addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
Duncan P. N. Exon Smithf3dc4292014-10-01 20:26:18 +00004332 addr.push_back(offset.getQuantity());
Guy Benyei11169dd2012-12-18 14:30:41 +00004333 if (isByRef) {
Duncan P. N. Exon Smithf3dc4292014-10-01 20:26:18 +00004334 addr.push_back(llvm::dwarf::DW_OP_deref);
Florian Hahn3dbcced2017-06-13 18:06:15 +00004335 addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
Guy Benyei11169dd2012-12-18 14:30:41 +00004336 // offset of __forwarding field
Eric Christophere7b87e52014-10-26 23:40:33 +00004337 offset =
4338 CGM.getContext().toCharUnitsFromBits(target.getPointerSizeInBits(0));
Duncan P. N. Exon Smithf3dc4292014-10-01 20:26:18 +00004339 addr.push_back(offset.getQuantity());
4340 addr.push_back(llvm::dwarf::DW_OP_deref);
Florian Hahn3dbcced2017-06-13 18:06:15 +00004341 addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
Guy Benyei11169dd2012-12-18 14:30:41 +00004342 // offset of x field
4343 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
Duncan P. N. Exon Smithf3dc4292014-10-01 20:26:18 +00004344 addr.push_back(offset.getQuantity());
Guy Benyei11169dd2012-12-18 14:30:41 +00004345 }
4346
4347 // Create the descriptor for the variable.
Victor Leschuka7ece032016-10-20 00:13:19 +00004348 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
Duncan P. N. Exon Smithe4306542015-07-31 17:56:14 +00004349 auto *D = DBuilder.createAutoVariable(
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004350 cast<llvm::DILocalScope>(LexicalBlockStack.back()), VD->getName(), Unit,
Victor Leschuka7ece032016-10-20 00:13:19 +00004351 Line, Ty, false, llvm::DINode::FlagZero, Align);
Adrian Prantl0f6df002013-03-29 19:20:35 +00004352
Guy Benyei11169dd2012-12-18 14:30:41 +00004353 // Insert an llvm.dbg.declare into the current block.
Adrian Prantlb7acfc02017-02-27 21:30:05 +00004354 auto DL =
4355 llvm::DebugLoc::get(Line, Column, LexicalBlockStack.back(), CurInlinedAt);
Adrian Prantlc3782a12017-04-18 01:22:01 +00004356 auto *Expr = DBuilder.createExpression(addr);
Duncan P. N. Exon Smithfe88b482015-04-15 21:18:30 +00004357 if (InsertPoint)
Adrian Prantlc3782a12017-04-18 01:22:01 +00004358 DBuilder.insertDeclare(Storage, D, Expr, DL, InsertPoint);
Duncan P. N. Exon Smithfe88b482015-04-15 21:18:30 +00004359 else
Adrian Prantlc3782a12017-04-18 01:22:01 +00004360 DBuilder.insertDeclare(Storage, D, Expr, DL, Builder.GetInsertBlock());
Guy Benyei11169dd2012-12-18 14:30:41 +00004361}
4362
Guy Benyei11169dd2012-12-18 14:30:41 +00004363void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
4364 unsigned ArgNo,
4365 CGBuilderTy &Builder) {
Amy Huang53539bb2020-01-13 15:54:54 -08004366 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
Duncan P. N. Exon Smithe4306542015-07-31 17:56:14 +00004367 EmitDeclare(VD, AI, ArgNo, Builder);
Guy Benyei11169dd2012-12-18 14:30:41 +00004368}
4369
4370namespace {
Eric Christophere7b87e52014-10-26 23:40:33 +00004371struct BlockLayoutChunk {
4372 uint64_t OffsetInBits;
4373 const BlockDecl::Capture *Capture;
4374};
4375bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
4376 return l.OffsetInBits < r.OffsetInBits;
4377}
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004378} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00004379
Scott Linder58df0e42018-08-08 15:56:12 +00004380void CGDebugInfo::collectDefaultFieldsForBlockLiteralDeclare(
4381 const CGBlockInfo &Block, const ASTContext &Context, SourceLocation Loc,
4382 const llvm::StructLayout &BlockLayout, llvm::DIFile *Unit,
4383 SmallVectorImpl<llvm::Metadata *> &Fields) {
4384 // Blocks in OpenCL have unique constraints which make the standard fields
4385 // redundant while requiring size and align fields for enqueue_kernel. See
4386 // initializeForBlockHeader in CGBlocks.cpp
4387 if (CGM.getLangOpts().OpenCL) {
4388 Fields.push_back(createFieldType("__size", Context.IntTy, Loc, AS_public,
4389 BlockLayout.getElementOffsetInBits(0),
4390 Unit, Unit));
4391 Fields.push_back(createFieldType("__align", Context.IntTy, Loc, AS_public,
4392 BlockLayout.getElementOffsetInBits(1),
4393 Unit, Unit));
4394 } else {
4395 Fields.push_back(createFieldType("__isa", Context.VoidPtrTy, Loc, AS_public,
4396 BlockLayout.getElementOffsetInBits(0),
4397 Unit, Unit));
4398 Fields.push_back(createFieldType("__flags", Context.IntTy, Loc, AS_public,
4399 BlockLayout.getElementOffsetInBits(1),
4400 Unit, Unit));
4401 Fields.push_back(
4402 createFieldType("__reserved", Context.IntTy, Loc, AS_public,
4403 BlockLayout.getElementOffsetInBits(2), Unit, Unit));
4404 auto *FnTy = Block.getBlockExpr()->getFunctionType();
4405 auto FnPtrType = CGM.getContext().getPointerType(FnTy->desugar());
4406 Fields.push_back(createFieldType("__FuncPtr", FnPtrType, Loc, AS_public,
4407 BlockLayout.getElementOffsetInBits(3),
4408 Unit, Unit));
4409 Fields.push_back(createFieldType(
4410 "__descriptor",
4411 Context.getPointerType(Block.NeedsCopyDispose
4412 ? Context.getBlockDescriptorExtendedType()
4413 : Context.getBlockDescriptorType()),
4414 Loc, AS_public, BlockLayout.getElementOffsetInBits(4), Unit, Unit));
4415 }
4416}
4417
Guy Benyei11169dd2012-12-18 14:30:41 +00004418void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
Adrian Prantl356347b2017-10-26 20:08:52 +00004419 StringRef Name,
David Blaikie77bbb5f2014-08-08 17:10:14 +00004420 unsigned ArgNo,
Adrian Prantl356347b2017-10-26 20:08:52 +00004421 llvm::AllocaInst *Alloca,
Guy Benyei11169dd2012-12-18 14:30:41 +00004422 CGBuilderTy &Builder) {
Amy Huang53539bb2020-01-13 15:54:54 -08004423 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00004424 ASTContext &C = CGM.getContext();
4425 const BlockDecl *blockDecl = block.getBlockDecl();
4426
4427 // Collect some general information about the block's location.
4428 SourceLocation loc = blockDecl->getCaretLocation();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004429 llvm::DIFile *tunit = getOrCreateFile(loc);
Guy Benyei11169dd2012-12-18 14:30:41 +00004430 unsigned line = getLineNumber(loc);
4431 unsigned column = getColumnNumber(loc);
Eric Christopherb2a008c2013-05-16 00:45:12 +00004432
Guy Benyei11169dd2012-12-18 14:30:41 +00004433 // Build the debug-info type for the block literal.
Adrian Prantl6ec370a2015-09-10 18:39:45 +00004434 getDeclContextDescriptor(blockDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00004435
4436 const llvm::StructLayout *blockLayout =
Eric Christophere7b87e52014-10-26 23:40:33 +00004437 CGM.getDataLayout().getStructLayout(block.StructureType);
Guy Benyei11169dd2012-12-18 14:30:41 +00004438
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00004439 SmallVector<llvm::Metadata *, 16> fields;
Scott Linder58df0e42018-08-08 15:56:12 +00004440 collectDefaultFieldsForBlockLiteralDeclare(block, C, loc, *blockLayout, tunit,
4441 fields);
Guy Benyei11169dd2012-12-18 14:30:41 +00004442
4443 // We want to sort the captures by offset, not because DWARF
4444 // requires this, but because we're paranoid about debuggers.
4445 SmallVector<BlockLayoutChunk, 8> chunks;
4446
4447 // 'this' capture.
4448 if (blockDecl->capturesCXXThis()) {
4449 BlockLayoutChunk chunk;
4450 chunk.OffsetInBits =
Eric Christophere7b87e52014-10-26 23:40:33 +00004451 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
Craig Topper8a13c412014-05-21 05:09:00 +00004452 chunk.Capture = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004453 chunks.push_back(chunk);
4454 }
4455
4456 // Variable captures.
Aaron Ballman9371dd22014-03-14 18:34:04 +00004457 for (const auto &capture : blockDecl->captures()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004458 const VarDecl *variable = capture.getVariable();
4459 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
4460
4461 // Ignore constant captures.
4462 if (captureInfo.isConstant())
4463 continue;
4464
4465 BlockLayoutChunk chunk;
4466 chunk.OffsetInBits =
Eric Christophere7b87e52014-10-26 23:40:33 +00004467 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
Guy Benyei11169dd2012-12-18 14:30:41 +00004468 chunk.Capture = &capture;
4469 chunks.push_back(chunk);
4470 }
4471
4472 // Sort by offset.
4473 llvm::array_pod_sort(chunks.begin(), chunks.end());
4474
David Majnemer58ed0f32016-07-17 00:39:12 +00004475 for (const BlockLayoutChunk &Chunk : chunks) {
4476 uint64_t offsetInBits = Chunk.OffsetInBits;
4477 const BlockDecl::Capture *capture = Chunk.Capture;
Guy Benyei11169dd2012-12-18 14:30:41 +00004478
4479 // If we have a null capture, this must be the C++ 'this' capture.
4480 if (!capture) {
Adrian Prantl2526fca2016-04-18 23:48:16 +00004481 QualType type;
4482 if (auto *Method =
4483 cast_or_null<CXXMethodDecl>(blockDecl->getNonClosureContext()))
Brian Gesiak5488ab42019-01-11 01:54:53 +00004484 type = Method->getThisType();
Adrian Prantl2526fca2016-04-18 23:48:16 +00004485 else if (auto *RDecl = dyn_cast<CXXRecordDecl>(blockDecl->getParent()))
4486 type = QualType(RDecl->getTypeForDecl(), 0);
4487 else
4488 llvm_unreachable("unexpected block declcontext");
Guy Benyei11169dd2012-12-18 14:30:41 +00004489
David Majnemerb4b671e2016-06-30 03:01:59 +00004490 fields.push_back(createFieldType("this", type, loc, AS_public,
Guy Benyei11169dd2012-12-18 14:30:41 +00004491 offsetInBits, tunit, tunit));
4492 continue;
4493 }
4494
4495 const VarDecl *variable = capture->getVariable();
4496 StringRef name = variable->getName();
4497
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004498 llvm::DIType *fieldType;
Guy Benyei11169dd2012-12-18 14:30:41 +00004499 if (capture->isByRef()) {
David Majnemer34b57492014-07-30 01:30:47 +00004500 TypeInfo PtrInfo = C.getTypeInfo(C.VoidPtrTy);
Victor Leschuka7ece032016-10-20 00:13:19 +00004501 auto Align = PtrInfo.AlignIsRequired ? PtrInfo.Align : 0;
Adrian Prantl05a623e2018-09-10 16:14:28 +00004502 // FIXME: This recomputes the layout of the BlockByRefWrapper.
Guy Benyei11169dd2012-12-18 14:30:41 +00004503 uint64_t xoffset;
Adrian Prantl05a623e2018-09-10 16:14:28 +00004504 fieldType =
4505 EmitTypeForVarWithBlocksAttr(variable, &xoffset).BlockByRefWrapper;
David Majnemer34b57492014-07-30 01:30:47 +00004506 fieldType = DBuilder.createPointerType(fieldType, PtrInfo.Width);
Victor Leschuka7ece032016-10-20 00:13:19 +00004507 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
4508 PtrInfo.Width, Align, offsetInBits,
4509 llvm::DINode::FlagZero, fieldType);
Guy Benyei11169dd2012-12-18 14:30:41 +00004510 } else {
Victor Leschuka7ece032016-10-20 00:13:19 +00004511 auto Align = getDeclAlignIfRequired(variable, CGM.getContext());
David Majnemerb4b671e2016-06-30 03:01:59 +00004512 fieldType = createFieldType(name, variable->getType(), loc, AS_public,
Victor Leschuka7ece032016-10-20 00:13:19 +00004513 offsetInBits, Align, tunit, tunit);
Guy Benyei11169dd2012-12-18 14:30:41 +00004514 }
4515 fields.push_back(fieldType);
4516 }
4517
4518 SmallString<36> typeName;
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004519 llvm::raw_svector_ostream(typeName)
4520 << "__block_literal_" << CGM.getUniqueBlockCount();
Guy Benyei11169dd2012-12-18 14:30:41 +00004521
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004522 llvm::DINodeArray fieldsArray = DBuilder.getOrCreateArray(fields);
Guy Benyei11169dd2012-12-18 14:30:41 +00004523
Leny Kholodovdf050fd2016-09-06 17:06:14 +00004524 llvm::DIType *type =
4525 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
Victor Leschuka7ece032016-10-20 00:13:19 +00004526 CGM.getContext().toBits(block.BlockSize), 0,
Leny Kholodovdf050fd2016-09-06 17:06:14 +00004527 llvm::DINode::FlagZero, nullptr, fieldsArray);
Guy Benyei11169dd2012-12-18 14:30:41 +00004528 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
4529
4530 // Get overall information about the block.
Leny Kholodov80c047d2016-09-06 10:48:04 +00004531 llvm::DINode::DIFlags flags = llvm::DINode::FlagArtificial;
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004532 auto *scope = cast<llvm::DILocalScope>(LexicalBlockStack.back());
Guy Benyei11169dd2012-12-18 14:30:41 +00004533
4534 // Create the descriptor for the parameter.
Duncan P. N. Exon Smithe4306542015-07-31 17:56:14 +00004535 auto *debugVar = DBuilder.createParameterVariable(
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004536 scope, Name, ArgNo, tunit, line, type, CGM.getLangOpts().Optimize, flags);
Adrian Prantl51936dd2013-03-14 17:53:33 +00004537
Adrian Prantl616bef42013-03-14 21:52:59 +00004538 // Insert an llvm.dbg.declare into the current block.
Adrian Prantl356347b2017-10-26 20:08:52 +00004539 DBuilder.insertDeclare(Alloca, debugVar, DBuilder.createExpression(),
Adrian Prantlb7acfc02017-02-27 21:30:05 +00004540 llvm::DebugLoc::get(line, column, scope, CurInlinedAt),
Duncan P. N. Exon Smithfe88b482015-04-15 21:18:30 +00004541 Builder.GetInsertBlock());
Guy Benyei11169dd2012-12-18 14:30:41 +00004542}
4543
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004544llvm::DIDerivedType *
David Blaikie6943dea2013-08-20 01:28:15 +00004545CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) {
Amy Huangdd3a9ca2019-05-30 22:04:11 +00004546 if (!D || !D->isStaticDataMember())
Duncan P. N. Exon Smithc09c5482015-04-20 21:17:26 +00004547 return nullptr;
Saleem Abdulrasoolcd187f02015-02-28 00:13:13 +00004548
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00004549 auto MI = StaticDataMemberCache.find(D->getCanonicalDecl());
David Blaikie6943dea2013-08-20 01:28:15 +00004550 if (MI != StaticDataMemberCache.end()) {
4551 assert(MI->second && "Static data member declaration should still exist");
Duncan P. N. Exon Smithac346ba2015-07-24 18:05:58 +00004552 return MI->second;
Evgeniy Stepanov37b3f732013-08-16 10:35:31 +00004553 }
David Blaikiece763042013-08-20 21:49:21 +00004554
4555 // If the member wasn't found in the cache, lazily construct and add it to the
4556 // type (used when a limited form of the type is emitted).
Adrian Prantl21361fb2014-08-29 22:44:27 +00004557 auto DC = D->getDeclContext();
Adrian Prantl6ec370a2015-09-10 18:39:45 +00004558 auto *Ctxt = cast<llvm::DICompositeType>(getDeclContextDescriptor(D));
Adrian Prantl21361fb2014-08-29 22:44:27 +00004559 return CreateRecordStaticField(D, Ctxt, cast<RecordDecl>(DC));
David Blaikie6943dea2013-08-20 01:28:15 +00004560}
4561
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004562llvm::DIGlobalVariableExpression *CGDebugInfo::CollectAnonRecordDecls(
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004563 const RecordDecl *RD, llvm::DIFile *Unit, unsigned LineNo,
4564 StringRef LinkageName, llvm::GlobalVariable *Var, llvm::DIScope *DContext) {
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004565 llvm::DIGlobalVariableExpression *GVE = nullptr;
Eric Christophercab9fae2014-04-10 05:20:00 +00004566
4567 for (const auto *Field : RD->fields()) {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004568 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
Eric Christophercab9fae2014-04-10 05:20:00 +00004569 StringRef FieldName = Field->getName();
4570
4571 // Ignore unnamed fields, but recurse into anonymous records.
4572 if (FieldName.empty()) {
David Majnemer58ed0f32016-07-17 00:39:12 +00004573 if (const auto *RT = dyn_cast<RecordType>(Field->getType()))
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004574 GVE = CollectAnonRecordDecls(RT->getDecl(), Unit, LineNo, LinkageName,
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004575 Var, DContext);
Eric Christophercab9fae2014-04-10 05:20:00 +00004576 continue;
4577 }
4578 // Use VarDecl's Tag, Scope and Line number.
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004579 GVE = DBuilder.createGlobalVariableExpression(
4580 DContext, FieldName, LinkageName, Unit, LineNo, FieldTy,
4581 Var->hasLocalLinkage());
4582 Var->addDebugInfo(GVE);
Eric Christophercab9fae2014-04-10 05:20:00 +00004583 }
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004584 return GVE;
Eric Christophercab9fae2014-04-10 05:20:00 +00004585}
4586
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00004587void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
Guy Benyei11169dd2012-12-18 14:30:41 +00004588 const VarDecl *D) {
Amy Huang53539bb2020-01-13 15:54:54 -08004589 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
Paul Robinsonb17327d2016-04-27 17:37:12 +00004590 if (D->hasAttr<NoDebugAttr>())
4591 return;
Adrian Prantl338ef7a2016-11-09 00:42:03 +00004592
Luboš Luňák4f2104c2019-11-02 16:39:59 +01004593 llvm::TimeTraceScope TimeScope("DebugGlobalVariable", [&]() {
4594 std::string Name;
4595 llvm::raw_string_ostream OS(Name);
4596 D->getNameForDiagnostic(OS, getPrintingPolicy(),
4597 /*Qualified=*/true);
4598 return Name;
4599 });
4600
Adrian Prantl338ef7a2016-11-09 00:42:03 +00004601 // If we already created a DIGlobalVariable for this declaration, just attach
4602 // it to the llvm::GlobalVariable.
4603 auto Cached = DeclCache.find(D->getCanonicalDecl());
4604 if (Cached != DeclCache.end())
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004605 return Var->addDebugInfo(
4606 cast<llvm::DIGlobalVariableExpression>(Cached->second));
Adrian Prantl338ef7a2016-11-09 00:42:03 +00004607
Guy Benyei11169dd2012-12-18 14:30:41 +00004608 // Create global variable debug descriptor.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004609 llvm::DIFile *Unit = nullptr;
4610 llvm::DIScope *DContext = nullptr;
Frederic Riss9db79f12014-11-18 03:40:46 +00004611 unsigned LineNo;
4612 StringRef DeclName, LinkageName;
4613 QualType T;
Matthew Voss20165362018-10-03 18:45:04 +00004614 llvm::MDTuple *TemplateParameters = nullptr;
4615 collectVarDeclProps(D, Unit, LineNo, T, DeclName, LinkageName,
4616 TemplateParameters, DContext);
Eric Christophercab9fae2014-04-10 05:20:00 +00004617
4618 // Attempt to store one global variable for the declaration - even if we
4619 // emit a lot of fields.
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004620 llvm::DIGlobalVariableExpression *GVE = nullptr;
Eric Christophercab9fae2014-04-10 05:20:00 +00004621
4622 // If this is an anonymous union then we'll want to emit a global
4623 // variable for each member of the anonymous union so that it's possible
4624 // to find the name of any field in the union.
4625 if (T->isUnionType() && DeclName.empty()) {
Reid Kleckner43ecd7c2015-11-20 17:41:12 +00004626 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
Eric Christophere7b87e52014-10-26 23:40:33 +00004627 assert(RD->isAnonymousStructOrUnion() &&
4628 "unnamed non-anonymous struct or union?");
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004629 GVE = CollectAnonRecordDecls(RD, Unit, LineNo, LinkageName, Var, DContext);
Eric Christophercab9fae2014-04-10 05:20:00 +00004630 } else {
Victor Leschuka7ece032016-10-20 00:13:19 +00004631 auto Align = getDeclAlignIfRequired(D, CGM.getContext());
Konstantin Zhuravlyov2b4917f2017-03-09 18:06:23 +00004632
4633 SmallVector<int64_t, 4> Expr;
4634 unsigned AddressSpace =
4635 CGM.getContext().getTargetAddressSpace(D->getType());
Alexey Bataev1a9e05d2019-02-05 19:45:57 +00004636 if (CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) {
4637 if (D->hasAttr<CUDASharedAttr>())
4638 AddressSpace =
4639 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared);
4640 else if (D->hasAttr<CUDAConstantAttr>())
4641 AddressSpace =
4642 CGM.getContext().getTargetAddressSpace(LangAS::cuda_constant);
4643 }
Konstantin Zhuravlyov2b4917f2017-03-09 18:06:23 +00004644 AppendAddressSpaceXDeref(AddressSpace, Expr);
4645
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004646 GVE = DBuilder.createGlobalVariableExpression(
Eric Christophercab9fae2014-04-10 05:20:00 +00004647 DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),
Yonghong Songe3d8ee32019-11-22 08:45:37 -08004648 Var->hasLocalLinkage(), true,
Konstantin Zhuravlyov2b4917f2017-03-09 18:06:23 +00004649 Expr.empty() ? nullptr : DBuilder.createExpression(Expr),
Matthew Voss20165362018-10-03 18:45:04 +00004650 getOrCreateStaticDataMemberDeclarationOrNull(D), TemplateParameters,
4651 Align);
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004652 Var->addDebugInfo(GVE);
Eric Christophercab9fae2014-04-10 05:20:00 +00004653 }
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004654 DeclCache[D->getCanonicalDecl()].reset(GVE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004655}
4656
Peter Collingbourneeeb56ab2016-09-13 01:13:19 +00004657void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD, const APValue &Init) {
Amy Huang53539bb2020-01-13 15:54:54 -08004658 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
Paul Robinsonb17327d2016-04-27 17:37:12 +00004659 if (VD->hasAttr<NoDebugAttr>())
4660 return;
Luboš Luňák4f2104c2019-11-02 16:39:59 +01004661 llvm::TimeTraceScope TimeScope("DebugConstGlobalVariable", [&]() {
4662 std::string Name;
4663 llvm::raw_string_ostream OS(Name);
4664 VD->getNameForDiagnostic(OS, getPrintingPolicy(),
4665 /*Qualified=*/true);
4666 return Name;
4667 });
4668
Victor Leschuka7ece032016-10-20 00:13:19 +00004669 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00004670 // Create the descriptor for the variable.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004671 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00004672 StringRef Name = VD->getName();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004673 llvm::DIType *Ty = getOrCreateType(VD->getType(), Unit);
Amy Huang63305c82019-05-22 15:48:59 +00004674
David Majnemer58ed0f32016-07-17 00:39:12 +00004675 if (const auto *ECD = dyn_cast<EnumConstantDecl>(VD)) {
4676 const auto *ED = cast<EnumDecl>(ECD->getDeclContext());
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00004677 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
Amy Huangdd3a9ca2019-05-30 22:04:11 +00004678
Yuanfang Chen48c6fad2019-09-04 20:58:15 +00004679 if (CGM.getCodeGenOpts().EmitCodeView) {
4680 // If CodeView, emit enums as global variables, unless they are defined
4681 // inside a class. We do this because MSVC doesn't emit S_CONSTANTs for
4682 // enums in classes, and because it is difficult to attach this scope
4683 // information to the global variable.
4684 if (isa<RecordDecl>(ED->getDeclContext()))
4685 return;
4686 } else {
4687 // If not CodeView, emit DW_TAG_enumeration_type if necessary. For
4688 // example: for "enum { ZERO };", a DW_TAG_enumeration_type is created the
4689 // first time `ZERO` is referenced in a function.
4690 llvm::DIType *EDTy =
4691 getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
4692 assert (EDTy->getTag() == llvm::dwarf::DW_TAG_enumeration_type);
4693 (void)EDTy;
Amy Huangdd3a9ca2019-05-30 22:04:11 +00004694 return;
Yuanfang Chen48c6fad2019-09-04 20:58:15 +00004695 }
Amy Huang63305c82019-05-22 15:48:59 +00004696 }
4697
Amy Huang325003b2019-05-29 21:45:34 +00004698 llvm::DIScope *DContext = nullptr;
4699
4700 // Do not emit separate definitions for function local consts.
David Blaikiea15565562014-04-04 20:56:17 +00004701 if (isa<FunctionDecl>(VD->getDeclContext()))
4702 return;
Amy Huang325003b2019-05-29 21:45:34 +00004703
4704 // Emit definition for static members in CodeView.
David Blaikiebb113912014-04-05 07:23:17 +00004705 VD = cast<ValueDecl>(VD->getCanonicalDecl());
Amy Huangdd3a9ca2019-05-30 22:04:11 +00004706 auto *VarD = dyn_cast<VarDecl>(VD);
4707 if (VarD && VarD->isStaticDataMember()) {
David Blaikieaf080852014-11-21 00:20:58 +00004708 auto *RD = cast<RecordDecl>(VarD->getDeclContext());
Adrian Prantl6ec370a2015-09-10 18:39:45 +00004709 getDeclContextDescriptor(VarD);
David Blaikie423eb5a2014-11-19 19:42:40 +00004710 // Ensure that the type is retained even though it's otherwise unreferenced.
Duncan P. N. Exon Smith383f8412016-04-23 21:08:27 +00004711 //
4712 // FIXME: This is probably unnecessary, since Ty should reference RD
4713 // through its scope.
David Blaikie423eb5a2014-11-19 19:42:40 +00004714 RetainedTypes.push_back(
David Blaikieaf080852014-11-21 00:20:58 +00004715 CGM.getContext().getRecordType(RD).getAsOpaquePtr());
David Blaikie423eb5a2014-11-19 19:42:40 +00004716
Amy Huang325003b2019-05-29 21:45:34 +00004717 if (!CGM.getCodeGenOpts().EmitCodeView)
4718 return;
4719
4720 // Use the global scope for static members.
4721 DContext = getContextDescriptor(
4722 cast<Decl>(CGM.getContext().getTranslationUnitDecl()), TheCU);
4723 } else {
4724 DContext = getDeclContextDescriptor(VD);
4725 }
David Blaikieaf080852014-11-21 00:20:58 +00004726
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00004727 auto &GV = DeclCache[VD];
4728 if (GV)
David Blaikiebb113912014-04-05 07:23:17 +00004729 return;
Peter Collingbourneeeb56ab2016-09-13 01:13:19 +00004730 llvm::DIExpression *InitExpr = nullptr;
Peter Collingbourneb7013632016-12-16 22:10:52 +00004731 if (CGM.getContext().getTypeSize(VD->getType()) <= 64) {
4732 // FIXME: Add a representation for integer constants wider than 64 bits.
4733 if (Init.isInt())
4734 InitExpr =
4735 DBuilder.createConstantValueExpression(Init.getInt().getExtValue());
4736 else if (Init.isFloat())
4737 InitExpr = DBuilder.createConstantValueExpression(
4738 Init.getFloat().bitcastToAPInt().getZExtValue());
4739 }
Matthew Voss20165362018-10-03 18:45:04 +00004740
4741 llvm::MDTuple *TemplateParameters = nullptr;
4742
4743 if (isa<VarTemplateSpecializationDecl>(VD))
4744 if (VarD) {
4745 llvm::DINodeArray parameterNodes = CollectVarTemplateParams(VarD, &*Unit);
4746 TemplateParameters = parameterNodes.get();
4747 }
4748
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004749 GV.reset(DBuilder.createGlobalVariableExpression(
David Blaikie506a7452014-04-05 07:46:57 +00004750 DContext, Name, StringRef(), Unit, getLineNumber(VD->getLocation()), Ty,
Yonghong Songe3d8ee32019-11-22 08:45:37 -08004751 true, true, InitExpr, getOrCreateStaticDataMemberDeclarationOrNull(VarD),
Matthew Voss20165362018-10-03 18:45:04 +00004752 TemplateParameters, Align));
David Blaikiebd483762013-05-20 04:58:53 +00004753}
4754
Yonghong Songe3d8ee32019-11-22 08:45:37 -08004755void CGDebugInfo::EmitExternalVariable(llvm::GlobalVariable *Var,
4756 const VarDecl *D) {
Amy Huang53539bb2020-01-13 15:54:54 -08004757 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
Yonghong Songe3d8ee32019-11-22 08:45:37 -08004758 if (D->hasAttr<NoDebugAttr>())
4759 return;
4760
4761 auto Align = getDeclAlignIfRequired(D, CGM.getContext());
4762 llvm::DIFile *Unit = getOrCreateFile(D->getLocation());
4763 StringRef Name = D->getName();
4764 llvm::DIType *Ty = getOrCreateType(D->getType(), Unit);
4765
4766 llvm::DIScope *DContext = getDeclContextDescriptor(D);
4767 llvm::DIGlobalVariableExpression *GVE =
4768 DBuilder.createGlobalVariableExpression(
4769 DContext, Name, StringRef(), Unit, getLineNumber(D->getLocation()),
4770 Ty, false, false, nullptr, nullptr, nullptr, Align);
4771 Var->addDebugInfo(GVE);
4772}
4773
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004774llvm::DIScope *CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
David Blaikiebd483762013-05-20 04:58:53 +00004775 if (!LexicalBlockStack.empty())
Duncan P. N. Exon Smithfc8d9d92015-04-20 18:32:15 +00004776 return LexicalBlockStack.back();
Adrian Prantl5c8bd882015-09-11 17:23:08 +00004777 llvm::DIScope *Mod = getParentModuleOrNull(D);
4778 return getContextDescriptor(D, Mod ? Mod : TheCU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004779}
4780
David Blaikie9f88fe82013-04-22 06:13:21 +00004781void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
Amy Huang53539bb2020-01-13 15:54:54 -08004782 if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
David Blaikiebd483762013-05-20 04:58:53 +00004783 return;
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +00004784 const NamespaceDecl *NSDecl = UD.getNominatedNamespace();
Adrian McCarthyab1e7862016-07-21 18:43:20 +00004785 if (!NSDecl->isAnonymousNamespace() ||
4786 CGM.getCodeGenOpts().DebugExplicitImport) {
Adrian Prantl5649b0e2017-07-19 00:09:58 +00004787 auto Loc = UD.getLocation();
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +00004788 DBuilder.createImportedModule(
4789 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
Adrian Prantl5649b0e2017-07-19 00:09:58 +00004790 getOrCreateNamespace(NSDecl), getOrCreateFile(Loc), getLineNumber(Loc));
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +00004791 }
David Blaikie9f88fe82013-04-22 06:13:21 +00004792}
4793
David Blaikiebd483762013-05-20 04:58:53 +00004794void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
Amy Huang53539bb2020-01-13 15:54:54 -08004795 if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
David Blaikiebd483762013-05-20 04:58:53 +00004796 return;
4797 assert(UD.shadow_size() &&
4798 "We shouldn't be codegening an invalid UsingDecl containing no decls");
4799 // Emitting one decl is sufficient - debuggers can detect that this is an
4800 // overloaded name & provide lookup for all the overloads.
4801 const UsingShadowDecl &USD = **UD.shadow_begin();
David Blaikie2a58a182016-08-05 19:03:01 +00004802
4803 // FIXME: Skip functions with undeduced auto return type for now since we
4804 // don't currently have the plumbing for separate declarations & definitions
4805 // of free functions and mismatched types (auto in the declaration, concrete
4806 // return type in the definition)
4807 if (const auto *FD = dyn_cast<FunctionDecl>(USD.getUnderlyingDecl()))
4808 if (const auto *AT =
Simon Pilgrim7e38f0c2019-10-07 16:42:25 +00004809 FD->getType()->castAs<FunctionProtoType>()->getContainedAutoType())
David Blaikie2a58a182016-08-05 19:03:01 +00004810 if (AT->getDeducedType().isNull())
4811 return;
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004812 if (llvm::DINode *Target =
Adrian Prantl5649b0e2017-07-19 00:09:58 +00004813 getDeclarationOrDefinition(USD.getUnderlyingDecl())) {
4814 auto Loc = USD.getLocation();
David Blaikiebd483762013-05-20 04:58:53 +00004815 DBuilder.createImportedDeclaration(
4816 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
Adrian Prantl5649b0e2017-07-19 00:09:58 +00004817 getOrCreateFile(Loc), getLineNumber(Loc));
4818 }
David Blaikiebd483762013-05-20 04:58:53 +00004819}
4820
Adrian Prantlc4bb47e2015-06-30 17:39:51 +00004821void CGDebugInfo::EmitImportDecl(const ImportDecl &ID) {
David Blaikieaf09f4a2016-05-03 23:06:40 +00004822 if (CGM.getCodeGenOpts().getDebuggerTuning() != llvm::DebuggerKind::LLDB)
4823 return;
Adrian Prantl8a634c12015-12-18 19:44:31 +00004824 if (Module *M = ID.getImportedModule()) {
Reid Klecknerc915cb92020-02-27 18:13:54 -08004825 auto Info = ASTSourceDescriptor(*M);
Adrian Prantl5649b0e2017-07-19 00:09:58 +00004826 auto Loc = ID.getLocation();
Adrian Prantl8a634c12015-12-18 19:44:31 +00004827 DBuilder.createImportedDeclaration(
4828 getCurrentContextDescriptor(cast<Decl>(ID.getDeclContext())),
Adrian Prantl5649b0e2017-07-19 00:09:58 +00004829 getOrCreateModuleRef(Info, DebugTypeExtRefs), getOrCreateFile(Loc),
4830 getLineNumber(Loc));
Adrian Prantl8a634c12015-12-18 19:44:31 +00004831 }
Adrian Prantlc4bb47e2015-06-30 17:39:51 +00004832}
4833
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004834llvm::DIImportedEntity *
David Blaikief121b932013-05-20 22:50:41 +00004835CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
Amy Huang53539bb2020-01-13 15:54:54 -08004836 if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
Duncan P. N. Exon Smithdadc2b62015-04-21 18:43:54 +00004837 return nullptr;
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00004838 auto &VH = NamespaceAliasCache[&NA];
David Blaikief121b932013-05-20 22:50:41 +00004839 if (VH)
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004840 return cast<llvm::DIImportedEntity>(VH);
4841 llvm::DIImportedEntity *R;
Adrian Prantl5649b0e2017-07-19 00:09:58 +00004842 auto Loc = NA.getLocation();
David Majnemer58ed0f32016-07-17 00:39:12 +00004843 if (const auto *Underlying =
David Blaikief121b932013-05-20 22:50:41 +00004844 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
4845 // This could cache & dedup here rather than relying on metadata deduping.
David Blaikie551fb0a2014-04-06 06:30:03 +00004846 R = DBuilder.createImportedDeclaration(
David Blaikief121b932013-05-20 22:50:41 +00004847 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
Adrian Prantl5649b0e2017-07-19 00:09:58 +00004848 EmitNamespaceAlias(*Underlying), getOrCreateFile(Loc),
4849 getLineNumber(Loc), NA.getName());
David Blaikief121b932013-05-20 22:50:41 +00004850 else
David Blaikie551fb0a2014-04-06 06:30:03 +00004851 R = DBuilder.createImportedDeclaration(
David Blaikief121b932013-05-20 22:50:41 +00004852 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
Adrian Prantlddb8e062017-05-12 16:23:53 +00004853 getOrCreateNamespace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
Adrian Prantl5649b0e2017-07-19 00:09:58 +00004854 getOrCreateFile(Loc), getLineNumber(Loc), NA.getName());
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00004855 VH.reset(R);
David Blaikief121b932013-05-20 22:50:41 +00004856 return R;
4857}
4858
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004859llvm::DINamespace *
Adrian Prantlddb8e062017-05-12 16:23:53 +00004860CGDebugInfo::getOrCreateNamespace(const NamespaceDecl *NSDecl) {
4861 // Don't canonicalize the NamespaceDecl here: The DINamespace will be uniqued
4862 // if necessary, and this way multiple declarations of the same namespace in
4863 // different parent modules stay distinct.
4864 auto I = NamespaceCache.find(NSDecl);
Adrian Prantld8870552017-05-11 22:59:19 +00004865 if (I != NamespaceCache.end())
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004866 return cast<llvm::DINamespace>(I->second);
Eric Christopherb2a008c2013-05-16 00:45:12 +00004867
Adrian Prantl6ec370a2015-09-10 18:39:45 +00004868 llvm::DIScope *Context = getDeclContextDescriptor(NSDecl);
Adrian Prantld8870552017-05-11 22:59:19 +00004869 // Don't trust the context if it is a DIModule (see comment above).
Adrian Prantlddb8e062017-05-12 16:23:53 +00004870 llvm::DINamespace *NS =
4871 DBuilder.createNameSpace(Context, NSDecl->getName(), NSDecl->isInline());
4872 NamespaceCache[NSDecl].reset(NS);
Guy Benyei11169dd2012-12-18 14:30:41 +00004873 return NS;
4874}
4875
Adrian Prantla5206ce2015-09-22 23:26:43 +00004876void CGDebugInfo::setDwoId(uint64_t Signature) {
4877 assert(TheCU && "no main compile unit");
4878 TheCU->setDWOId(Signature);
4879}
4880
Guy Benyei11169dd2012-12-18 14:30:41 +00004881void CGDebugInfo::finalize() {
David Blaikie87dab872014-05-07 16:56:58 +00004882 // Creating types might create further types - invalidating the current
4883 // element and the size(), so don't cache/reference them.
4884 for (size_t i = 0; i != ObjCInterfaceCache.size(); ++i) {
4885 ObjCInterfaceCacheEntry E = ObjCInterfaceCache[i];
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004886 llvm::DIType *Ty = E.Type->getDecl()->getDefinition()
Duncan P. N. Exon Smith497d4d462015-04-11 19:05:04 +00004887 ? CreateTypeDefinition(E.Type, E.Unit)
4888 : E.Decl;
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004889 DBuilder.replaceTemporary(llvm::TempDIType(E.Decl), Ty);
David Blaikie87dab872014-05-07 16:56:58 +00004890 }
4891
Adrian Prantle0cabe22019-11-21 09:56:01 -08004892 // Add methods to interface.
4893 for (const auto &P : ObjCMethodCache) {
4894 if (P.second.empty())
4895 continue;
Jonas Devlieghered8ba8ae2018-06-27 17:31:59 +00004896
Adrian Prantle0cabe22019-11-21 09:56:01 -08004897 QualType QTy(P.first->getTypeForDecl(), 0);
4898 auto It = TypeCache.find(QTy.getAsOpaquePtr());
4899 assert(It != TypeCache.end());
Jonas Devlieghered8ba8ae2018-06-27 17:31:59 +00004900
Adrian Prantle0cabe22019-11-21 09:56:01 -08004901 llvm::DICompositeType *InterfaceDecl =
4902 cast<llvm::DICompositeType>(It->second);
Jonas Devlieghered8ba8ae2018-06-27 17:31:59 +00004903
Adrian Prantle0cabe22019-11-21 09:56:01 -08004904 auto CurElts = InterfaceDecl->getElements();
4905 SmallVector<llvm::Metadata *, 16> EltTys(CurElts.begin(), CurElts.end());
4906
4907 // For DWARF v4 or earlier, only add objc_direct methods.
4908 for (auto &SubprogramDirect : P.second)
4909 if (CGM.getCodeGenOpts().DwarfVersion >= 5 || SubprogramDirect.getInt())
4910 EltTys.push_back(SubprogramDirect.getPointer());
4911
4912 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
4913 DBuilder.replaceArrays(InterfaceDecl, Elements);
Jonas Devlieghered8ba8ae2018-06-27 17:31:59 +00004914 }
4915
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004916 for (const auto &P : ReplaceMap) {
4917 assert(P.second);
4918 auto *Ty = cast<llvm::DIType>(P.second);
Duncan P. N. Exon Smith4caa7f22015-04-16 01:00:56 +00004919 assert(Ty->isForwardDecl());
Eric Christopherb2a008c2013-05-16 00:45:12 +00004920
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004921 auto It = TypeCache.find(P.first);
4922 assert(It != TypeCache.end());
4923 assert(It->second);
Adrian Prantl73409ce2013-03-11 18:33:46 +00004924
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004925 DBuilder.replaceTemporary(llvm::TempDIType(Ty),
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004926 cast<llvm::DIType>(It->second));
Guy Benyei11169dd2012-12-18 14:30:41 +00004927 }
Adrian Prantl73409ce2013-03-11 18:33:46 +00004928
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004929 for (const auto &P : FwdDeclReplaceMap) {
4930 assert(P.second);
4931 llvm::TempMDNode FwdDecl(cast<llvm::MDNode>(P.second));
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00004932 llvm::Metadata *Repl;
Frederic Rissd253ed62014-11-18 03:40:51 +00004933
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004934 auto It = DeclCache.find(P.first);
Adrian Prantl97f76852014-12-19 01:02:11 +00004935 // If there has been no definition for the declaration, call RAUW
Frederic Rissd253ed62014-11-18 03:40:51 +00004936 // with ourselves, that will destroy the temporary MDNode and
4937 // replace it with a standard one, avoiding leaking memory.
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004938 if (It == DeclCache.end())
4939 Repl = P.second;
Frederic Rissd253ed62014-11-18 03:40:51 +00004940 else
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004941 Repl = It->second;
Frederic Rissdce60a72014-11-19 18:53:46 +00004942
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004943 if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(Repl))
4944 Repl = GVE->getVariable();
Duncan P. N. Exon Smithd899f6e2015-04-18 00:07:30 +00004945 DBuilder.replaceTemporary(std::move(FwdDecl), cast<llvm::MDNode>(Repl));
Frederic Rissd253ed62014-11-18 03:40:51 +00004946 }
4947
Adrian Prantl73409ce2013-03-11 18:33:46 +00004948 // We keep our own list of retained types, because we need to look
4949 // up the final type in the type cache.
Adrian Prantl3a884fa2015-08-27 22:56:46 +00004950 for (auto &RT : RetainedTypes)
Adrian Prantlad9a195e2015-08-27 21:21:19 +00004951 if (auto MD = TypeCache[RT])
4952 DBuilder.retainType(cast<llvm::DIType>(MD));
Adrian Prantl73409ce2013-03-11 18:33:46 +00004953
Guy Benyei11169dd2012-12-18 14:30:41 +00004954 DBuilder.finalize();
4955}
David Blaikie66088d52014-09-24 17:01:27 +00004956
4957void CGDebugInfo::EmitExplicitCastType(QualType Ty) {
Amy Huang53539bb2020-01-13 15:54:54 -08004958 if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
David Blaikie66088d52014-09-24 17:01:27 +00004959 return;
Duncan P. N. Exon Smith5043f912015-03-27 22:58:05 +00004960
Adrian Prantlc2a44ec2018-12-11 16:58:46 +00004961 if (auto *DieTy = getOrCreateType(Ty, TheCU->getFile()))
Duncan P. N. Exon Smith5043f912015-03-27 22:58:05 +00004962 // Don't ignore in case of explicit cast where it is referenced indirectly.
4963 DBuilder.retainType(DieTy);
David Blaikie66088d52014-09-24 17:01:27 +00004964}
Amara Emerson652795d2016-11-10 14:44:30 +00004965
4966llvm::DebugLoc CGDebugInfo::SourceLocToDebugLoc(SourceLocation Loc) {
4967 if (LexicalBlockStack.empty())
4968 return llvm::DebugLoc();
4969
4970 llvm::MDNode *Scope = LexicalBlockStack.back();
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004971 return llvm::DebugLoc::get(getLineNumber(Loc), getColumnNumber(Loc), Scope);
Amara Emerson652795d2016-11-10 14:44:30 +00004972}
Vedant Kumar5931b4e2018-10-05 20:37:17 +00004973
4974llvm::DINode::DIFlags CGDebugInfo::getCallSiteRelatedAttrs() const {
4975 // Call site-related attributes are only useful in optimized programs, and
4976 // when there's a possibility of debugging backtraces.
4977 if (!CGM.getLangOpts().Optimize || DebugKind == codegenoptions::NoDebugInfo ||
4978 DebugKind == codegenoptions::LocTrackingOnly)
4979 return llvm::DINode::FlagZero;
4980
4981 // Call site-related attributes are available in DWARF v5. Some debuggers,
4982 // while not fully DWARF v5-compliant, may accept these attributes as if they
4983 // were part of DWARF v4.
4984 bool SupportsDWARFv4Ext =
4985 CGM.getCodeGenOpts().DwarfVersion == 4 &&
Djordje Todorovic639d36b2019-06-26 09:38:09 +00004986 (CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB ||
Vedant Kumar568db782019-11-13 18:19:32 -08004987 CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::GDB);
Djordje Todorovic639d36b2019-06-26 09:38:09 +00004988
Djordje Todorovicd9b96212020-03-19 12:13:18 +01004989 if (!SupportsDWARFv4Ext && CGM.getCodeGenOpts().DwarfVersion < 5)
Vedant Kumar5931b4e2018-10-05 20:37:17 +00004990 return llvm::DINode::FlagZero;
4991
4992 return llvm::DINode::FlagAllCallsDescribed;
4993}