blob: 74c079b0bd098d2a02bfb125742dd947bc63c303 [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
234 // like basic_string and vector.
235 if (CGM.getCodeGenOpts().EmitCodeView)
236 PP.MSVCFormatting = true;
237
Adrian Prantl56acd5a2018-12-05 18:37:44 +0000238 // Apply -fdebug-prefix-map.
Richard Smithdbcb6902019-10-15 17:51:08 -0700239 PP.Callbacks = &PrintCB;
Reid Kleckner59d12202017-08-08 01:33:53 +0000240 return PP;
241}
242
Guy Benyei11169dd2012-12-18 14:30:41 +0000243StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
Eric Christophere7b87e52014-10-26 23:40:33 +0000244 assert(FD && "Invalid FunctionDecl!");
Guy Benyei11169dd2012-12-18 14:30:41 +0000245 IdentifierInfo *FII = FD->getIdentifier();
Eric Christophere7b87e52014-10-26 23:40:33 +0000246 FunctionTemplateSpecializationInfo *Info =
247 FD->getTemplateSpecializationInfo();
Reid Kleckner60103382015-12-16 02:04:40 +0000248
Reid Kleckner31abd802016-06-30 17:41:31 +0000249 // Emit the unqualified name in normal operation. LLVM and the debugger can
250 // compute the fully qualified name from the scope chain. If we're only
251 // emitting line table info, there won't be any scope chains, so emit the
252 // fully qualified name here so that stack traces are more accurate.
253 // FIXME: Do this when emitting DWARF as well as when emitting CodeView after
254 // evaluating the size impact.
255 bool UseQualifiedName = DebugKind == codegenoptions::DebugLineTablesOnly &&
256 CGM.getCodeGenOpts().EmitCodeView;
257
258 if (!Info && FII && !UseQualifiedName)
Guy Benyei11169dd2012-12-18 14:30:41 +0000259 return FII->getName();
260
Benjamin Kramer9170e912013-02-22 15:46:01 +0000261 SmallString<128> NS;
262 llvm::raw_svector_ostream OS(NS);
Reid Kleckner31abd802016-06-30 17:41:31 +0000263 if (!UseQualifiedName)
264 FD->printName(OS);
265 else
Reid Kleckner59d12202017-08-08 01:33:53 +0000266 FD->printQualifiedName(OS, getPrintingPolicy());
Guy Benyei11169dd2012-12-18 14:30:41 +0000267
Reid Kleckner829398e2016-06-17 16:11:20 +0000268 // Add any template specialization args.
269 if (Info) {
270 const TemplateArgumentList *TArgs = Info->TemplateArguments;
Serge Pavlov03e672c2017-11-28 16:14:14 +0000271 printTemplateArgumentList(OS, TArgs->asArray(), getPrintingPolicy());
Guy Benyei11169dd2012-12-18 14:30:41 +0000272 }
273
274 // Copy this name on the side and use its reference.
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +0000275 return internString(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +0000276}
277
278StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
279 SmallString<256> MethodName;
280 llvm::raw_svector_ostream OS(MethodName);
281 OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
282 const DeclContext *DC = OMD->getDeclContext();
David Majnemer58ed0f32016-07-17 00:39:12 +0000283 if (const auto *OID = dyn_cast<ObjCImplementationDecl>(DC)) {
Eric Christophere7b87e52014-10-26 23:40:33 +0000284 OS << OID->getName();
David Majnemer58ed0f32016-07-17 00:39:12 +0000285 } else if (const auto *OID = dyn_cast<ObjCInterfaceDecl>(DC)) {
Eric Christophere7b87e52014-10-26 23:40:33 +0000286 OS << OID->getName();
David Majnemer58ed0f32016-07-17 00:39:12 +0000287 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(DC)) {
Douglas Gregoracf4fd32015-11-03 01:15:46 +0000288 if (OC->IsClassExtension()) {
289 OS << OC->getClassInterface()->getName();
290 } else {
David Majnemer58ed0f32016-07-17 00:39:12 +0000291 OS << OC->getIdentifier()->getNameStart() << '('
Douglas Gregoracf4fd32015-11-03 01:15:46 +0000292 << OC->getIdentifier()->getNameStart() << ')';
293 }
David Majnemer58ed0f32016-07-17 00:39:12 +0000294 } else if (const auto *OCD = dyn_cast<ObjCCategoryImplDecl>(DC)) {
Jonas Devlieghere9ef49652018-06-28 10:56:40 +0000295 OS << OCD->getClassInterface()->getName() << '(' << OCD->getName() << ')';
Guy Benyei11169dd2012-12-18 14:30:41 +0000296 }
297 OS << ' ' << OMD->getSelector().getAsString() << ']';
298
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +0000299 return internString(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +0000300}
301
Guy Benyei11169dd2012-12-18 14:30:41 +0000302StringRef CGDebugInfo::getSelectorName(Selector S) {
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +0000303 return internString(S.getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +0000304}
305
Eric Christophere7b87e52014-10-26 23:40:33 +0000306StringRef CGDebugInfo::getClassName(const RecordDecl *RD) {
David Majnemerbc5976a2016-07-01 23:12:54 +0000307 if (isa<ClassTemplateSpecializationDecl>(RD)) {
308 SmallString<128> Name;
David Blaikie65813a32014-04-02 18:21:09 +0000309 llvm::raw_svector_ostream OS(Name);
David Blaikie9fdd09a2019-10-18 23:58:34 +0000310 PrintingPolicy PP = getPrintingPolicy();
311 PP.PrintCanonicalTypes = true;
312 RD->getNameForDiagnostic(OS, PP,
David Blaikie65813a32014-04-02 18:21:09 +0000313 /*Qualified*/ false);
David Majnemerbc5976a2016-07-01 23:12:54 +0000314
315 // Copy this name on the side and use its reference.
316 return internString(Name);
Benjamin Kramer9170e912013-02-22 15:46:01 +0000317 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000318
David Majnemerbc5976a2016-07-01 23:12:54 +0000319 // quick optimization to avoid having to intern strings that are already
320 // stored reliably elsewhere
321 if (const IdentifierInfo *II = RD->getIdentifier())
322 return II->getName();
323
324 // The CodeView printer in LLVM wants to see the names of unnamed types: it is
325 // used to reconstruct the fully qualified type names.
326 if (CGM.getCodeGenOpts().EmitCodeView) {
327 if (const TypedefNameDecl *D = RD->getTypedefNameForAnonDecl()) {
328 assert(RD->getDeclContext() == D->getDeclContext() &&
329 "Typedef should not be in another decl context!");
330 assert(D->getDeclName().getAsIdentifierInfo() &&
331 "Typedef was not named!");
332 return D->getDeclName().getAsIdentifierInfo()->getName();
333 }
334
335 if (CGM.getLangOpts().CPlusPlus) {
336 StringRef Name;
337
338 ASTContext &Context = CGM.getContext();
339 if (const DeclaratorDecl *DD = Context.getDeclaratorForUnnamedTagDecl(RD))
340 // Anonymous types without a name for linkage purposes have their
341 // declarator mangled in if they have one.
342 Name = DD->getName();
343 else if (const TypedefNameDecl *TND =
344 Context.getTypedefNameForUnnamedTagDecl(RD))
345 // Anonymous types without a name for linkage purposes have their
346 // associate typedef mangled in if they have one.
347 Name = TND->getName();
348
349 if (!Name.empty()) {
350 SmallString<256> UnnamedType("<unnamed-type-");
351 UnnamedType += Name;
352 UnnamedType += '>';
353 return internString(UnnamedType);
354 }
355 }
356 }
357
358 return StringRef();
Guy Benyei11169dd2012-12-18 14:30:41 +0000359}
360
Scott Linder94834f12018-02-12 19:47:05 +0000361Optional<llvm::DIFile::ChecksumKind>
Amjad Aboude2aab8c2016-12-25 10:12:27 +0000362CGDebugInfo::computeChecksum(FileID FID, SmallString<32> &Checksum) const {
363 Checksum.clear();
364
Paul Robinson76178632018-05-25 22:35:59 +0000365 if (!CGM.getCodeGenOpts().EmitCodeView &&
366 CGM.getCodeGenOpts().DwarfVersion < 5)
Scott Linder94834f12018-02-12 19:47:05 +0000367 return None;
Amjad Aboude2aab8c2016-12-25 10:12:27 +0000368
369 SourceManager &SM = CGM.getContext().getSourceManager();
370 bool Invalid;
Nico Weber04347d82019-04-04 21:06:41 +0000371 const llvm::MemoryBuffer *MemBuffer = SM.getBuffer(FID, &Invalid);
Paul Robinson76178632018-05-25 22:35:59 +0000372 if (Invalid)
Scott Linder94834f12018-02-12 19:47:05 +0000373 return None;
Amjad Aboude2aab8c2016-12-25 10:12:27 +0000374
375 llvm::MD5 Hash;
376 llvm::MD5::MD5Result Result;
377
378 Hash.update(MemBuffer->getBuffer());
379 Hash.final(Result);
380
381 Hash.stringifyResult(Result, Checksum);
382 return llvm::DIFile::CSK_MD5;
383}
384
Jonas Devlieghere9ef49652018-06-28 10:56:40 +0000385Optional<StringRef> CGDebugInfo::getSource(const SourceManager &SM,
386 FileID FID) {
Scott Lindera2fbcef2018-02-26 17:32:31 +0000387 if (!CGM.getCodeGenOpts().EmbedSource)
388 return None;
389
390 bool SourceInvalid = false;
391 StringRef Source = SM.getBufferData(FID, &SourceInvalid);
392
393 if (SourceInvalid)
394 return None;
395
396 return Source;
397}
398
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +0000399llvm::DIFile *CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000400 if (!Loc.isValid())
401 // If Location is not valid then use main input file.
Adrian Prantlc2a44ec2018-12-11 16:58:46 +0000402 return TheCU->getFile();
Guy Benyei11169dd2012-12-18 14:30:41 +0000403
404 SourceManager &SM = CGM.getContext().getSourceManager();
405 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
406
Adrian Prantl212c1042018-12-06 18:44:50 +0000407 StringRef FileName = PLoc.getFilename();
408 if (PLoc.isInvalid() || FileName.empty())
Guy Benyei11169dd2012-12-18 14:30:41 +0000409 // If the location is not valid then use main input file.
Adrian Prantlc2a44ec2018-12-11 16:58:46 +0000410 return TheCU->getFile();
Guy Benyei11169dd2012-12-18 14:30:41 +0000411
412 // Cache the results.
Adrian Prantl212c1042018-12-06 18:44:50 +0000413 auto It = DIFileCache.find(FileName.data());
Jonas Devlieghere9ef49652018-06-28 10:56:40 +0000414 if (It != DIFileCache.end()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000415 // Verify that the information still exists.
Jonas Devlieghere9ef49652018-06-28 10:56:40 +0000416 if (llvm::Metadata *V = It->second)
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +0000417 return cast<llvm::DIFile>(V);
Guy Benyei11169dd2012-12-18 14:30:41 +0000418 }
419
Amjad Aboude2aab8c2016-12-25 10:12:27 +0000420 SmallString<32> Checksum;
Alexandre Ganea047e65d2019-05-21 19:40:28 +0000421
422 // Compute the checksum if possible. If the location is affected by a #line
423 // directive that refers to a file, PLoc will have an invalid FileID, and we
424 // will correctly get no checksum.
Scott Linder94834f12018-02-12 19:47:05 +0000425 Optional<llvm::DIFile::ChecksumKind> CSKind =
Alexandre Ganea047e65d2019-05-21 19:40:28 +0000426 computeChecksum(PLoc.getFileID(), Checksum);
Scott Linder94834f12018-02-12 19:47:05 +0000427 Optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo;
428 if (CSKind)
429 CSInfo.emplace(*CSKind, Checksum);
Adrian Prantlaa5bad42018-12-11 16:58:43 +0000430 return createFile(FileName, CSInfo, getSource(SM, SM.getFileID(Loc)));
431}
Amjad Aboude2aab8c2016-12-25 10:12:27 +0000432
Adrian Prantlaa5bad42018-12-11 16:58:43 +0000433llvm::DIFile *
434CGDebugInfo::createFile(StringRef FileName,
435 Optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo,
436 Optional<StringRef> Source) {
Adrian Prantl212c1042018-12-06 18:44:50 +0000437 StringRef Dir;
438 StringRef File;
439 std::string RemappedFile = remapDIPath(FileName);
440 std::string CurDir = remapDIPath(getCurrentDirname());
441 SmallString<128> DirBuf;
442 SmallString<128> FileBuf;
443 if (llvm::sys::path::is_absolute(RemappedFile)) {
444 // Strip the common prefix (if it is more than just "/") from current
445 // directory and FileName for a more space-efficient encoding.
446 auto FileIt = llvm::sys::path::begin(RemappedFile);
447 auto FileE = llvm::sys::path::end(RemappedFile);
448 auto CurDirIt = llvm::sys::path::begin(CurDir);
449 auto CurDirE = llvm::sys::path::end(CurDir);
450 for (; CurDirIt != CurDirE && *CurDirIt == *FileIt; ++CurDirIt, ++FileIt)
451 llvm::sys::path::append(DirBuf, *CurDirIt);
452 if (std::distance(llvm::sys::path::begin(CurDir), CurDirIt) == 1) {
Adrian Prantl0feb7b72019-02-05 21:21:01 +0000453 // Don't strip the common prefix if it is only the root "/"
454 // since that would make LLVM diagnostic locations confusing.
Adrian Prantl212c1042018-12-06 18:44:50 +0000455 Dir = {};
456 File = RemappedFile;
457 } else {
458 for (; FileIt != FileE; ++FileIt)
459 llvm::sys::path::append(FileBuf, *FileIt);
460 Dir = DirBuf;
461 File = FileBuf;
462 }
463 } else {
464 Dir = CurDir;
465 File = RemappedFile;
466 }
Adrian Prantlaa5bad42018-12-11 16:58:43 +0000467 llvm::DIFile *F = DBuilder.createFile(File, Dir, CSInfo, Source);
Adrian Prantl212c1042018-12-06 18:44:50 +0000468 DIFileCache[FileName.data()].reset(F);
Guy Benyei11169dd2012-12-18 14:30:41 +0000469 return F;
470}
471
Saleem Abdulrasool436256a2015-10-12 20:21:08 +0000472std::string CGDebugInfo::remapDIPath(StringRef Path) const {
473 for (const auto &Entry : DebugPrefixMap)
Fangrui Song3bb24bf2019-11-26 16:09:22 -0800474 if (Path.startswith(Entry.first))
475 return (Twine(Entry.second) + Path.substr(Entry.first.size())).str();
476 return Path.str();
Guy Benyei11169dd2012-12-18 14:30:41 +0000477}
478
Guy Benyei11169dd2012-12-18 14:30:41 +0000479unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
480 if (Loc.isInvalid() && CurLoc.isInvalid())
481 return 0;
482 SourceManager &SM = CGM.getContext().getSourceManager();
483 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
Eric Christophere7b87e52014-10-26 23:40:33 +0000484 return PLoc.isValid() ? PLoc.getLine() : 0;
Guy Benyei11169dd2012-12-18 14:30:41 +0000485}
486
Adrian Prantlc7822422013-03-12 20:43:25 +0000487unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000488 // We may not want column information at all.
Adrian Prantlc7822422013-03-12 20:43:25 +0000489 if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo)
Guy Benyei11169dd2012-12-18 14:30:41 +0000490 return 0;
491
492 // If the location is invalid then use the current column.
493 if (Loc.isInvalid() && CurLoc.isInvalid())
494 return 0;
495 SourceManager &SM = CGM.getContext().getSourceManager();
496 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
Eric Christophere7b87e52014-10-26 23:40:33 +0000497 return PLoc.isValid() ? PLoc.getColumn() : 0;
Guy Benyei11169dd2012-12-18 14:30:41 +0000498}
499
500StringRef CGDebugInfo::getCurrentDirname() {
501 if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
502 return CGM.getCodeGenOpts().DebugCompilationDir;
503
504 if (!CWDName.empty())
505 return CWDName;
506 SmallString<256> CWD;
507 llvm::sys::fs::current_path(CWD);
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +0000508 return CWDName = internString(CWD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000509}
510
Guy Benyei11169dd2012-12-18 14:30:41 +0000511void CGDebugInfo::CreateCompileUnit() {
Amjad Aboude2aab8c2016-12-25 10:12:27 +0000512 SmallString<32> Checksum;
Scott Linder94834f12018-02-12 19:47:05 +0000513 Optional<llvm::DIFile::ChecksumKind> CSKind;
514 Optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo;
Guy Benyei11169dd2012-12-18 14:30:41 +0000515
David Blaikieaabde052014-05-14 00:29:00 +0000516 // Should we be asking the SourceManager for the main file name, instead of
517 // accepting it as an argument? This just causes the main file name to
518 // mismatch with source locations and create extra lexical scopes or
519 // mismatched debug info (a CU with a DW_AT_file of "-", because that's what
520 // the driver passed, but functions/other things have DW_AT_file of "<stdin>"
521 // because that's what the SourceManager says)
522
Guy Benyei11169dd2012-12-18 14:30:41 +0000523 // Get absolute path name.
524 SourceManager &SM = CGM.getContext().getSourceManager();
525 std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
526 if (MainFileName.empty())
David Blaikieaabde052014-05-14 00:29:00 +0000527 MainFileName = "<stdin>";
Guy Benyei11169dd2012-12-18 14:30:41 +0000528
529 // The main file name provided via the "-main-file-name" option contains just
530 // the file name itself with no path information. This file name may have had
531 // a relative path, so we look into the actual file entry for the main
532 // file to determine the real absolute path for the file.
533 std::string MainFileDir;
534 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
Benjamin Krameradcd0262020-01-28 20:23:46 +0100535 MainFileDir = std::string(MainFile->getDir()->getName());
Adrian Prantl122e7af2019-10-21 16:44:37 +0000536 if (!llvm::sys::path::is_absolute(MainFileName)) {
Eric Christopher0a1301f2014-02-26 02:49:36 +0000537 llvm::SmallString<1024> MainFileDirSS(MainFileDir);
538 llvm::sys::path::append(MainFileDirSS, MainFileName);
Benjamin Krameradcd0262020-01-28 20:23:46 +0100539 MainFileName =
540 std::string(llvm::sys::path::remove_leading_dotslash(MainFileDirSS));
Yaron Keren9fb7e902013-10-21 20:07:37 +0000541 }
Taewook Oh0fb5b782017-08-16 19:36:24 +0000542 // If the main file name provided is identical to the input file name, and
543 // if the input file is a preprocessed source, use the module name for
544 // debug info. The module name comes from the name specified in the first
545 // linemarker if the input is a preprocessed source.
546 if (MainFile->getName() == MainFileName &&
547 FrontendOptions::getInputKindForExtension(
548 MainFile->getName().rsplit('.').second)
549 .isPreprocessed())
550 MainFileName = CGM.getModule().getName().str();
551
Amjad Aboude2aab8c2016-12-25 10:12:27 +0000552 CSKind = computeChecksum(SM.getMainFileID(), Checksum);
Guy Benyei11169dd2012-12-18 14:30:41 +0000553 }
554
Ed Masteda706022014-05-07 12:49:30 +0000555 llvm::dwarf::SourceLanguage LangTag;
Guy Benyei11169dd2012-12-18 14:30:41 +0000556 const LangOptions &LO = CGM.getLangOpts();
557 if (LO.CPlusPlus) {
Erik Pilkingtonfa983902018-10-30 20:31:30 +0000558 if (LO.ObjC)
Guy Benyei11169dd2012-12-18 14:30:41 +0000559 LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
Adrian Prantl350de4f2019-09-24 00:38:49 +0000560 else if (LO.CPlusPlus14)
561 LangTag = llvm::dwarf::DW_LANG_C_plus_plus_14;
562 else if (LO.CPlusPlus11)
563 LangTag = llvm::dwarf::DW_LANG_C_plus_plus_11;
Guy Benyei11169dd2012-12-18 14:30:41 +0000564 else
565 LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
Erik Pilkingtonfa983902018-10-30 20:31:30 +0000566 } else if (LO.ObjC) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000567 LangTag = llvm::dwarf::DW_LANG_ObjC;
Pirama Arumuga Nainara7484c92016-06-21 21:35:11 +0000568 } else if (LO.RenderScript) {
569 LangTag = llvm::dwarf::DW_LANG_GOOGLE_RenderScript;
Guy Benyei11169dd2012-12-18 14:30:41 +0000570 } else if (LO.C99) {
571 LangTag = llvm::dwarf::DW_LANG_C99;
572 } else {
573 LangTag = llvm::dwarf::DW_LANG_C89;
574 }
575
576 std::string Producer = getClangFullVersion();
577
578 // Figure out which version of the ObjC runtime we have.
579 unsigned RuntimeVers = 0;
Erik Pilkingtonfa983902018-10-30 20:31:30 +0000580 if (LO.ObjC)
Guy Benyei11169dd2012-12-18 14:30:41 +0000581 RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
582
Adrian Prantl826824e2016-04-08 22:43:06 +0000583 llvm::DICompileUnit::DebugEmissionKind EmissionKind;
584 switch (DebugKind) {
585 case codegenoptions::NoDebugInfo:
586 case codegenoptions::LocTrackingOnly:
587 EmissionKind = llvm::DICompileUnit::NoDebug;
588 break;
589 case codegenoptions::DebugLineTablesOnly:
590 EmissionKind = llvm::DICompileUnit::LineTablesOnly;
591 break;
Alexey Bataev80e1b5e2018-08-31 13:56:14 +0000592 case codegenoptions::DebugDirectivesOnly:
593 EmissionKind = llvm::DICompileUnit::DebugDirectivesOnly;
594 break;
Amy Huang53539bb2020-01-13 15:54:54 -0800595 case codegenoptions::DebugInfoConstructor:
Adrian Prantl826824e2016-04-08 22:43:06 +0000596 case codegenoptions::LimitedDebugInfo:
597 case codegenoptions::FullDebugInfo:
598 EmissionKind = llvm::DICompileUnit::FullDebug;
599 break;
600 }
601
Adrian Prantl046d1002018-12-13 17:53:29 +0000602 uint64_t DwoId = 0;
603 auto &CGOpts = CGM.getCodeGenOpts();
604 // The DIFile used by the CU is distinct from the main source
605 // file. Its directory part specifies what becomes the
606 // DW_AT_comp_dir (the compilation directory), even if the source
607 // file was specified with an absolute path.
Scott Linder94834f12018-02-12 19:47:05 +0000608 if (CSKind)
609 CSInfo.emplace(*CSKind, Checksum);
Adrian Prantl046d1002018-12-13 17:53:29 +0000610 llvm::DIFile *CUFile = DBuilder.createFile(
611 remapDIPath(MainFileName), remapDIPath(getCurrentDirname()), CSInfo,
612 getSource(SM, SM.getMainFileID()));
Scott Linder94834f12018-02-12 19:47:05 +0000613
Adrian Prantl842ea702020-03-12 14:19:04 -0700614 StringRef Sysroot, SDK;
615 if (CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB) {
Adrian Prantl7b303702020-01-14 13:37:04 -0800616 Sysroot = CGM.getHeaderSearchOpts().Sysroot;
Adrian Prantl842ea702020-03-12 14:19:04 -0700617 auto B = llvm::sys::path::rbegin(Sysroot);
618 auto E = llvm::sys::path::rend(Sysroot);
619 auto It = std::find_if(B, E, [](auto SDK) { return SDK.endswith(".sdk"); });
620 if (It != E)
621 SDK = *It;
622 }
Adrian Prantl7b303702020-01-14 13:37:04 -0800623
Guy Benyei11169dd2012-12-18 14:30:41 +0000624 // Create new compile unit.
Eric Christophere4200a22014-02-27 01:25:08 +0000625 TheCU = DBuilder.createCompileUnit(
Adrian Prantl046d1002018-12-13 17:53:29 +0000626 LangTag, CUFile, CGOpts.EmitVersionIdentMetadata ? Producer : "",
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +0000627 LO.Optimize || CGOpts.PrepareForLTO || CGOpts.PrepareForThinLTO,
Aaron Puchert45611612019-06-26 21:39:19 +0000628 CGOpts.DwarfDebugFlags, RuntimeVers, CGOpts.SplitDwarfFile, EmissionKind,
629 DwoId, CGOpts.SplitDwarfInlining, CGOpts.DebugInfoForProfiling,
David Blaikie9982bb82018-08-16 23:56:32 +0000630 CGM.getTarget().getTriple().isNVPTX()
631 ? llvm::DICompileUnit::DebugNameTableKind::None
David Blaikie65864522018-08-20 20:14:08 +0000632 : static_cast<llvm::DICompileUnit::DebugNameTableKind>(
David Blaikie27692de2018-11-13 20:08:13 +0000633 CGOpts.DebugNameTable),
Adrian Prantlceae4712020-03-18 15:48:23 -0700634 CGOpts.DebugRangesBaseAddress, remapDIPath(Sysroot), SDK);
Guy Benyei11169dd2012-12-18 14:30:41 +0000635}
636
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +0000637llvm::DIType *CGDebugInfo::CreateType(const BuiltinType *BT) {
Ed Masteda706022014-05-07 12:49:30 +0000638 llvm::dwarf::TypeKind Encoding;
Guy Benyei11169dd2012-12-18 14:30:41 +0000639 StringRef BTName;
640 switch (BT->getKind()) {
641#define BUILTIN_TYPE(Id, SingletonId)
Eric Christophere7b87e52014-10-26 23:40:33 +0000642#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
Guy Benyei11169dd2012-12-18 14:30:41 +0000643#include "clang/AST/BuiltinTypes.def"
644 case BuiltinType::Dependent:
645 llvm_unreachable("Unexpected builtin type");
646 case BuiltinType::NullPtr:
Peter Collingbourne5c5e6172013-06-27 22:51:01 +0000647 return DBuilder.createNullPtrType();
Guy Benyei11169dd2012-12-18 14:30:41 +0000648 case BuiltinType::Void:
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +0000649 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000650 case BuiltinType::ObjCClass:
David Blaikief427b002014-05-06 03:42:01 +0000651 if (!ClassTy)
Adrian Prantlc2a44ec2018-12-11 16:58:46 +0000652 ClassTy =
653 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
654 "objc_class", TheCU, TheCU->getFile(), 0);
Guy Benyei11169dd2012-12-18 14:30:41 +0000655 return ClassTy;
656 case BuiltinType::ObjCId: {
657 // typedef struct objc_class *Class;
658 // typedef struct objc_object {
659 // Class isa;
660 // } *id;
661
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000662 if (ObjTy)
Guy Benyei11169dd2012-12-18 14:30:41 +0000663 return ObjTy;
664
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000665 if (!ClassTy)
Adrian Prantlc2a44ec2018-12-11 16:58:46 +0000666 ClassTy =
667 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
668 "objc_class", TheCU, TheCU->getFile(), 0);
Guy Benyei11169dd2012-12-18 14:30:41 +0000669
670 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
Eric Christopherb2a008c2013-05-16 00:45:12 +0000671
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +0000672 auto *ISATy = DBuilder.createPointerType(ClassTy, Size);
Guy Benyei11169dd2012-12-18 14:30:41 +0000673
Adrian Prantlc2a44ec2018-12-11 16:58:46 +0000674 ObjTy = DBuilder.createStructType(TheCU, "objc_object", TheCU->getFile(), 0,
675 0, 0, llvm::DINode::FlagZero, nullptr,
676 llvm::DINodeArray());
Guy Benyei11169dd2012-12-18 14:30:41 +0000677
Duncan P. N. Exon Smithc8ee63e2014-12-18 00:48:56 +0000678 DBuilder.replaceArrays(
Leny Kholodovdf050fd2016-09-06 17:06:14 +0000679 ObjTy, DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
Adrian Prantlc2a44ec2018-12-11 16:58:46 +0000680 ObjTy, "isa", TheCU->getFile(), 0, Size, 0, 0,
Leny Kholodovdf050fd2016-09-06 17:06:14 +0000681 llvm::DINode::FlagZero, ISATy)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000682 return ObjTy;
683 }
684 case BuiltinType::ObjCSel: {
David Blaikief427b002014-05-06 03:42:01 +0000685 if (!SelTy)
686 SelTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
687 "objc_selector", TheCU,
Adrian Prantlc2a44ec2018-12-11 16:58:46 +0000688 TheCU->getFile(), 0);
Guy Benyei11169dd2012-12-18 14:30:41 +0000689 return SelTy;
690 }
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000691
Jonas Devlieghere9ef49652018-06-28 10:56:40 +0000692#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
693 case BuiltinType::Id: \
694 return getOrCreateStructPtrType("opencl_" #ImgType "_" #Suffix "_t", \
Alexey Bader954ba212016-04-08 13:40:33 +0000695 SingletonId);
Alexey Baderb62f1442016-04-13 08:33:41 +0000696#include "clang/Basic/OpenCLImageTypes.def"
Guy Benyei61054192013-02-07 10:55:47 +0000697 case BuiltinType::OCLSampler:
Jonas Devlieghere9ef49652018-06-28 10:56:40 +0000698 return getOrCreateStructPtrType("opencl_sampler_t", OCLSamplerDITy);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +0000699 case BuiltinType::OCLEvent:
Eric Christophere7b87e52014-10-26 23:40:33 +0000700 return getOrCreateStructPtrType("opencl_event_t", OCLEventDITy);
Alexey Bader9c8453f2015-09-15 11:18:52 +0000701 case BuiltinType::OCLClkEvent:
702 return getOrCreateStructPtrType("opencl_clk_event_t", OCLClkEventDITy);
703 case BuiltinType::OCLQueue:
704 return getOrCreateStructPtrType("opencl_queue_t", OCLQueueDITy);
Alexey Bader9c8453f2015-09-15 11:18:52 +0000705 case BuiltinType::OCLReserveID:
706 return getOrCreateStructPtrType("opencl_reserve_id_t", OCLReserveIDDITy);
Andrew Savonichev3fee3512018-11-08 11:25:41 +0000707#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
708 case BuiltinType::Id: \
709 return getOrCreateStructPtrType("opencl_" #ExtType, Id##Ty);
710#include "clang/Basic/OpenCLExtensionTypes.def"
Richard Sandifordeb485fb2019-08-09 08:52:54 +0000711 // TODO: real support for SVE types requires more infrastructure
712 // to be added first. The types have a variable length and are
713 // represented in debug info as types whose length depends on a
714 // target-specific pseudo register.
715#define SVE_TYPE(Name, Id, SingletonId) \
716 case BuiltinType::Id:
717#include "clang/Basic/AArch64SVEACLETypes.def"
718 {
719 unsigned DiagID = CGM.getDiags().getCustomDiagID(
720 DiagnosticsEngine::Error,
721 "cannot yet generate debug info for SVE type '%0'");
722 auto Name = BT->getName(CGM.getContext().getPrintingPolicy());
723 CGM.getDiags().Report(DiagID) << Name;
724 // Return something safe.
725 return CreateType(cast<const BuiltinType>(CGM.getContext().IntTy));
726 }
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000727
Guy Benyei11169dd2012-12-18 14:30:41 +0000728 case BuiltinType::UChar:
Eric Christophere7b87e52014-10-26 23:40:33 +0000729 case BuiltinType::Char_U:
730 Encoding = llvm::dwarf::DW_ATE_unsigned_char;
731 break;
Guy Benyei11169dd2012-12-18 14:30:41 +0000732 case BuiltinType::Char_S:
Eric Christophere7b87e52014-10-26 23:40:33 +0000733 case BuiltinType::SChar:
734 Encoding = llvm::dwarf::DW_ATE_signed_char;
735 break;
Richard Smith3a8244d2018-05-01 05:02:45 +0000736 case BuiltinType::Char8:
Guy Benyei11169dd2012-12-18 14:30:41 +0000737 case BuiltinType::Char16:
Eric Christophere7b87e52014-10-26 23:40:33 +0000738 case BuiltinType::Char32:
739 Encoding = llvm::dwarf::DW_ATE_UTF;
740 break;
Guy Benyei11169dd2012-12-18 14:30:41 +0000741 case BuiltinType::UShort:
742 case BuiltinType::UInt:
743 case BuiltinType::UInt128:
744 case BuiltinType::ULong:
745 case BuiltinType::WChar_U:
Eric Christophere7b87e52014-10-26 23:40:33 +0000746 case BuiltinType::ULongLong:
747 Encoding = llvm::dwarf::DW_ATE_unsigned;
748 break;
Guy Benyei11169dd2012-12-18 14:30:41 +0000749 case BuiltinType::Short:
750 case BuiltinType::Int:
751 case BuiltinType::Int128:
752 case BuiltinType::Long:
753 case BuiltinType::WChar_S:
Eric Christophere7b87e52014-10-26 23:40:33 +0000754 case BuiltinType::LongLong:
755 Encoding = llvm::dwarf::DW_ATE_signed;
756 break;
757 case BuiltinType::Bool:
758 Encoding = llvm::dwarf::DW_ATE_boolean;
759 break;
Guy Benyei11169dd2012-12-18 14:30:41 +0000760 case BuiltinType::Half:
761 case BuiltinType::Float:
762 case BuiltinType::LongDouble:
Sjoerd Meijercc623ad2017-09-08 15:15:00 +0000763 case BuiltinType::Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +0000764 case BuiltinType::Float128:
Eric Christophere7b87e52014-10-26 23:40:33 +0000765 case BuiltinType::Double:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +0000766 // FIXME: For targets where long double and __float128 have the same size,
767 // they are currently indistinguishable in the debugger without some
768 // special treatment. However, there is currently no consensus on encoding
769 // and this should be updated once a DWARF encoding exists for distinct
770 // floating point types of the same size.
Eric Christophere7b87e52014-10-26 23:40:33 +0000771 Encoding = llvm::dwarf::DW_ATE_float;
772 break;
Leonard Chanf921d852018-06-04 16:07:52 +0000773 case BuiltinType::ShortAccum:
774 case BuiltinType::Accum:
775 case BuiltinType::LongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +0000776 case BuiltinType::ShortFract:
777 case BuiltinType::Fract:
778 case BuiltinType::LongFract:
779 case BuiltinType::SatShortFract:
780 case BuiltinType::SatFract:
781 case BuiltinType::SatLongFract:
782 case BuiltinType::SatShortAccum:
783 case BuiltinType::SatAccum:
784 case BuiltinType::SatLongAccum:
Leonard Chanf921d852018-06-04 16:07:52 +0000785 Encoding = llvm::dwarf::DW_ATE_signed_fixed;
786 break;
787 case BuiltinType::UShortAccum:
788 case BuiltinType::UAccum:
789 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +0000790 case BuiltinType::UShortFract:
791 case BuiltinType::UFract:
792 case BuiltinType::ULongFract:
793 case BuiltinType::SatUShortAccum:
794 case BuiltinType::SatUAccum:
795 case BuiltinType::SatULongAccum:
796 case BuiltinType::SatUShortFract:
797 case BuiltinType::SatUFract:
798 case BuiltinType::SatULongFract:
Leonard Chanf921d852018-06-04 16:07:52 +0000799 Encoding = llvm::dwarf::DW_ATE_unsigned_fixed;
800 break;
Guy Benyei11169dd2012-12-18 14:30:41 +0000801 }
802
803 switch (BT->getKind()) {
Eric Christophere7b87e52014-10-26 23:40:33 +0000804 case BuiltinType::Long:
805 BTName = "long int";
806 break;
807 case BuiltinType::LongLong:
808 BTName = "long long int";
809 break;
810 case BuiltinType::ULong:
811 BTName = "long unsigned int";
812 break;
813 case BuiltinType::ULongLong:
814 BTName = "long long unsigned int";
815 break;
Guy Benyei11169dd2012-12-18 14:30:41 +0000816 default:
817 BTName = BT->getName(CGM.getLangOpts());
818 break;
819 }
Victor Leschuka7ece032016-10-20 00:13:19 +0000820 // Bit size and offset of the type.
Guy Benyei11169dd2012-12-18 14:30:41 +0000821 uint64_t Size = CGM.getContext().getTypeSize(BT);
Victor Leschuka7ece032016-10-20 00:13:19 +0000822 return DBuilder.createBasicType(BTName, Size, Encoding);
Guy Benyei11169dd2012-12-18 14:30:41 +0000823}
824
Awanish Pandeyc83602f2020-01-23 16:06:52 +0530825llvm::DIType *CGDebugInfo::CreateType(const AutoType *Ty) {
826 return DBuilder.createUnspecifiedType("auto");
827}
828
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +0000829llvm::DIType *CGDebugInfo::CreateType(const ComplexType *Ty) {
Victor Leschuka7ece032016-10-20 00:13:19 +0000830 // Bit size and offset of the type.
Ed Masteda706022014-05-07 12:49:30 +0000831 llvm::dwarf::TypeKind Encoding = llvm::dwarf::DW_ATE_complex_float;
Guy Benyei11169dd2012-12-18 14:30:41 +0000832 if (Ty->isComplexIntegerType())
833 Encoding = llvm::dwarf::DW_ATE_lo_user;
834
835 uint64_t Size = CGM.getContext().getTypeSize(Ty);
Victor Leschuka7ece032016-10-20 00:13:19 +0000836 return DBuilder.createBasicType("complex", Size, Encoding);
Guy Benyei11169dd2012-12-18 14:30:41 +0000837}
838
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +0000839llvm::DIType *CGDebugInfo::CreateQualifiedType(QualType Ty,
840 llvm::DIFile *Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000841 QualifierCollector Qc;
842 const Type *T = Qc.strip(Ty);
843
844 // Ignore these qualifiers for now.
845 Qc.removeObjCGCAttr();
846 Qc.removeAddressSpace();
847 Qc.removeObjCLifetime();
848
849 // We will create one Derived type for one qualifier and recurse to handle any
850 // additional ones.
Ed Masteda706022014-05-07 12:49:30 +0000851 llvm::dwarf::Tag Tag;
Guy Benyei11169dd2012-12-18 14:30:41 +0000852 if (Qc.hasConst()) {
853 Tag = llvm::dwarf::DW_TAG_const_type;
854 Qc.removeConst();
855 } else if (Qc.hasVolatile()) {
856 Tag = llvm::dwarf::DW_TAG_volatile_type;
857 Qc.removeVolatile();
858 } else if (Qc.hasRestrict()) {
859 Tag = llvm::dwarf::DW_TAG_restrict_type;
860 Qc.removeRestrict();
861 } else {
862 assert(Qc.empty() && "Unknown type qualifier for debug info");
863 return getOrCreateType(QualType(T, 0), Unit);
864 }
865
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +0000866 auto *FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +0000867
868 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
869 // CVR derived types.
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +0000870 return DBuilder.createQualifiedType(Tag, FromTy);
Guy Benyei11169dd2012-12-18 14:30:41 +0000871}
872
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +0000873llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
874 llvm::DIFile *Unit) {
Fariborz Jahanian65f1fa12013-02-21 20:42:11 +0000875
876 // The frontend treats 'id' as a typedef to an ObjCObjectType,
877 // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
878 // debug info, we want to emit 'id' in both cases.
879 if (Ty->isObjCQualifiedIdType())
Eric Christophere7b87e52014-10-26 23:40:33 +0000880 return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
Fariborz Jahanian65f1fa12013-02-21 20:42:11 +0000881
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +0000882 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
883 Ty->getPointeeType(), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +0000884}
885
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +0000886llvm::DIType *CGDebugInfo::CreateType(const PointerType *Ty,
887 llvm::DIFile *Unit) {
Eric Christopherb2a008c2013-05-16 00:45:12 +0000888 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +0000889 Ty->getPointeeType(), Unit);
890}
891
Adrian Prantlc6f91a22015-06-15 23:18:16 +0000892/// \return whether a C++ mangling exists for the type defined by TD.
893static bool hasCXXMangling(const TagDecl *TD, llvm::DICompileUnit *TheCU) {
894 switch (TheCU->getSourceLanguage()) {
895 case llvm::dwarf::DW_LANG_C_plus_plus:
Adrian Prantl350de4f2019-09-24 00:38:49 +0000896 case llvm::dwarf::DW_LANG_C_plus_plus_11:
897 case llvm::dwarf::DW_LANG_C_plus_plus_14:
Adrian Prantlc6f91a22015-06-15 23:18:16 +0000898 return true;
899 case llvm::dwarf::DW_LANG_ObjC_plus_plus:
900 return isa<CXXRecordDecl>(TD) || isa<EnumDecl>(TD);
901 default:
902 return false;
903 }
904}
905
Reid Kleckner59320fc2018-08-17 20:59:52 +0000906// Determines if the debug info for this tag declaration needs a type
907// identifier. The purpose of the unique identifier is to deduplicate type
908// information for identical types across TUs. Because of the C++ one definition
909// rule (ODR), it is valid to assume that the type is defined the same way in
910// every TU and its debug info is equivalent.
911//
912// C does not have the ODR, and it is common for codebases to contain multiple
913// different definitions of a struct with the same name in different TUs.
914// Therefore, if the type doesn't have a C++ mangling, don't give it an
915// identifer. Type information in C is smaller and simpler than C++ type
916// information, so the increase in debug info size is negligible.
917//
918// If the type is not externally visible, it should be unique to the current TU,
919// and should not need an identifier to participate in type deduplication.
920// However, when emitting CodeView, the format internally uses these
921// unique type name identifers for references between debug info. For example,
922// the method of a class in an anonymous namespace uses the identifer to refer
923// to its parent class. The Microsoft C++ ABI attempts to provide unique names
924// for such types, so when emitting CodeView, always use identifiers for C++
925// types. This may create problems when attempting to emit CodeView when the MS
926// C++ ABI is not in use.
Jonas Devlieghere9ef49652018-06-28 10:56:40 +0000927static bool needsTypeIdentifier(const TagDecl *TD, CodeGenModule &CGM,
Brock Wyma8557ec52018-05-22 12:41:19 +0000928 llvm::DICompileUnit *TheCU) {
929 // We only add a type identifier for types with C++ name mangling.
930 if (!hasCXXMangling(TD, TheCU))
931 return false;
932
Brock Wyma8557ec52018-05-22 12:41:19 +0000933 // Externally visible types with C++ mangling need a type identifier.
934 if (TD->isExternallyVisible())
935 return true;
936
Reid Kleckner59320fc2018-08-17 20:59:52 +0000937 // CodeView types with C++ mangling need a type identifier.
938 if (CGM.getCodeGenOpts().EmitCodeView)
939 return true;
940
Brock Wyma8557ec52018-05-22 12:41:19 +0000941 return false;
942}
943
Reid Kleckner59320fc2018-08-17 20:59:52 +0000944// Returns a unique type identifier string if one exists, or an empty string.
Jonas Devlieghere9ef49652018-06-28 10:56:40 +0000945static SmallString<256> getTypeIdentifier(const TagType *Ty, CodeGenModule &CGM,
Brock Wyma8557ec52018-05-22 12:41:19 +0000946 llvm::DICompileUnit *TheCU) {
947 SmallString<256> Identifier;
Manman Rene0064d82013-08-29 23:19:58 +0000948 const TagDecl *TD = Ty->getDecl();
Adrian Prantlc6f91a22015-06-15 23:18:16 +0000949
Brock Wyma8557ec52018-05-22 12:41:19 +0000950 if (!needsTypeIdentifier(TD, CGM, TheCU))
951 return Identifier;
David Blaikief0d66552019-04-25 20:05:47 +0000952 if (const auto *RD = dyn_cast<CXXRecordDecl>(TD))
953 if (RD->getDefinition())
954 if (RD->isDynamicClass() &&
955 CGM.getVTableLinkage(RD) == llvm::GlobalValue::ExternalLinkage)
956 return Identifier;
Adrian Prantlc6f91a22015-06-15 23:18:16 +0000957
Manman Rene0064d82013-08-29 23:19:58 +0000958 // TODO: This is using the RTTI name. Is there a better way to get
959 // a unique string for a type?
Brock Wyma8557ec52018-05-22 12:41:19 +0000960 llvm::raw_svector_ostream Out(Identifier);
Manman Rene0064d82013-08-29 23:19:58 +0000961 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(QualType(Ty, 0), Out);
Brock Wyma8557ec52018-05-22 12:41:19 +0000962 return Identifier;
Manman Rene0064d82013-08-29 23:19:58 +0000963}
964
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +0000965/// \return the appropriate DWARF tag for a composite type.
Adrian Prantl5f66bae2015-02-11 17:45:15 +0000966static llvm::dwarf::Tag getTagForRecord(const RecordDecl *RD) {
Jonas Devlieghere9ef49652018-06-28 10:56:40 +0000967 llvm::dwarf::Tag Tag;
Adrian Prantl5f66bae2015-02-11 17:45:15 +0000968 if (RD->isStruct() || RD->isInterface())
969 Tag = llvm::dwarf::DW_TAG_structure_type;
970 else if (RD->isUnion())
971 Tag = llvm::dwarf::DW_TAG_union_type;
972 else {
973 // FIXME: This could be a struct type giving a default visibility different
974 // than C++ class type, but needs llvm metadata changes first.
975 assert(RD->isClass());
976 Tag = llvm::dwarf::DW_TAG_class_type;
977 }
978 return Tag;
979}
980
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +0000981llvm::DICompositeType *
Manman Ren1b457022013-08-28 21:20:28 +0000982CGDebugInfo::getOrCreateRecordFwdDecl(const RecordType *Ty,
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +0000983 llvm::DIScope *Ctx) {
Manman Ren1b457022013-08-28 21:20:28 +0000984 const RecordDecl *RD = Ty->getDecl();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +0000985 if (llvm::DIType *T = getTypeOrNull(CGM.getContext().getRecordType(RD)))
986 return cast<llvm::DICompositeType>(T);
987 llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +0000988 unsigned Line = getLineNumber(RD->getLocation());
989 StringRef RDName = getClassName(RD);
990
Peter Collingbourned251b0a2015-03-01 22:07:04 +0000991 uint64_t Size = 0;
Victor Leschuk802e4a52016-10-19 22:11:07 +0000992 uint32_t Align = 0;
Peter Collingbourned251b0a2015-03-01 22:07:04 +0000993
Amy Huangbcf66082020-02-04 13:20:13 -0800994 llvm::DINode::DIFlags Flags = llvm::DINode::FlagFwdDecl;
995
996 // Add flag to nontrivial forward declarations. To be consistent with MSVC,
997 // add the flag if a record has no definition because we don't know whether
998 // it will be trivial or not.
999 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1000 if (!CXXRD->hasDefinition() ||
1001 (CXXRD->hasDefinition() && !CXXRD->isTrivial()))
1002 Flags |= llvm::DINode::FlagNonTrivial;
1003
Guy Benyei11169dd2012-12-18 14:30:41 +00001004 // Create the type.
Brock Wyma8557ec52018-05-22 12:41:19 +00001005 SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001006 llvm::DICompositeType *RetTy = DBuilder.createReplaceableCompositeType(
Amy Huangbcf66082020-02-04 13:20:13 -08001007 getTagForRecord(RD), RDName, Ctx, DefUnit, Line, 0, Size, Align, Flags,
1008 Identifier);
Paul Robinson1787f812017-09-28 18:37:02 +00001009 if (CGM.getCodeGenOpts().DebugFwdTemplateParams)
1010 if (auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD))
1011 DBuilder.replaceArrays(RetTy, llvm::DINodeArray(),
1012 CollectCXXTemplateParams(TSpecial, DefUnit));
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001013 ReplaceMap.emplace_back(
1014 std::piecewise_construct, std::make_tuple(Ty),
1015 std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
David Blaikief427b002014-05-06 03:42:01 +00001016 return RetTy;
Guy Benyei11169dd2012-12-18 14:30:41 +00001017}
1018
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001019llvm::DIType *CGDebugInfo::CreatePointerLikeType(llvm::dwarf::Tag Tag,
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00001020 const Type *Ty,
1021 QualType PointeeTy,
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001022 llvm::DIFile *Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001023 // Bit size, align and offset of the type.
1024 // Size is always the size of a pointer. We can't use getTypeSize here
1025 // because that does not return the correct value for references.
Konstantin Zhuravlyovd1ba16e2017-03-08 23:56:48 +00001026 unsigned AddressSpace = CGM.getContext().getTargetAddressSpace(PointeeTy);
1027 uint64_t Size = CGM.getTarget().getPointerWidth(AddressSpace);
Victor Leschuka7ece032016-10-20 00:13:19 +00001028 auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
Konstantin Zhuravlyovd1ba16e2017-03-08 23:56:48 +00001029 Optional<unsigned> DWARFAddressSpace =
1030 CGM.getTarget().getDWARFAddressSpace(AddressSpace);
Guy Benyei11169dd2012-12-18 14:30:41 +00001031
Keno Fischer87842f32015-11-16 09:04:13 +00001032 if (Tag == llvm::dwarf::DW_TAG_reference_type ||
1033 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
1034 return DBuilder.createReferenceType(Tag, getOrCreateType(PointeeTy, Unit),
Konstantin Zhuravlyovd1ba16e2017-03-08 23:56:48 +00001035 Size, Align, DWARFAddressSpace);
Keno Fischer87842f32015-11-16 09:04:13 +00001036 else
1037 return DBuilder.createPointerType(getOrCreateType(PointeeTy, Unit), Size,
Konstantin Zhuravlyovd1ba16e2017-03-08 23:56:48 +00001038 Align, DWARFAddressSpace);
Guy Benyei11169dd2012-12-18 14:30:41 +00001039}
1040
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001041llvm::DIType *CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
1042 llvm::DIType *&Cache) {
Eric Christopherf8bc4d82013-07-18 00:52:50 +00001043 if (Cache)
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001044 return Cache;
David Blaikiefefc7f72013-05-21 17:58:54 +00001045 Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
Adrian Prantlc2a44ec2018-12-11 16:58:46 +00001046 TheCU, TheCU->getFile(), 0);
David Blaikiefefc7f72013-05-21 17:58:54 +00001047 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1048 Cache = DBuilder.createPointerType(Cache, Size);
1049 return Cache;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001050}
1051
Scott Linder58df0e42018-08-08 15:56:12 +00001052uint64_t CGDebugInfo::collectDefaultElementTypesForBlockPointer(
1053 const BlockPointerType *Ty, llvm::DIFile *Unit, llvm::DIDerivedType *DescTy,
1054 unsigned LineNo, SmallVectorImpl<llvm::Metadata *> &EltTys) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001055 QualType FType;
Guy Benyei11169dd2012-12-18 14:30:41 +00001056
Scott Linder58df0e42018-08-08 15:56:12 +00001057 // Advanced by calls to CreateMemberType in increments of FType, then
1058 // returned as the overall size of the default elements.
1059 uint64_t FieldOffset = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00001060
Scott Linder58df0e42018-08-08 15:56:12 +00001061 // Blocks in OpenCL have unique constraints which make the standard fields
1062 // redundant while requiring size and align fields for enqueue_kernel. See
1063 // initializeForBlockHeader in CGBlocks.cpp
Scott Linder2b5cf042018-07-30 20:31:11 +00001064 if (CGM.getLangOpts().OpenCL) {
1065 FType = CGM.getContext().IntTy;
1066 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
1067 EltTys.push_back(CreateMemberType(Unit, FType, "__align", &FieldOffset));
1068 } else {
1069 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1070 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
1071 FType = CGM.getContext().IntTy;
1072 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
1073 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
1074 FType = CGM.getContext().getPointerType(Ty->getPointeeType());
1075 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
1076 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
Scott Linder58df0e42018-08-08 15:56:12 +00001077 uint64_t FieldSize = CGM.getContext().getTypeSize(Ty);
1078 uint32_t FieldAlign = CGM.getContext().getTypeAlign(Ty);
Scott Linder2b5cf042018-07-30 20:31:11 +00001079 EltTys.push_back(DBuilder.createMemberType(
Scott Linder58df0e42018-08-08 15:56:12 +00001080 Unit, "__descriptor", nullptr, LineNo, FieldSize, FieldAlign,
1081 FieldOffset, llvm::DINode::FlagZero, DescTy));
Scott Lindera7c45682018-07-30 22:52:07 +00001082 FieldOffset += FieldSize;
Scott Linder2b5cf042018-07-30 20:31:11 +00001083 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001084
Scott Linder58df0e42018-08-08 15:56:12 +00001085 return FieldOffset;
1086}
1087
1088llvm::DIType *CGDebugInfo::CreateType(const BlockPointerType *Ty,
1089 llvm::DIFile *Unit) {
1090 SmallVector<llvm::Metadata *, 8> EltTys;
1091 QualType FType;
1092 uint64_t FieldOffset;
1093 llvm::DINodeArray Elements;
1094
1095 FieldOffset = 0;
1096 FType = CGM.getContext().UnsignedLongTy;
1097 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
1098 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
1099
1100 Elements = DBuilder.getOrCreateArray(EltTys);
1101 EltTys.clear();
1102
1103 llvm::DINode::DIFlags Flags = llvm::DINode::FlagAppleBlock;
1104
1105 auto *EltTy =
1106 DBuilder.createStructType(Unit, "__block_descriptor", nullptr, 0,
1107 FieldOffset, 0, Flags, nullptr, Elements);
1108
1109 // Bit size, align and offset of the type.
1110 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1111
1112 auto *DescTy = DBuilder.createPointerType(EltTy, Size);
1113
1114 FieldOffset = collectDefaultElementTypesForBlockPointer(Ty, Unit, DescTy,
1115 0, EltTys);
1116
Guy Benyei11169dd2012-12-18 14:30:41 +00001117 Elements = DBuilder.getOrCreateArray(EltTys);
1118
Adrian Prantl3d2c0512015-07-07 00:49:35 +00001119 // The __block_literal_generic structs are marked with a special
1120 // DW_AT_APPLE_BLOCK attribute and are an implementation detail only
1121 // the debugger needs to know about. To allow type uniquing, emit
1122 // them without a name or a location.
Scott Linder58df0e42018-08-08 15:56:12 +00001123 EltTy = DBuilder.createStructType(Unit, "", nullptr, 0, FieldOffset, 0,
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00001124 Flags, nullptr, Elements);
Guy Benyei11169dd2012-12-18 14:30:41 +00001125
Adrian Prantl3d2c0512015-07-07 00:49:35 +00001126 return DBuilder.createPointerType(EltTy, Size);
Guy Benyei11169dd2012-12-18 14:30:41 +00001127}
1128
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001129llvm::DIType *CGDebugInfo::CreateType(const TemplateSpecializationType *Ty,
1130 llvm::DIFile *Unit) {
David Blaikief1b382e2014-04-06 17:14:06 +00001131 assert(Ty->isTypeAlias());
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001132 llvm::DIType *Src = getOrCreateType(Ty->getAliasedType(), Unit);
David Blaikief1b382e2014-04-06 17:14:06 +00001133
David Blaikie8472fa62019-06-08 00:01:21 +00001134 auto *AliasDecl =
1135 cast<TypeAliasTemplateDecl>(Ty->getTemplateName().getAsTemplateDecl())
1136 ->getTemplatedDecl();
1137
1138 if (AliasDecl->hasAttr<NoDebugAttr>())
1139 return Src;
1140
David Blaikief1b382e2014-04-06 17:14:06 +00001141 SmallString<128> NS;
1142 llvm::raw_svector_ostream OS(NS);
Serge Pavlov03e672c2017-11-28 16:14:14 +00001143 Ty->getTemplateName().print(OS, getPrintingPolicy(), /*qualified*/ false);
1144 printTemplateArgumentList(OS, Ty->template_arguments(), getPrintingPolicy());
David Blaikief1b382e2014-04-06 17:14:06 +00001145
David Blaikief1b382e2014-04-06 17:14:06 +00001146 SourceLocation Loc = AliasDecl->getLocation();
Adrian Prantlb67dbce2015-09-11 18:45:02 +00001147 return DBuilder.createTypedef(Src, OS.str(), getOrCreateFile(Loc),
1148 getLineNumber(Loc),
Sam McCalld27a16e2019-11-18 15:53:22 +01001149 getDeclContextDescriptor(AliasDecl));
David Blaikief1b382e2014-04-06 17:14:06 +00001150}
1151
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001152llvm::DIType *CGDebugInfo::CreateType(const TypedefType *Ty,
1153 llvm::DIFile *Unit) {
David Blaikie8472fa62019-06-08 00:01:21 +00001154 llvm::DIType *Underlying =
1155 getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
1156
1157 if (Ty->getDecl()->hasAttr<NoDebugAttr>())
1158 return Underlying;
1159
Guy Benyei11169dd2012-12-18 14:30:41 +00001160 // We don't set size information, but do specify where the typedef was
1161 // declared.
Amjad Abouddc4531e2016-04-30 01:44:38 +00001162 SourceLocation Loc = Ty->getDecl()->getLocation();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001163
Sourabh Singh Tomarf1e39882019-12-03 09:29:54 +05301164 uint32_t Align = getDeclAlignIfRequired(Ty->getDecl(), CGM.getContext());
Duncan P. N. Exon Smith4078ad42015-04-16 16:36:45 +00001165 // Typedefs are derived from some other type.
Sam McCalld27a16e2019-11-18 15:53:22 +01001166 return DBuilder.createTypedef(Underlying, Ty->getDecl()->getName(),
1167 getOrCreateFile(Loc), getLineNumber(Loc),
Sourabh Singh Tomarf1e39882019-12-03 09:29:54 +05301168 getDeclContextDescriptor(Ty->getDecl()), Align);
Guy Benyei11169dd2012-12-18 14:30:41 +00001169}
1170
Reid Klecknerf00f8032016-06-08 20:41:54 +00001171static unsigned getDwarfCC(CallingConv CC) {
1172 switch (CC) {
1173 case CC_C:
1174 // Avoid emitting DW_AT_calling_convention if the C convention was used.
1175 return 0;
1176
1177 case CC_X86StdCall:
1178 return llvm::dwarf::DW_CC_BORLAND_stdcall;
1179 case CC_X86FastCall:
1180 return llvm::dwarf::DW_CC_BORLAND_msfastcall;
1181 case CC_X86ThisCall:
1182 return llvm::dwarf::DW_CC_BORLAND_thiscall;
1183 case CC_X86VectorCall:
1184 return llvm::dwarf::DW_CC_LLVM_vectorcall;
1185 case CC_X86Pascal:
1186 return llvm::dwarf::DW_CC_BORLAND_pascal;
Martin Storsjo022e7822017-07-17 20:49:45 +00001187 case CC_Win64:
Jonas Devliegheref0702682018-03-22 13:53:30 +00001188 return llvm::dwarf::DW_CC_LLVM_Win64;
Reid Klecknerf00f8032016-06-08 20:41:54 +00001189 case CC_X86_64SysV:
Jonas Devliegheref0702682018-03-22 13:53:30 +00001190 return llvm::dwarf::DW_CC_LLVM_X86_64SysV;
Reid Klecknerf00f8032016-06-08 20:41:54 +00001191 case CC_AAPCS:
Sander de Smalen44a22532018-11-26 16:38:37 +00001192 case CC_AArch64VectorCall:
Jonas Devliegheref0702682018-03-22 13:53:30 +00001193 return llvm::dwarf::DW_CC_LLVM_AAPCS;
Reid Klecknerf00f8032016-06-08 20:41:54 +00001194 case CC_AAPCS_VFP:
Jonas Devliegheref0702682018-03-22 13:53:30 +00001195 return llvm::dwarf::DW_CC_LLVM_AAPCS_VFP;
Reid Klecknerf00f8032016-06-08 20:41:54 +00001196 case CC_IntelOclBicc:
Jonas Devliegheref0702682018-03-22 13:53:30 +00001197 return llvm::dwarf::DW_CC_LLVM_IntelOclBicc;
Reid Klecknerf00f8032016-06-08 20:41:54 +00001198 case CC_SpirFunction:
Jonas Devliegheref0702682018-03-22 13:53:30 +00001199 return llvm::dwarf::DW_CC_LLVM_SpirFunction;
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00001200 case CC_OpenCLKernel:
Jonas Devliegheref0702682018-03-22 13:53:30 +00001201 return llvm::dwarf::DW_CC_LLVM_OpenCLKernel;
Reid Klecknerf00f8032016-06-08 20:41:54 +00001202 case CC_Swift:
Jonas Devliegheref0702682018-03-22 13:53:30 +00001203 return llvm::dwarf::DW_CC_LLVM_Swift;
Reid Klecknerf00f8032016-06-08 20:41:54 +00001204 case CC_PreserveMost:
Jonas Devliegheref0702682018-03-22 13:53:30 +00001205 return llvm::dwarf::DW_CC_LLVM_PreserveMost;
Reid Klecknerf00f8032016-06-08 20:41:54 +00001206 case CC_PreserveAll:
Jonas Devliegheref0702682018-03-22 13:53:30 +00001207 return llvm::dwarf::DW_CC_LLVM_PreserveAll;
Erich Keane757d3172016-11-02 18:29:35 +00001208 case CC_X86RegCall:
Jonas Devliegheref0702682018-03-22 13:53:30 +00001209 return llvm::dwarf::DW_CC_LLVM_X86RegCall;
Reid Klecknerf00f8032016-06-08 20:41:54 +00001210 }
1211 return 0;
1212}
1213
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001214llvm::DIType *CGDebugInfo::CreateType(const FunctionType *Ty,
1215 llvm::DIFile *Unit) {
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001216 SmallVector<llvm::Metadata *, 16> EltTys;
Guy Benyei11169dd2012-12-18 14:30:41 +00001217
1218 // Add the result type at least.
Alp Toker314cc812014-01-25 16:55:45 +00001219 EltTys.push_back(getOrCreateType(Ty->getReturnType(), Unit));
Guy Benyei11169dd2012-12-18 14:30:41 +00001220
1221 // Set up remainder of arguments if there is a prototype.
Adrian Prantl800faef2014-02-25 23:42:18 +00001222 // otherwise emit it as a variadic function.
Guy Benyei11169dd2012-12-18 14:30:41 +00001223 if (isa<FunctionNoProtoType>(Ty))
1224 EltTys.push_back(DBuilder.createUnspecifiedParameter());
David Majnemer58ed0f32016-07-17 00:39:12 +00001225 else if (const auto *FPT = dyn_cast<FunctionProtoType>(Ty)) {
1226 for (const QualType &ParamType : FPT->param_types())
1227 EltTys.push_back(getOrCreateType(ParamType, Unit));
Adrian Prantld45ba252014-02-25 19:38:11 +00001228 if (FPT->isVariadic())
1229 EltTys.push_back(DBuilder.createUnspecifiedParameter());
Guy Benyei11169dd2012-12-18 14:30:41 +00001230 }
1231
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001232 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
Leny Kholodov80c047d2016-09-06 10:48:04 +00001233 return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
Reid Klecknerf00f8032016-06-08 20:41:54 +00001234 getDwarfCC(Ty->getCallConv()));
Guy Benyei11169dd2012-12-18 14:30:41 +00001235}
1236
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001237/// Convert an AccessSpecifier into the corresponding DINode flag.
Adrian Prantl21361fb2014-08-29 22:44:27 +00001238/// As an optimization, return 0 if the access specifier equals the
1239/// default for the containing type.
Leny Kholodovdf050fd2016-09-06 17:06:14 +00001240static llvm::DINode::DIFlags getAccessFlag(AccessSpecifier Access,
1241 const RecordDecl *RD) {
Adrian Prantl21361fb2014-08-29 22:44:27 +00001242 AccessSpecifier Default = clang::AS_none;
1243 if (RD && RD->isClass())
1244 Default = clang::AS_private;
1245 else if (RD && (RD->isStruct() || RD->isUnion()))
1246 Default = clang::AS_public;
1247
1248 if (Access == Default)
Leny Kholodov80c047d2016-09-06 10:48:04 +00001249 return llvm::DINode::FlagZero;
Adrian Prantl21361fb2014-08-29 22:44:27 +00001250
Eric Christophere7b87e52014-10-26 23:40:33 +00001251 switch (Access) {
1252 case clang::AS_private:
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001253 return llvm::DINode::FlagPrivate;
Eric Christophere7b87e52014-10-26 23:40:33 +00001254 case clang::AS_protected:
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001255 return llvm::DINode::FlagProtected;
Eric Christophere7b87e52014-10-26 23:40:33 +00001256 case clang::AS_public:
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001257 return llvm::DINode::FlagPublic;
Eric Christophere7b87e52014-10-26 23:40:33 +00001258 case clang::AS_none:
Leny Kholodov80c047d2016-09-06 10:48:04 +00001259 return llvm::DINode::FlagZero;
Adrian Prantl21361fb2014-08-29 22:44:27 +00001260 }
1261 llvm_unreachable("unexpected access enumerator");
1262}
Guy Benyei11169dd2012-12-18 14:30:41 +00001263
David Majnemerb4b671e2016-06-30 03:01:59 +00001264llvm::DIType *CGDebugInfo::createBitFieldType(const FieldDecl *BitFieldDecl,
1265 llvm::DIScope *RecordTy,
1266 const RecordDecl *RD) {
1267 StringRef Name = BitFieldDecl->getName();
1268 QualType Ty = BitFieldDecl->getType();
1269 SourceLocation Loc = BitFieldDecl->getLocation();
1270 llvm::DIFile *VUnit = getOrCreateFile(Loc);
1271 llvm::DIType *DebugType = getOrCreateType(Ty, VUnit);
1272
1273 // Get the location for the field.
1274 llvm::DIFile *File = getOrCreateFile(Loc);
1275 unsigned Line = getLineNumber(Loc);
1276
1277 const CGBitFieldInfo &BitFieldInfo =
1278 CGM.getTypes().getCGRecordLayout(RD).getBitFieldInfo(BitFieldDecl);
1279 uint64_t SizeInBits = BitFieldInfo.Size;
1280 assert(SizeInBits > 0 && "found named 0-width bitfield");
David Majnemerb4b671e2016-06-30 03:01:59 +00001281 uint64_t StorageOffsetInBits =
1282 CGM.getContext().toBits(BitFieldInfo.StorageOffset);
Reid Kleckner06a4b2a2017-06-12 19:57:56 +00001283 uint64_t Offset = BitFieldInfo.Offset;
1284 // The bit offsets for big endian machines are reversed for big
1285 // endian target, compensate for that as the DIDerivedType requires
1286 // un-reversed offsets.
1287 if (CGM.getDataLayout().isBigEndian())
1288 Offset = BitFieldInfo.StorageSize - BitFieldInfo.Size - Offset;
1289 uint64_t OffsetInBits = StorageOffsetInBits + Offset;
Leny Kholodov80c047d2016-09-06 10:48:04 +00001290 llvm::DINode::DIFlags Flags = getAccessFlag(BitFieldDecl->getAccess(), RD);
David Majnemerb4b671e2016-06-30 03:01:59 +00001291 return DBuilder.createBitFieldMemberType(
Victor Leschuka7ece032016-10-20 00:13:19 +00001292 RecordTy, Name, File, Line, SizeInBits, OffsetInBits, StorageOffsetInBits,
1293 Flags, DebugType);
David Majnemerb4b671e2016-06-30 03:01:59 +00001294}
1295
1296llvm::DIType *
1297CGDebugInfo::createFieldType(StringRef name, QualType type, SourceLocation loc,
1298 AccessSpecifier AS, uint64_t offsetInBits,
Victor Leschuka7ece032016-10-20 00:13:19 +00001299 uint32_t AlignInBits, llvm::DIFile *tunit,
1300 llvm::DIScope *scope, const RecordDecl *RD) {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001301 llvm::DIType *debugType = getOrCreateType(type, tunit);
Guy Benyei11169dd2012-12-18 14:30:41 +00001302
1303 // Get the location for the field.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001304 llvm::DIFile *file = getOrCreateFile(loc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001305 unsigned line = getLineNumber(loc);
1306
David Majnemer34b57492014-07-30 01:30:47 +00001307 uint64_t SizeInBits = 0;
Victor Leschuka7ece032016-10-20 00:13:19 +00001308 auto Align = AlignInBits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001309 if (!type->isIncompleteArrayType()) {
David Majnemer34b57492014-07-30 01:30:47 +00001310 TypeInfo TI = CGM.getContext().getTypeInfo(type);
1311 SizeInBits = TI.Width;
Victor Leschuka7ece032016-10-20 00:13:19 +00001312 if (!Align)
1313 Align = getTypeAlignIfRequired(type, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00001314 }
1315
Leny Kholodov80c047d2016-09-06 10:48:04 +00001316 llvm::DINode::DIFlags flags = getAccessFlag(AS, RD);
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00001317 return DBuilder.createMemberType(scope, name, file, line, SizeInBits, Align,
1318 offsetInBits, flags, debugType);
Guy Benyei11169dd2012-12-18 14:30:41 +00001319}
1320
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001321void CGDebugInfo::CollectRecordLambdaFields(
1322 const CXXRecordDecl *CXXDecl, SmallVectorImpl<llvm::Metadata *> &elements,
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001323 llvm::DIType *RecordTy) {
Eric Christopher91a31902013-01-16 01:22:32 +00001324 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
1325 // has the name and the location of the variable so we should iterate over
1326 // both concurrently.
1327 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
1328 RecordDecl::field_iterator Field = CXXDecl->field_begin();
1329 unsigned fieldno = 0;
1330 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
Eric Christophere7b87e52014-10-26 23:40:33 +00001331 E = CXXDecl->captures_end();
1332 I != E; ++I, ++Field, ++fieldno) {
Benjamin Kramerf3ca26982014-05-10 16:31:55 +00001333 const LambdaCapture &C = *I;
Eric Christopher91a31902013-01-16 01:22:32 +00001334 if (C.capturesVariable()) {
David Majnemerb4b671e2016-06-30 03:01:59 +00001335 SourceLocation Loc = C.getLocation();
1336 assert(!Field->isBitField() && "lambdas don't have bitfield members!");
Eric Christopher91a31902013-01-16 01:22:32 +00001337 VarDecl *V = C.getCapturedVar();
Eric Christopher91a31902013-01-16 01:22:32 +00001338 StringRef VName = V->getName();
David Majnemerb4b671e2016-06-30 03:01:59 +00001339 llvm::DIFile *VUnit = getOrCreateFile(Loc);
Victor Leschuka7ece032016-10-20 00:13:19 +00001340 auto Align = getDeclAlignIfRequired(V, CGM.getContext());
David Majnemerb4b671e2016-06-30 03:01:59 +00001341 llvm::DIType *FieldType = createFieldType(
1342 VName, Field->getType(), Loc, Field->getAccess(),
Victor Leschuka7ece032016-10-20 00:13:19 +00001343 layout.getFieldOffset(fieldno), Align, VUnit, RecordTy, CXXDecl);
David Majnemerb4b671e2016-06-30 03:01:59 +00001344 elements.push_back(FieldType);
Alexey Bataev39c81e22014-08-28 04:28:19 +00001345 } else if (C.capturesThis()) {
Eric Christopher91a31902013-01-16 01:22:32 +00001346 // TODO: Need to handle 'this' in some way by probably renaming the
1347 // this of the lambda class and having a field member of 'this' or
1348 // by using AT_object_pointer for the function and having that be
1349 // used as 'this' for semantic references.
Eric Christopher91a31902013-01-16 01:22:32 +00001350 FieldDecl *f = *Field;
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001351 llvm::DIFile *VUnit = getOrCreateFile(f->getLocation());
Eric Christopher91a31902013-01-16 01:22:32 +00001352 QualType type = f->getType();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001353 llvm::DIType *fieldType = createFieldType(
David Majnemerb4b671e2016-06-30 03:01:59 +00001354 "this", type, f->getLocation(), f->getAccess(),
Eric Christophere7b87e52014-10-26 23:40:33 +00001355 layout.getFieldOffset(fieldno), VUnit, RecordTy, CXXDecl);
Eric Christopher91a31902013-01-16 01:22:32 +00001356
1357 elements.push_back(fieldType);
1358 }
1359 }
1360}
1361
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001362llvm::DIDerivedType *
1363CGDebugInfo::CreateRecordStaticField(const VarDecl *Var, llvm::DIType *RecordTy,
Duncan P. N. Exon Smithc09c5482015-04-20 21:17:26 +00001364 const RecordDecl *RD) {
Eric Christopher91a31902013-01-16 01:22:32 +00001365 // Create the descriptor for the static variable, with or without
1366 // constant initializers.
David Blaikie8e707bb2014-10-14 22:22:17 +00001367 Var = Var->getCanonicalDecl();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001368 llvm::DIFile *VUnit = getOrCreateFile(Var->getLocation());
1369 llvm::DIType *VTy = getOrCreateType(Var->getType(), VUnit);
Eric Christopher91a31902013-01-16 01:22:32 +00001370
Eric Christopher91a31902013-01-16 01:22:32 +00001371 unsigned LineNumber = getLineNumber(Var->getLocation());
1372 StringRef VName = Var->getName();
Craig Topper8a13c412014-05-21 05:09:00 +00001373 llvm::Constant *C = nullptr;
Eric Christopher91a31902013-01-16 01:22:32 +00001374 if (Var->getInit()) {
1375 const APValue *Value = Var->evaluateValue();
David Blaikied42917f2013-01-20 01:19:17 +00001376 if (Value) {
1377 if (Value->isInt())
1378 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
1379 if (Value->isFloat())
1380 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
1381 }
Eric Christopher91a31902013-01-16 01:22:32 +00001382 }
1383
Leny Kholodov80c047d2016-09-06 10:48:04 +00001384 llvm::DINode::DIFlags Flags = getAccessFlag(Var->getAccess(), RD);
Victor Leschuka7ece032016-10-20 00:13:19 +00001385 auto Align = getDeclAlignIfRequired(Var, CGM.getContext());
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001386 llvm::DIDerivedType *GV = DBuilder.createStaticMemberType(
Victor Leschuka7ece032016-10-20 00:13:19 +00001387 RecordTy, VName, VUnit, LineNumber, VTy, Flags, C, Align);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001388 StaticDataMemberCache[Var->getCanonicalDecl()].reset(GV);
David Blaikieae019462013-08-15 22:50:29 +00001389 return GV;
Eric Christopher91a31902013-01-16 01:22:32 +00001390}
1391
Eric Christophere7b87e52014-10-26 23:40:33 +00001392void CGDebugInfo::CollectRecordNormalField(
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001393 const FieldDecl *field, uint64_t OffsetInBits, llvm::DIFile *tunit,
1394 SmallVectorImpl<llvm::Metadata *> &elements, llvm::DIType *RecordTy,
Eric Christophere7b87e52014-10-26 23:40:33 +00001395 const RecordDecl *RD) {
Eric Christopher91a31902013-01-16 01:22:32 +00001396 StringRef name = field->getName();
1397 QualType type = field->getType();
1398
1399 // Ignore unnamed fields unless they're anonymous structs/unions.
1400 if (name.empty() && !type->isRecordType())
1401 return;
1402
David Majnemerb4b671e2016-06-30 03:01:59 +00001403 llvm::DIType *FieldType;
Eric Christopher91a31902013-01-16 01:22:32 +00001404 if (field->isBitField()) {
David Majnemerb4b671e2016-06-30 03:01:59 +00001405 FieldType = createBitFieldType(field, RecordTy, RD);
1406 } else {
Victor Leschuka7ece032016-10-20 00:13:19 +00001407 auto Align = getDeclAlignIfRequired(field, CGM.getContext());
David Majnemerb4b671e2016-06-30 03:01:59 +00001408 FieldType =
1409 createFieldType(name, type, field->getLocation(), field->getAccess(),
Victor Leschuka7ece032016-10-20 00:13:19 +00001410 OffsetInBits, Align, tunit, RecordTy, RD);
Eric Christopher91a31902013-01-16 01:22:32 +00001411 }
1412
David Majnemerb4b671e2016-06-30 03:01:59 +00001413 elements.push_back(FieldType);
Eric Christopher91a31902013-01-16 01:22:32 +00001414}
1415
Reid Klecknere2e82062017-08-08 20:30:14 +00001416void CGDebugInfo::CollectRecordNestedType(
1417 const TypeDecl *TD, SmallVectorImpl<llvm::Metadata *> &elements) {
1418 QualType Ty = CGM.getContext().getTypeDeclType(TD);
Reid Kleckner755220b2016-08-01 18:56:13 +00001419 // Injected class names are not considered nested records.
1420 if (isa<InjectedClassNameType>(Ty))
1421 return;
Reid Klecknere2e82062017-08-08 20:30:14 +00001422 SourceLocation Loc = TD->getLocation();
Adrian McCarthyab1e7862016-07-21 18:43:20 +00001423 llvm::DIType *nestedType = getOrCreateType(Ty, getOrCreateFile(Loc));
1424 elements.push_back(nestedType);
1425}
1426
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001427void CGDebugInfo::CollectRecordFields(
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001428 const RecordDecl *record, llvm::DIFile *tunit,
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001429 SmallVectorImpl<llvm::Metadata *> &elements,
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001430 llvm::DICompositeType *RecordTy) {
David Majnemer58ed0f32016-07-17 00:39:12 +00001431 const auto *CXXDecl = dyn_cast<CXXRecordDecl>(record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001432
Eric Christopher91a31902013-01-16 01:22:32 +00001433 if (CXXDecl && CXXDecl->isLambda())
1434 CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
1435 else {
1436 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001437
Eric Christopher91a31902013-01-16 01:22:32 +00001438 // Field number for non-static fields.
Eric Christopher0f7594372013-01-04 17:59:07 +00001439 unsigned fieldNo = 0;
Eric Christopher91a31902013-01-16 01:22:32 +00001440
Eric Christopher91a31902013-01-16 01:22:32 +00001441 // Static and non-static members should appear in the same order as
1442 // the corresponding declarations in the source program.
Aaron Ballman629afae2014-03-07 19:56:05 +00001443 for (const auto *I : record->decls())
1444 if (const auto *V = dyn_cast<VarDecl>(I)) {
Paul Robinsonb17327d2016-04-27 17:37:12 +00001445 if (V->hasAttr<NoDebugAttr>())
1446 continue;
Reid Kleckner891b2712018-07-20 20:55:00 +00001447
1448 // Skip variable template specializations when emitting CodeView. MSVC
1449 // doesn't emit them.
1450 if (CGM.getCodeGenOpts().EmitCodeView &&
1451 isa<VarTemplateSpecializationDecl>(V))
1452 continue;
1453
David Blaikie4f3b7362019-06-17 19:40:52 +00001454 if (isa<VarTemplatePartialSpecializationDecl>(V))
1455 continue;
1456
David Blaikiece763042013-08-20 21:49:21 +00001457 // Reuse the existing static member declaration if one exists
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001458 auto MI = StaticDataMemberCache.find(V->getCanonicalDecl());
David Blaikiece763042013-08-20 21:49:21 +00001459 if (MI != StaticDataMemberCache.end()) {
1460 assert(MI->second &&
1461 "Static data member declaration should still exist");
Duncan P. N. Exon Smithac346ba2015-07-24 18:05:58 +00001462 elements.push_back(MI->second);
Adrian Prantl21361fb2014-08-29 22:44:27 +00001463 } else {
1464 auto Field = CreateRecordStaticField(V, RecordTy, record);
1465 elements.push_back(Field);
1466 }
Aaron Ballman629afae2014-03-07 19:56:05 +00001467 } else if (const auto *field = dyn_cast<FieldDecl>(I)) {
Eric Christophere7b87e52014-10-26 23:40:33 +00001468 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo), tunit,
1469 elements, RecordTy, record);
Eric Christopher91a31902013-01-16 01:22:32 +00001470
1471 // Bump field number for next field.
1472 ++fieldNo;
Reid Kleckner891b2712018-07-20 20:55:00 +00001473 } else if (CGM.getCodeGenOpts().EmitCodeView) {
1474 // Debug info for nested types is included in the member list only for
1475 // CodeView.
Reid Klecknere2e82062017-08-08 20:30:14 +00001476 if (const auto *nestedType = dyn_cast<TypeDecl>(I))
1477 if (!nestedType->isImplicit() &&
1478 nestedType->getDeclContext() == record)
1479 CollectRecordNestedType(nestedType, elements);
1480 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001481 }
1482}
1483
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001484llvm::DISubroutineType *
Guy Benyei11169dd2012-12-18 14:30:41 +00001485CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
Awanish Pandeyc83602f2020-01-23 16:06:52 +05301486 llvm::DIFile *Unit, bool decl) {
David Blaikie7eb06852013-01-07 23:06:35 +00001487 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
David Blaikie2aaf0652013-01-07 22:24:59 +00001488 if (Method->isStatic())
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001489 return cast_or_null<llvm::DISubroutineType>(
Duncan P. N. Exon Smithc7551282015-04-06 23:21:33 +00001490 getOrCreateType(QualType(Func, 0), Unit));
Awanish Pandeyc83602f2020-01-23 16:06:52 +05301491 return getOrCreateInstanceMethodType(Method->getThisType(), Func, Unit, decl);
David Blaikie7eb06852013-01-07 23:06:35 +00001492}
David Blaikie2aaf0652013-01-07 22:24:59 +00001493
Awanish Pandeyc83602f2020-01-23 16:06:52 +05301494llvm::DISubroutineType *
1495CGDebugInfo::getOrCreateInstanceMethodType(QualType ThisPtr,
1496 const FunctionProtoType *Func,
1497 llvm::DIFile *Unit, bool decl) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001498 // Add "this" pointer.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001499 llvm::DITypeRefArray Args(
1500 cast<llvm::DISubroutineType>(getOrCreateType(QualType(Func, 0), Unit))
Duncan P. N. Exon Smithc7551282015-04-06 23:21:33 +00001501 ->getTypeArray());
Duncan P. N. Exon Smitha98fac62015-04-07 04:14:45 +00001502 assert(Args.size() && "Invalid number of arguments!");
Guy Benyei11169dd2012-12-18 14:30:41 +00001503
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001504 SmallVector<llvm::Metadata *, 16> Elts;
Guy Benyei11169dd2012-12-18 14:30:41 +00001505 // First element is always return type. For 'void' functions it is NULL.
Awanish Pandeyc83602f2020-01-23 16:06:52 +05301506 QualType temp = Func->getReturnType();
1507 if (temp->getTypeClass() == Type::Auto && decl)
1508 Elts.push_back(CreateType(cast<AutoType>(temp)));
1509 else
1510 Elts.push_back(Args[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001511
David Blaikie2aaf0652013-01-07 22:24:59 +00001512 // "this" pointer is always first argument.
David Blaikie7eb06852013-01-07 23:06:35 +00001513 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
David Blaikie2aaf0652013-01-07 22:24:59 +00001514 if (isa<ClassTemplateSpecializationDecl>(RD)) {
1515 // Create pointer type directly in this case.
1516 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
1517 QualType PointeeTy = ThisPtrTy->getPointeeType();
1518 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCallc8e01702013-04-16 22:48:15 +00001519 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
Victor Leschuka7ece032016-10-20 00:13:19 +00001520 auto Align = getTypeAlignIfRequired(ThisPtrTy, CGM.getContext());
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001521 llvm::DIType *PointeeType = getOrCreateType(PointeeTy, Unit);
1522 llvm::DIType *ThisPtrType =
Eric Christophere7b87e52014-10-26 23:40:33 +00001523 DBuilder.createPointerType(PointeeType, Size, Align);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001524 TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);
David Blaikie2aaf0652013-01-07 22:24:59 +00001525 // TODO: This and the artificial type below are misleading, the
1526 // types aren't artificial the argument is, but the current
1527 // metadata doesn't represent that.
1528 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1529 Elts.push_back(ThisPtrType);
1530 } else {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001531 llvm::DIType *ThisPtrType = getOrCreateType(ThisPtr, Unit);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001532 TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);
David Blaikie2aaf0652013-01-07 22:24:59 +00001533 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1534 Elts.push_back(ThisPtrType);
Guy Benyei11169dd2012-12-18 14:30:41 +00001535 }
1536
1537 // Copy rest of the arguments.
Duncan P. N. Exon Smitha98fac62015-04-07 04:14:45 +00001538 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1539 Elts.push_back(Args[i]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001540
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001541 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
Guy Benyei11169dd2012-12-18 14:30:41 +00001542
Leny Kholodov80c047d2016-09-06 10:48:04 +00001543 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
Adrian Prantl0630eb72013-12-18 21:48:18 +00001544 if (Func->getExtProtoInfo().RefQualifier == RQ_LValue)
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001545 Flags |= llvm::DINode::FlagLValueReference;
Adrian Prantl0630eb72013-12-18 21:48:18 +00001546 if (Func->getExtProtoInfo().RefQualifier == RQ_RValue)
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001547 Flags |= llvm::DINode::FlagRValueReference;
Adrian Prantl0630eb72013-12-18 21:48:18 +00001548
Reid Klecknerf00f8032016-06-08 20:41:54 +00001549 return DBuilder.createSubroutineType(EltTypeArray, Flags,
1550 getDwarfCC(Func->getCallConv()));
Guy Benyei11169dd2012-12-18 14:30:41 +00001551}
1552
Eric Christopherb2a008c2013-05-16 00:45:12 +00001553/// isFunctionLocalClass - Return true if CXXRecordDecl is defined
Guy Benyei11169dd2012-12-18 14:30:41 +00001554/// inside a function.
1555static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
David Majnemer58ed0f32016-07-17 00:39:12 +00001556 if (const auto *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
Guy Benyei11169dd2012-12-18 14:30:41 +00001557 return isFunctionLocalClass(NRD);
1558 if (isa<FunctionDecl>(RD->getDeclContext()))
1559 return true;
1560 return false;
1561}
1562
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001563llvm::DISubprogram *CGDebugInfo::CreateCXXMemberFunction(
1564 const CXXMethodDecl *Method, llvm::DIFile *Unit, llvm::DIType *RecordTy) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001565 bool IsCtorOrDtor =
Eric Christophere7b87e52014-10-26 23:40:33 +00001566 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
Eric Christopherb2a008c2013-05-16 00:45:12 +00001567
Guy Benyei11169dd2012-12-18 14:30:41 +00001568 StringRef MethodName = getFunctionName(Method);
Awanish Pandeyc83602f2020-01-23 16:06:52 +05301569 llvm::DISubroutineType *MethodTy = getOrCreateMethodType(Method, Unit, true);
Guy Benyei11169dd2012-12-18 14:30:41 +00001570
1571 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1572 // make sense to give a single ctor/dtor a linkage name.
1573 StringRef MethodLinkageName;
David Blaikie71647672016-04-12 21:22:48 +00001574 // FIXME: 'isFunctionLocalClass' seems like an arbitrary/unintentional
1575 // property to use here. It may've been intended to model "is non-external
1576 // type" but misses cases of non-function-local but non-external classes such
1577 // as those in anonymous namespaces as well as the reverse - external types
1578 // that are function local, such as those in (non-local) inline functions.
Guy Benyei11169dd2012-12-18 14:30:41 +00001579 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1580 MethodLinkageName = CGM.getMangledName(Method);
1581
1582 // Get the location for the method.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001583 llvm::DIFile *MethodDefUnit = nullptr;
David Blaikie7fceebf2013-08-19 03:37:48 +00001584 unsigned MethodLine = 0;
1585 if (!Method->isImplicit()) {
1586 MethodDefUnit = getOrCreateFile(Method->getLocation());
1587 MethodLine = getLineNumber(Method->getLocation());
1588 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001589
1590 // Collect virtual method info.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001591 llvm::DIType *ContainingType = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001592 unsigned VIndex = 0;
Leny Kholodov80c047d2016-09-06 10:48:04 +00001593 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
Paul Robinsoncda54212018-11-19 18:29:28 +00001594 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
Reid Kleckner0358cbf2016-07-01 02:41:25 +00001595 int ThisAdjustment = 0;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001596
Guy Benyei11169dd2012-12-18 14:30:41 +00001597 if (Method->isVirtual()) {
1598 if (Method->isPure())
Paul Robinsoncda54212018-11-19 18:29:28 +00001599 SPFlags |= llvm::DISubprogram::SPFlagPureVirtual;
Guy Benyei11169dd2012-12-18 14:30:41 +00001600 else
Paul Robinsoncda54212018-11-19 18:29:28 +00001601 SPFlags |= llvm::DISubprogram::SPFlagVirtual;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001602
Reid Kleckner216d0a12016-06-16 20:08:51 +00001603 if (CGM.getTarget().getCXXABI().isItaniumFamily()) {
1604 // It doesn't make sense to give a virtual destructor a vtable index,
1605 // since a single destructor has two entries in the vtable.
1606 if (!isa<CXXDestructorDecl>(Method))
1607 VIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(Method);
1608 } else {
1609 // Emit MS ABI vftable information. There is only one entry for the
1610 // deleting dtor.
1611 const auto *DD = dyn_cast<CXXDestructorDecl>(Method);
1612 GlobalDecl GD = DD ? GlobalDecl(DD, Dtor_Deleting) : GlobalDecl(Method);
Reid Klecknercbec0262018-04-02 20:00:39 +00001613 MethodVFTableLocation ML =
Reid Kleckner216d0a12016-06-16 20:08:51 +00001614 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD);
1615 VIndex = ML.Index;
Reid Klecknerc4871ed2016-06-22 18:34:45 +00001616
1617 // CodeView only records the vftable offset in the class that introduces
1618 // the virtual method. This is possible because, unlike Itanium, the MS
1619 // C++ ABI does not include all virtual methods from non-primary bases in
1620 // the vtable for the most derived class. For example, if C inherits from
1621 // A and B, C's primary vftable will not include B's virtual methods.
Benjamin Krameracfa3392017-12-17 23:52:45 +00001622 if (Method->size_overridden_methods() == 0)
Reid Klecknerc4871ed2016-06-22 18:34:45 +00001623 Flags |= llvm::DINode::FlagIntroducedVirtual;
1624
Reid Kleckner0358cbf2016-07-01 02:41:25 +00001625 // The 'this' adjustment accounts for both the virtual and non-virtual
1626 // portions of the adjustment. Presumably the debugger only uses it when
1627 // it knows the dynamic type of an object.
1628 ThisAdjustment = CGM.getCXXABI()
1629 .getVirtualFunctionPrologueThisAdjustment(GD)
1630 .getQuantity();
Reid Kleckner216d0a12016-06-16 20:08:51 +00001631 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001632 ContainingType = RecordTy;
1633 }
1634
Adrian Prantlf919be32019-10-29 09:20:14 -07001635 // We're checking for deleted C++ special member functions
1636 // [Ctors,Dtors, Copy/Move]
Sourabh Singh Tomar52ea3082019-11-02 01:28:40 +05301637 auto checkAttrDeleted = [&](const auto *Method) {
Adrian Prantlf919be32019-10-29 09:20:14 -07001638 if (Method->getCanonicalDecl()->isDeleted())
1639 SPFlags |= llvm::DISubprogram::SPFlagDeleted;
1640 };
1641
1642 switch (Method->getKind()) {
1643
1644 case Decl::CXXConstructor:
1645 case Decl::CXXDestructor:
1646 checkAttrDeleted(Method);
1647 break;
1648 case Decl::CXXMethod:
1649 if (Method->isCopyAssignmentOperator() ||
1650 Method->isMoveAssignmentOperator())
1651 checkAttrDeleted(Method);
1652 break;
1653 default:
1654 break;
1655 }
1656
Adrian Prantla9cfde12019-10-16 16:30:38 +00001657 if (Method->isNoReturn())
1658 Flags |= llvm::DINode::FlagNoReturn;
Adrian Prantlf919be32019-10-29 09:20:14 -07001659
Adrian McCarthyd91bf392017-09-13 20:53:55 +00001660 if (Method->isStatic())
1661 Flags |= llvm::DINode::FlagStaticMember;
Guy Benyei11169dd2012-12-18 14:30:41 +00001662 if (Method->isImplicit())
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001663 Flags |= llvm::DINode::FlagArtificial;
Adrian Prantl21361fb2014-08-29 22:44:27 +00001664 Flags |= getAccessFlag(Method->getAccess(), Method->getParent());
David Majnemer58ed0f32016-07-17 00:39:12 +00001665 if (const auto *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001666 if (CXXC->isExplicit())
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001667 Flags |= llvm::DINode::FlagExplicit;
David Majnemer58ed0f32016-07-17 00:39:12 +00001668 } else if (const auto *CXXC = dyn_cast<CXXConversionDecl>(Method)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001669 if (CXXC->isExplicit())
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001670 Flags |= llvm::DINode::FlagExplicit;
Guy Benyei11169dd2012-12-18 14:30:41 +00001671 }
1672 if (Method->hasPrototype())
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001673 Flags |= llvm::DINode::FlagPrototyped;
Adrian Prantl0630eb72013-12-18 21:48:18 +00001674 if (Method->getRefQualifier() == RQ_LValue)
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001675 Flags |= llvm::DINode::FlagLValueReference;
Adrian Prantl0630eb72013-12-18 21:48:18 +00001676 if (Method->getRefQualifier() == RQ_RValue)
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001677 Flags |= llvm::DINode::FlagRValueReference;
Paul Robinsoncda54212018-11-19 18:29:28 +00001678 if (CGM.getLangOpts().Optimize)
1679 SPFlags |= llvm::DISubprogram::SPFlagOptimized;
Guy Benyei11169dd2012-12-18 14:30:41 +00001680
Amy Huang651128f2020-01-03 16:28:48 -08001681 // In this debug mode, emit type info for a class when its constructor type
1682 // info is emitted.
1683 if (DebugKind == codegenoptions::DebugInfoConstructor)
1684 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
1685 completeClass(CD->getParent());
1686
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001687 llvm::DINodeArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1688 llvm::DISubprogram *SP = DBuilder.createMethod(
Eric Christophere7b87e52014-10-26 23:40:33 +00001689 RecordTy, MethodName, MethodLinkageName, MethodDefUnit, MethodLine,
Paul Robinsoncda54212018-11-19 18:29:28 +00001690 MethodTy, VIndex, ThisAdjustment, ContainingType, Flags, SPFlags,
Reid Kleckner0358cbf2016-07-01 02:41:25 +00001691 TParamsArray.get());
Eric Christopherb2a008c2013-05-16 00:45:12 +00001692
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001693 SPCache[Method->getCanonicalDecl()].reset(SP);
Guy Benyei11169dd2012-12-18 14:30:41 +00001694
1695 return SP;
1696}
1697
Eric Christophere7b87e52014-10-26 23:40:33 +00001698void CGDebugInfo::CollectCXXMemberFunctions(
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001699 const CXXRecordDecl *RD, llvm::DIFile *Unit,
1700 SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001701
1702 // Since we want more than just the individual member decls if we
1703 // have templated functions iterate over every declaration to gather
1704 // the functions.
Eric Christophere7b87e52014-10-26 23:40:33 +00001705 for (const auto *I : RD->decls()) {
David Blaikiefd580722014-10-06 05:18:55 +00001706 const auto *Method = dyn_cast<CXXMethodDecl>(I);
1707 // If the member is implicit, don't add it to the member list. This avoids
1708 // the member being added to type units by LLVM, while still allowing it
1709 // to be emitted into the type declaration/reference inside the compile
1710 // unit.
Paul Robinson6a7511b2015-06-25 17:50:43 +00001711 // Ditto 'nodebug' methods, for consistency with CodeGenFunction.cpp.
David Blaikie6dddfe32014-10-06 05:52:27 +00001712 // FIXME: Handle Using(Shadow?)Decls here to create
1713 // DW_TAG_imported_declarations inside the class for base decls brought into
1714 // derived classes. GDB doesn't seem to notice/leverage these when I tried
1715 // it, so I'm not rushing to fix this. (GCC seems to produce them, if
1716 // referenced)
Paul Robinson6a7511b2015-06-25 17:50:43 +00001717 if (!Method || Method->isImplicit() || Method->hasAttr<NoDebugAttr>())
David Blaikiefd580722014-10-06 05:18:55 +00001718 continue;
David Blaikie42edade2014-11-11 20:44:45 +00001719
Simon Pilgrim7e38f0c2019-10-07 16:42:25 +00001720 if (Method->getType()->castAs<FunctionProtoType>()->getContainedAutoType())
David Blaikie42edade2014-11-11 20:44:45 +00001721 continue;
1722
David Blaikiefd580722014-10-06 05:18:55 +00001723 // Reuse the existing member function declaration if it exists.
1724 // It may be associated with the declaration of the type & should be
1725 // reused as we're building the definition.
1726 //
1727 // This situation can arise in the vtable-based debug info reduction where
1728 // implicit members are emitted in a non-vtable TU.
1729 auto MI = SPCache.find(Method->getCanonicalDecl());
1730 EltTys.push_back(MI == SPCache.end()
1731 ? CreateCXXMemberFunction(Method, Unit, RecordTy)
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001732 : static_cast<llvm::Metadata *>(MI->second));
Guy Benyei11169dd2012-12-18 14:30:41 +00001733 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00001734}
Guy Benyei11169dd2012-12-18 14:30:41 +00001735
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001736void CGDebugInfo::CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile *Unit,
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001737 SmallVectorImpl<llvm::Metadata *> &EltTys,
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001738 llvm::DIType *RecordTy) {
Bob Haarmandff36732016-10-25 22:19:32 +00001739 llvm::DenseSet<CanonicalDeclPtr<const CXXRecordDecl>> SeenTypes;
1740 CollectCXXBasesAux(RD, Unit, EltTys, RecordTy, RD->bases(), SeenTypes,
1741 llvm::DINode::FlagZero);
Eric Christopherb2a008c2013-05-16 00:45:12 +00001742
Bob Haarmandff36732016-10-25 22:19:32 +00001743 // If we are generating CodeView debug info, we also need to emit records for
1744 // indirect virtual base classes.
1745 if (CGM.getCodeGenOpts().EmitCodeView) {
1746 CollectCXXBasesAux(RD, Unit, EltTys, RecordTy, RD->vbases(), SeenTypes,
1747 llvm::DINode::FlagIndirectVirtualBase);
1748 }
1749}
1750
1751void CGDebugInfo::CollectCXXBasesAux(
1752 const CXXRecordDecl *RD, llvm::DIFile *Unit,
1753 SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy,
1754 const CXXRecordDecl::base_class_const_range &Bases,
1755 llvm::DenseSet<CanonicalDeclPtr<const CXXRecordDecl>> &SeenTypes,
1756 llvm::DINode::DIFlags StartingFlags) {
1757 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1758 for (const auto &BI : Bases) {
David Majnemer58ed0f32016-07-17 00:39:12 +00001759 const auto *Base =
Simon Pilgrim1cd399c2019-10-03 11:22:48 +00001760 cast<CXXRecordDecl>(BI.getType()->castAs<RecordType>()->getDecl());
Bob Haarmandff36732016-10-25 22:19:32 +00001761 if (!SeenTypes.insert(Base).second)
1762 continue;
1763 auto *BaseTy = getOrCreateType(BI.getType(), Unit);
1764 llvm::DINode::DIFlags BFlags = StartingFlags;
1765 uint64_t BaseOffset;
Brock Wyma3db2b102018-05-14 21:21:22 +00001766 uint32_t VBPtrOffset = 0;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001767
Aaron Ballman574705e2014-03-13 15:41:46 +00001768 if (BI.isVirtual()) {
Reid Klecknerd3b23d62014-08-07 21:29:25 +00001769 if (CGM.getTarget().getCXXABI().isItaniumFamily()) {
1770 // virtual base offset offset is -ve. The code generator emits dwarf
1771 // expression where it expects +ve number.
Eric Christophere7b87e52014-10-26 23:40:33 +00001772 BaseOffset = 0 - CGM.getItaniumVTableContext()
1773 .getVirtualBaseOffsetOffset(RD, Base)
1774 .getQuantity();
Reid Klecknerd3b23d62014-08-07 21:29:25 +00001775 } else {
1776 // In the MS ABI, store the vbtable offset, which is analogous to the
1777 // vbase offset offset in Itanium.
1778 BaseOffset =
1779 4 * CGM.getMicrosoftVTableContext().getVBTableIndex(RD, Base);
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00001780 VBPtrOffset = CGM.getContext()
1781 .getASTRecordLayout(RD)
1782 .getVBPtrOffset()
1783 .getQuantity();
Reid Klecknerd3b23d62014-08-07 21:29:25 +00001784 }
Bob Haarmandff36732016-10-25 22:19:32 +00001785 BFlags |= llvm::DINode::FlagVirtual;
Guy Benyei11169dd2012-12-18 14:30:41 +00001786 } else
1787 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1788 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1789 // BI->isVirtual() and bits when not.
Eric Christopherb2a008c2013-05-16 00:45:12 +00001790
Adrian Prantl21361fb2014-08-29 22:44:27 +00001791 BFlags |= getAccessFlag(BI.getAccessSpecifier(), RD);
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00001792 llvm::DIType *DTy = DBuilder.createInheritance(RecordTy, BaseTy, BaseOffset,
1793 VBPtrOffset, BFlags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001794 EltTys.push_back(DTy);
1795 }
1796}
1797
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001798llvm::DINodeArray
Eric Christophere7b87e52014-10-26 23:40:33 +00001799CGDebugInfo::CollectTemplateParams(const TemplateParameterList *TPList,
1800 ArrayRef<TemplateArgument> TAList,
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001801 llvm::DIFile *Unit) {
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001802 SmallVector<llvm::Metadata *, 16> TemplateParams;
Guy Benyei11169dd2012-12-18 14:30:41 +00001803 for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1804 const TemplateArgument &TA = TAList[i];
David Blaikie47c11502013-06-22 18:59:18 +00001805 StringRef Name;
Awanish Pandey7a42bab2020-03-02 10:52:12 +05301806 bool defaultParameter = false;
David Blaikie47c11502013-06-22 18:59:18 +00001807 if (TPList)
1808 Name = TPList->getParam(i)->getName();
David Blaikie38079fd2013-05-10 21:53:14 +00001809 switch (TA.getKind()) {
1810 case TemplateArgument::Type: {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001811 llvm::DIType *TTy = getOrCreateType(TA.getAsType(), Unit);
Awanish Pandey7a42bab2020-03-02 10:52:12 +05301812
1813 if (TPList)
1814 if (auto *templateType =
1815 dyn_cast_or_null<TemplateTypeParmDecl>(TPList->getParam(i)))
1816 if (templateType->hasDefaultArgument())
1817 defaultParameter =
1818 templateType->getDefaultArgument() == TA.getAsType();
1819
1820 TemplateParams.push_back(DBuilder.createTemplateTypeParameter(
1821 TheCU, Name, TTy, defaultParameter));
1822
David Blaikie38079fd2013-05-10 21:53:14 +00001823 } break;
1824 case TemplateArgument::Integral: {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001825 llvm::DIType *TTy = getOrCreateType(TA.getIntegralType(), Unit);
Awanish Pandey7a42bab2020-03-02 10:52:12 +05301826 if (TPList && CGM.getCodeGenOpts().DwarfVersion >= 5)
1827 if (auto *templateType =
1828 dyn_cast_or_null<NonTypeTemplateParmDecl>(TPList->getParam(i)))
David Blaikiee9644e62020-04-05 12:49:02 -07001829 if (templateType->hasDefaultArgument() &&
1830 !templateType->getDefaultArgument()->isValueDependent())
David Blaikiedb927192020-04-01 13:00:12 -07001831 defaultParameter = llvm::APSInt::isSameValue(
Awanish Pandey7a42bab2020-03-02 10:52:12 +05301832 templateType->getDefaultArgument()->EvaluateKnownConstInt(
David Blaikiedb927192020-04-01 13:00:12 -07001833 CGM.getContext()),
1834 TA.getAsIntegral());
Awanish Pandey7a42bab2020-03-02 10:52:12 +05301835
Duncan P. N. Exon Smithdadc2b62015-04-21 18:43:54 +00001836 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
Awanish Pandey7a42bab2020-03-02 10:52:12 +05301837 TheCU, Name, TTy, defaultParameter,
Duncan P. N. Exon Smithdadc2b62015-04-21 18:43:54 +00001838 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral())));
David Blaikie38079fd2013-05-10 21:53:14 +00001839 } break;
1840 case TemplateArgument::Declaration: {
1841 const ValueDecl *D = TA.getAsDecl();
David Blaikieb5c7e6a2014-10-18 02:21:26 +00001842 QualType T = TA.getParamTypeForDecl().getDesugaredType(CGM.getContext());
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001843 llvm::DIType *TTy = getOrCreateType(T, Unit);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001844 llvm::Constant *V = nullptr;
Michael Liao982cbb62019-03-06 21:16:27 +00001845 // Skip retrieve the value if that template parameter has cuda device
1846 // attribute, i.e. that value is not available at the host side.
1847 if (!CGM.getLangOpts().CUDA || CGM.getLangOpts().CUDAIsDevice ||
1848 !D->hasAttr<CUDADeviceAttr>()) {
1849 const CXXMethodDecl *MD;
1850 // Variable pointer template parameters have a value that is the address
1851 // of the variable.
1852 if (const auto *VD = dyn_cast<VarDecl>(D))
1853 V = CGM.GetAddrOfGlobalVar(VD);
1854 // Member function pointers have special support for building them,
1855 // though this is currently unsupported in LLVM CodeGen.
1856 else if ((MD = dyn_cast<CXXMethodDecl>(D)) && MD->isInstance())
1857 V = CGM.getCXXABI().EmitMemberFunctionPointer(MD);
1858 else if (const auto *FD = dyn_cast<FunctionDecl>(D))
1859 V = CGM.GetAddrOfFunction(FD);
1860 // Member data pointers have special handling too to compute the fixed
1861 // offset within the object.
1862 else if (const auto *MPT =
1863 dyn_cast<MemberPointerType>(T.getTypePtr())) {
1864 // These five lines (& possibly the above member function pointer
1865 // handling) might be able to be refactored to use similar code in
1866 // CodeGenModule::getMemberPointerConstant
1867 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
1868 CharUnits chars =
1869 CGM.getContext().toCharUnitsFromBits((int64_t)fieldOffset);
1870 V = CGM.getCXXABI().EmitMemberDataPointer(MPT, chars);
1871 }
Simon Pilgrimcfee2ef2019-10-16 10:38:49 +00001872 assert(V && "Failed to find template parameter pointer");
Michael Liao982cbb62019-03-06 21:16:27 +00001873 V = V->stripPointerCasts();
David Blaikie38079fd2013-05-10 21:53:14 +00001874 }
Duncan P. N. Exon Smithdadc2b62015-04-21 18:43:54 +00001875 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
Awanish Pandey7a42bab2020-03-02 10:52:12 +05301876 TheCU, Name, TTy, defaultParameter, cast_or_null<llvm::Constant>(V)));
David Blaikie38079fd2013-05-10 21:53:14 +00001877 } break;
1878 case TemplateArgument::NullPtr: {
1879 QualType T = TA.getNullPtrType();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001880 llvm::DIType *TTy = getOrCreateType(T, Unit);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001881 llvm::Constant *V = nullptr;
David Blaikie38079fd2013-05-10 21:53:14 +00001882 // Special case member data pointer null values since they're actually -1
1883 // instead of zero.
David Majnemer58ed0f32016-07-17 00:39:12 +00001884 if (const auto *MPT = dyn_cast<MemberPointerType>(T.getTypePtr()))
David Blaikie38079fd2013-05-10 21:53:14 +00001885 // But treat member function pointers as simple zero integers because
1886 // it's easier than having a special case in LLVM's CodeGen. If LLVM
1887 // CodeGen grows handling for values of non-null member function
1888 // pointers then perhaps we could remove this special case and rely on
1889 // EmitNullMemberPointer for member function pointers.
1890 if (MPT->isMemberDataPointer())
1891 V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
1892 if (!V)
1893 V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
Awanish Pandey7a42bab2020-03-02 10:52:12 +05301894 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
1895 TheCU, Name, TTy, defaultParameter, V));
David Blaikie38079fd2013-05-10 21:53:14 +00001896 } break;
Duncan P. N. Exon Smithdadc2b62015-04-21 18:43:54 +00001897 case TemplateArgument::Template:
1898 TemplateParams.push_back(DBuilder.createTemplateTemplateParameter(
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00001899 TheCU, Name, nullptr,
Duncan P. N. Exon Smithdadc2b62015-04-21 18:43:54 +00001900 TA.getAsTemplate().getAsTemplateDecl()->getQualifiedNameAsString()));
1901 break;
1902 case TemplateArgument::Pack:
1903 TemplateParams.push_back(DBuilder.createTemplateParameterPack(
1904 TheCU, Name, nullptr,
1905 CollectTemplateParams(nullptr, TA.getPackAsArray(), Unit)));
1906 break;
David Majnemer5559d472013-08-24 08:21:10 +00001907 case TemplateArgument::Expression: {
1908 const Expr *E = TA.getAsExpr();
1909 QualType T = E->getType();
David Majnemer922ad9f2014-10-24 19:49:04 +00001910 if (E->isGLValue())
1911 T = CGM.getContext().getLValueReferenceType(T);
John McCallde0fe072017-08-15 21:42:52 +00001912 llvm::Constant *V = ConstantEmitter(CGM).emitAbstract(E, T);
David Majnemer5559d472013-08-24 08:21:10 +00001913 assert(V && "Expression in template argument isn't constant");
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001914 llvm::DIType *TTy = getOrCreateType(T, Unit);
Duncan P. N. Exon Smithdadc2b62015-04-21 18:43:54 +00001915 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
Awanish Pandey7a42bab2020-03-02 10:52:12 +05301916 TheCU, Name, TTy, defaultParameter, V->stripPointerCasts()));
David Majnemer5559d472013-08-24 08:21:10 +00001917 } break;
David Blaikie2b93c542013-05-10 23:36:06 +00001918 // And the following should never occur:
David Blaikie38079fd2013-05-10 21:53:14 +00001919 case TemplateArgument::TemplateExpansion:
David Blaikie38079fd2013-05-10 21:53:14 +00001920 case TemplateArgument::Null:
1921 llvm_unreachable(
1922 "These argument types shouldn't exist in concrete types");
Guy Benyei11169dd2012-12-18 14:30:41 +00001923 }
1924 }
1925 return DBuilder.getOrCreateArray(TemplateParams);
1926}
1927
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001928llvm::DINodeArray
Duncan P. N. Exon Smith8e47da42015-04-21 20:07:29 +00001929CGDebugInfo::CollectFunctionTemplateParams(const FunctionDecl *FD,
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001930 llvm::DIFile *Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001931 if (FD->getTemplatedKind() ==
1932 FunctionDecl::TK_FunctionTemplateSpecialization) {
Eric Christophere7b87e52014-10-26 23:40:33 +00001933 const TemplateParameterList *TList = FD->getTemplateSpecializationInfo()
1934 ->getTemplate()
1935 ->getTemplateParameters();
David Blaikie47c11502013-06-22 18:59:18 +00001936 return CollectTemplateParams(
1937 TList, FD->getTemplateSpecializationArgs()->asArray(), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00001938 }
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001939 return llvm::DINodeArray();
Guy Benyei11169dd2012-12-18 14:30:41 +00001940}
1941
Matthew Voss20165362018-10-03 18:45:04 +00001942llvm::DINodeArray CGDebugInfo::CollectVarTemplateParams(const VarDecl *VL,
Reid Kleckner2dbd5d82019-05-02 17:45:54 +00001943 llvm::DIFile *Unit) {
1944 // Always get the full list of parameters, not just the ones from the
1945 // specialization. A partial specialization may have fewer parameters than
1946 // there are arguments.
1947 auto *TS = dyn_cast<VarTemplateSpecializationDecl>(VL);
1948 if (!TS)
1949 return llvm::DINodeArray();
1950 VarTemplateDecl *T = TS->getSpecializedTemplate();
1951 const TemplateParameterList *TList = T->getTemplateParameters();
1952 auto TA = TS->getTemplateArgs().asArray();
1953 return CollectTemplateParams(TList, TA, Unit);
Matthew Voss20165362018-10-03 18:45:04 +00001954}
1955
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001956llvm::DINodeArray CGDebugInfo::CollectCXXTemplateParams(
1957 const ClassTemplateSpecializationDecl *TSpecial, llvm::DIFile *Unit) {
Reid Kleckner2dbd5d82019-05-02 17:45:54 +00001958 // Always get the full list of parameters, not just the ones from the
1959 // specialization. A partial specialization may have fewer parameters than
1960 // there are arguments.
Adrian Prantl649f0302014-04-17 01:04:01 +00001961 TemplateParameterList *TPList =
Eric Christophere7b87e52014-10-26 23:40:33 +00001962 TSpecial->getSpecializedTemplate()->getTemplateParameters();
Adrian Prantl2c92e9c2014-04-17 00:30:48 +00001963 const TemplateArgumentList &TAList = TSpecial->getTemplateArgs();
David Blaikie47c11502013-06-22 18:59:18 +00001964 return CollectTemplateParams(TPList, TAList.asArray(), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00001965}
1966
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001967llvm::DIType *CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile *Unit) {
Duncan P. N. Exon Smithb7470232015-04-15 23:48:50 +00001968 if (VTablePtrType)
Guy Benyei11169dd2012-12-18 14:30:41 +00001969 return VTablePtrType;
1970
1971 ASTContext &Context = CGM.getContext();
1972
1973 /* Function type */
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001974 llvm::Metadata *STy = getOrCreateType(Context.IntTy, Unit);
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001975 llvm::DITypeRefArray SElements = DBuilder.getOrCreateTypeArray(STy);
Eric Christopher28a6db52015-10-15 06:56:08 +00001976 llvm::DIType *SubTy = DBuilder.createSubroutineType(SElements);
Guy Benyei11169dd2012-12-18 14:30:41 +00001977 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
Konstantin Zhuravlyovd1ba16e2017-03-08 23:56:48 +00001978 unsigned VtblPtrAddressSpace = CGM.getTarget().getVtblPtrAddressSpace();
1979 Optional<unsigned> DWARFAddressSpace =
1980 CGM.getTarget().getDWARFAddressSpace(VtblPtrAddressSpace);
1981
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00001982 llvm::DIType *vtbl_ptr_type = DBuilder.createPointerType(
1983 SubTy, Size, 0, DWARFAddressSpace, "__vtbl_ptr_type");
Guy Benyei11169dd2012-12-18 14:30:41 +00001984 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1985 return VTablePtrType;
1986}
1987
Guy Benyei11169dd2012-12-18 14:30:41 +00001988StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +00001989 // Copy the gdb compatible name on the side and use its reference.
1990 return internString("_vptr$", RD->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00001991}
1992
Reid Kleckner105c5652019-04-24 22:45:44 +00001993StringRef CGDebugInfo::getDynamicInitializerName(const VarDecl *VD,
1994 DynamicInitKind StubKind,
1995 llvm::Function *InitFn) {
1996 // If we're not emitting codeview, use the mangled name. For Itanium, this is
1997 // arbitrary.
Alexandre Ganeacaf31662019-11-15 16:21:17 -05001998 if (!CGM.getCodeGenOpts().EmitCodeView)
Reid Kleckner105c5652019-04-24 22:45:44 +00001999 return InitFn->getName();
2000
2001 // Print the normal qualified name for the variable, then break off the last
2002 // NNS, and add the appropriate other text. Clang always prints the global
2003 // variable name without template arguments, so we can use rsplit("::") and
2004 // then recombine the pieces.
2005 SmallString<128> QualifiedGV;
2006 StringRef Quals;
2007 StringRef GVName;
2008 {
2009 llvm::raw_svector_ostream OS(QualifiedGV);
2010 VD->printQualifiedName(OS, getPrintingPolicy());
2011 std::tie(Quals, GVName) = OS.str().rsplit("::");
2012 if (GVName.empty())
2013 std::swap(Quals, GVName);
2014 }
2015
2016 SmallString<128> InitName;
2017 llvm::raw_svector_ostream OS(InitName);
2018 if (!Quals.empty())
2019 OS << Quals << "::";
2020
2021 switch (StubKind) {
2022 case DynamicInitKind::NoStub:
2023 llvm_unreachable("not an initializer");
2024 case DynamicInitKind::Initializer:
2025 OS << "`dynamic initializer for '";
2026 break;
2027 case DynamicInitKind::AtExit:
2028 OS << "`dynamic atexit destructor for '";
2029 break;
2030 }
2031
2032 OS << GVName;
2033
2034 // Add any template specialization args.
2035 if (const auto *VTpl = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
2036 printTemplateArgumentList(OS, VTpl->getTemplateArgs().asArray(),
2037 getPrintingPolicy());
2038 }
2039
2040 OS << '\'';
2041
2042 return internString(OS.str());
2043}
2044
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002045void CGDebugInfo::CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile *Unit,
Reid Klecknerdc124992016-08-31 16:11:43 +00002046 SmallVectorImpl<llvm::Metadata *> &EltTys,
2047 llvm::DICompositeType *RecordTy) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002048 // If this class is not dynamic then there is not any vtable info to collect.
2049 if (!RD->isDynamicClass())
2050 return;
2051
Reid Kleckner59812422016-08-31 20:35:01 +00002052 // Don't emit any vtable shape or vptr info if this class doesn't have an
2053 // extendable vfptr. This can happen if the class doesn't have virtual
2054 // methods, or in the MS ABI if those virtual methods only come from virtually
2055 // inherited bases.
2056 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2057 if (!RL.hasExtendableVFPtr())
2058 return;
2059
Reid Klecknerdc124992016-08-31 16:11:43 +00002060 // CodeView needs to know how large the vtable of every dynamic class is, so
2061 // emit a special named pointer type into the element list. The vptr type
2062 // points to this type as well.
2063 llvm::DIType *VPtrTy = nullptr;
2064 bool NeedVTableShape = CGM.getCodeGenOpts().EmitCodeView &&
2065 CGM.getTarget().getCXXABI().isMicrosoft();
2066 if (NeedVTableShape) {
2067 uint64_t PtrWidth =
2068 CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
2069 const VTableLayout &VFTLayout =
2070 CGM.getMicrosoftVTableContext().getVFTableLayout(RD, CharUnits::Zero());
2071 unsigned VSlotCount =
Peter Collingbournee53683f2016-09-08 01:14:39 +00002072 VFTLayout.vtable_components().size() - CGM.getLangOpts().RTTIData;
Reid Klecknerdc124992016-08-31 16:11:43 +00002073 unsigned VTableWidth = PtrWidth * VSlotCount;
Konstantin Zhuravlyovd1ba16e2017-03-08 23:56:48 +00002074 unsigned VtblPtrAddressSpace = CGM.getTarget().getVtblPtrAddressSpace();
2075 Optional<unsigned> DWARFAddressSpace =
2076 CGM.getTarget().getDWARFAddressSpace(VtblPtrAddressSpace);
Reid Klecknerdc124992016-08-31 16:11:43 +00002077
2078 // Create a very wide void* type and insert it directly in the element list.
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00002079 llvm::DIType *VTableType = DBuilder.createPointerType(
2080 nullptr, VTableWidth, 0, DWARFAddressSpace, "__vtbl_ptr_type");
Reid Klecknerdc124992016-08-31 16:11:43 +00002081 EltTys.push_back(VTableType);
2082
2083 // The vptr is a pointer to this special vtable type.
2084 VPtrTy = DBuilder.createPointerType(VTableType, PtrWidth);
2085 }
2086
2087 // If there is a primary base then the artificial vptr member lives there.
Reid Klecknerdc124992016-08-31 16:11:43 +00002088 if (RL.getPrimaryBase())
2089 return;
2090
2091 if (!VPtrTy)
2092 VPtrTy = getOrCreateVTablePtrType(Unit);
2093
Guy Benyei11169dd2012-12-18 14:30:41 +00002094 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00002095 llvm::DIType *VPtrMember =
2096 DBuilder.createMemberType(Unit, getVTableName(RD), Unit, 0, Size, 0, 0,
2097 llvm::DINode::FlagArtificial, VPtrTy);
Reid Klecknerdc124992016-08-31 16:11:43 +00002098 EltTys.push_back(VPtrMember);
Guy Benyei11169dd2012-12-18 14:30:41 +00002099}
2100
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002101llvm::DIType *CGDebugInfo::getOrCreateRecordType(QualType RTy,
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00002102 SourceLocation Loc) {
Amy Huang53539bb2020-01-13 15:54:54 -08002103 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002104 llvm::DIType *T = getOrCreateType(RTy, getOrCreateFile(Loc));
Guy Benyei11169dd2012-12-18 14:30:41 +00002105 return T;
2106}
2107
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002108llvm::DIType *CGDebugInfo::getOrCreateInterfaceType(QualType D,
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00002109 SourceLocation Loc) {
Adrian Prantlad9a195e2015-08-27 21:21:19 +00002110 return getOrCreateStandaloneType(D, Loc);
2111}
2112
2113llvm::DIType *CGDebugInfo::getOrCreateStandaloneType(QualType D,
2114 SourceLocation Loc) {
Amy Huang53539bb2020-01-13 15:54:54 -08002115 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
Adrian Prantlad9a195e2015-08-27 21:21:19 +00002116 assert(!D.isNull() && "null type");
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002117 llvm::DIType *T = getOrCreateType(D, getOrCreateFile(Loc));
Adrian Prantlad9a195e2015-08-27 21:21:19 +00002118 assert(T && "could not create debug info for type");
Adrian Prantl3a884fa2015-08-27 22:56:46 +00002119
Adrian Prantl73409ce2013-03-11 18:33:46 +00002120 RetainedTypes.push_back(D.getAsOpaquePtr());
Guy Benyei11169dd2012-12-18 14:30:41 +00002121 return T;
2122}
2123
Amy Huang0d0334f2019-04-12 20:25:30 +00002124void CGDebugInfo::addHeapAllocSiteMetadata(llvm::Instruction *CI,
2125 QualType D,
2126 SourceLocation Loc) {
2127 llvm::MDNode *node;
2128 if (D.getTypePtr()->isVoidPointerType()) {
2129 node = llvm::MDNode::get(CGM.getLLVMContext(), None);
2130 } else {
2131 QualType PointeeTy = D.getTypePtr()->getPointeeType();
2132 node = getOrCreateType(PointeeTy, getOrCreateFile(Loc));
2133 }
Amy Huangfc79ab92019-04-23 21:12:58 +00002134
Amy Huang0d0334f2019-04-12 20:25:30 +00002135 CI->setMetadata("heapallocsite", node);
2136}
2137
David Blaikie483a9da2014-05-06 18:35:21 +00002138void CGDebugInfo::completeType(const EnumDecl *ED) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00002139 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
David Blaikie483a9da2014-05-06 18:35:21 +00002140 return;
2141 QualType Ty = CGM.getContext().getEnumType(ED);
Eric Christophere7b87e52014-10-26 23:40:33 +00002142 void *TyPtr = Ty.getAsOpaquePtr();
David Blaikie483a9da2014-05-06 18:35:21 +00002143 auto I = TypeCache.find(TyPtr);
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002144 if (I == TypeCache.end() || !cast<llvm::DIType>(I->second)->isForwardDecl())
David Blaikie483a9da2014-05-06 18:35:21 +00002145 return;
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002146 llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<EnumType>());
Duncan P. N. Exon Smith4caa7f22015-04-16 01:00:56 +00002147 assert(!Res->isForwardDecl());
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002148 TypeCache[TyPtr].reset(Res);
David Blaikie483a9da2014-05-06 18:35:21 +00002149}
2150
David Blaikieb2e86eb2013-08-15 20:49:17 +00002151void CGDebugInfo::completeType(const RecordDecl *RD) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00002152 if (DebugKind > codegenoptions::LimitedDebugInfo ||
David Blaikieb2e86eb2013-08-15 20:49:17 +00002153 !CGM.getLangOpts().CPlusPlus)
2154 completeRequiredType(RD);
2155}
2156
David Blaikieb11c8732017-01-30 06:36:08 +00002157/// Return true if the class or any of its methods are marked dllimport.
2158static bool isClassOrMethodDLLImport(const CXXRecordDecl *RD) {
2159 if (RD->hasAttr<DLLImportAttr>())
2160 return true;
2161 for (const CXXMethodDecl *MD : RD->methods())
2162 if (MD->hasAttr<DLLImportAttr>())
2163 return true;
2164 return false;
2165}
2166
Adrian Prantla43acdc2017-07-24 23:48:51 +00002167/// Does a type definition exist in an imported clang module?
2168static bool isDefinedInClangModule(const RecordDecl *RD) {
2169 // Only definitions that where imported from an AST file come from a module.
2170 if (!RD || !RD->isFromASTFile())
2171 return false;
2172 // Anonymous entities cannot be addressed. Treat them as not from module.
2173 if (!RD->isExternallyVisible() && RD->getName().empty())
2174 return false;
2175 if (auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD)) {
2176 if (!CXXDecl->isCompleteDefinition())
2177 return false;
Adrian Prantlba6fdc52018-10-24 00:06:02 +00002178 // Check wether RD is a template.
Adrian Prantla43acdc2017-07-24 23:48:51 +00002179 auto TemplateKind = CXXDecl->getTemplateSpecializationKind();
2180 if (TemplateKind != TSK_Undeclared) {
Adrian Prantlba6fdc52018-10-24 00:06:02 +00002181 // Unfortunately getOwningModule() isn't accurate enough to find the
2182 // owning module of a ClassTemplateSpecializationDecl that is inside a
2183 // namespace spanning multiple modules.
2184 bool Explicit = false;
2185 if (auto *TD = dyn_cast<ClassTemplateSpecializationDecl>(CXXDecl))
2186 Explicit = TD->isExplicitInstantiationOrSpecialization();
2187 if (!Explicit && CXXDecl->getEnclosingNamespaceContext())
2188 return false;
Adrian Prantla43acdc2017-07-24 23:48:51 +00002189 // This is a template, check the origin of the first member.
2190 if (CXXDecl->field_begin() == CXXDecl->field_end())
2191 return TemplateKind == TSK_ExplicitInstantiationDeclaration;
2192 if (!CXXDecl->field_begin()->isFromASTFile())
2193 return false;
2194 }
2195 }
2196 return true;
2197}
2198
David Blaikie6943dea2013-08-20 01:28:15 +00002199void CGDebugInfo::completeClassData(const RecordDecl *RD) {
David Blaikieb11c8732017-01-30 06:36:08 +00002200 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
2201 if (CXXRD->isDynamicClass() &&
2202 CGM.getVTableLinkage(CXXRD) ==
2203 llvm::GlobalValue::AvailableExternallyLinkage &&
2204 !isClassOrMethodDLLImport(CXXRD))
2205 return;
Adrian Prantla43acdc2017-07-24 23:48:51 +00002206
2207 if (DebugTypeExtRefs && isDefinedInClangModule(RD->getDefinition()))
2208 return;
2209
David Blaikieb11c8732017-01-30 06:36:08 +00002210 completeClass(RD);
2211}
2212
2213void CGDebugInfo::completeClass(const RecordDecl *RD) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00002214 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
Michael Gottesman349542b2013-08-19 18:46:16 +00002215 return;
David Blaikie6943dea2013-08-20 01:28:15 +00002216 QualType Ty = CGM.getContext().getRecordType(RD);
Eric Christophere7b87e52014-10-26 23:40:33 +00002217 void *TyPtr = Ty.getAsOpaquePtr();
David Blaikieef8a9512014-05-05 23:23:53 +00002218 auto I = TypeCache.find(TyPtr);
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002219 if (I != TypeCache.end() && !cast<llvm::DIType>(I->second)->isForwardDecl())
David Blaikieb2e86eb2013-08-15 20:49:17 +00002220 return;
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002221 llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<RecordType>());
Duncan P. N. Exon Smith4caa7f22015-04-16 01:00:56 +00002222 assert(!Res->isForwardDecl());
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002223 TypeCache[TyPtr].reset(Res);
David Blaikieb2e86eb2013-08-15 20:49:17 +00002224}
2225
David Blaikie0e716b42014-03-03 23:48:23 +00002226static bool hasExplicitMemberDefinition(CXXRecordDecl::method_iterator I,
2227 CXXRecordDecl::method_iterator End) {
David Majnemer58ed0f32016-07-17 00:39:12 +00002228 for (CXXMethodDecl *MD : llvm::make_range(I, End))
2229 if (FunctionDecl *Tmpl = MD->getInstantiatedFromMemberFunction())
David Blaikief7f21852014-03-04 03:08:14 +00002230 if (!Tmpl->isImplicit() && Tmpl->isThisDeclarationADefinition() &&
David Majnemer58ed0f32016-07-17 00:39:12 +00002231 !MD->getMemberSpecializationInfo()->isExplicitSpecialization())
David Blaikie0e716b42014-03-03 23:48:23 +00002232 return true;
2233 return false;
2234}
2235
Benjamin Kramer8c305922016-02-02 11:06:51 +00002236static bool shouldOmitDefinition(codegenoptions::DebugInfoKind DebugKind,
2237 bool DebugTypeExtRefs, const RecordDecl *RD,
David Blaikie0e716b42014-03-03 23:48:23 +00002238 const LangOptions &LangOpts) {
Adrian Prantl88d79172016-04-26 21:58:18 +00002239 if (DebugTypeExtRefs && isDefinedInClangModule(RD->getDefinition()))
Adrian Prantl43e00812016-01-19 23:42:53 +00002240 return true;
Adrian Prantl5c8bd882015-09-11 17:23:08 +00002241
David Blaikie1ac9c982017-04-11 21:13:37 +00002242 if (auto *ES = RD->getASTContext().getExternalSource())
2243 if (ES->hasExternalDefinitions(RD) == ExternalASTSource::EK_Always)
2244 return true;
2245
Benjamin Kramer8c305922016-02-02 11:06:51 +00002246 if (DebugKind > codegenoptions::LimitedDebugInfo)
David Blaikie0e716b42014-03-03 23:48:23 +00002247 return false;
2248
2249 if (!LangOpts.CPlusPlus)
2250 return false;
2251
2252 if (!RD->isCompleteDefinitionRequired())
2253 return true;
2254
David Majnemer58ed0f32016-07-17 00:39:12 +00002255 const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
David Blaikie0e716b42014-03-03 23:48:23 +00002256
2257 if (!CXXDecl)
2258 return false;
2259
Adrian McCarthy99242982016-08-16 22:11:18 +00002260 // Only emit complete debug info for a dynamic class when its vtable is
2261 // emitted. However, Microsoft debuggers don't resolve type information
Reid Klecknerc9404e12016-09-09 16:27:04 +00002262 // across DLL boundaries, so skip this optimization if the class or any of its
2263 // methods are marked dllimport. This isn't a complete solution, since objects
2264 // without any dllimport methods can be used in one DLL and constructed in
2265 // another, but it is the current behavior of LimitedDebugInfo.
Adrian McCarthy99242982016-08-16 22:11:18 +00002266 if (CXXDecl->hasDefinition() && CXXDecl->isDynamicClass() &&
Reid Klecknerc9404e12016-09-09 16:27:04 +00002267 !isClassOrMethodDLLImport(CXXDecl))
David Blaikie0e716b42014-03-03 23:48:23 +00002268 return true;
2269
Amy Huang651128f2020-01-03 16:28:48 -08002270 // In constructor debug mode, only emit debug info for a class when its
2271 // constructor is emitted. Skip this optimization if the class or any of
2272 // its methods are marked dllimport.
2273 if (DebugKind == codegenoptions::DebugInfoConstructor &&
Amy Huang11a04a62020-03-31 13:31:42 -07002274 !CXXDecl->isLambda() && !CXXDecl->hasConstexprNonCopyMoveConstructor() &&
2275 !isClassOrMethodDLLImport(CXXDecl))
2276 for (const auto *Ctor : CXXDecl->ctors())
Amy Huang651128f2020-01-03 16:28:48 -08002277 if (Ctor->isUserProvided())
2278 return true;
Amy Huang651128f2020-01-03 16:28:48 -08002279
David Blaikie0e716b42014-03-03 23:48:23 +00002280 TemplateSpecializationKind Spec = TSK_Undeclared;
David Majnemer58ed0f32016-07-17 00:39:12 +00002281 if (const auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD))
David Blaikie0e716b42014-03-03 23:48:23 +00002282 Spec = SD->getSpecializationKind();
2283
2284 if (Spec == TSK_ExplicitInstantiationDeclaration &&
2285 hasExplicitMemberDefinition(CXXDecl->method_begin(),
2286 CXXDecl->method_end()))
2287 return true;
2288
2289 return false;
2290}
2291
Reid Kleckner6c7b1c62016-09-13 00:01:23 +00002292void CGDebugInfo::completeRequiredType(const RecordDecl *RD) {
2293 if (shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD, CGM.getLangOpts()))
2294 return;
2295
2296 QualType Ty = CGM.getContext().getRecordType(RD);
2297 llvm::DIType *T = getTypeOrNull(Ty);
2298 if (T && T->isForwardDecl())
2299 completeClassData(RD);
2300}
2301
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002302llvm::DIType *CGDebugInfo::CreateType(const RecordType *Ty) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002303 RecordDecl *RD = Ty->getDecl();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002304 llvm::DIType *T = cast_or_null<llvm::DIType>(getTypeOrNull(QualType(Ty, 0)));
Adrian Prantl5c8bd882015-09-11 17:23:08 +00002305 if (T || shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD,
2306 CGM.getLangOpts())) {
David Blaikie3b1cc9b2013-09-06 06:45:04 +00002307 if (!T)
Adrian Prantl6ec370a2015-09-10 18:39:45 +00002308 T = getOrCreateRecordFwdDecl(Ty, getDeclContextDescriptor(RD));
David Blaikie3b1cc9b2013-09-06 06:45:04 +00002309 return T;
David Blaikiee36464c2013-06-05 05:32:23 +00002310 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002311
David Blaikieb2e86eb2013-08-15 20:49:17 +00002312 return CreateTypeDefinition(Ty);
2313}
2314
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002315llvm::DIType *CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) {
David Blaikieb2e86eb2013-08-15 20:49:17 +00002316 RecordDecl *RD = Ty->getDecl();
2317
Guy Benyei11169dd2012-12-18 14:30:41 +00002318 // Get overall information about the record type for the debug info.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002319 llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00002320
2321 // Records and classes and unions can all be recursive. To handle them, we
2322 // first generate a debug descriptor for the struct as a forward declaration.
2323 // Then (if it is a definition) we go through and get debug info for all of
2324 // its members. Finally, we create a descriptor for the complete type (which
2325 // may refer to the forward decl if the struct is recursive) and replace all
2326 // uses of the forward declaration with the final definition.
Duncan P. N. Exon Smithbd210e62015-07-24 20:34:41 +00002327 llvm::DICompositeType *FwdDecl = getOrCreateLimitedType(Ty, DefUnit);
Guy Benyei11169dd2012-12-18 14:30:41 +00002328
Adrian Prantl5f66bae2015-02-11 17:45:15 +00002329 const RecordDecl *D = RD->getDefinition();
2330 if (!D || !D->isCompleteDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00002331 return FwdDecl;
2332
David Majnemer58ed0f32016-07-17 00:39:12 +00002333 if (const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
David Blaikieadfbf992013-08-18 16:55:33 +00002334 CollectContainingType(CXXDecl, FwdDecl);
2335
Guy Benyei11169dd2012-12-18 14:30:41 +00002336 // Push the struct on region stack.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002337 LexicalBlockStack.emplace_back(&*FwdDecl);
2338 RegionMap[Ty->getDecl()].reset(FwdDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00002339
Guy Benyei11169dd2012-12-18 14:30:41 +00002340 // Convert all the elements.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002341 SmallVector<llvm::Metadata *, 16> EltTys;
David Blaikie6943dea2013-08-20 01:28:15 +00002342 // what about nested types?
Guy Benyei11169dd2012-12-18 14:30:41 +00002343
2344 // Note: The split of CXXDecl information here is intentional, the
2345 // gdb tests will depend on a certain ordering at printout. The debug
2346 // information offsets are still correct if we merge them all together
2347 // though.
David Majnemer58ed0f32016-07-17 00:39:12 +00002348 const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
Guy Benyei11169dd2012-12-18 14:30:41 +00002349 if (CXXDecl) {
2350 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
Reid Klecknerdc124992016-08-31 16:11:43 +00002351 CollectVTableInfo(CXXDecl, DefUnit, EltTys, FwdDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00002352 }
2353
Eric Christopher91a31902013-01-16 01:22:32 +00002354 // Collect data fields (including static variables and any initializers).
Guy Benyei11169dd2012-12-18 14:30:41 +00002355 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
Eric Christopher2df080e2013-10-11 18:16:51 +00002356 if (CXXDecl)
Guy Benyei11169dd2012-12-18 14:30:41 +00002357 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00002358
2359 LexicalBlockStack.pop_back();
2360 RegionMap.erase(Ty->getDecl());
2361
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002362 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
Duncan P. N. Exon Smithc8ee63e2014-12-18 00:48:56 +00002363 DBuilder.replaceArrays(FwdDecl, Elements);
Guy Benyei11169dd2012-12-18 14:30:41 +00002364
Adrian Prantl5f66bae2015-02-11 17:45:15 +00002365 if (FwdDecl->isTemporary())
Duncan P. N. Exon Smith4078ad42015-04-16 16:36:45 +00002366 FwdDecl =
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002367 llvm::MDNode::replaceWithPermanent(llvm::TempDICompositeType(FwdDecl));
Adrian Prantl5f66bae2015-02-11 17:45:15 +00002368
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002369 RegionMap[Ty->getDecl()].reset(FwdDecl);
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00002370 return FwdDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00002371}
2372
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002373llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectType *Ty,
2374 llvm::DIFile *Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002375 // Ignore protocols.
2376 return getOrCreateType(Ty->getBaseType(), Unit);
2377}
2378
Manman Rene6be26c2016-09-13 17:25:08 +00002379llvm::DIType *CGDebugInfo::CreateType(const ObjCTypeParamType *Ty,
2380 llvm::DIFile *Unit) {
2381 // Ignore protocols.
2382 SourceLocation Loc = Ty->getDecl()->getLocation();
2383
2384 // Use Typedefs to represent ObjCTypeParamType.
2385 return DBuilder.createTypedef(
2386 getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit),
2387 Ty->getDecl()->getName(), getOrCreateFile(Loc), getLineNumber(Loc),
Sam McCalld27a16e2019-11-18 15:53:22 +01002388 getDeclContextDescriptor(Ty->getDecl()));
Manman Rene6be26c2016-09-13 17:25:08 +00002389}
2390
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00002391/// \return true if Getter has the default name for the property PD.
2392static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,
2393 const ObjCMethodDecl *Getter) {
2394 assert(PD);
2395 if (!Getter)
2396 return true;
2397
2398 assert(Getter->getDeclName().isObjCZeroArgSelector());
2399 return PD->getName() ==
Eric Christophere7b87e52014-10-26 23:40:33 +00002400 Getter->getDeclName().getObjCSelector().getNameForSlot(0);
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00002401}
2402
2403/// \return true if Setter has the default name for the property PD.
2404static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,
2405 const ObjCMethodDecl *Setter) {
2406 assert(PD);
2407 if (!Setter)
2408 return true;
2409
2410 assert(Setter->getDeclName().isObjCOneArgSelector());
Adrian Prantla4ce9062013-06-07 22:29:12 +00002411 return SelectorTable::constructSetterName(PD->getName()) ==
Eric Christophere7b87e52014-10-26 23:40:33 +00002412 Setter->getDeclName().getObjCSelector().getNameForSlot(0);
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00002413}
2414
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002415llvm::DIType *CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
2416 llvm::DIFile *Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002417 ObjCInterfaceDecl *ID = Ty->getDecl();
2418 if (!ID)
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00002419 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00002420
Adrian Prantl50fd1a82016-04-20 23:59:32 +00002421 // Return a forward declaration if this type was imported from a clang module,
2422 // and this is not the compile unit with the implementation of the type (which
2423 // may contain hidden ivars).
2424 if (DebugTypeExtRefs && ID->isFromASTFile() && ID->getDefinition() &&
2425 !ID->getImplementation())
Adrian Prantl5c8bd882015-09-11 17:23:08 +00002426 return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
2427 ID->getName(),
2428 getDeclContextDescriptor(ID), Unit, 0);
2429
Guy Benyei11169dd2012-12-18 14:30:41 +00002430 // Get overall information about the record type for the debug info.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002431 llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00002432 unsigned Line = getLineNumber(ID->getLocation());
Duncan P. N. Exon Smith798d5652015-04-15 23:19:15 +00002433 auto RuntimeLang =
2434 static_cast<llvm::dwarf::SourceLanguage>(TheCU->getSourceLanguage());
Guy Benyei11169dd2012-12-18 14:30:41 +00002435
2436 // If this is just a forward declaration return a special forward-declaration
2437 // debug type since we won't be able to lay out the entire type.
2438 ObjCInterfaceDecl *Def = ID->getDefinition();
David Blaikieef8a9512014-05-05 23:23:53 +00002439 if (!Def || !Def->getImplementation()) {
Adrian Prantl42ce2d32015-10-01 16:57:02 +00002440 llvm::DIScope *Mod = getParentModuleOrNull(ID);
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002441 llvm::DIType *FwdDecl = DBuilder.createReplaceableCompositeType(
Adrian Prantl42ce2d32015-10-01 16:57:02 +00002442 llvm::dwarf::DW_TAG_structure_type, ID->getName(), Mod ? Mod : TheCU,
2443 DefUnit, Line, RuntimeLang);
David Blaikieef8a9512014-05-05 23:23:53 +00002444 ObjCInterfaceCache.push_back(ObjCInterfaceCacheEntry(Ty, FwdDecl, Unit));
Guy Benyei11169dd2012-12-18 14:30:41 +00002445 return FwdDecl;
2446 }
2447
David Blaikieef8a9512014-05-05 23:23:53 +00002448 return CreateTypeDefinition(Ty, Unit);
2449}
2450
Reid Klecknerc915cb92020-02-27 18:13:54 -08002451llvm::DIModule *CGDebugInfo::getOrCreateModuleRef(ASTSourceDescriptor Mod,
2452 bool CreateSkeletonCU) {
Adrian Prantleb66a262015-09-24 16:10:04 +00002453 // Use the Module pointer as the key into the cache. This is a
2454 // nullptr if the "Module" is a PCH, which is safe because we don't
2455 // support chained PCH debug info, so there can only be a single PCH.
2456 const Module *M = Mod.getModuleOrNull();
Adrian Prantl9e8ea352015-09-29 20:44:46 +00002457 auto ModRef = ModuleCache.find(M);
2458 if (ModRef != ModuleCache.end())
2459 return cast<llvm::DIModule>(ModRef->second);
Adrian Prantl2388ead2015-06-30 18:01:05 +00002460
2461 // Macro definitions that were defined with "-D" on the command line.
2462 SmallString<128> ConfigMacros;
2463 {
2464 llvm::raw_svector_ostream OS(ConfigMacros);
2465 const auto &PPOpts = CGM.getPreprocessorOpts();
2466 unsigned I = 0;
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002467 // Translate the macro definitions back into a command line.
Adrian Prantl2388ead2015-06-30 18:01:05 +00002468 for (auto &M : PPOpts.Macros) {
2469 if (++I > 1)
2470 OS << " ";
2471 const std::string &Macro = M.first;
2472 bool Undef = M.second;
2473 OS << "\"-" << (Undef ? 'U' : 'D');
2474 for (char c : Macro)
2475 switch (c) {
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00002476 case '\\':
2477 OS << "\\\\";
2478 break;
2479 case '"':
2480 OS << "\\\"";
2481 break;
2482 default:
2483 OS << c;
Adrian Prantl2388ead2015-06-30 18:01:05 +00002484 }
2485 OS << '\"';
Adrian Prantlc4bb47e2015-06-30 17:39:51 +00002486 }
Adrian Prantlc4bb47e2015-06-30 17:39:51 +00002487 }
Adrian Prantl66689202015-09-18 23:01:45 +00002488
Adrian Prantl835e6632015-09-24 16:10:10 +00002489 bool IsRootModule = M ? !M->Parent : true;
Adrian Prantl7b6b9a12019-02-08 23:15:42 +00002490 // When a module name is specified as -fmodule-name, that module gets a
2491 // clang::Module object, but it won't actually be built or imported; it will
2492 // be textual.
Adrian Prantle308e422019-02-15 20:24:26 +00002493 if (CreateSkeletonCU && IsRootModule && Mod.getASTFile().empty() && M)
2494 assert(StringRef(M->Name).startswith(CGM.getLangOpts().ModuleName) &&
Adrian Prantl7b6b9a12019-02-08 23:15:42 +00002495 "clang module without ASTFile must be specified by -fmodule-name");
2496
Adrian Prantl22d5bd02020-03-18 15:30:20 -07002497 // Return a StringRef to the remapped Path.
2498 auto RemapPath = [this](StringRef Path) -> std::string {
2499 std::string Remapped = remapDIPath(Path);
2500 StringRef Relative(Remapped);
2501 StringRef CompDir = TheCU->getDirectory();
2502 if (Relative.consume_front(CompDir))
2503 Relative.consume_front(llvm::sys::path::get_separator());
2504
2505 return Relative.str();
2506 };
2507
Adrian Prantl7b6b9a12019-02-08 23:15:42 +00002508 if (CreateSkeletonCU && IsRootModule && !Mod.getASTFile().empty()) {
Adrian Prantlc96da8f2016-01-22 17:43:43 +00002509 // PCH files don't have a signature field in the control block,
2510 // but LLVM detects skeleton CUs by looking for a non-zero DWO id.
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002511 // We use the lower 64 bits for debug info.
2512 uint64_t Signature =
2513 Mod.getSignature()
2514 ? (uint64_t)Mod.getSignature()[1] << 32 | Mod.getSignature()[0]
2515 : ~1ULL;
Adrian Prantl66689202015-09-18 23:01:45 +00002516 llvm::DIBuilder DIB(CGM.getModule());
Adrian Prantl079c6dd2020-03-18 13:14:07 -07002517 SmallString<0> PCM;
Adrian Prantl43580a52020-03-18 13:15:14 -07002518 if (!llvm::sys::path::is_absolute(Mod.getASTFile()))
Adrian Prantl079c6dd2020-03-18 13:14:07 -07002519 PCM = Mod.getPath();
2520 llvm::sys::path::append(PCM, Mod.getASTFile());
Adrian Prantl22d5bd02020-03-18 15:30:20 -07002521 DIB.createCompileUnit(
2522 TheCU->getSourceLanguage(),
2523 // TODO: Support "Source" from external AST providers?
2524 DIB.createFile(Mod.getModuleName(), TheCU->getDirectory()),
2525 TheCU->getProducer(), false, StringRef(), 0, RemapPath(PCM),
2526 llvm::DICompileUnit::FullDebug, Signature);
Adrian Prantl66689202015-09-18 23:01:45 +00002527 DIB.finalize();
Adrian Prantl2f957ac2015-09-19 00:59:22 +00002528 }
Adrian Prantl7b6b9a12019-02-08 23:15:42 +00002529
Adrian Prantl835e6632015-09-24 16:10:10 +00002530 llvm::DIModule *Parent =
2531 IsRootModule ? nullptr
Reid Klecknerc915cb92020-02-27 18:13:54 -08002532 : getOrCreateModuleRef(ASTSourceDescriptor(*M->Parent),
2533 CreateSkeletonCU);
Adrian Prantl22d5bd02020-03-18 15:30:20 -07002534 std::string IncludePath = Mod.getPath().str();
Adrian Prantleb66a262015-09-24 16:10:04 +00002535 llvm::DIModule *DIMod =
Adrian Prantl835e6632015-09-24 16:10:10 +00002536 DBuilder.createModule(Parent, Mod.getModuleName(), ConfigMacros,
Adrian Prantl22d5bd02020-03-18 15:30:20 -07002537 RemapPath(IncludePath));
Adrian Prantl9e8ea352015-09-29 20:44:46 +00002538 ModuleCache[M].reset(DIMod);
Adrian Prantleb66a262015-09-24 16:10:04 +00002539 return DIMod;
Adrian Prantlc4bb47e2015-06-30 17:39:51 +00002540}
2541
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002542llvm::DIType *CGDebugInfo::CreateTypeDefinition(const ObjCInterfaceType *Ty,
2543 llvm::DIFile *Unit) {
David Blaikieef8a9512014-05-05 23:23:53 +00002544 ObjCInterfaceDecl *ID = Ty->getDecl();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002545 llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
David Blaikieef8a9512014-05-05 23:23:53 +00002546 unsigned Line = getLineNumber(ID->getLocation());
Duncan P. N. Exon Smith798d5652015-04-15 23:19:15 +00002547 unsigned RuntimeLang = TheCU->getSourceLanguage();
Guy Benyei11169dd2012-12-18 14:30:41 +00002548
2549 // Bit size, align and offset of the type.
2550 uint64_t Size = CGM.getContext().getTypeSize(Ty);
Victor Leschuka7ece032016-10-20 00:13:19 +00002551 auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00002552
Leny Kholodov80c047d2016-09-06 10:48:04 +00002553 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
Guy Benyei11169dd2012-12-18 14:30:41 +00002554 if (ID->getImplementation())
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002555 Flags |= llvm::DINode::FlagObjcClassComplete;
Guy Benyei11169dd2012-12-18 14:30:41 +00002556
Adrian Prantlfd696112015-10-01 00:48:51 +00002557 llvm::DIScope *Mod = getParentModuleOrNull(ID);
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002558 llvm::DICompositeType *RealDecl = DBuilder.createStructType(
Adrian Prantlfd696112015-10-01 00:48:51 +00002559 Mod ? Mod : Unit, ID->getName(), DefUnit, Line, Size, Align, Flags,
2560 nullptr, llvm::DINodeArray(), RuntimeLang);
Guy Benyei11169dd2012-12-18 14:30:41 +00002561
David Blaikieef8a9512014-05-05 23:23:53 +00002562 QualType QTy(Ty, 0);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002563 TypeCache[QTy.getAsOpaquePtr()].reset(RealDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00002564
Eric Christopher35f1f9f2013-07-14 21:00:07 +00002565 // Push the struct on region stack.
Duncan P. N. Exon Smith4078ad42015-04-16 16:36:45 +00002566 LexicalBlockStack.emplace_back(RealDecl);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002567 RegionMap[Ty->getDecl()].reset(RealDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00002568
2569 // Convert all the elements.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002570 SmallVector<llvm::Metadata *, 16> EltTys;
Guy Benyei11169dd2012-12-18 14:30:41 +00002571
2572 ObjCInterfaceDecl *SClass = ID->getSuperClass();
2573 if (SClass) {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002574 llvm::DIType *SClassTy =
Eric Christophere7b87e52014-10-26 23:40:33 +00002575 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
Duncan P. N. Exon Smithb7470232015-04-15 23:48:50 +00002576 if (!SClassTy)
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00002577 return nullptr;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002578
Brock Wyma3db2b102018-05-14 21:21:22 +00002579 llvm::DIType *InhTag = DBuilder.createInheritance(RealDecl, SClassTy, 0, 0,
Leny Kholodovdf050fd2016-09-06 17:06:14 +00002580 llvm::DINode::FlagZero);
Guy Benyei11169dd2012-12-18 14:30:41 +00002581 EltTys.push_back(InhTag);
2582 }
2583
Eric Christopher35f1f9f2013-07-14 21:00:07 +00002584 // Create entries for all of the properties.
Nico Weber7123bca2015-12-04 19:14:14 +00002585 auto AddProperty = [&](const ObjCPropertyDecl *PD) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002586 SourceLocation Loc = PD->getLocation();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002587 llvm::DIFile *PUnit = getOrCreateFile(Loc);
Guy Benyei11169dd2012-12-18 14:30:41 +00002588 unsigned PLine = getLineNumber(Loc);
2589 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
2590 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
Eric Christophere7b87e52014-10-26 23:40:33 +00002591 llvm::MDNode *PropertyNode = DBuilder.createObjCProperty(
2592 PD->getName(), PUnit, PLine,
2593 hasDefaultGetterName(PD, Getter) ? ""
2594 : getSelectorName(PD->getGetterName()),
2595 hasDefaultSetterName(PD, Setter) ? ""
2596 : getSelectorName(PD->getSetterName()),
2597 PD->getPropertyAttributes(), getOrCreateType(PD->getType(), PUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00002598 EltTys.push_back(PropertyNode);
Nico Weber7123bca2015-12-04 19:14:14 +00002599 };
2600 {
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00002601 llvm::SmallPtrSet<const IdentifierInfo *, 16> PropertySet;
Nico Weberde059e12015-12-04 19:35:45 +00002602 for (const ObjCCategoryDecl *ClassExt : ID->known_extensions())
Manman Renefe1bac2016-01-27 20:00:32 +00002603 for (auto *PD : ClassExt->properties()) {
Nico Weberde059e12015-12-04 19:35:45 +00002604 PropertySet.insert(PD->getIdentifier());
2605 AddProperty(PD);
2606 }
Manman Renefe1bac2016-01-27 20:00:32 +00002607 for (const auto *PD : ID->properties()) {
Nico Weber7123bca2015-12-04 19:14:14 +00002608 // Don't emit duplicate metadata for properties that were already in a
2609 // class extension.
2610 if (!PropertySet.insert(PD->getIdentifier()).second)
2611 continue;
2612 AddProperty(PD);
2613 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002614 }
2615
2616 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
2617 unsigned FieldNo = 0;
2618 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
2619 Field = Field->getNextIvar(), ++FieldNo) {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002620 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
Duncan P. N. Exon Smithb7470232015-04-15 23:48:50 +00002621 if (!FieldTy)
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00002622 return nullptr;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002623
Guy Benyei11169dd2012-12-18 14:30:41 +00002624 StringRef FieldName = Field->getName();
2625
2626 // Ignore unnamed fields.
2627 if (FieldName.empty())
2628 continue;
2629
2630 // Get the location for the field.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002631 llvm::DIFile *FieldDefUnit = getOrCreateFile(Field->getLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00002632 unsigned FieldLine = getLineNumber(Field->getLocation());
2633 QualType FType = Field->getType();
2634 uint64_t FieldSize = 0;
Victor Leschuk802e4a52016-10-19 22:11:07 +00002635 uint32_t FieldAlign = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00002636
2637 if (!FType->isIncompleteArrayType()) {
2638
2639 // Bit size, align and offset of the type.
2640 FieldSize = Field->isBitField()
Eric Christopher35f1f9f2013-07-14 21:00:07 +00002641 ? Field->getBitWidthValue(CGM.getContext())
2642 : CGM.getContext().getTypeSize(FType);
Victor Leschuka7ece032016-10-20 00:13:19 +00002643 FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00002644 }
2645
2646 uint64_t FieldOffset;
2647 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
2648 // We don't know the runtime offset of an ivar if we're using the
2649 // non-fragile ABI. For bitfields, use the bit offset into the first
2650 // byte of storage of the bitfield. For other fields, use zero.
2651 if (Field->isBitField()) {
Eric Christophere7b87e52014-10-26 23:40:33 +00002652 FieldOffset =
2653 CGM.getObjCRuntime().ComputeBitfieldBitOffset(CGM, ID, Field);
Guy Benyei11169dd2012-12-18 14:30:41 +00002654 FieldOffset %= CGM.getContext().getCharWidth();
2655 } else {
2656 FieldOffset = 0;
2657 }
2658 } else {
2659 FieldOffset = RL.getFieldOffset(FieldNo);
2660 }
2661
Leny Kholodov80c047d2016-09-06 10:48:04 +00002662 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
Guy Benyei11169dd2012-12-18 14:30:41 +00002663 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002664 Flags = llvm::DINode::FlagProtected;
Guy Benyei11169dd2012-12-18 14:30:41 +00002665 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002666 Flags = llvm::DINode::FlagPrivate;
Adrian Prantl21361fb2014-08-29 22:44:27 +00002667 else if (Field->getAccessControl() == ObjCIvarDecl::Public)
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002668 Flags = llvm::DINode::FlagPublic;
Guy Benyei11169dd2012-12-18 14:30:41 +00002669
Craig Topper8a13c412014-05-21 05:09:00 +00002670 llvm::MDNode *PropertyNode = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00002671 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00002672 if (ObjCPropertyImplDecl *PImpD =
Eric Christophere7b87e52014-10-26 23:40:33 +00002673 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002674 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
Eric Christopherc0c5d462013-02-21 22:35:08 +00002675 SourceLocation Loc = PD->getLocation();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002676 llvm::DIFile *PUnit = getOrCreateFile(Loc);
Eric Christopherc0c5d462013-02-21 22:35:08 +00002677 unsigned PLine = getLineNumber(Loc);
Adrian Prantl901cc4a2019-11-08 09:24:31 -08002678 ObjCMethodDecl *Getter = PImpD->getGetterMethodDecl();
2679 ObjCMethodDecl *Setter = PImpD->getSetterMethodDecl();
Eric Christophere7b87e52014-10-26 23:40:33 +00002680 PropertyNode = DBuilder.createObjCProperty(
2681 PD->getName(), PUnit, PLine,
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00002682 hasDefaultGetterName(PD, Getter)
2683 ? ""
2684 : getSelectorName(PD->getGetterName()),
2685 hasDefaultSetterName(PD, Setter)
2686 ? ""
2687 : getSelectorName(PD->getSetterName()),
Eric Christophere7b87e52014-10-26 23:40:33 +00002688 PD->getPropertyAttributes(),
2689 getOrCreateType(PD->getType(), PUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00002690 }
2691 }
2692 }
Eric Christophere7b87e52014-10-26 23:40:33 +00002693 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit, FieldLine,
2694 FieldSize, FieldAlign, FieldOffset, Flags,
2695 FieldTy, PropertyNode);
Guy Benyei11169dd2012-12-18 14:30:41 +00002696 EltTys.push_back(FieldTy);
2697 }
2698
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002699 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
Duncan P. N. Exon Smithc8ee63e2014-12-18 00:48:56 +00002700 DBuilder.replaceArrays(RealDecl, Elements);
Adrian Prantla03a85a2013-03-06 22:03:30 +00002701
Guy Benyei11169dd2012-12-18 14:30:41 +00002702 LexicalBlockStack.pop_back();
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00002703 return RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00002704}
2705
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002706llvm::DIType *CGDebugInfo::CreateType(const VectorType *Ty,
2707 llvm::DIFile *Unit) {
2708 llvm::DIType *ElementTy = getOrCreateType(Ty->getElementType(), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00002709 int64_t Count = Ty->getNumElements();
Guy Benyei11169dd2012-12-18 14:30:41 +00002710
Sander de Smalen891af03a2018-02-03 13:55:59 +00002711 llvm::Metadata *Subscript;
2712 QualType QTy(Ty, 0);
2713 auto SizeExpr = SizeExprCache.find(QTy);
2714 if (SizeExpr != SizeExprCache.end())
2715 Subscript = DBuilder.getOrCreateSubrange(0, SizeExpr->getSecond());
2716 else
2717 Subscript = DBuilder.getOrCreateSubrange(0, Count ? Count : -1);
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002718 llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
Guy Benyei11169dd2012-12-18 14:30:41 +00002719
2720 uint64_t Size = CGM.getContext().getTypeSize(Ty);
Victor Leschuka7ece032016-10-20 00:13:19 +00002721 auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00002722
2723 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
2724}
2725
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002726llvm::DIType *CGDebugInfo::CreateType(const ArrayType *Ty, llvm::DIFile *Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002727 uint64_t Size;
Victor Leschuk802e4a52016-10-19 22:11:07 +00002728 uint32_t Align;
Guy Benyei11169dd2012-12-18 14:30:41 +00002729
2730 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
David Majnemer58ed0f32016-07-17 00:39:12 +00002731 if (const auto *VAT = dyn_cast<VariableArrayType>(Ty)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002732 Size = 0;
Victor Leschuka7ece032016-10-20 00:13:19 +00002733 Align = getTypeAlignIfRequired(CGM.getContext().getBaseElementType(VAT),
2734 CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00002735 } else if (Ty->isIncompleteArrayType()) {
2736 Size = 0;
2737 if (Ty->getElementType()->isIncompleteType())
2738 Align = 0;
2739 else
Victor Leschuka7ece032016-10-20 00:13:19 +00002740 Align = getTypeAlignIfRequired(Ty->getElementType(), CGM.getContext());
David Blaikief03b2e82013-05-09 20:48:12 +00002741 } else if (Ty->isIncompleteType()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002742 Size = 0;
2743 Align = 0;
2744 } else {
2745 // Size and align of the whole array, not the element type.
2746 Size = CGM.getContext().getTypeSize(Ty);
Victor Leschuka7ece032016-10-20 00:13:19 +00002747 Align = getTypeAlignIfRequired(Ty, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00002748 }
2749
2750 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
2751 // interior arrays, do we care? Why aren't nested arrays represented the
2752 // obvious/recursive way?
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002753 SmallVector<llvm::Metadata *, 8> Subscripts;
Guy Benyei11169dd2012-12-18 14:30:41 +00002754 QualType EltTy(Ty, 0);
2755 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
2756 // If the number of elements is known, then count is that number. Otherwise,
2757 // it's -1. This allows us to represent a subrange with an array of 0
2758 // elements, like this:
2759 //
2760 // struct foo {
2761 // int x[0];
2762 // };
Eric Christophere7b87e52014-10-26 23:40:33 +00002763 int64_t Count = -1; // Count == -1 is an unbounded array.
David Majnemer58ed0f32016-07-17 00:39:12 +00002764 if (const auto *CAT = dyn_cast<ConstantArrayType>(Ty))
Guy Benyei11169dd2012-12-18 14:30:41 +00002765 Count = CAT->getSize().getZExtValue();
David Blaikie87173f12016-08-22 17:49:56 +00002766 else if (const auto *VAT = dyn_cast<VariableArrayType>(Ty)) {
Eli Friedman01d6b962016-10-19 22:16:32 +00002767 if (Expr *Size = VAT->getSizeExpr()) {
Fangrui Song407659a2018-11-30 23:41:18 +00002768 Expr::EvalResult Result;
2769 if (Size->EvaluateAsInt(Result, CGM.getContext()))
2770 Count = Result.Val.getInt().getExtValue();
Eli Friedman01d6b962016-10-19 22:16:32 +00002771 }
David Blaikie87173f12016-08-22 17:49:56 +00002772 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00002773
Sander de Smalen891af03a2018-02-03 13:55:59 +00002774 auto SizeNode = SizeExprCache.find(EltTy);
2775 if (SizeNode != SizeExprCache.end())
2776 Subscripts.push_back(
2777 DBuilder.getOrCreateSubrange(0, SizeNode->getSecond()));
2778 else
2779 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
Guy Benyei11169dd2012-12-18 14:30:41 +00002780 EltTy = Ty->getElementType();
2781 }
2782
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002783 llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
Guy Benyei11169dd2012-12-18 14:30:41 +00002784
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00002785 return DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
2786 SubscriptArray);
Guy Benyei11169dd2012-12-18 14:30:41 +00002787}
2788
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002789llvm::DIType *CGDebugInfo::CreateType(const LValueReferenceType *Ty,
2790 llvm::DIFile *Unit) {
Eric Christophere7b87e52014-10-26 23:40:33 +00002791 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type, Ty,
2792 Ty->getPointeeType(), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00002793}
2794
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002795llvm::DIType *CGDebugInfo::CreateType(const RValueReferenceType *Ty,
2796 llvm::DIFile *Unit) {
Eric Christophere7b87e52014-10-26 23:40:33 +00002797 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type, Ty,
2798 Ty->getPointeeType(), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00002799}
2800
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002801llvm::DIType *CGDebugInfo::CreateType(const MemberPointerType *Ty,
2802 llvm::DIFile *U) {
Leny Kholodov80c047d2016-09-06 10:48:04 +00002803 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
Reid Klecknerfb727182016-06-17 22:27:59 +00002804 uint64_t Size = 0;
2805
2806 if (!Ty->isIncompleteType()) {
2807 Size = CGM.getContext().getTypeSize(Ty);
2808
2809 // Set the MS inheritance model. There is no flag for the unspecified model.
2810 if (CGM.getTarget().getCXXABI().isMicrosoft()) {
2811 switch (Ty->getMostRecentCXXRecordDecl()->getMSInheritanceModel()) {
Reid Klecknera9cc64e2019-11-15 18:49:32 -08002812 case MSInheritanceModel::Single:
Reid Klecknerfb727182016-06-17 22:27:59 +00002813 Flags |= llvm::DINode::FlagSingleInheritance;
2814 break;
Reid Klecknera9cc64e2019-11-15 18:49:32 -08002815 case MSInheritanceModel::Multiple:
Reid Klecknerfb727182016-06-17 22:27:59 +00002816 Flags |= llvm::DINode::FlagMultipleInheritance;
2817 break;
Reid Klecknera9cc64e2019-11-15 18:49:32 -08002818 case MSInheritanceModel::Virtual:
Reid Klecknerfb727182016-06-17 22:27:59 +00002819 Flags |= llvm::DINode::FlagVirtualInheritance;
2820 break;
Reid Klecknera9cc64e2019-11-15 18:49:32 -08002821 case MSInheritanceModel::Unspecified:
Reid Klecknerfb727182016-06-17 22:27:59 +00002822 break;
2823 }
2824 }
2825 }
2826
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002827 llvm::DIType *ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
David Majnemer5fd33e02015-04-24 01:25:08 +00002828 if (Ty->isMemberDataPointerType())
David Blaikie2c705ca2013-01-19 19:20:56 +00002829 return DBuilder.createMemberPointerType(
Reid Klecknerfb727182016-06-17 22:27:59 +00002830 getOrCreateType(Ty->getPointeeType(), U), ClassType, Size, /*Align=*/0,
2831 Flags);
Adrian Prantl0866acd2013-12-19 01:38:47 +00002832
2833 const FunctionProtoType *FPT =
Eric Christophere7b87e52014-10-26 23:40:33 +00002834 Ty->getPointeeType()->getAs<FunctionProtoType>();
2835 return DBuilder.createMemberPointerType(
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00002836 getOrCreateInstanceMethodType(
2837 CXXMethodDecl::getThisType(FPT, Ty->getMostRecentCXXRecordDecl()),
Awanish Pandeyc83602f2020-01-23 16:06:52 +05302838 FPT, U, false),
Reid Klecknerfb727182016-06-17 22:27:59 +00002839 ClassType, Size, /*Align=*/0, Flags);
Guy Benyei11169dd2012-12-18 14:30:41 +00002840}
2841
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002842llvm::DIType *CGDebugInfo::CreateType(const AtomicType *Ty, llvm::DIFile *U) {
Victor Leschuk0df190372016-10-31 19:09:47 +00002843 auto *FromTy = getOrCreateType(Ty->getValueType(), U);
2844 return DBuilder.createQualifiedType(llvm::dwarf::DW_TAG_atomic_type, FromTy);
Guy Benyei11169dd2012-12-18 14:30:41 +00002845}
2846
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00002847llvm::DIType *CGDebugInfo::CreateType(const PipeType *Ty, llvm::DIFile *U) {
Xiuli Pan9c14e282016-01-09 12:53:17 +00002848 return getOrCreateType(Ty->getElementType(), U);
2849}
2850
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002851llvm::DIType *CGDebugInfo::CreateEnumType(const EnumType *Ty) {
Manman Ren1b457022013-08-28 21:20:28 +00002852 const EnumDecl *ED = Ty->getDecl();
Adrian Prantl5c8bd882015-09-11 17:23:08 +00002853
Guy Benyei11169dd2012-12-18 14:30:41 +00002854 uint64_t Size = 0;
Victor Leschuk802e4a52016-10-19 22:11:07 +00002855 uint32_t Align = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00002856 if (!ED->getTypeForDecl()->isIncompleteType()) {
2857 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
Victor Leschuka7ece032016-10-20 00:13:19 +00002858 Align = getDeclAlignIfRequired(ED, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00002859 }
2860
Brock Wyma8557ec52018-05-22 12:41:19 +00002861 SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
Manman Rene0064d82013-08-29 23:19:58 +00002862
Adrian Prantl5c8bd882015-09-11 17:23:08 +00002863 bool isImportedFromModule =
2864 DebugTypeExtRefs && ED->isFromASTFile() && ED->getDefinition();
2865
Guy Benyei11169dd2012-12-18 14:30:41 +00002866 // If this is just a forward declaration, construct an appropriately
2867 // marked node and just return it.
Adrian Prantl5c8bd882015-09-11 17:23:08 +00002868 if (isImportedFromModule || !ED->getDefinition()) {
Adrian Prantl45946062016-02-23 19:30:08 +00002869 // Note that it is possible for enums to be created as part of
2870 // their own declcontext. In this case a FwdDecl will be created
2871 // twice. This doesn't cause a problem because both FwdDecls are
2872 // entered into the ReplaceMap: finalize() will replace the first
2873 // FwdDecl with the second and then replace the second with
2874 // complete type.
Amjad Abouddc4531e2016-04-30 01:44:38 +00002875 llvm::DIScope *EDContext = getDeclContextDescriptor(ED);
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002876 llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
Adrian Prantlff9d83c2016-02-08 17:03:28 +00002877 llvm::TempDIScope TmpContext(DBuilder.createReplaceableCompositeType(
2878 llvm::dwarf::DW_TAG_enumeration_type, "", TheCU, DefUnit, 0));
Adrian Prantla40030f2016-02-06 01:59:09 +00002879
Guy Benyei11169dd2012-12-18 14:30:41 +00002880 unsigned Line = getLineNumber(ED->getLocation());
2881 StringRef EDName = ED->getName();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002882 llvm::DIType *RetTy = DBuilder.createReplaceableCompositeType(
Adrian Prantl45946062016-02-23 19:30:08 +00002883 llvm::dwarf::DW_TAG_enumeration_type, EDName, EDContext, DefUnit, Line,
Brock Wyma8557ec52018-05-22 12:41:19 +00002884 0, Size, Align, llvm::DINode::FlagFwdDecl, Identifier);
Adrian Prantla40030f2016-02-06 01:59:09 +00002885
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002886 ReplaceMap.emplace_back(
2887 std::piecewise_construct, std::make_tuple(Ty),
2888 std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
David Blaikief427b002014-05-06 03:42:01 +00002889 return RetTy;
Guy Benyei11169dd2012-12-18 14:30:41 +00002890 }
2891
David Blaikie483a9da2014-05-06 18:35:21 +00002892 return CreateTypeDefinition(Ty);
2893}
2894
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002895llvm::DIType *CGDebugInfo::CreateTypeDefinition(const EnumType *Ty) {
David Blaikie483a9da2014-05-06 18:35:21 +00002896 const EnumDecl *ED = Ty->getDecl();
2897 uint64_t Size = 0;
Victor Leschuk802e4a52016-10-19 22:11:07 +00002898 uint32_t Align = 0;
David Blaikie483a9da2014-05-06 18:35:21 +00002899 if (!ED->getTypeForDecl()->isIncompleteType()) {
2900 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
Victor Leschuka7ece032016-10-20 00:13:19 +00002901 Align = getDeclAlignIfRequired(ED, CGM.getContext());
David Blaikie483a9da2014-05-06 18:35:21 +00002902 }
2903
Brock Wyma8557ec52018-05-22 12:41:19 +00002904 SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
David Blaikie483a9da2014-05-06 18:35:21 +00002905
Duncan P. N. Exon Smithdadc2b62015-04-21 18:43:54 +00002906 // Create elements for each enumerator.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002907 SmallVector<llvm::Metadata *, 16> Enumerators;
Guy Benyei11169dd2012-12-18 14:30:41 +00002908 ED = ED->getDefinition();
Momchil Velikov25f6be52018-02-12 16:12:52 +00002909 bool IsSigned = ED->getIntegerType()->isSignedIntegerType();
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00002910 for (const auto *Enum : ED->enumerators()) {
Momchil Velikov25f6be52018-02-12 16:12:52 +00002911 const auto &InitVal = Enum->getInitVal();
2912 auto Value = IsSigned ? InitVal.getSExtValue() : InitVal.getZExtValue();
2913 Enumerators.push_back(
2914 DBuilder.createEnumerator(Enum->getName(), Value, !IsSigned));
Guy Benyei11169dd2012-12-18 14:30:41 +00002915 }
2916
2917 // Return a CompositeType for the enum itself.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002918 llvm::DINodeArray EltArray = DBuilder.getOrCreateArray(Enumerators);
Guy Benyei11169dd2012-12-18 14:30:41 +00002919
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002920 llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00002921 unsigned Line = getLineNumber(ED->getLocation());
Amjad Abouddc4531e2016-04-30 01:44:38 +00002922 llvm::DIScope *EnumContext = getDeclContextDescriptor(ED);
Momchil Velikov25f6be52018-02-12 16:12:52 +00002923 llvm::DIType *ClassTy = getOrCreateType(ED->getIntegerType(), DefUnit);
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00002924 return DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit,
2925 Line, Size, Align, EltArray, ClassTy,
Paul Robinsonb1ce7c82019-01-08 16:28:11 +00002926 Identifier, ED->isScoped());
Guy Benyei11169dd2012-12-18 14:30:41 +00002927}
2928
Amjad Aboud546bc112017-02-09 22:07:24 +00002929llvm::DIMacro *CGDebugInfo::CreateMacro(llvm::DIMacroFile *Parent,
2930 unsigned MType, SourceLocation LineLoc,
2931 StringRef Name, StringRef Value) {
2932 unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(LineLoc);
2933 return DBuilder.createMacro(Parent, Line, MType, Name, Value);
2934}
2935
2936llvm::DIMacroFile *CGDebugInfo::CreateTempMacroFile(llvm::DIMacroFile *Parent,
2937 SourceLocation LineLoc,
2938 SourceLocation FileLoc) {
2939 llvm::DIFile *FName = getOrCreateFile(FileLoc);
2940 unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(LineLoc);
2941 return DBuilder.createTempMacroFile(Parent, Line, FName);
2942}
2943
David Blaikie05491062013-01-21 04:37:12 +00002944static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
2945 Qualifiers Quals;
Guy Benyei11169dd2012-12-18 14:30:41 +00002946 do {
Adrian Prantl179af902013-09-26 21:35:50 +00002947 Qualifiers InnerQuals = T.getLocalQualifiers();
2948 // Qualifiers::operator+() doesn't like it if you add a Qualifier
2949 // that is already there.
2950 Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals);
2951 Quals += InnerQuals;
Guy Benyei11169dd2012-12-18 14:30:41 +00002952 QualType LastT = T;
2953 switch (T->getTypeClass()) {
2954 default:
David Blaikie05491062013-01-21 04:37:12 +00002955 return C.getQualifiedType(T.getTypePtr(), Quals);
David Blaikief1b382e2014-04-06 17:14:06 +00002956 case Type::TemplateSpecialization: {
2957 const auto *Spec = cast<TemplateSpecializationType>(T);
2958 if (Spec->isTypeAlias())
2959 return C.getQualifiedType(T.getTypePtr(), Quals);
2960 T = Spec->desugar();
Eric Christophere7b87e52014-10-26 23:40:33 +00002961 break;
2962 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002963 case Type::TypeOfExpr:
2964 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
2965 break;
2966 case Type::TypeOf:
2967 T = cast<TypeOfType>(T)->getUnderlyingType();
2968 break;
2969 case Type::Decltype:
2970 T = cast<DecltypeType>(T)->getUnderlyingType();
2971 break;
2972 case Type::UnaryTransform:
2973 T = cast<UnaryTransformType>(T)->getUnderlyingType();
2974 break;
2975 case Type::Attributed:
2976 T = cast<AttributedType>(T)->getEquivalentType();
2977 break;
2978 case Type::Elaborated:
2979 T = cast<ElaboratedType>(T)->getNamedType();
2980 break;
2981 case Type::Paren:
2982 T = cast<ParenType>(T)->getInnerType();
2983 break;
Leonard Chanc72aaf62019-05-07 03:20:17 +00002984 case Type::MacroQualified:
2985 T = cast<MacroQualifiedType>(T)->getUnderlyingType();
2986 break;
David Blaikie05491062013-01-21 04:37:12 +00002987 case Type::SubstTemplateTypeParm:
Guy Benyei11169dd2012-12-18 14:30:41 +00002988 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
Guy Benyei11169dd2012-12-18 14:30:41 +00002989 break;
Richard Smitha0abc422017-02-22 00:13:14 +00002990 case Type::Auto:
2991 case Type::DeducedTemplateSpecialization: {
2992 QualType DT = cast<DeducedType>(T)->getDeducedType();
David Blaikie42edade2014-11-11 20:44:45 +00002993 assert(!DT.isNull() && "Undeduced types shouldn't reach here.");
David Blaikie22c460a02013-05-24 21:24:35 +00002994 T = DT;
Guy Benyei11169dd2012-12-18 14:30:41 +00002995 break;
2996 }
Jordan Rose303e2f12016-11-10 23:28:17 +00002997 case Type::Adjusted:
2998 case Type::Decayed:
2999 // Decayed and adjusted types use the adjusted type in LLVM and DWARF.
3000 T = cast<AdjustedType>(T)->getAdjustedType();
3001 break;
3002 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00003003
Guy Benyei11169dd2012-12-18 14:30:41 +00003004 assert(T != LastT && "Type unwrapping failed to unwrap!");
NAKAMURA Takumi3e0a3632013-01-21 10:51:28 +00003005 (void)LastT;
Guy Benyei11169dd2012-12-18 14:30:41 +00003006 } while (true);
3007}
3008
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003009llvm::DIType *CGDebugInfo::getTypeOrNull(QualType Ty) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003010
3011 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00003012 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Eric Christopherb2a008c2013-05-16 00:45:12 +00003013
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00003014 auto It = TypeCache.find(Ty.getAsOpaquePtr());
3015 if (It != TypeCache.end()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003016 // Verify that the debug info still exists.
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00003017 if (llvm::Metadata *V = It->second)
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003018 return cast<llvm::DIType>(V);
Guy Benyei11169dd2012-12-18 14:30:41 +00003019 }
3020
Duncan P. N. Exon Smithc7551282015-04-06 23:21:33 +00003021 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003022}
3023
David Blaikie0e716b42014-03-03 23:48:23 +00003024void CGDebugInfo::completeTemplateDefinition(
3025 const ClassTemplateSpecializationDecl &SD) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00003026 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
David Blaikie0856f662014-03-04 22:01:08 +00003027 return;
David Blaikie1ac9c982017-04-11 21:13:37 +00003028 completeUnusedClass(SD);
3029}
David Blaikie0856f662014-03-04 22:01:08 +00003030
David Blaikie1ac9c982017-04-11 21:13:37 +00003031void CGDebugInfo::completeUnusedClass(const CXXRecordDecl &D) {
3032 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
3033 return;
3034
3035 completeClassData(&D);
David Blaikie0e716b42014-03-03 23:48:23 +00003036 // In case this type has no member function definitions being emitted, ensure
3037 // it is retained
David Blaikie1ac9c982017-04-11 21:13:37 +00003038 RetainedTypes.push_back(CGM.getContext().getRecordType(&D).getAsOpaquePtr());
David Blaikie0e716b42014-03-03 23:48:23 +00003039}
3040
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003041llvm::DIType *CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile *Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003042 if (Ty.isNull())
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00003043 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003044
Luboš Luňák4f2104c2019-11-02 16:39:59 +01003045 llvm::TimeTraceScope TimeScope("DebugType", [&]() {
3046 std::string Name;
3047 llvm::raw_string_ostream OS(Name);
3048 Ty.print(OS, getPrintingPolicy());
3049 return Name;
3050 });
3051
Guy Benyei11169dd2012-12-18 14:30:41 +00003052 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00003053 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00003054
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00003055 if (auto *T = getTypeOrNull(Ty))
Guy Benyei11169dd2012-12-18 14:30:41 +00003056 return T;
3057
Adrian Prantlca844182015-09-11 17:23:03 +00003058 llvm::DIType *Res = CreateTypeNode(Ty, Unit);
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00003059 void *TyPtr = Ty.getAsOpaquePtr();
Adrian Prantl73409ce2013-03-11 18:33:46 +00003060
3061 // And update the type cache.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003062 TypeCache[TyPtr].reset(Res);
Guy Benyei11169dd2012-12-18 14:30:41 +00003063
Guy Benyei11169dd2012-12-18 14:30:41 +00003064 return Res;
3065}
3066
Adrian Prantl5c8bd882015-09-11 17:23:08 +00003067llvm::DIModule *CGDebugInfo::getParentModuleOrNull(const Decl *D) {
Adrian Prantl335f5c72015-10-02 17:36:14 +00003068 // A forward declaration inside a module header does not belong to the module.
3069 if (isa<RecordDecl>(D) && !cast<RecordDecl>(D)->getDefinition())
3070 return nullptr;
Adrian Prantl85d938a2015-09-21 17:48:37 +00003071 if (DebugTypeExtRefs && D->isFromASTFile()) {
3072 // Record a reference to an imported clang module or precompiled header.
3073 auto *Reader = CGM.getContext().getExternalSource();
3074 auto Idx = D->getOwningModuleID();
3075 auto Info = Reader->getSourceDescriptor(Idx);
3076 if (Info)
3077 return getOrCreateModuleRef(*Info, /*SkeletonCU=*/true);
3078 } else if (ClangModuleMap) {
Adrian Prantl9402cef2015-09-20 16:51:35 +00003079 // We are building a clang module or a precompiled header.
3080 //
3081 // TODO: When D is a CXXRecordDecl or a C++ Enum, the ODR applies
3082 // and it wouldn't be necessary to specify the parent scope
3083 // because the type is already unique by definition (it would look
3084 // like the output of -fno-standalone-debug). On the other hand,
3085 // the parent scope helps a consumer to quickly locate the object
3086 // file where the type's definition is located, so it might be
3087 // best to make this behavior a command line or debugger tuning
3088 // option.
Richard Smith54f04402017-05-18 02:29:20 +00003089 if (Module *M = D->getOwningModule()) {
Adrian Prantlaa5d08d2016-01-22 21:14:41 +00003090 // This is a (sub-)module.
Reid Klecknerc915cb92020-02-27 18:13:54 -08003091 auto Info = ASTSourceDescriptor(*M);
Adrian Prantl9402cef2015-09-20 16:51:35 +00003092 return getOrCreateModuleRef(Info, /*SkeletonCU=*/false);
Adrian Prantlaa5d08d2016-01-22 21:14:41 +00003093 } else {
3094 // This the precompiled header being built.
3095 return getOrCreateModuleRef(PCHDescriptor, /*SkeletonCU=*/false);
Adrian Prantl9402cef2015-09-20 16:51:35 +00003096 }
3097 }
Adrian Prantl5c8bd882015-09-11 17:23:08 +00003098
Adrian Prantl9402cef2015-09-20 16:51:35 +00003099 return nullptr;
Adrian Prantl5c8bd882015-09-11 17:23:08 +00003100}
3101
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003102llvm::DIType *CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile *Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003103 // Handle qualifiers, which recursively handles what they refer to.
3104 if (Ty.hasLocalQualifiers())
David Blaikie99dab3b2013-09-04 22:03:57 +00003105 return CreateQualifiedType(Ty, Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00003106
Guy Benyei11169dd2012-12-18 14:30:41 +00003107 // Work out details of type.
3108 switch (Ty->getTypeClass()) {
3109#define TYPE(Class, Base)
3110#define ABSTRACT_TYPE(Class, Base)
3111#define NON_CANONICAL_TYPE(Class, Base)
3112#define DEPENDENT_TYPE(Class, Base) case Type::Class:
John McCall36b12a82019-10-02 06:35:23 +00003113#include "clang/AST/TypeNodes.inc"
Guy Benyei11169dd2012-12-18 14:30:41 +00003114 llvm_unreachable("Dependent types cannot show up in debug information");
3115
3116 case Type::ExtVector:
3117 case Type::Vector:
3118 return CreateType(cast<VectorType>(Ty), Unit);
3119 case Type::ObjCObjectPointer:
3120 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
3121 case Type::ObjCObject:
3122 return CreateType(cast<ObjCObjectType>(Ty), Unit);
Manman Rene6be26c2016-09-13 17:25:08 +00003123 case Type::ObjCTypeParam:
3124 return CreateType(cast<ObjCTypeParamType>(Ty), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00003125 case Type::ObjCInterface:
3126 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
3127 case Type::Builtin:
3128 return CreateType(cast<BuiltinType>(Ty));
3129 case Type::Complex:
3130 return CreateType(cast<ComplexType>(Ty));
3131 case Type::Pointer:
3132 return CreateType(cast<PointerType>(Ty), Unit);
3133 case Type::BlockPointer:
3134 return CreateType(cast<BlockPointerType>(Ty), Unit);
3135 case Type::Typedef:
David Blaikie99dab3b2013-09-04 22:03:57 +00003136 return CreateType(cast<TypedefType>(Ty), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00003137 case Type::Record:
David Blaikie99dab3b2013-09-04 22:03:57 +00003138 return CreateType(cast<RecordType>(Ty));
Guy Benyei11169dd2012-12-18 14:30:41 +00003139 case Type::Enum:
Manman Ren1b457022013-08-28 21:20:28 +00003140 return CreateEnumType(cast<EnumType>(Ty));
Guy Benyei11169dd2012-12-18 14:30:41 +00003141 case Type::FunctionProto:
3142 case Type::FunctionNoProto:
3143 return CreateType(cast<FunctionType>(Ty), Unit);
3144 case Type::ConstantArray:
3145 case Type::VariableArray:
3146 case Type::IncompleteArray:
3147 return CreateType(cast<ArrayType>(Ty), Unit);
3148
3149 case Type::LValueReference:
3150 return CreateType(cast<LValueReferenceType>(Ty), Unit);
3151 case Type::RValueReference:
3152 return CreateType(cast<RValueReferenceType>(Ty), Unit);
3153
3154 case Type::MemberPointer:
3155 return CreateType(cast<MemberPointerType>(Ty), Unit);
3156
3157 case Type::Atomic:
3158 return CreateType(cast<AtomicType>(Ty), Unit);
3159
Xiuli Pan9c14e282016-01-09 12:53:17 +00003160 case Type::Pipe:
3161 return CreateType(cast<PipeType>(Ty), Unit);
3162
Guy Benyei11169dd2012-12-18 14:30:41 +00003163 case Type::TemplateSpecialization:
David Blaikief1b382e2014-04-06 17:14:06 +00003164 return CreateType(cast<TemplateSpecializationType>(Ty), Unit);
3165
David Blaikie42edade2014-11-11 20:44:45 +00003166 case Type::Auto:
David Blaikief1b382e2014-04-06 17:14:06 +00003167 case Type::Attributed:
Jordan Rose303e2f12016-11-10 23:28:17 +00003168 case Type::Adjusted:
3169 case Type::Decayed:
Richard Smith600b5262017-01-26 20:40:47 +00003170 case Type::DeducedTemplateSpecialization:
Guy Benyei11169dd2012-12-18 14:30:41 +00003171 case Type::Elaborated:
3172 case Type::Paren:
Leonard Chanc72aaf62019-05-07 03:20:17 +00003173 case Type::MacroQualified:
Guy Benyei11169dd2012-12-18 14:30:41 +00003174 case Type::SubstTemplateTypeParm:
3175 case Type::TypeOfExpr:
3176 case Type::TypeOf:
3177 case Type::Decltype:
3178 case Type::UnaryTransform:
David Blaikie66ed89d2013-07-13 21:08:08 +00003179 case Type::PackExpansion:
David Blaikie22c460a02013-05-24 21:24:35 +00003180 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003181 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00003182
David Blaikie42edade2014-11-11 20:44:45 +00003183 llvm_unreachable("type should have been unwrapped!");
Guy Benyei11169dd2012-12-18 14:30:41 +00003184}
3185
Duncan P. N. Exon Smithbd210e62015-07-24 20:34:41 +00003186llvm::DICompositeType *CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty,
3187 llvm::DIFile *Unit) {
David Blaikie4a2b5ef2013-08-12 22:24:20 +00003188 QualType QTy(Ty, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00003189
Duncan P. N. Exon Smithbd210e62015-07-24 20:34:41 +00003190 auto *T = cast_or_null<llvm::DICompositeType>(getTypeOrNull(QTy));
Guy Benyei11169dd2012-12-18 14:30:41 +00003191
3192 // We may have cached a forward decl when we could have created
3193 // a non-forward decl. Go ahead and create a non-forward decl
3194 // now.
Duncan P. N. Exon Smith4caa7f22015-04-16 01:00:56 +00003195 if (T && !T->isForwardDecl())
Eric Christophere7b87e52014-10-26 23:40:33 +00003196 return T;
Guy Benyei11169dd2012-12-18 14:30:41 +00003197
3198 // Otherwise create the type.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003199 llvm::DICompositeType *Res = CreateLimitedType(Ty);
David Blaikie8d5e1282013-08-20 21:03:29 +00003200
3201 // Propagate members from the declaration to the definition
3202 // CreateType(const RecordType*) will overwrite this with the members in the
3203 // correct order if the full type is needed.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003204 DBuilder.replaceArrays(Res, T ? T->getElements() : llvm::DINodeArray());
Guy Benyei11169dd2012-12-18 14:30:41 +00003205
Guy Benyei11169dd2012-12-18 14:30:41 +00003206 // And update the type cache.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003207 TypeCache[QTy.getAsOpaquePtr()].reset(Res);
Guy Benyei11169dd2012-12-18 14:30:41 +00003208 return Res;
3209}
3210
3211// TODO: Currently used for context chains when limiting debug info.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003212llvm::DICompositeType *CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003213 RecordDecl *RD = Ty->getDecl();
Eric Christopherb2a008c2013-05-16 00:45:12 +00003214
Guy Benyei11169dd2012-12-18 14:30:41 +00003215 // Get overall information about the record type for the debug info.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003216 llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00003217 unsigned Line = getLineNumber(RD->getLocation());
3218 StringRef RDName = getClassName(RD);
3219
Amjad Abouddc4531e2016-04-30 01:44:38 +00003220 llvm::DIScope *RDContext = getDeclContextDescriptor(RD);
Guy Benyei11169dd2012-12-18 14:30:41 +00003221
David Blaikied2785892013-08-18 17:36:19 +00003222 // If we ended up creating the type during the context chain construction,
3223 // just return that.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003224 auto *T = cast_or_null<llvm::DICompositeType>(
Duncan P. N. Exon Smithc7551282015-04-06 23:21:33 +00003225 getTypeOrNull(CGM.getContext().getRecordType(RD)));
Duncan P. N. Exon Smith4caa7f22015-04-16 01:00:56 +00003226 if (T && (!T->isForwardDecl() || !RD->getDefinition()))
Eric Christophere7b87e52014-10-26 23:40:33 +00003227 return T;
David Blaikied2785892013-08-18 17:36:19 +00003228
Adrian Prantl381e7552014-02-04 21:29:50 +00003229 // If this is just a forward or incomplete declaration, construct an
3230 // appropriately marked node and just return it.
3231 const RecordDecl *D = RD->getDefinition();
3232 if (!D || !D->isCompleteDefinition())
Manman Ren1b457022013-08-28 21:20:28 +00003233 return getOrCreateRecordFwdDecl(Ty, RDContext);
Guy Benyei11169dd2012-12-18 14:30:41 +00003234
3235 uint64_t Size = CGM.getContext().getTypeSize(Ty);
Victor Leschuka7ece032016-10-20 00:13:19 +00003236 auto Align = getDeclAlignIfRequired(D, CGM.getContext());
Eric Christopherb2a008c2013-05-16 00:45:12 +00003237
Brock Wyma8557ec52018-05-22 12:41:19 +00003238 SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
Manman Rene0064d82013-08-29 23:19:58 +00003239
Shafik Yaghmour528f5da2019-08-27 20:17:35 +00003240 // Explicitly record the calling convention and export symbols for C++
3241 // records.
Adrian Prantl6c5f03a2018-01-05 01:13:52 +00003242 auto Flags = llvm::DINode::FlagZero;
3243 if (auto CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3244 if (CGM.getCXXABI().getRecordArgABI(CXXRD) == CGCXXABI::RAA_Indirect)
3245 Flags |= llvm::DINode::FlagTypePassByReference;
3246 else
3247 Flags |= llvm::DINode::FlagTypePassByValue;
Aaron Smith044326c2018-07-23 20:49:07 +00003248
Aaron Smithfa7745b2019-04-11 20:24:54 +00003249 // Record if a C++ record is non-trivial type.
3250 if (!CXXRD->isTrivial())
Aaron Smithf0d27332019-02-26 03:49:05 +00003251 Flags |= llvm::DINode::FlagNonTrivial;
Shafik Yaghmour528f5da2019-08-27 20:17:35 +00003252
3253 // Record exports it symbols to the containing structure.
3254 if (CXXRD->isAnonymousStructOrUnion())
3255 Flags |= llvm::DINode::FlagExportSymbols;
Adrian Prantl6c5f03a2018-01-05 01:13:52 +00003256 }
3257
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003258 llvm::DICompositeType *RealDecl = DBuilder.createReplaceableCompositeType(
Leny Kholodov80c047d2016-09-06 10:48:04 +00003259 getTagForRecord(RD), RDName, RDContext, DefUnit, Line, 0, Size, Align,
Brock Wyma8557ec52018-05-22 12:41:19 +00003260 Flags, Identifier);
Guy Benyei11169dd2012-12-18 14:30:41 +00003261
Duncan P. N. Exon Smithf9521b02016-04-17 07:45:08 +00003262 // Elements of composite types usually have back to the type, creating
3263 // uniquing cycles. Distinct nodes are more efficient.
3264 switch (RealDecl->getTag()) {
3265 default:
3266 llvm_unreachable("invalid composite type tag");
3267
3268 case llvm::dwarf::DW_TAG_array_type:
3269 case llvm::dwarf::DW_TAG_enumeration_type:
3270 // Array elements and most enumeration elements don't have back references,
3271 // so they don't tend to be involved in uniquing cycles and there is some
3272 // chance of merging them when linking together two modules. Only make
3273 // them distinct if they are ODR-uniqued.
Brock Wyma8557ec52018-05-22 12:41:19 +00003274 if (Identifier.empty())
Duncan P. N. Exon Smithf9521b02016-04-17 07:45:08 +00003275 break;
Galina Kistanova0872d6c2017-06-03 06:30:46 +00003276 LLVM_FALLTHROUGH;
Duncan P. N. Exon Smithf9521b02016-04-17 07:45:08 +00003277
3278 case llvm::dwarf::DW_TAG_structure_type:
3279 case llvm::dwarf::DW_TAG_union_type:
3280 case llvm::dwarf::DW_TAG_class_type:
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00003281 // Immediately resolve to a distinct node.
Duncan P. N. Exon Smithf9521b02016-04-17 07:45:08 +00003282 RealDecl =
3283 llvm::MDNode::replaceWithDistinct(llvm::TempDICompositeType(RealDecl));
3284 break;
3285 }
3286
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003287 RegionMap[Ty->getDecl()].reset(RealDecl);
3288 TypeCache[QualType(Ty, 0).getAsOpaquePtr()].reset(RealDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00003289
David Majnemer58ed0f32016-07-17 00:39:12 +00003290 if (const auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD))
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003291 DBuilder.replaceArrays(RealDecl, llvm::DINodeArray(),
Duncan P. N. Exon Smithc8ee63e2014-12-18 00:48:56 +00003292 CollectCXXTemplateParams(TSpecial, DefUnit));
David Blaikie952dac32013-08-15 22:42:12 +00003293 return RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00003294}
3295
David Blaikieadfbf992013-08-18 16:55:33 +00003296void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD,
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003297 llvm::DICompositeType *RealDecl) {
David Blaikieadfbf992013-08-18 16:55:33 +00003298 // A class's primary base or the class itself contains the vtable.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003299 llvm::DICompositeType *ContainingType = nullptr;
David Blaikieadfbf992013-08-18 16:55:33 +00003300 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
3301 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
Alp Tokerd4733632013-12-05 04:47:09 +00003302 // Seek non-virtual primary base root.
David Blaikieadfbf992013-08-18 16:55:33 +00003303 while (1) {
3304 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
3305 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
3306 if (PBT && !BRL.isPrimaryBaseVirtual())
3307 PBase = PBT;
3308 else
3309 break;
3310 }
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003311 ContainingType = cast<llvm::DICompositeType>(
David Blaikieadfbf992013-08-18 16:55:33 +00003312 getOrCreateType(QualType(PBase->getTypeForDecl(), 0),
3313 getOrCreateFile(RD->getLocation())));
3314 } else if (RD->isDynamicClass())
3315 ContainingType = RealDecl;
3316
Duncan P. N. Exon Smithc8ee63e2014-12-18 00:48:56 +00003317 DBuilder.replaceVTableHolder(RealDecl, ContainingType);
David Blaikieadfbf992013-08-18 16:55:33 +00003318}
3319
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003320llvm::DIType *CGDebugInfo::CreateMemberType(llvm::DIFile *Unit, QualType FType,
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00003321 StringRef Name, uint64_t *Offset) {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003322 llvm::DIType *FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00003323 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
Victor Leschuka7ece032016-10-20 00:13:19 +00003324 auto FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext());
Leny Kholodovdf050fd2016-09-06 17:06:14 +00003325 llvm::DIType *Ty =
3326 DBuilder.createMemberType(Unit, Name, Unit, 0, FieldSize, FieldAlign,
3327 *Offset, llvm::DINode::FlagZero, FieldTy);
Guy Benyei11169dd2012-12-18 14:30:41 +00003328 *Offset += FieldSize;
3329 return Ty;
3330}
3331
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003332void CGDebugInfo::collectFunctionDeclProps(GlobalDecl GD, llvm::DIFile *Unit,
Duncan P. N. Exon Smith8e47da42015-04-21 20:07:29 +00003333 StringRef &Name,
3334 StringRef &LinkageName,
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003335 llvm::DIScope *&FDContext,
3336 llvm::DINodeArray &TParamsArray,
Leny Kholodov80c047d2016-09-06 10:48:04 +00003337 llvm::DINode::DIFlags &Flags) {
David Majnemer58ed0f32016-07-17 00:39:12 +00003338 const auto *FD = cast<FunctionDecl>(GD.getDecl());
Frederic Riss9db79f12014-11-18 03:40:46 +00003339 Name = getFunctionName(FD);
3340 // Use mangled name as linkage name for C/C++ functions.
3341 if (FD->hasPrototype()) {
3342 LinkageName = CGM.getMangledName(GD);
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003343 Flags |= llvm::DINode::FlagPrototyped;
Frederic Riss9db79f12014-11-18 03:40:46 +00003344 }
3345 // No need to replicate the linkage name if it isn't different from the
3346 // subprogram name, no need to have it at all unless coverage is enabled or
Dehao Chenb3a70de2017-01-19 00:44:21 +00003347 // debug is set to more than just line tables or extra debug info is needed.
Benjamin Kramer8c305922016-02-02 11:06:51 +00003348 if (LinkageName == Name || (!CGM.getCodeGenOpts().EmitGcovArcs &&
3349 !CGM.getCodeGenOpts().EmitGcovNotes &&
Dehao Chenb3a70de2017-01-19 00:44:21 +00003350 !CGM.getCodeGenOpts().DebugInfoForProfiling &&
Benjamin Kramer8c305922016-02-02 11:06:51 +00003351 DebugKind <= codegenoptions::DebugLineTablesOnly))
Frederic Riss9db79f12014-11-18 03:40:46 +00003352 LinkageName = StringRef();
3353
Amy Huang53539bb2020-01-13 15:54:54 -08003354 if (CGM.getCodeGenOpts().hasReducedDebugInfo()) {
Frederic Riss9db79f12014-11-18 03:40:46 +00003355 if (const NamespaceDecl *NSDecl =
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00003356 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
Adrian Prantlddb8e062017-05-12 16:23:53 +00003357 FDContext = getOrCreateNamespace(NSDecl);
Frederic Riss9db79f12014-11-18 03:40:46 +00003358 else if (const RecordDecl *RDecl =
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00003359 dyn_cast_or_null<RecordDecl>(FD->getDeclContext())) {
Adrian Prantl5c8bd882015-09-11 17:23:08 +00003360 llvm::DIScope *Mod = getParentModuleOrNull(RDecl);
3361 FDContext = getContextDescriptor(RDecl, Mod ? Mod : TheCU);
3362 }
Adrian Prantlfd5ac8a2016-08-17 16:20:32 +00003363 // Check if it is a noreturn-marked function
3364 if (FD->isNoReturn())
3365 Flags |= llvm::DINode::FlagNoReturn;
Frederic Riss9db79f12014-11-18 03:40:46 +00003366 // Collect template parameters.
3367 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
3368 }
3369}
3370
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003371void CGDebugInfo::collectVarDeclProps(const VarDecl *VD, llvm::DIFile *&Unit,
Frederic Riss9db79f12014-11-18 03:40:46 +00003372 unsigned &LineNo, QualType &T,
3373 StringRef &Name, StringRef &LinkageName,
Matthew Voss20165362018-10-03 18:45:04 +00003374 llvm::MDTuple *&TemplateParameters,
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003375 llvm::DIScope *&VDContext) {
Frederic Riss9db79f12014-11-18 03:40:46 +00003376 Unit = getOrCreateFile(VD->getLocation());
3377 LineNo = getLineNumber(VD->getLocation());
3378
3379 setLocation(VD->getLocation());
3380
3381 T = VD->getType();
3382 if (T->isIncompleteArrayType()) {
3383 // CodeGen turns int[] into int[1] so we'll do the same here.
3384 llvm::APInt ConstVal(32, 1);
3385 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3386
Richard Smith772e2662019-10-04 01:25:59 +00003387 T = CGM.getContext().getConstantArrayType(ET, ConstVal, nullptr,
3388 ArrayType::Normal, 0);
Frederic Riss9db79f12014-11-18 03:40:46 +00003389 }
3390
3391 Name = VD->getName();
3392 if (VD->getDeclContext() && !isa<FunctionDecl>(VD->getDeclContext()) &&
3393 !isa<ObjCMethodDecl>(VD->getDeclContext()))
3394 LinkageName = CGM.getMangledName(VD);
3395 if (LinkageName == Name)
3396 LinkageName = StringRef();
3397
Matthew Voss20165362018-10-03 18:45:04 +00003398 if (isa<VarTemplateSpecializationDecl>(VD)) {
3399 llvm::DINodeArray parameterNodes = CollectVarTemplateParams(VD, &*Unit);
3400 TemplateParameters = parameterNodes.get();
3401 } else {
3402 TemplateParameters = nullptr;
3403 }
3404
Frederic Riss9db79f12014-11-18 03:40:46 +00003405 // Since we emit declarations (DW_AT_members) for static members, place the
3406 // definition of those static members in the namespace they were declared in
3407 // in the source code (the lexical decl context).
3408 // FIXME: Generalize this for even non-member global variables where the
3409 // declaration and definition may have different lexical decl contexts, once
3410 // we have support for emitting declarations of (non-member) global variables.
Saleem Abdulrasoolcd187f02015-02-28 00:13:13 +00003411 const DeclContext *DC = VD->isStaticDataMember() ? VD->getLexicalDeclContext()
3412 : VD->getDeclContext();
3413 // When a record type contains an in-line initialization of a static data
3414 // member, and the record type is marked as __declspec(dllexport), an implicit
3415 // definition of the member will be created in the record context. DWARF
3416 // doesn't seem to have a nice way to describe this in a form that consumers
3417 // are likely to understand, so fake the "normal" situation of a definition
3418 // outside the class by putting it in the global scope.
3419 if (DC->isRecord())
3420 DC = CGM.getContext().getTranslationUnitDecl();
Adrian Prantl5c8bd882015-09-11 17:23:08 +00003421
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00003422 llvm::DIScope *Mod = getParentModuleOrNull(VD);
3423 VDContext = getContextDescriptor(cast<Decl>(DC), Mod ? Mod : TheCU);
Frederic Riss9db79f12014-11-18 03:40:46 +00003424}
3425
Adrian Prantlb7acfc02017-02-27 21:30:05 +00003426llvm::DISubprogram *CGDebugInfo::getFunctionFwdDeclOrStub(GlobalDecl GD,
3427 bool Stub) {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003428 llvm::DINodeArray TParamsArray;
Frederic Rissd253ed62014-11-18 03:40:51 +00003429 StringRef Name, LinkageName;
Leny Kholodov80c047d2016-09-06 10:48:04 +00003430 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
Paul Robinsoncda54212018-11-19 18:29:28 +00003431 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
Adrian Prantlb7acfc02017-02-27 21:30:05 +00003432 SourceLocation Loc = GD.getDecl()->getLocation();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003433 llvm::DIFile *Unit = getOrCreateFile(Loc);
3434 llvm::DIScope *DContext = Unit;
Frederic Rissd253ed62014-11-18 03:40:51 +00003435 unsigned Line = getLineNumber(Loc);
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00003436 collectFunctionDeclProps(GD, Unit, Name, LinkageName, DContext, TParamsArray,
3437 Flags);
Simon Pilgrimcfee2ef2019-10-16 10:38:49 +00003438 auto *FD = cast<FunctionDecl>(GD.getDecl());
Adrian Prantlb7acfc02017-02-27 21:30:05 +00003439
Frederic Rissd253ed62014-11-18 03:40:51 +00003440 // Build function type.
3441 SmallVector<QualType, 16> ArgTypes;
Simon Pilgrimcfee2ef2019-10-16 10:38:49 +00003442 for (const ParmVarDecl *Parm : FD->parameters())
3443 ArgTypes.push_back(Parm->getType());
3444
Reid Klecknerf00f8032016-06-08 20:41:54 +00003445 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
3446 QualType FnType = CGM.getContext().getFunctionType(
3447 FD->getReturnType(), ArgTypes, FunctionProtoType::ExtProtoInfo(CC));
Paul Robinsoncda54212018-11-19 18:29:28 +00003448 if (!FD->isExternallyVisible())
3449 SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;
3450 if (CGM.getLangOpts().Optimize)
3451 SPFlags |= llvm::DISubprogram::SPFlagOptimized;
3452
Adrian Prantlb7acfc02017-02-27 21:30:05 +00003453 if (Stub) {
Vedant Kumar5931b4e2018-10-05 20:37:17 +00003454 Flags |= getCallSiteRelatedAttrs();
Paul Robinsoncda54212018-11-19 18:29:28 +00003455 SPFlags |= llvm::DISubprogram::SPFlagDefinition;
Adrian Prantlb7acfc02017-02-27 21:30:05 +00003456 return DBuilder.createFunction(
3457 DContext, Name, LinkageName, Unit, Line,
Paul Robinsoncda54212018-11-19 18:29:28 +00003458 getOrCreateFunctionType(GD.getDecl(), FnType, Unit), 0, Flags, SPFlags,
Adrian Prantlb7acfc02017-02-27 21:30:05 +00003459 TParamsArray.get(), getFunctionDeclaration(FD));
3460 }
3461
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003462 llvm::DISubprogram *SP = DBuilder.createTempFunctionFwdDecl(
Duncan P. N. Exon Smithebad0aa2015-04-07 16:50:49 +00003463 DContext, Name, LinkageName, Unit, Line,
Paul Robinsoncda54212018-11-19 18:29:28 +00003464 getOrCreateFunctionType(GD.getDecl(), FnType, Unit), 0, Flags, SPFlags,
Duncan P. N. Exon Smithebad0aa2015-04-07 16:50:49 +00003465 TParamsArray.get(), getFunctionDeclaration(FD));
George Burgess IV00f70bd2018-03-01 05:43:23 +00003466 const FunctionDecl *CanonDecl = FD->getCanonicalDecl();
Duncan P. N. Exon Smith4078ad42015-04-16 16:36:45 +00003467 FwdDeclReplaceMap.emplace_back(std::piecewise_construct,
3468 std::make_tuple(CanonDecl),
3469 std::make_tuple(SP));
Frederic Rissd253ed62014-11-18 03:40:51 +00003470 return SP;
3471}
3472
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00003473llvm::DISubprogram *CGDebugInfo::getFunctionForwardDeclaration(GlobalDecl GD) {
Adrian Prantlb7acfc02017-02-27 21:30:05 +00003474 return getFunctionFwdDeclOrStub(GD, /* Stub = */ false);
3475}
3476
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00003477llvm::DISubprogram *CGDebugInfo::getFunctionStub(GlobalDecl GD) {
Adrian Prantlb7acfc02017-02-27 21:30:05 +00003478 return getFunctionFwdDeclOrStub(GD, /* Stub = */ true);
3479}
3480
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003481llvm::DIGlobalVariable *
Frederic Rissd253ed62014-11-18 03:40:51 +00003482CGDebugInfo::getGlobalVariableForwardDeclaration(const VarDecl *VD) {
3483 QualType T;
3484 StringRef Name, LinkageName;
3485 SourceLocation Loc = VD->getLocation();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003486 llvm::DIFile *Unit = getOrCreateFile(Loc);
3487 llvm::DIScope *DContext = Unit;
Frederic Rissd253ed62014-11-18 03:40:51 +00003488 unsigned Line = getLineNumber(Loc);
Matthew Voss20165362018-10-03 18:45:04 +00003489 llvm::MDTuple *TemplateParameters = nullptr;
Frederic Rissd253ed62014-11-18 03:40:51 +00003490
Matthew Voss20165362018-10-03 18:45:04 +00003491 collectVarDeclProps(VD, Unit, Line, T, Name, LinkageName, TemplateParameters,
3492 DContext);
Victor Leschuka7ece032016-10-20 00:13:19 +00003493 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
Duncan P. N. Exon Smithdadc2b62015-04-21 18:43:54 +00003494 auto *GV = DBuilder.createTempGlobalVariableFwdDecl(
3495 DContext, Name, LinkageName, Unit, Line, getOrCreateType(T, Unit),
Matthew Voss20165362018-10-03 18:45:04 +00003496 !VD->isExternallyVisible(), nullptr, TemplateParameters, Align);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003497 FwdDeclReplaceMap.emplace_back(
3498 std::piecewise_construct,
3499 std::make_tuple(cast<VarDecl>(VD->getCanonicalDecl())),
3500 std::make_tuple(static_cast<llvm::Metadata *>(GV)));
Frederic Rissd253ed62014-11-18 03:40:51 +00003501 return GV;
3502}
3503
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003504llvm::DINode *CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
David Blaikiebd483762013-05-20 04:58:53 +00003505 // We only need a declaration (not a definition) of the type - so use whatever
3506 // we would otherwise do to get a type for a pointee. (forward declarations in
3507 // limited debug info, full definitions (if the type definition is available)
3508 // in unlimited debug info)
David Majnemer58ed0f32016-07-17 00:39:12 +00003509 if (const auto *TD = dyn_cast<TypeDecl>(D))
David Blaikie6b7d060c2013-08-12 23:14:36 +00003510 return getOrCreateType(CGM.getContext().getTypeDeclType(TD),
David Blaikie99dab3b2013-09-04 22:03:57 +00003511 getOrCreateFile(TD->getLocation()));
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003512 auto I = DeclCache.find(D->getCanonicalDecl());
Frederic Rissd253ed62014-11-18 03:40:51 +00003513
Adrian Prantl5f4740d2016-12-20 02:10:02 +00003514 if (I != DeclCache.end()) {
3515 auto N = I->second;
3516 if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(N))
3517 return GVE->getVariable();
3518 return dyn_cast_or_null<llvm::DINode>(N);
3519 }
Frederic Rissd253ed62014-11-18 03:40:51 +00003520
3521 // No definition for now. Emit a forward definition that might be
3522 // merged with a potential upcoming definition.
David Majnemer58ed0f32016-07-17 00:39:12 +00003523 if (const auto *FD = dyn_cast<FunctionDecl>(D))
Frederic Rissd253ed62014-11-18 03:40:51 +00003524 return getFunctionForwardDeclaration(FD);
3525 else if (const auto *VD = dyn_cast<VarDecl>(D))
3526 return getGlobalVariableForwardDeclaration(VD);
3527
Duncan P. N. Exon Smith4078ad42015-04-16 16:36:45 +00003528 return nullptr;
David Blaikiebd483762013-05-20 04:58:53 +00003529}
3530
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003531llvm::DISubprogram *CGDebugInfo::getFunctionDeclaration(const Decl *D) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00003532 if (!D || DebugKind <= codegenoptions::DebugLineTablesOnly)
Duncan P. N. Exon Smitha7fbcbf2015-04-20 22:09:57 +00003533 return nullptr;
David Blaikie18cfbc52013-06-22 00:09:36 +00003534
David Majnemer58ed0f32016-07-17 00:39:12 +00003535 const auto *FD = dyn_cast<FunctionDecl>(D);
Eric Christophere7b87e52014-10-26 23:40:33 +00003536 if (!FD)
Duncan P. N. Exon Smitha7fbcbf2015-04-20 22:09:57 +00003537 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003538
3539 // Setup context.
Adrian Prantl6ec370a2015-09-10 18:39:45 +00003540 auto *S = getDeclContextDescriptor(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00003541
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003542 auto MI = SPCache.find(FD->getCanonicalDecl());
David Blaikiefd07c602013-08-09 17:20:05 +00003543 if (MI == SPCache.end()) {
David Majnemer58ed0f32016-07-17 00:39:12 +00003544 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {
Duncan P. N. Exon Smithc09c5482015-04-20 21:17:26 +00003545 return CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()),
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003546 cast<llvm::DICompositeType>(S));
David Blaikiefd07c602013-08-09 17:20:05 +00003547 }
3548 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003549 if (MI != SPCache.end()) {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003550 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
Duncan P. N. Exon Smith87afdeb2015-04-14 03:24:14 +00003551 if (SP && !SP->isDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00003552 return SP;
3553 }
3554
Aaron Ballman86c93902014-03-06 23:45:36 +00003555 for (auto NextFD : FD->redecls()) {
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003556 auto MI = SPCache.find(NextFD->getCanonicalDecl());
Guy Benyei11169dd2012-12-18 14:30:41 +00003557 if (MI != SPCache.end()) {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003558 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
Duncan P. N. Exon Smith87afdeb2015-04-14 03:24:14 +00003559 if (SP && !SP->isDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00003560 return SP;
3561 }
3562 }
Duncan P. N. Exon Smitha7fbcbf2015-04-20 22:09:57 +00003563 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003564}
3565
Adrian Prantl901cc4a2019-11-08 09:24:31 -08003566llvm::DISubprogram *CGDebugInfo::getObjCMethodDeclaration(
3567 const Decl *D, llvm::DISubroutineType *FnType, unsigned LineNo,
3568 llvm::DINode::DIFlags Flags, llvm::DISubprogram::DISPFlags SPFlags) {
3569 if (!D || DebugKind <= codegenoptions::DebugLineTablesOnly)
3570 return nullptr;
3571
Adrian Prantle0cabe22019-11-21 09:56:01 -08003572 const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
3573 if (!OMD)
3574 return nullptr;
3575
3576 if (CGM.getCodeGenOpts().DwarfVersion < 5 && !OMD->isDirectMethod())
Adrian Prantl901cc4a2019-11-08 09:24:31 -08003577 return nullptr;
3578
Raphael Isemannccfab8e2019-12-17 09:36:57 +01003579 if (OMD->isDirectMethod())
3580 SPFlags |= llvm::DISubprogram::SPFlagObjCDirect;
3581
Adrian Prantl901cc4a2019-11-08 09:24:31 -08003582 // Starting with DWARF V5 method declarations are emitted as children of
3583 // the interface type.
Adrian Prantl901cc4a2019-11-08 09:24:31 -08003584 auto *ID = dyn_cast_or_null<ObjCInterfaceDecl>(D->getDeclContext());
3585 if (!ID)
3586 ID = OMD->getClassInterface();
3587 if (!ID)
3588 return nullptr;
3589 QualType QTy(ID->getTypeForDecl(), 0);
3590 auto It = TypeCache.find(QTy.getAsOpaquePtr());
3591 if (It == TypeCache.end())
3592 return nullptr;
3593 auto *InterfaceType = cast<llvm::DICompositeType>(It->second);
3594 llvm::DISubprogram *FD = DBuilder.createFunction(
3595 InterfaceType, getObjCMethodName(OMD), StringRef(),
3596 InterfaceType->getFile(), LineNo, FnType, LineNo, Flags, SPFlags);
3597 DBuilder.finalizeSubprogram(FD);
Adrian Prantle0cabe22019-11-21 09:56:01 -08003598 ObjCMethodCache[ID].push_back({FD, OMD->isDirectMethod()});
Adrian Prantl901cc4a2019-11-08 09:24:31 -08003599 return FD;
3600}
3601
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00003602// getOrCreateFunctionType - Construct type. If it is a c++ method, include
Guy Benyei11169dd2012-12-18 14:30:41 +00003603// implicit parameter "this".
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003604llvm::DISubroutineType *CGDebugInfo::getOrCreateFunctionType(const Decl *D,
Duncan P. N. Exon Smith4078ad42015-04-16 16:36:45 +00003605 QualType FnType,
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003606 llvm::DIFile *F) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00003607 if (!D || DebugKind <= codegenoptions::DebugLineTablesOnly)
Duncan P. N. Exon Smitha7fbcbf2015-04-20 22:09:57 +00003608 // Create fake but valid subroutine type. Otherwise -verify would fail, and
3609 // subprogram DIE will miss DW_AT_decl_file and DW_AT_decl_line fields.
Eric Christopher28a6db52015-10-15 06:56:08 +00003610 return DBuilder.createSubroutineType(DBuilder.getOrCreateTypeArray(None));
Guy Benyei11169dd2012-12-18 14:30:41 +00003611
David Majnemer58ed0f32016-07-17 00:39:12 +00003612 if (const auto *Method = dyn_cast<CXXMethodDecl>(D))
Awanish Pandeyc83602f2020-01-23 16:06:52 +05303613 return getOrCreateMethodType(Method, F, false);
Reid Klecknerf00f8032016-06-08 20:41:54 +00003614
3615 const auto *FTy = FnType->getAs<FunctionType>();
3616 CallingConv CC = FTy ? FTy->getCallConv() : CallingConv::CC_C;
3617
David Majnemer58ed0f32016-07-17 00:39:12 +00003618 if (const auto *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003619 // Add "self" and "_cmd"
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003620 SmallVector<llvm::Metadata *, 16> Elts;
Guy Benyei11169dd2012-12-18 14:30:41 +00003621
3622 // First element is always return type. For 'void' functions it is NULL.
Alp Toker314cc812014-01-25 16:55:45 +00003623 QualType ResultTy = OMethod->getReturnType();
Adrian Prantl5f360102013-05-22 21:37:49 +00003624
3625 // Replace the instancetype keyword with the actual type.
3626 if (ResultTy == CGM.getContext().getObjCInstanceType())
3627 ResultTy = CGM.getContext().getPointerType(
Eric Christophere7b87e52014-10-26 23:40:33 +00003628 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
Adrian Prantl5f360102013-05-22 21:37:49 +00003629
Adrian Prantl7bec9032013-05-10 21:08:31 +00003630 Elts.push_back(getOrCreateType(ResultTy, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00003631 // "self" pointer is always first argument.
Adrian Prantl748a6cd2015-09-08 20:41:52 +00003632 QualType SelfDeclTy;
3633 if (auto *SelfDecl = OMethod->getSelfDecl())
3634 SelfDeclTy = SelfDecl->getType();
3635 else if (auto *FPT = dyn_cast<FunctionProtoType>(FnType))
3636 if (FPT->getNumParams() > 1)
3637 SelfDeclTy = FPT->getParamType(0);
3638 if (!SelfDeclTy.isNull())
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00003639 Elts.push_back(
3640 CreateSelfType(SelfDeclTy, getOrCreateType(SelfDeclTy, F)));
Guy Benyei11169dd2012-12-18 14:30:41 +00003641 // "_cmd" pointer is always second argument.
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00003642 Elts.push_back(DBuilder.createArtificialType(
Adrian Prantl748a6cd2015-09-08 20:41:52 +00003643 getOrCreateType(CGM.getContext().getObjCSelType(), F)));
Guy Benyei11169dd2012-12-18 14:30:41 +00003644 // Get rest of the arguments.
David Majnemer59f77922016-06-24 04:05:48 +00003645 for (const auto *PI : OMethod->parameters())
Aaron Ballman43b68be2014-03-07 17:50:17 +00003646 Elts.push_back(getOrCreateType(PI->getType(), F));
Frederic Riss787d9d62014-08-12 04:42:23 +00003647 // Variadic methods need a special marker at the end of the type list.
3648 if (OMethod->isVariadic())
3649 Elts.push_back(DBuilder.createUnspecifiedParameter());
Guy Benyei11169dd2012-12-18 14:30:41 +00003650
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003651 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
Leny Kholodov80c047d2016-09-06 10:48:04 +00003652 return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
3653 getDwarfCC(CC));
Guy Benyei11169dd2012-12-18 14:30:41 +00003654 }
Adrian Prantld45ba252014-02-25 19:38:11 +00003655
Adrian Prantl800faef2014-02-25 23:42:18 +00003656 // Handle variadic function types; they need an additional
3657 // unspecified parameter.
David Majnemer58ed0f32016-07-17 00:39:12 +00003658 if (const auto *FD = dyn_cast<FunctionDecl>(D))
Adrian Prantld45ba252014-02-25 19:38:11 +00003659 if (FD->isVariadic()) {
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003660 SmallVector<llvm::Metadata *, 16> EltTys;
Adrian Prantld45ba252014-02-25 19:38:11 +00003661 EltTys.push_back(getOrCreateType(FD->getReturnType(), F));
David Majnemer58ed0f32016-07-17 00:39:12 +00003662 if (const auto *FPT = dyn_cast<FunctionProtoType>(FnType))
3663 for (QualType ParamType : FPT->param_types())
3664 EltTys.push_back(getOrCreateType(ParamType, F));
Adrian Prantld45ba252014-02-25 19:38:11 +00003665 EltTys.push_back(DBuilder.createUnspecifiedParameter());
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003666 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
Leny Kholodov80c047d2016-09-06 10:48:04 +00003667 return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
3668 getDwarfCC(CC));
Adrian Prantld45ba252014-02-25 19:38:11 +00003669 }
3670
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003671 return cast<llvm::DISubroutineType>(getOrCreateType(FnType, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00003672}
3673
Eric Christophere7b87e52014-10-26 23:40:33 +00003674void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, SourceLocation Loc,
3675 SourceLocation ScopeLoc, QualType FnType,
Brock Wyma94ece8f2018-04-16 16:53:57 +00003676 llvm::Function *Fn, bool CurFuncIsThunk,
3677 CGBuilderTy &Builder) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003678
3679 StringRef Name;
3680 StringRef LinkageName;
3681
3682 FnBeginRegionCount.push_back(LexicalBlockStack.size());
3683
3684 const Decl *D = GD.getDecl();
Craig Topper8a13c412014-05-21 05:09:00 +00003685 bool HasDecl = (D != nullptr);
Eric Christopher885c41b2014-04-01 22:25:28 +00003686
Leny Kholodov80c047d2016-09-06 10:48:04 +00003687 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
Paul Robinsoncda54212018-11-19 18:29:28 +00003688 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003689 llvm::DIFile *Unit = getOrCreateFile(Loc);
3690 llvm::DIScope *FDContext = Unit;
3691 llvm::DINodeArray TParamsArray;
Guy Benyei11169dd2012-12-18 14:30:41 +00003692 if (!HasDecl) {
3693 // Use llvm function name.
David Blaikieebe87e12013-08-27 23:57:18 +00003694 LinkageName = Fn->getName();
David Majnemer58ed0f32016-07-17 00:39:12 +00003695 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Duncan P. N. Exon Smitha7fbcbf2015-04-20 22:09:57 +00003696 // If there is a subprogram for this function available then use it.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003697 auto FI = SPCache.find(FD->getCanonicalDecl());
Guy Benyei11169dd2012-12-18 14:30:41 +00003698 if (FI != SPCache.end()) {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003699 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
Duncan P. N. Exon Smith87afdeb2015-04-14 03:24:14 +00003700 if (SP && SP->isDefinition()) {
Duncan P. N. Exon Smithd899f6e2015-04-18 00:07:30 +00003701 LexicalBlockStack.emplace_back(SP);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003702 RegionMap[D].reset(SP);
Guy Benyei11169dd2012-12-18 14:30:41 +00003703 return;
3704 }
3705 }
Frederic Riss9db79f12014-11-18 03:40:46 +00003706 collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
3707 TParamsArray, Flags);
David Majnemer58ed0f32016-07-17 00:39:12 +00003708 } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003709 Name = getObjCMethodName(OMD);
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003710 Flags |= llvm::DINode::FlagPrototyped;
Reid Kleckner105c5652019-04-24 22:45:44 +00003711 } else if (isa<VarDecl>(D) &&
3712 GD.getDynamicInitKind() != DynamicInitKind::NoStub) {
3713 // This is a global initializer or atexit destructor for a global variable.
3714 Name = getDynamicInitializerName(cast<VarDecl>(D), GD.getDynamicInitKind(),
3715 Fn);
Guy Benyei11169dd2012-12-18 14:30:41 +00003716 } else {
Guy Benyei11169dd2012-12-18 14:30:41 +00003717 Name = Fn->getName();
shafik428583d2020-02-05 10:39:35 -08003718
Michael Liao318d0ed2020-02-06 12:19:55 -05003719 if (isa<BlockDecl>(D))
shafik428583d2020-02-05 10:39:35 -08003720 LinkageName = Name;
3721
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003722 Flags |= llvm::DINode::FlagPrototyped;
Guy Benyei11169dd2012-12-18 14:30:41 +00003723 }
David Majnemer58ed0f32016-07-17 00:39:12 +00003724 if (Name.startswith("\01"))
Guy Benyei11169dd2012-12-18 14:30:41 +00003725 Name = Name.substr(1);
3726
Alexandre Ganeacaf31662019-11-15 16:21:17 -05003727 if (!HasDecl || D->isImplicit() || D->hasAttr<ArtificialAttr>()) {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003728 Flags |= llvm::DINode::FlagArtificial;
Adrian Prantldb763572016-11-09 21:43:51 +00003729 // Artificial functions should not silently reuse CurLoc.
3730 CurLoc = SourceLocation();
Adrian Prantl42d71b92014-04-10 23:21:53 +00003731 }
Brock Wyma94ece8f2018-04-16 16:53:57 +00003732
3733 if (CurFuncIsThunk)
3734 Flags |= llvm::DINode::FlagThunk;
3735
Paul Robinsoncda54212018-11-19 18:29:28 +00003736 if (Fn->hasLocalLinkage())
3737 SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;
3738 if (CGM.getLangOpts().Optimize)
3739 SPFlags |= llvm::DISubprogram::SPFlagOptimized;
3740
Vedant Kumar5931b4e2018-10-05 20:37:17 +00003741 llvm::DINode::DIFlags FlagsForDef = Flags | getCallSiteRelatedAttrs();
Paul Robinsoncda54212018-11-19 18:29:28 +00003742 llvm::DISubprogram::DISPFlags SPFlagsForDef =
3743 SPFlags | llvm::DISubprogram::SPFlagDefinition;
Vedant Kumar5931b4e2018-10-05 20:37:17 +00003744
Adrian Prantl42d71b92014-04-10 23:21:53 +00003745 unsigned LineNo = getLineNumber(Loc);
3746 unsigned ScopeLine = getLineNumber(ScopeLoc);
Adrian Prantl901cc4a2019-11-08 09:24:31 -08003747 llvm::DISubroutineType *DIFnType = getOrCreateFunctionType(D, FnType, Unit);
3748 llvm::DISubprogram *Decl = nullptr;
3749 if (D)
3750 Decl = isa<ObjCMethodDecl>(D)
3751 ? getObjCMethodDeclaration(D, DIFnType, LineNo, Flags, SPFlags)
3752 : getFunctionDeclaration(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00003753
Eric Christopher8018e412014-03-27 18:50:35 +00003754 // FIXME: The function declaration we're constructing here is mostly reusing
3755 // declarations from CXXMethodDecl and not constructing new ones for arbitrary
3756 // FunctionDecls. When/if we fix this we can have FDContext be TheCU/null for
3757 // all subprograms instead of the actual context since subprogram definitions
3758 // are emitted as CU level entities by the backend.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003759 llvm::DISubprogram *SP = DBuilder.createFunction(
Adrian Prantl901cc4a2019-11-08 09:24:31 -08003760 FDContext, Name, LinkageName, Unit, LineNo, DIFnType, ScopeLine,
3761 FlagsForDef, SPFlagsForDef, TParamsArray.get(), Decl);
Peter Collingbourne0900fe02015-11-05 22:04:14 +00003762 Fn->setSubprogram(SP);
Frederic Rissb1ab28c2014-11-05 19:19:04 +00003763 // We might get here with a VarDecl in the case we're generating
3764 // code for the initialization of globals. Do not record these decls
3765 // as they will overwrite the actual VarDecl Decl in the cache.
3766 if (HasDecl && isa<FunctionDecl>(D))
David Majnemer58ed0f32016-07-17 00:39:12 +00003767 DeclCache[D->getCanonicalDecl()].reset(SP);
Guy Benyei11169dd2012-12-18 14:30:41 +00003768
Adrian Prantlbebb8932014-03-21 21:01:58 +00003769 // Push the function onto the lexical block stack.
Duncan P. N. Exon Smithd899f6e2015-04-18 00:07:30 +00003770 LexicalBlockStack.emplace_back(SP);
Adrian Prantlbebb8932014-03-21 21:01:58 +00003771
Guy Benyei11169dd2012-12-18 14:30:41 +00003772 if (HasDecl)
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003773 RegionMap[D].reset(SP);
Guy Benyei11169dd2012-12-18 14:30:41 +00003774}
3775
Vedant Kumar8bd52142019-07-11 19:28:07 +00003776void CGDebugInfo::EmitFunctionDecl(GlobalDecl GD, SourceLocation Loc,
3777 QualType FnType, llvm::Function *Fn) {
Adrian Prantl748a6cd2015-09-08 20:41:52 +00003778 StringRef Name;
3779 StringRef LinkageName;
3780
3781 const Decl *D = GD.getDecl();
3782 if (!D)
Vedant Kumar8bd52142019-07-11 19:28:07 +00003783 return;
Adrian Prantl748a6cd2015-09-08 20:41:52 +00003784
Luboš Luňák4f2104c2019-11-02 16:39:59 +01003785 llvm::TimeTraceScope TimeScope("DebugFunction", [&]() {
3786 std::string Name;
3787 llvm::raw_string_ostream OS(Name);
3788 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
3789 ND->getNameForDiagnostic(OS, getPrintingPolicy(),
3790 /*Qualified=*/true);
3791 return Name;
3792 });
3793
Leny Kholodov80c047d2016-09-06 10:48:04 +00003794 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
Adrian Prantl748a6cd2015-09-08 20:41:52 +00003795 llvm::DIFile *Unit = getOrCreateFile(Loc);
Vedant Kumar8bd52142019-07-11 19:28:07 +00003796 bool IsDeclForCallSite = Fn ? true : false;
Djordje Todorovic0f651682019-06-27 06:44:44 +00003797 llvm::DIScope *FDContext =
3798 IsDeclForCallSite ? Unit : getDeclContextDescriptor(D);
Adrian Prantl748a6cd2015-09-08 20:41:52 +00003799 llvm::DINodeArray TParamsArray;
3800 if (isa<FunctionDecl>(D)) {
3801 // If there is a DISubprogram for this function available then use it.
3802 collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
3803 TParamsArray, Flags);
David Majnemer58ed0f32016-07-17 00:39:12 +00003804 } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) {
Adrian Prantl748a6cd2015-09-08 20:41:52 +00003805 Name = getObjCMethodName(OMD);
3806 Flags |= llvm::DINode::FlagPrototyped;
3807 } else {
3808 llvm_unreachable("not a function or ObjC method");
3809 }
3810 if (!Name.empty() && Name[0] == '\01')
3811 Name = Name.substr(1);
3812
3813 if (D->isImplicit()) {
3814 Flags |= llvm::DINode::FlagArtificial;
3815 // Artificial functions without a location should not silently reuse CurLoc.
3816 if (Loc.isInvalid())
3817 CurLoc = SourceLocation();
3818 }
3819 unsigned LineNo = getLineNumber(Loc);
3820 unsigned ScopeLine = 0;
Paul Robinsoncda54212018-11-19 18:29:28 +00003821 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
3822 if (CGM.getLangOpts().Optimize)
3823 SPFlags |= llvm::DISubprogram::SPFlagOptimized;
Adrian Prantl748a6cd2015-09-08 20:41:52 +00003824
Djordje Todorovic0f651682019-06-27 06:44:44 +00003825 llvm::DISubprogram *SP = DBuilder.createFunction(
Adrian Prantle76bda52016-04-15 15:55:45 +00003826 FDContext, Name, LinkageName, Unit, LineNo,
Paul Robinsoncda54212018-11-19 18:29:28 +00003827 getOrCreateFunctionType(D, FnType, Unit), ScopeLine, Flags, SPFlags,
Djordje Todorovic0f651682019-06-27 06:44:44 +00003828 TParamsArray.get(), getFunctionDeclaration(D));
Vedant Kumar8bd52142019-07-11 19:28:07 +00003829
3830 if (IsDeclForCallSite)
3831 Fn->setSubprogram(SP);
3832
Djordje Todorovic0f651682019-06-27 06:44:44 +00003833 DBuilder.retainType(SP);
3834}
3835
3836void CGDebugInfo::EmitFuncDeclForCallSite(llvm::CallBase *CallOrInvoke,
3837 QualType CalleeType,
3838 const FunctionDecl *CalleeDecl) {
Vedant Kumar568db782019-11-13 18:19:32 -08003839 if (!CallOrInvoke)
Djordje Todorovic0f651682019-06-27 06:44:44 +00003840 return;
Djordje Todorovic0f651682019-06-27 06:44:44 +00003841 auto *Func = CallOrInvoke->getCalledFunction();
3842 if (!Func)
3843 return;
Vedant Kumar568db782019-11-13 18:19:32 -08003844 if (Func->getSubprogram())
3845 return;
3846
3847 // Do not emit a declaration subprogram for a builtin or if call site info
3848 // isn't required. Also, elide declarations for functions with reserved names,
3849 // as call site-related features aren't interesting in this case (& also, the
3850 // compiler may emit calls to these functions without debug locations, which
3851 // makes the verifier complain).
3852 if (CalleeDecl->getBuiltinID() != 0 ||
3853 getCallSiteRelatedAttrs() == llvm::DINode::FlagZero)
3854 return;
3855 if (const auto *Id = CalleeDecl->getIdentifier())
3856 if (Id->isReservedName())
3857 return;
Djordje Todorovic0f651682019-06-27 06:44:44 +00003858
3859 // If there is no DISubprogram attached to the function being called,
3860 // create the one describing the function in order to have complete
3861 // call site debug info.
Vedant Kumar8bd52142019-07-11 19:28:07 +00003862 if (!CalleeDecl->isStatic() && !CalleeDecl->isInlined())
Michael Liao4cf01ed2020-03-18 01:43:20 -04003863 EmitFunctionDecl(CalleeDecl, CalleeDecl->getLocation(), CalleeType, Func);
Adrian Prantl748a6cd2015-09-08 20:41:52 +00003864}
3865
Adrian Prantlb7acfc02017-02-27 21:30:05 +00003866void CGDebugInfo::EmitInlineFunctionStart(CGBuilderTy &Builder, GlobalDecl GD) {
3867 const auto *FD = cast<FunctionDecl>(GD.getDecl());
3868 // If there is a subprogram for this function available then use it.
3869 auto FI = SPCache.find(FD->getCanonicalDecl());
3870 llvm::DISubprogram *SP = nullptr;
3871 if (FI != SPCache.end())
3872 SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
Adrian Prantl8040a212017-08-23 21:24:12 +00003873 if (!SP || !SP->isDefinition())
Adrian Prantlb7acfc02017-02-27 21:30:05 +00003874 SP = getFunctionStub(GD);
3875 FnBeginRegionCount.push_back(LexicalBlockStack.size());
3876 LexicalBlockStack.emplace_back(SP);
3877 setInlinedAt(Builder.getCurrentDebugLocation());
3878 EmitLocation(Builder, FD->getLocation());
3879}
3880
3881void CGDebugInfo::EmitInlineFunctionEnd(CGBuilderTy &Builder) {
3882 assert(CurInlinedAt && "unbalanced inline scope stack");
Keno Fischer41d4b4e2017-06-01 21:14:03 +00003883 EmitFunctionEnd(Builder, nullptr);
Adrian Prantlb7acfc02017-02-27 21:30:05 +00003884 setInlinedAt(llvm::DebugLoc(CurInlinedAt).getInlinedAt());
3885}
3886
Calixte Denizetfcd661d2018-09-24 18:24:18 +00003887void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003888 // Update our current location
3889 setLocation(Loc);
3890
Adrian Prantl42ab39f2018-11-09 21:17:38 +00003891 if (CurLoc.isInvalid() || CurLoc.isMacroID() || LexicalBlockStack.empty())
Eric Christophere7b87e52014-10-26 23:40:33 +00003892 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00003893
Adrian Prantle83b1302014-01-07 22:05:52 +00003894 llvm::MDNode *Scope = LexicalBlockStack.back();
Calixte Denizetfcd661d2018-09-24 18:24:18 +00003895 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(
3896 getLineNumber(CurLoc), getColumnNumber(CurLoc), Scope, CurInlinedAt));
Guy Benyei11169dd2012-12-18 14:30:41 +00003897}
3898
Guy Benyei11169dd2012-12-18 14:30:41 +00003899void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
Duncan P. N. Exon Smitha66e3052014-12-09 19:22:40 +00003900 llvm::MDNode *Back = nullptr;
3901 if (!LexicalBlockStack.empty())
3902 Back = LexicalBlockStack.back().get();
Duncan P. N. Exon Smithd899f6e2015-04-18 00:07:30 +00003903 LexicalBlockStack.emplace_back(DBuilder.createLexicalBlock(
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003904 cast<llvm::DIScope>(Back), getOrCreateFile(CurLoc), getLineNumber(CurLoc),
Duncan P. N. Exon Smithd899f6e2015-04-18 00:07:30 +00003905 getColumnNumber(CurLoc)));
Guy Benyei11169dd2012-12-18 14:30:41 +00003906}
3907
Konstantin Zhuravlyov2b4917f2017-03-09 18:06:23 +00003908void CGDebugInfo::AppendAddressSpaceXDeref(
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00003909 unsigned AddressSpace, SmallVectorImpl<int64_t> &Expr) const {
Konstantin Zhuravlyov2b4917f2017-03-09 18:06:23 +00003910 Optional<unsigned> DWARFAddressSpace =
3911 CGM.getTarget().getDWARFAddressSpace(AddressSpace);
3912 if (!DWARFAddressSpace)
3913 return;
3914
3915 Expr.push_back(llvm::dwarf::DW_OP_constu);
3916 Expr.push_back(DWARFAddressSpace.getValue());
3917 Expr.push_back(llvm::dwarf::DW_OP_swap);
3918 Expr.push_back(llvm::dwarf::DW_OP_xderef);
3919}
3920
Eric Christopher0fdcb312013-05-16 00:52:20 +00003921void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
3922 SourceLocation Loc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003923 // Set our current location.
3924 setLocation(Loc);
3925
Guy Benyei11169dd2012-12-18 14:30:41 +00003926 // Emit a line table change for the current location inside the new scope.
Adrian Prantlb7acfc02017-02-27 21:30:05 +00003927 Builder.SetCurrentDebugLocation(
3928 llvm::DebugLoc::get(getLineNumber(Loc), getColumnNumber(Loc),
3929 LexicalBlockStack.back(), CurInlinedAt));
David Blaikie60a877b2014-10-22 19:34:33 +00003930
Benjamin Kramer8c305922016-02-02 11:06:51 +00003931 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
David Blaikie60a877b2014-10-22 19:34:33 +00003932 return;
3933
3934 // Create a new lexical block and push it on the stack.
3935 CreateLexicalBlock(Loc);
Guy Benyei11169dd2012-12-18 14:30:41 +00003936}
3937
Eric Christopher0fdcb312013-05-16 00:52:20 +00003938void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
3939 SourceLocation Loc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003940 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
3941
3942 // Provide an entry in the line table for the end of the block.
Calixte Denizetfcd661d2018-09-24 18:24:18 +00003943 EmitLocation(Builder, Loc);
Guy Benyei11169dd2012-12-18 14:30:41 +00003944
Benjamin Kramer8c305922016-02-02 11:06:51 +00003945 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
David Blaikie60a877b2014-10-22 19:34:33 +00003946 return;
3947
Guy Benyei11169dd2012-12-18 14:30:41 +00003948 LexicalBlockStack.pop_back();
3949}
3950
Keno Fischer41d4b4e2017-06-01 21:14:03 +00003951void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder, llvm::Function *Fn) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003952 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
3953 unsigned RCount = FnBeginRegionCount.back();
3954 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
3955
3956 // Pop all regions for this function.
David Blaikie60a877b2014-10-22 19:34:33 +00003957 while (LexicalBlockStack.size() != RCount) {
3958 // Provide an entry in the line table for the end of the block.
Calixte Denizetfcd661d2018-09-24 18:24:18 +00003959 EmitLocation(Builder, CurLoc);
David Blaikie60a877b2014-10-22 19:34:33 +00003960 LexicalBlockStack.pop_back();
3961 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003962 FnBeginRegionCount.pop_back();
Keno Fischer41d4b4e2017-06-01 21:14:03 +00003963
3964 if (Fn && Fn->getSubprogram())
3965 DBuilder.finalizeSubprogram(Fn->getSubprogram());
Guy Benyei11169dd2012-12-18 14:30:41 +00003966}
3967
Adrian Prantl05a623e2018-09-10 16:14:28 +00003968CGDebugInfo::BlockByRefType
3969CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
3970 uint64_t *XOffset) {
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003971 SmallVector<llvm::Metadata *, 5> EltTys;
Guy Benyei11169dd2012-12-18 14:30:41 +00003972 QualType FType;
3973 uint64_t FieldSize, FieldOffset;
Victor Leschuk802e4a52016-10-19 22:11:07 +00003974 uint32_t FieldAlign;
Eric Christopherb2a008c2013-05-16 00:45:12 +00003975
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003976 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
Eric Christopherb2a008c2013-05-16 00:45:12 +00003977 QualType Type = VD->getType();
Guy Benyei11169dd2012-12-18 14:30:41 +00003978
3979 FieldOffset = 0;
3980 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
3981 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
3982 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
3983 FType = CGM.getContext().IntTy;
3984 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
3985 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
3986
3987 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
3988 if (HasCopyAndDispose) {
3989 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
Eric Christophere7b87e52014-10-26 23:40:33 +00003990 EltTys.push_back(
3991 CreateMemberType(Unit, FType, "__copy_helper", &FieldOffset));
3992 EltTys.push_back(
3993 CreateMemberType(Unit, FType, "__destroy_helper", &FieldOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00003994 }
3995 bool HasByrefExtendedLayout;
3996 Qualifiers::ObjCLifetime Lifetime;
Eric Christophere7b87e52014-10-26 23:40:33 +00003997 if (CGM.getContext().getByrefLifetime(Type, Lifetime,
3998 HasByrefExtendedLayout) &&
3999 HasByrefExtendedLayout) {
Adrian Prantlead2ba42013-07-23 00:12:14 +00004000 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
Eric Christophere7b87e52014-10-26 23:40:33 +00004001 EltTys.push_back(
4002 CreateMemberType(Unit, FType, "__byref_variable_layout", &FieldOffset));
Adrian Prantlead2ba42013-07-23 00:12:14 +00004003 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00004004
Guy Benyei11169dd2012-12-18 14:30:41 +00004005 CharUnits Align = CGM.getContext().getDeclAlign(VD);
4006 if (Align > CGM.getContext().toCharUnitsFromBits(
Eric Christophere7b87e52014-10-26 23:40:33 +00004007 CGM.getTarget().getPointerAlign(0))) {
4008 CharUnits FieldOffsetInBytes =
4009 CGM.getContext().toCharUnitsFromBits(FieldOffset);
Rui Ueyama83aa9792016-01-14 21:00:27 +00004010 CharUnits AlignedOffsetInBytes = FieldOffsetInBytes.alignTo(Align);
Eric Christophere7b87e52014-10-26 23:40:33 +00004011 CharUnits NumPaddingBytes = AlignedOffsetInBytes - FieldOffsetInBytes;
Eric Christopherb2a008c2013-05-16 00:45:12 +00004012
Guy Benyei11169dd2012-12-18 14:30:41 +00004013 if (NumPaddingBytes.isPositive()) {
4014 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
Richard Smith772e2662019-10-04 01:25:59 +00004015 FType = CGM.getContext().getConstantArrayType(
4016 CGM.getContext().CharTy, pad, nullptr, ArrayType::Normal, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00004017 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
4018 }
4019 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00004020
Guy Benyei11169dd2012-12-18 14:30:41 +00004021 FType = Type;
Adrian Prantl05a623e2018-09-10 16:14:28 +00004022 llvm::DIType *WrappedTy = getOrCreateType(FType, Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00004023 FieldSize = CGM.getContext().getTypeSize(FType);
4024 FieldAlign = CGM.getContext().toBits(Align);
4025
Eric Christopherb2a008c2013-05-16 00:45:12 +00004026 *XOffset = FieldOffset;
Adrian Prantl05a623e2018-09-10 16:14:28 +00004027 llvm::DIType *FieldTy = DBuilder.createMemberType(
4028 Unit, VD->getName(), Unit, 0, FieldSize, FieldAlign, FieldOffset,
4029 llvm::DINode::FlagZero, WrappedTy);
Guy Benyei11169dd2012-12-18 14:30:41 +00004030 EltTys.push_back(FieldTy);
4031 FieldOffset += FieldSize;
Eric Christopherb2a008c2013-05-16 00:45:12 +00004032
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004033 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
Adrian Prantl05a623e2018-09-10 16:14:28 +00004034 return {DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0,
4035 llvm::DINode::FlagZero, nullptr, Elements),
4036 WrappedTy};
Guy Benyei11169dd2012-12-18 14:30:41 +00004037}
4038
Sander de Smalen891af03a2018-02-03 13:55:59 +00004039llvm::DILocalVariable *CGDebugInfo::EmitDeclare(const VarDecl *VD,
4040 llvm::Value *Storage,
4041 llvm::Optional<unsigned> ArgNo,
Amy Huang7fac5c82019-06-20 17:15:21 +00004042 CGBuilderTy &Builder,
4043 const bool UsePointerValue) {
Amy Huang53539bb2020-01-13 15:54:54 -08004044 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00004045 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
Paul Robinsonafd2dde2016-06-16 00:42:36 +00004046 if (VD->hasAttr<NoDebugAttr>())
Sander de Smalen891af03a2018-02-03 13:55:59 +00004047 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004048
David Blaikie7fceebf2013-08-19 03:37:48 +00004049 bool Unwritten =
4050 VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) &&
4051 cast<Decl>(VD->getDeclContext())->isImplicit());
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004052 llvm::DIFile *Unit = nullptr;
David Blaikie7fceebf2013-08-19 03:37:48 +00004053 if (!Unwritten)
4054 Unit = getOrCreateFile(VD->getLocation());
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004055 llvm::DIType *Ty;
Guy Benyei11169dd2012-12-18 14:30:41 +00004056 uint64_t XOffset = 0;
4057 if (VD->hasAttr<BlocksAttr>())
Adrian Prantl05a623e2018-09-10 16:14:28 +00004058 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset).WrappedType;
Eric Christopherb2a008c2013-05-16 00:45:12 +00004059 else
Guy Benyei11169dd2012-12-18 14:30:41 +00004060 Ty = getOrCreateType(VD->getType(), Unit);
4061
4062 // If there is no debug info for this type then do not emit debug info
4063 // for this variable.
4064 if (!Ty)
Sander de Smalen891af03a2018-02-03 13:55:59 +00004065 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004066
Guy Benyei11169dd2012-12-18 14:30:41 +00004067 // Get location information.
David Blaikie7fceebf2013-08-19 03:37:48 +00004068 unsigned Line = 0;
4069 unsigned Column = 0;
4070 if (!Unwritten) {
4071 Line = getLineNumber(VD->getLocation());
4072 Column = getColumnNumber(VD->getLocation());
4073 }
Konstantin Zhuravlyov2b4917f2017-03-09 18:06:23 +00004074 SmallVector<int64_t, 13> Expr;
Leny Kholodov80c047d2016-09-06 10:48:04 +00004075 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
Guy Benyei11169dd2012-12-18 14:30:41 +00004076 if (VD->isImplicit())
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004077 Flags |= llvm::DINode::FlagArtificial;
Victor Leschuka7ece032016-10-20 00:13:19 +00004078
4079 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
4080
Konstantin Zhuravlyov2b4917f2017-03-09 18:06:23 +00004081 unsigned AddressSpace = CGM.getContext().getTargetAddressSpace(VD->getType());
4082 AppendAddressSpaceXDeref(AddressSpace, Expr);
4083
Alexey Bataev24f710182017-06-09 13:55:08 +00004084 // If this is implicit parameter of CXXThis or ObjCSelf kind, then give it an
4085 // object pointer flag.
Alexey Bataev56223232017-06-09 13:40:18 +00004086 if (const auto *IPD = dyn_cast<ImplicitParamDecl>(VD)) {
4087 if (IPD->getParameterKind() == ImplicitParamDecl::CXXThis ||
4088 IPD->getParameterKind() == ImplicitParamDecl::ObjCSelf)
4089 Flags |= llvm::DINode::FlagObjectPointer;
4090 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004091
Adrian Prantlc3782a12017-04-18 01:22:01 +00004092 // Note: Older versions of clang used to emit byval references with an extra
4093 // DW_OP_deref, because they referenced the IR arg directly instead of
4094 // referencing an alloca. Newer versions of LLVM don't treat allocas
4095 // differently from other function arguments when used in a dbg.declare.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004096 auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
Guy Benyei11169dd2012-12-18 14:30:41 +00004097 StringRef Name = VD->getName();
4098 if (!Name.empty()) {
4099 if (VD->hasAttr<BlocksAttr>()) {
Adrian Prantlc3782a12017-04-18 01:22:01 +00004100 // Here, we need an offset *into* the alloca.
Guy Benyei11169dd2012-12-18 14:30:41 +00004101 CharUnits offset = CharUnits::fromQuantity(32);
Florian Hahn3dbcced2017-06-13 18:06:15 +00004102 Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
Guy Benyei11169dd2012-12-18 14:30:41 +00004103 // offset of __forwarding field
4104 offset = CGM.getContext().toCharUnitsFromBits(
Eric Christophere7b87e52014-10-26 23:40:33 +00004105 CGM.getTarget().getPointerWidth(0));
Adrian Prantl7c6f9442015-01-19 17:51:58 +00004106 Expr.push_back(offset.getQuantity());
4107 Expr.push_back(llvm::dwarf::DW_OP_deref);
Florian Hahn3dbcced2017-06-13 18:06:15 +00004108 Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
Guy Benyei11169dd2012-12-18 14:30:41 +00004109 // offset of x field
4110 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
Adrian Prantl7c6f9442015-01-19 17:51:58 +00004111 Expr.push_back(offset.getQuantity());
Adrian Prantlc3782a12017-04-18 01:22:01 +00004112 }
David Majnemer58ed0f32016-07-17 00:39:12 +00004113 } else if (const auto *RT = dyn_cast<RecordType>(VD->getType())) {
Adrian Prantl0d820892015-04-29 15:05:50 +00004114 // If VD is an anonymous union then Storage represents value for
4115 // all union fields.
George Burgess IV00f70bd2018-03-01 05:43:23 +00004116 const RecordDecl *RD = RT->getDecl();
Adrian Prantl0d820892015-04-29 15:05:50 +00004117 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
Adrian Prantl00820ab2015-04-29 16:52:31 +00004118 // GDB has trouble finding local variables in anonymous unions, so we emit
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004119 // artificial local variables for each of the members.
Adrian Prantl00820ab2015-04-29 16:52:31 +00004120 //
4121 // FIXME: Remove this code as soon as GDB supports this.
4122 // The debug info verifier in LLVM operates based on the assumption that a
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004123 // variable has the same size as its storage and we had to disable the
4124 // check for artificial variables.
Adrian Prantl0d820892015-04-29 15:05:50 +00004125 for (const auto *Field : RD->fields()) {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004126 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
Adrian Prantl0d820892015-04-29 15:05:50 +00004127 StringRef FieldName = Field->getName();
4128
4129 // Ignore unnamed fields. Do not ignore unnamed records.
4130 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
4131 continue;
4132
4133 // Use VarDecl's Tag, Scope and Line number.
Victor Leschuka7ece032016-10-20 00:13:19 +00004134 auto FieldAlign = getDeclAlignIfRequired(Field, CGM.getContext());
Duncan P. N. Exon Smithe4306542015-07-31 17:56:14 +00004135 auto *D = DBuilder.createAutoVariable(
4136 Scope, FieldName, Unit, Line, FieldTy, CGM.getLangOpts().Optimize,
Victor Leschuka7ece032016-10-20 00:13:19 +00004137 Flags | llvm::DINode::FlagArtificial, FieldAlign);
Adrian Prantl0d820892015-04-29 15:05:50 +00004138
4139 // Insert an llvm.dbg.declare into the current block.
Adrian Prantlb7acfc02017-02-27 21:30:05 +00004140 DBuilder.insertDeclare(
4141 Storage, D, DBuilder.createExpression(Expr),
4142 llvm::DebugLoc::get(Line, Column, Scope, CurInlinedAt),
4143 Builder.GetInsertBlock());
Adrian Prantl0d820892015-04-29 15:05:50 +00004144 }
Adrian Prantl0d820892015-04-29 15:05:50 +00004145 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004146 }
David Blaikiea76a7c92013-01-05 05:58:35 +00004147
Amy Huang7fac5c82019-06-20 17:15:21 +00004148 // Clang stores the sret pointer provided by the caller in a static alloca.
4149 // Use DW_OP_deref to tell the debugger to load the pointer and treat it as
4150 // the address of the variable.
4151 if (UsePointerValue) {
4152 assert(std::find(Expr.begin(), Expr.end(), llvm::dwarf::DW_OP_deref) ==
4153 Expr.end() &&
4154 "Debug info already contains DW_OP_deref.");
4155 Expr.push_back(llvm::dwarf::DW_OP_deref);
4156 }
4157
David Blaikiea76a7c92013-01-05 05:58:35 +00004158 // Create the descriptor for the variable.
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004159 auto *D = ArgNo ? DBuilder.createParameterVariable(
4160 Scope, Name, *ArgNo, Unit, Line, Ty,
4161 CGM.getLangOpts().Optimize, Flags)
4162 : DBuilder.createAutoVariable(Scope, Name, Unit, Line, Ty,
4163 CGM.getLangOpts().Optimize,
4164 Flags, Align);
David Blaikiea76a7c92013-01-05 05:58:35 +00004165
4166 // Insert an llvm.dbg.declare into the current block.
Duncan P. N. Exon Smithfe88b482015-04-15 21:18:30 +00004167 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
Adrian Prantlb7acfc02017-02-27 21:30:05 +00004168 llvm::DebugLoc::get(Line, Column, Scope, CurInlinedAt),
Duncan P. N. Exon Smithfe88b482015-04-15 21:18:30 +00004169 Builder.GetInsertBlock());
Sander de Smalen891af03a2018-02-03 13:55:59 +00004170
4171 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00004172}
4173
Sander de Smalen891af03a2018-02-03 13:55:59 +00004174llvm::DILocalVariable *
4175CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD, llvm::Value *Storage,
Amy Huang7fac5c82019-06-20 17:15:21 +00004176 CGBuilderTy &Builder,
4177 const bool UsePointerValue) {
Amy Huang53539bb2020-01-13 15:54:54 -08004178 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
Amy Huang7fac5c82019-06-20 17:15:21 +00004179 return EmitDeclare(VD, Storage, llvm::None, Builder, UsePointerValue);
Guy Benyei11169dd2012-12-18 14:30:41 +00004180}
4181
Hsiangkai Wang35751492019-01-24 05:34:29 +00004182void CGDebugInfo::EmitLabel(const LabelDecl *D, CGBuilderTy &Builder) {
Amy Huang53539bb2020-01-13 15:54:54 -08004183 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
Hsiangkai Wang35751492019-01-24 05:34:29 +00004184 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4185
4186 if (D->hasAttr<NoDebugAttr>())
4187 return;
4188
4189 auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
4190 llvm::DIFile *Unit = getOrCreateFile(D->getLocation());
4191
4192 // Get location information.
4193 unsigned Line = getLineNumber(D->getLocation());
4194 unsigned Column = getColumnNumber(D->getLocation());
4195
4196 StringRef Name = D->getName();
4197
4198 // Create the descriptor for the label.
4199 auto *L =
4200 DBuilder.createLabel(Scope, Name, Unit, Line, CGM.getLangOpts().Optimize);
4201
4202 // Insert an llvm.dbg.label into the current block.
4203 DBuilder.insertLabel(L,
4204 llvm::DebugLoc::get(Line, Column, Scope, CurInlinedAt),
4205 Builder.GetInsertBlock());
4206}
4207
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004208llvm::DIType *CGDebugInfo::CreateSelfType(const QualType &QualTy,
4209 llvm::DIType *Ty) {
4210 llvm::DIType *CachedTy = getTypeOrNull(QualTy);
Eric Christophere7b87e52014-10-26 23:40:33 +00004211 if (CachedTy)
4212 Ty = CachedTy;
Adrian Prantlde17db32013-03-29 19:20:29 +00004213 return DBuilder.createObjectPointerType(Ty);
4214}
4215
Eric Christophere7b87e52014-10-26 23:40:33 +00004216void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(
4217 const VarDecl *VD, llvm::Value *Storage, CGBuilderTy &Builder,
Adrian Prantl88eec392014-11-21 00:35:25 +00004218 const CGBlockInfo &blockInfo, llvm::Instruction *InsertPoint) {
Amy Huang53539bb2020-01-13 15:54:54 -08004219 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00004220 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
Eric Christopherb2a008c2013-05-16 00:45:12 +00004221
Craig Topper8a13c412014-05-21 05:09:00 +00004222 if (Builder.GetInsertBlock() == nullptr)
Guy Benyei11169dd2012-12-18 14:30:41 +00004223 return;
Paul Robinsonafd2dde2016-06-16 00:42:36 +00004224 if (VD->hasAttr<NoDebugAttr>())
4225 return;
Eric Christopherb2a008c2013-05-16 00:45:12 +00004226
Guy Benyei11169dd2012-12-18 14:30:41 +00004227 bool isByRef = VD->hasAttr<BlocksAttr>();
Eric Christopherb2a008c2013-05-16 00:45:12 +00004228
Guy Benyei11169dd2012-12-18 14:30:41 +00004229 uint64_t XOffset = 0;
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004230 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
4231 llvm::DIType *Ty;
Guy Benyei11169dd2012-12-18 14:30:41 +00004232 if (isByRef)
Adrian Prantl05a623e2018-09-10 16:14:28 +00004233 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset).WrappedType;
Eric Christopherb2a008c2013-05-16 00:45:12 +00004234 else
Guy Benyei11169dd2012-12-18 14:30:41 +00004235 Ty = getOrCreateType(VD->getType(), Unit);
4236
4237 // Self is passed along as an implicit non-arg variable in a
4238 // block. Mark it as the object pointer.
Alexey Bataev56223232017-06-09 13:40:18 +00004239 if (const auto *IPD = dyn_cast<ImplicitParamDecl>(VD))
4240 if (IPD->getParameterKind() == ImplicitParamDecl::ObjCSelf)
4241 Ty = CreateSelfType(VD->getType(), Ty);
Guy Benyei11169dd2012-12-18 14:30:41 +00004242
4243 // Get location information.
4244 unsigned Line = getLineNumber(VD->getLocation());
4245 unsigned Column = getColumnNumber(VD->getLocation());
4246
4247 const llvm::DataLayout &target = CGM.getDataLayout();
4248
4249 CharUnits offset = CharUnits::fromQuantity(
Eric Christophere7b87e52014-10-26 23:40:33 +00004250 target.getStructLayout(blockInfo.StructureType)
Guy Benyei11169dd2012-12-18 14:30:41 +00004251 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
4252
Duncan P. N. Exon Smithf3dc4292014-10-01 20:26:18 +00004253 SmallVector<int64_t, 9> addr;
Adrian Prantlc3782a12017-04-18 01:22:01 +00004254 addr.push_back(llvm::dwarf::DW_OP_deref);
Florian Hahn3dbcced2017-06-13 18:06:15 +00004255 addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
Duncan P. N. Exon Smithf3dc4292014-10-01 20:26:18 +00004256 addr.push_back(offset.getQuantity());
Guy Benyei11169dd2012-12-18 14:30:41 +00004257 if (isByRef) {
Duncan P. N. Exon Smithf3dc4292014-10-01 20:26:18 +00004258 addr.push_back(llvm::dwarf::DW_OP_deref);
Florian Hahn3dbcced2017-06-13 18:06:15 +00004259 addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
Guy Benyei11169dd2012-12-18 14:30:41 +00004260 // offset of __forwarding field
Eric Christophere7b87e52014-10-26 23:40:33 +00004261 offset =
4262 CGM.getContext().toCharUnitsFromBits(target.getPointerSizeInBits(0));
Duncan P. N. Exon Smithf3dc4292014-10-01 20:26:18 +00004263 addr.push_back(offset.getQuantity());
4264 addr.push_back(llvm::dwarf::DW_OP_deref);
Florian Hahn3dbcced2017-06-13 18:06:15 +00004265 addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
Guy Benyei11169dd2012-12-18 14:30:41 +00004266 // offset of x field
4267 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
Duncan P. N. Exon Smithf3dc4292014-10-01 20:26:18 +00004268 addr.push_back(offset.getQuantity());
Guy Benyei11169dd2012-12-18 14:30:41 +00004269 }
4270
4271 // Create the descriptor for the variable.
Victor Leschuka7ece032016-10-20 00:13:19 +00004272 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
Duncan P. N. Exon Smithe4306542015-07-31 17:56:14 +00004273 auto *D = DBuilder.createAutoVariable(
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004274 cast<llvm::DILocalScope>(LexicalBlockStack.back()), VD->getName(), Unit,
Victor Leschuka7ece032016-10-20 00:13:19 +00004275 Line, Ty, false, llvm::DINode::FlagZero, Align);
Adrian Prantl0f6df002013-03-29 19:20:35 +00004276
Guy Benyei11169dd2012-12-18 14:30:41 +00004277 // Insert an llvm.dbg.declare into the current block.
Adrian Prantlb7acfc02017-02-27 21:30:05 +00004278 auto DL =
4279 llvm::DebugLoc::get(Line, Column, LexicalBlockStack.back(), CurInlinedAt);
Adrian Prantlc3782a12017-04-18 01:22:01 +00004280 auto *Expr = DBuilder.createExpression(addr);
Duncan P. N. Exon Smithfe88b482015-04-15 21:18:30 +00004281 if (InsertPoint)
Adrian Prantlc3782a12017-04-18 01:22:01 +00004282 DBuilder.insertDeclare(Storage, D, Expr, DL, InsertPoint);
Duncan P. N. Exon Smithfe88b482015-04-15 21:18:30 +00004283 else
Adrian Prantlc3782a12017-04-18 01:22:01 +00004284 DBuilder.insertDeclare(Storage, D, Expr, DL, Builder.GetInsertBlock());
Guy Benyei11169dd2012-12-18 14:30:41 +00004285}
4286
Guy Benyei11169dd2012-12-18 14:30:41 +00004287void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
4288 unsigned ArgNo,
4289 CGBuilderTy &Builder) {
Amy Huang53539bb2020-01-13 15:54:54 -08004290 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
Duncan P. N. Exon Smithe4306542015-07-31 17:56:14 +00004291 EmitDeclare(VD, AI, ArgNo, Builder);
Guy Benyei11169dd2012-12-18 14:30:41 +00004292}
4293
4294namespace {
Eric Christophere7b87e52014-10-26 23:40:33 +00004295struct BlockLayoutChunk {
4296 uint64_t OffsetInBits;
4297 const BlockDecl::Capture *Capture;
4298};
4299bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
4300 return l.OffsetInBits < r.OffsetInBits;
4301}
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004302} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00004303
Scott Linder58df0e42018-08-08 15:56:12 +00004304void CGDebugInfo::collectDefaultFieldsForBlockLiteralDeclare(
4305 const CGBlockInfo &Block, const ASTContext &Context, SourceLocation Loc,
4306 const llvm::StructLayout &BlockLayout, llvm::DIFile *Unit,
4307 SmallVectorImpl<llvm::Metadata *> &Fields) {
4308 // Blocks in OpenCL have unique constraints which make the standard fields
4309 // redundant while requiring size and align fields for enqueue_kernel. See
4310 // initializeForBlockHeader in CGBlocks.cpp
4311 if (CGM.getLangOpts().OpenCL) {
4312 Fields.push_back(createFieldType("__size", Context.IntTy, Loc, AS_public,
4313 BlockLayout.getElementOffsetInBits(0),
4314 Unit, Unit));
4315 Fields.push_back(createFieldType("__align", Context.IntTy, Loc, AS_public,
4316 BlockLayout.getElementOffsetInBits(1),
4317 Unit, Unit));
4318 } else {
4319 Fields.push_back(createFieldType("__isa", Context.VoidPtrTy, Loc, AS_public,
4320 BlockLayout.getElementOffsetInBits(0),
4321 Unit, Unit));
4322 Fields.push_back(createFieldType("__flags", Context.IntTy, Loc, AS_public,
4323 BlockLayout.getElementOffsetInBits(1),
4324 Unit, Unit));
4325 Fields.push_back(
4326 createFieldType("__reserved", Context.IntTy, Loc, AS_public,
4327 BlockLayout.getElementOffsetInBits(2), Unit, Unit));
4328 auto *FnTy = Block.getBlockExpr()->getFunctionType();
4329 auto FnPtrType = CGM.getContext().getPointerType(FnTy->desugar());
4330 Fields.push_back(createFieldType("__FuncPtr", FnPtrType, Loc, AS_public,
4331 BlockLayout.getElementOffsetInBits(3),
4332 Unit, Unit));
4333 Fields.push_back(createFieldType(
4334 "__descriptor",
4335 Context.getPointerType(Block.NeedsCopyDispose
4336 ? Context.getBlockDescriptorExtendedType()
4337 : Context.getBlockDescriptorType()),
4338 Loc, AS_public, BlockLayout.getElementOffsetInBits(4), Unit, Unit));
4339 }
4340}
4341
Guy Benyei11169dd2012-12-18 14:30:41 +00004342void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
Adrian Prantl356347b2017-10-26 20:08:52 +00004343 StringRef Name,
David Blaikie77bbb5f2014-08-08 17:10:14 +00004344 unsigned ArgNo,
Adrian Prantl356347b2017-10-26 20:08:52 +00004345 llvm::AllocaInst *Alloca,
Guy Benyei11169dd2012-12-18 14:30:41 +00004346 CGBuilderTy &Builder) {
Amy Huang53539bb2020-01-13 15:54:54 -08004347 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00004348 ASTContext &C = CGM.getContext();
4349 const BlockDecl *blockDecl = block.getBlockDecl();
4350
4351 // Collect some general information about the block's location.
4352 SourceLocation loc = blockDecl->getCaretLocation();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004353 llvm::DIFile *tunit = getOrCreateFile(loc);
Guy Benyei11169dd2012-12-18 14:30:41 +00004354 unsigned line = getLineNumber(loc);
4355 unsigned column = getColumnNumber(loc);
Eric Christopherb2a008c2013-05-16 00:45:12 +00004356
Guy Benyei11169dd2012-12-18 14:30:41 +00004357 // Build the debug-info type for the block literal.
Adrian Prantl6ec370a2015-09-10 18:39:45 +00004358 getDeclContextDescriptor(blockDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00004359
4360 const llvm::StructLayout *blockLayout =
Eric Christophere7b87e52014-10-26 23:40:33 +00004361 CGM.getDataLayout().getStructLayout(block.StructureType);
Guy Benyei11169dd2012-12-18 14:30:41 +00004362
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00004363 SmallVector<llvm::Metadata *, 16> fields;
Scott Linder58df0e42018-08-08 15:56:12 +00004364 collectDefaultFieldsForBlockLiteralDeclare(block, C, loc, *blockLayout, tunit,
4365 fields);
Guy Benyei11169dd2012-12-18 14:30:41 +00004366
4367 // We want to sort the captures by offset, not because DWARF
4368 // requires this, but because we're paranoid about debuggers.
4369 SmallVector<BlockLayoutChunk, 8> chunks;
4370
4371 // 'this' capture.
4372 if (blockDecl->capturesCXXThis()) {
4373 BlockLayoutChunk chunk;
4374 chunk.OffsetInBits =
Eric Christophere7b87e52014-10-26 23:40:33 +00004375 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
Craig Topper8a13c412014-05-21 05:09:00 +00004376 chunk.Capture = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004377 chunks.push_back(chunk);
4378 }
4379
4380 // Variable captures.
Aaron Ballman9371dd22014-03-14 18:34:04 +00004381 for (const auto &capture : blockDecl->captures()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004382 const VarDecl *variable = capture.getVariable();
4383 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
4384
4385 // Ignore constant captures.
4386 if (captureInfo.isConstant())
4387 continue;
4388
4389 BlockLayoutChunk chunk;
4390 chunk.OffsetInBits =
Eric Christophere7b87e52014-10-26 23:40:33 +00004391 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
Guy Benyei11169dd2012-12-18 14:30:41 +00004392 chunk.Capture = &capture;
4393 chunks.push_back(chunk);
4394 }
4395
4396 // Sort by offset.
4397 llvm::array_pod_sort(chunks.begin(), chunks.end());
4398
David Majnemer58ed0f32016-07-17 00:39:12 +00004399 for (const BlockLayoutChunk &Chunk : chunks) {
4400 uint64_t offsetInBits = Chunk.OffsetInBits;
4401 const BlockDecl::Capture *capture = Chunk.Capture;
Guy Benyei11169dd2012-12-18 14:30:41 +00004402
4403 // If we have a null capture, this must be the C++ 'this' capture.
4404 if (!capture) {
Adrian Prantl2526fca2016-04-18 23:48:16 +00004405 QualType type;
4406 if (auto *Method =
4407 cast_or_null<CXXMethodDecl>(blockDecl->getNonClosureContext()))
Brian Gesiak5488ab42019-01-11 01:54:53 +00004408 type = Method->getThisType();
Adrian Prantl2526fca2016-04-18 23:48:16 +00004409 else if (auto *RDecl = dyn_cast<CXXRecordDecl>(blockDecl->getParent()))
4410 type = QualType(RDecl->getTypeForDecl(), 0);
4411 else
4412 llvm_unreachable("unexpected block declcontext");
Guy Benyei11169dd2012-12-18 14:30:41 +00004413
David Majnemerb4b671e2016-06-30 03:01:59 +00004414 fields.push_back(createFieldType("this", type, loc, AS_public,
Guy Benyei11169dd2012-12-18 14:30:41 +00004415 offsetInBits, tunit, tunit));
4416 continue;
4417 }
4418
4419 const VarDecl *variable = capture->getVariable();
4420 StringRef name = variable->getName();
4421
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004422 llvm::DIType *fieldType;
Guy Benyei11169dd2012-12-18 14:30:41 +00004423 if (capture->isByRef()) {
David Majnemer34b57492014-07-30 01:30:47 +00004424 TypeInfo PtrInfo = C.getTypeInfo(C.VoidPtrTy);
Victor Leschuka7ece032016-10-20 00:13:19 +00004425 auto Align = PtrInfo.AlignIsRequired ? PtrInfo.Align : 0;
Adrian Prantl05a623e2018-09-10 16:14:28 +00004426 // FIXME: This recomputes the layout of the BlockByRefWrapper.
Guy Benyei11169dd2012-12-18 14:30:41 +00004427 uint64_t xoffset;
Adrian Prantl05a623e2018-09-10 16:14:28 +00004428 fieldType =
4429 EmitTypeForVarWithBlocksAttr(variable, &xoffset).BlockByRefWrapper;
David Majnemer34b57492014-07-30 01:30:47 +00004430 fieldType = DBuilder.createPointerType(fieldType, PtrInfo.Width);
Victor Leschuka7ece032016-10-20 00:13:19 +00004431 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
4432 PtrInfo.Width, Align, offsetInBits,
4433 llvm::DINode::FlagZero, fieldType);
Guy Benyei11169dd2012-12-18 14:30:41 +00004434 } else {
Victor Leschuka7ece032016-10-20 00:13:19 +00004435 auto Align = getDeclAlignIfRequired(variable, CGM.getContext());
David Majnemerb4b671e2016-06-30 03:01:59 +00004436 fieldType = createFieldType(name, variable->getType(), loc, AS_public,
Victor Leschuka7ece032016-10-20 00:13:19 +00004437 offsetInBits, Align, tunit, tunit);
Guy Benyei11169dd2012-12-18 14:30:41 +00004438 }
4439 fields.push_back(fieldType);
4440 }
4441
4442 SmallString<36> typeName;
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004443 llvm::raw_svector_ostream(typeName)
4444 << "__block_literal_" << CGM.getUniqueBlockCount();
Guy Benyei11169dd2012-12-18 14:30:41 +00004445
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004446 llvm::DINodeArray fieldsArray = DBuilder.getOrCreateArray(fields);
Guy Benyei11169dd2012-12-18 14:30:41 +00004447
Leny Kholodovdf050fd2016-09-06 17:06:14 +00004448 llvm::DIType *type =
4449 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
Victor Leschuka7ece032016-10-20 00:13:19 +00004450 CGM.getContext().toBits(block.BlockSize), 0,
Leny Kholodovdf050fd2016-09-06 17:06:14 +00004451 llvm::DINode::FlagZero, nullptr, fieldsArray);
Guy Benyei11169dd2012-12-18 14:30:41 +00004452 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
4453
4454 // Get overall information about the block.
Leny Kholodov80c047d2016-09-06 10:48:04 +00004455 llvm::DINode::DIFlags flags = llvm::DINode::FlagArtificial;
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004456 auto *scope = cast<llvm::DILocalScope>(LexicalBlockStack.back());
Guy Benyei11169dd2012-12-18 14:30:41 +00004457
4458 // Create the descriptor for the parameter.
Duncan P. N. Exon Smithe4306542015-07-31 17:56:14 +00004459 auto *debugVar = DBuilder.createParameterVariable(
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004460 scope, Name, ArgNo, tunit, line, type, CGM.getLangOpts().Optimize, flags);
Adrian Prantl51936dd2013-03-14 17:53:33 +00004461
Adrian Prantl616bef42013-03-14 21:52:59 +00004462 // Insert an llvm.dbg.declare into the current block.
Adrian Prantl356347b2017-10-26 20:08:52 +00004463 DBuilder.insertDeclare(Alloca, debugVar, DBuilder.createExpression(),
Adrian Prantlb7acfc02017-02-27 21:30:05 +00004464 llvm::DebugLoc::get(line, column, scope, CurInlinedAt),
Duncan P. N. Exon Smithfe88b482015-04-15 21:18:30 +00004465 Builder.GetInsertBlock());
Guy Benyei11169dd2012-12-18 14:30:41 +00004466}
4467
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004468llvm::DIDerivedType *
David Blaikie6943dea2013-08-20 01:28:15 +00004469CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) {
Amy Huangdd3a9ca2019-05-30 22:04:11 +00004470 if (!D || !D->isStaticDataMember())
Duncan P. N. Exon Smithc09c5482015-04-20 21:17:26 +00004471 return nullptr;
Saleem Abdulrasoolcd187f02015-02-28 00:13:13 +00004472
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00004473 auto MI = StaticDataMemberCache.find(D->getCanonicalDecl());
David Blaikie6943dea2013-08-20 01:28:15 +00004474 if (MI != StaticDataMemberCache.end()) {
4475 assert(MI->second && "Static data member declaration should still exist");
Duncan P. N. Exon Smithac346ba2015-07-24 18:05:58 +00004476 return MI->second;
Evgeniy Stepanov37b3f732013-08-16 10:35:31 +00004477 }
David Blaikiece763042013-08-20 21:49:21 +00004478
4479 // If the member wasn't found in the cache, lazily construct and add it to the
4480 // type (used when a limited form of the type is emitted).
Adrian Prantl21361fb2014-08-29 22:44:27 +00004481 auto DC = D->getDeclContext();
Adrian Prantl6ec370a2015-09-10 18:39:45 +00004482 auto *Ctxt = cast<llvm::DICompositeType>(getDeclContextDescriptor(D));
Adrian Prantl21361fb2014-08-29 22:44:27 +00004483 return CreateRecordStaticField(D, Ctxt, cast<RecordDecl>(DC));
David Blaikie6943dea2013-08-20 01:28:15 +00004484}
4485
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004486llvm::DIGlobalVariableExpression *CGDebugInfo::CollectAnonRecordDecls(
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004487 const RecordDecl *RD, llvm::DIFile *Unit, unsigned LineNo,
4488 StringRef LinkageName, llvm::GlobalVariable *Var, llvm::DIScope *DContext) {
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004489 llvm::DIGlobalVariableExpression *GVE = nullptr;
Eric Christophercab9fae2014-04-10 05:20:00 +00004490
4491 for (const auto *Field : RD->fields()) {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004492 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
Eric Christophercab9fae2014-04-10 05:20:00 +00004493 StringRef FieldName = Field->getName();
4494
4495 // Ignore unnamed fields, but recurse into anonymous records.
4496 if (FieldName.empty()) {
David Majnemer58ed0f32016-07-17 00:39:12 +00004497 if (const auto *RT = dyn_cast<RecordType>(Field->getType()))
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004498 GVE = CollectAnonRecordDecls(RT->getDecl(), Unit, LineNo, LinkageName,
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004499 Var, DContext);
Eric Christophercab9fae2014-04-10 05:20:00 +00004500 continue;
4501 }
4502 // Use VarDecl's Tag, Scope and Line number.
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004503 GVE = DBuilder.createGlobalVariableExpression(
4504 DContext, FieldName, LinkageName, Unit, LineNo, FieldTy,
4505 Var->hasLocalLinkage());
4506 Var->addDebugInfo(GVE);
Eric Christophercab9fae2014-04-10 05:20:00 +00004507 }
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004508 return GVE;
Eric Christophercab9fae2014-04-10 05:20:00 +00004509}
4510
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00004511void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
Guy Benyei11169dd2012-12-18 14:30:41 +00004512 const VarDecl *D) {
Amy Huang53539bb2020-01-13 15:54:54 -08004513 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
Paul Robinsonb17327d2016-04-27 17:37:12 +00004514 if (D->hasAttr<NoDebugAttr>())
4515 return;
Adrian Prantl338ef7a2016-11-09 00:42:03 +00004516
Luboš Luňák4f2104c2019-11-02 16:39:59 +01004517 llvm::TimeTraceScope TimeScope("DebugGlobalVariable", [&]() {
4518 std::string Name;
4519 llvm::raw_string_ostream OS(Name);
4520 D->getNameForDiagnostic(OS, getPrintingPolicy(),
4521 /*Qualified=*/true);
4522 return Name;
4523 });
4524
Adrian Prantl338ef7a2016-11-09 00:42:03 +00004525 // If we already created a DIGlobalVariable for this declaration, just attach
4526 // it to the llvm::GlobalVariable.
4527 auto Cached = DeclCache.find(D->getCanonicalDecl());
4528 if (Cached != DeclCache.end())
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004529 return Var->addDebugInfo(
4530 cast<llvm::DIGlobalVariableExpression>(Cached->second));
Adrian Prantl338ef7a2016-11-09 00:42:03 +00004531
Guy Benyei11169dd2012-12-18 14:30:41 +00004532 // Create global variable debug descriptor.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004533 llvm::DIFile *Unit = nullptr;
4534 llvm::DIScope *DContext = nullptr;
Frederic Riss9db79f12014-11-18 03:40:46 +00004535 unsigned LineNo;
4536 StringRef DeclName, LinkageName;
4537 QualType T;
Matthew Voss20165362018-10-03 18:45:04 +00004538 llvm::MDTuple *TemplateParameters = nullptr;
4539 collectVarDeclProps(D, Unit, LineNo, T, DeclName, LinkageName,
4540 TemplateParameters, DContext);
Eric Christophercab9fae2014-04-10 05:20:00 +00004541
4542 // Attempt to store one global variable for the declaration - even if we
4543 // emit a lot of fields.
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004544 llvm::DIGlobalVariableExpression *GVE = nullptr;
Eric Christophercab9fae2014-04-10 05:20:00 +00004545
4546 // If this is an anonymous union then we'll want to emit a global
4547 // variable for each member of the anonymous union so that it's possible
4548 // to find the name of any field in the union.
4549 if (T->isUnionType() && DeclName.empty()) {
Reid Kleckner43ecd7c2015-11-20 17:41:12 +00004550 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
Eric Christophere7b87e52014-10-26 23:40:33 +00004551 assert(RD->isAnonymousStructOrUnion() &&
4552 "unnamed non-anonymous struct or union?");
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004553 GVE = CollectAnonRecordDecls(RD, Unit, LineNo, LinkageName, Var, DContext);
Eric Christophercab9fae2014-04-10 05:20:00 +00004554 } else {
Victor Leschuka7ece032016-10-20 00:13:19 +00004555 auto Align = getDeclAlignIfRequired(D, CGM.getContext());
Konstantin Zhuravlyov2b4917f2017-03-09 18:06:23 +00004556
4557 SmallVector<int64_t, 4> Expr;
4558 unsigned AddressSpace =
4559 CGM.getContext().getTargetAddressSpace(D->getType());
Alexey Bataev1a9e05d2019-02-05 19:45:57 +00004560 if (CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) {
4561 if (D->hasAttr<CUDASharedAttr>())
4562 AddressSpace =
4563 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared);
4564 else if (D->hasAttr<CUDAConstantAttr>())
4565 AddressSpace =
4566 CGM.getContext().getTargetAddressSpace(LangAS::cuda_constant);
4567 }
Konstantin Zhuravlyov2b4917f2017-03-09 18:06:23 +00004568 AppendAddressSpaceXDeref(AddressSpace, Expr);
4569
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004570 GVE = DBuilder.createGlobalVariableExpression(
Eric Christophercab9fae2014-04-10 05:20:00 +00004571 DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),
Yonghong Songe3d8ee32019-11-22 08:45:37 -08004572 Var->hasLocalLinkage(), true,
Konstantin Zhuravlyov2b4917f2017-03-09 18:06:23 +00004573 Expr.empty() ? nullptr : DBuilder.createExpression(Expr),
Matthew Voss20165362018-10-03 18:45:04 +00004574 getOrCreateStaticDataMemberDeclarationOrNull(D), TemplateParameters,
4575 Align);
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004576 Var->addDebugInfo(GVE);
Eric Christophercab9fae2014-04-10 05:20:00 +00004577 }
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004578 DeclCache[D->getCanonicalDecl()].reset(GVE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004579}
4580
Peter Collingbourneeeb56ab2016-09-13 01:13:19 +00004581void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD, const APValue &Init) {
Amy Huang53539bb2020-01-13 15:54:54 -08004582 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
Paul Robinsonb17327d2016-04-27 17:37:12 +00004583 if (VD->hasAttr<NoDebugAttr>())
4584 return;
Luboš Luňák4f2104c2019-11-02 16:39:59 +01004585 llvm::TimeTraceScope TimeScope("DebugConstGlobalVariable", [&]() {
4586 std::string Name;
4587 llvm::raw_string_ostream OS(Name);
4588 VD->getNameForDiagnostic(OS, getPrintingPolicy(),
4589 /*Qualified=*/true);
4590 return Name;
4591 });
4592
Victor Leschuka7ece032016-10-20 00:13:19 +00004593 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00004594 // Create the descriptor for the variable.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004595 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00004596 StringRef Name = VD->getName();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004597 llvm::DIType *Ty = getOrCreateType(VD->getType(), Unit);
Amy Huang63305c82019-05-22 15:48:59 +00004598
David Majnemer58ed0f32016-07-17 00:39:12 +00004599 if (const auto *ECD = dyn_cast<EnumConstantDecl>(VD)) {
4600 const auto *ED = cast<EnumDecl>(ECD->getDeclContext());
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00004601 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
Amy Huangdd3a9ca2019-05-30 22:04:11 +00004602
Yuanfang Chen48c6fad2019-09-04 20:58:15 +00004603 if (CGM.getCodeGenOpts().EmitCodeView) {
4604 // If CodeView, emit enums as global variables, unless they are defined
4605 // inside a class. We do this because MSVC doesn't emit S_CONSTANTs for
4606 // enums in classes, and because it is difficult to attach this scope
4607 // information to the global variable.
4608 if (isa<RecordDecl>(ED->getDeclContext()))
4609 return;
4610 } else {
4611 // If not CodeView, emit DW_TAG_enumeration_type if necessary. For
4612 // example: for "enum { ZERO };", a DW_TAG_enumeration_type is created the
4613 // first time `ZERO` is referenced in a function.
4614 llvm::DIType *EDTy =
4615 getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
4616 assert (EDTy->getTag() == llvm::dwarf::DW_TAG_enumeration_type);
4617 (void)EDTy;
Amy Huangdd3a9ca2019-05-30 22:04:11 +00004618 return;
Yuanfang Chen48c6fad2019-09-04 20:58:15 +00004619 }
Amy Huang63305c82019-05-22 15:48:59 +00004620 }
4621
Amy Huang325003b2019-05-29 21:45:34 +00004622 llvm::DIScope *DContext = nullptr;
4623
4624 // Do not emit separate definitions for function local consts.
David Blaikiea15565562014-04-04 20:56:17 +00004625 if (isa<FunctionDecl>(VD->getDeclContext()))
4626 return;
Amy Huang325003b2019-05-29 21:45:34 +00004627
4628 // Emit definition for static members in CodeView.
David Blaikiebb113912014-04-05 07:23:17 +00004629 VD = cast<ValueDecl>(VD->getCanonicalDecl());
Amy Huangdd3a9ca2019-05-30 22:04:11 +00004630 auto *VarD = dyn_cast<VarDecl>(VD);
4631 if (VarD && VarD->isStaticDataMember()) {
David Blaikieaf080852014-11-21 00:20:58 +00004632 auto *RD = cast<RecordDecl>(VarD->getDeclContext());
Adrian Prantl6ec370a2015-09-10 18:39:45 +00004633 getDeclContextDescriptor(VarD);
David Blaikie423eb5a2014-11-19 19:42:40 +00004634 // Ensure that the type is retained even though it's otherwise unreferenced.
Duncan P. N. Exon Smith383f8412016-04-23 21:08:27 +00004635 //
4636 // FIXME: This is probably unnecessary, since Ty should reference RD
4637 // through its scope.
David Blaikie423eb5a2014-11-19 19:42:40 +00004638 RetainedTypes.push_back(
David Blaikieaf080852014-11-21 00:20:58 +00004639 CGM.getContext().getRecordType(RD).getAsOpaquePtr());
David Blaikie423eb5a2014-11-19 19:42:40 +00004640
Amy Huang325003b2019-05-29 21:45:34 +00004641 if (!CGM.getCodeGenOpts().EmitCodeView)
4642 return;
4643
4644 // Use the global scope for static members.
4645 DContext = getContextDescriptor(
4646 cast<Decl>(CGM.getContext().getTranslationUnitDecl()), TheCU);
4647 } else {
4648 DContext = getDeclContextDescriptor(VD);
4649 }
David Blaikieaf080852014-11-21 00:20:58 +00004650
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00004651 auto &GV = DeclCache[VD];
4652 if (GV)
David Blaikiebb113912014-04-05 07:23:17 +00004653 return;
Peter Collingbourneeeb56ab2016-09-13 01:13:19 +00004654 llvm::DIExpression *InitExpr = nullptr;
Peter Collingbourneb7013632016-12-16 22:10:52 +00004655 if (CGM.getContext().getTypeSize(VD->getType()) <= 64) {
4656 // FIXME: Add a representation for integer constants wider than 64 bits.
4657 if (Init.isInt())
4658 InitExpr =
4659 DBuilder.createConstantValueExpression(Init.getInt().getExtValue());
4660 else if (Init.isFloat())
4661 InitExpr = DBuilder.createConstantValueExpression(
4662 Init.getFloat().bitcastToAPInt().getZExtValue());
4663 }
Matthew Voss20165362018-10-03 18:45:04 +00004664
4665 llvm::MDTuple *TemplateParameters = nullptr;
4666
4667 if (isa<VarTemplateSpecializationDecl>(VD))
4668 if (VarD) {
4669 llvm::DINodeArray parameterNodes = CollectVarTemplateParams(VarD, &*Unit);
4670 TemplateParameters = parameterNodes.get();
4671 }
4672
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004673 GV.reset(DBuilder.createGlobalVariableExpression(
David Blaikie506a7452014-04-05 07:46:57 +00004674 DContext, Name, StringRef(), Unit, getLineNumber(VD->getLocation()), Ty,
Yonghong Songe3d8ee32019-11-22 08:45:37 -08004675 true, true, InitExpr, getOrCreateStaticDataMemberDeclarationOrNull(VarD),
Matthew Voss20165362018-10-03 18:45:04 +00004676 TemplateParameters, Align));
David Blaikiebd483762013-05-20 04:58:53 +00004677}
4678
Yonghong Songe3d8ee32019-11-22 08:45:37 -08004679void CGDebugInfo::EmitExternalVariable(llvm::GlobalVariable *Var,
4680 const VarDecl *D) {
Amy Huang53539bb2020-01-13 15:54:54 -08004681 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
Yonghong Songe3d8ee32019-11-22 08:45:37 -08004682 if (D->hasAttr<NoDebugAttr>())
4683 return;
4684
4685 auto Align = getDeclAlignIfRequired(D, CGM.getContext());
4686 llvm::DIFile *Unit = getOrCreateFile(D->getLocation());
4687 StringRef Name = D->getName();
4688 llvm::DIType *Ty = getOrCreateType(D->getType(), Unit);
4689
4690 llvm::DIScope *DContext = getDeclContextDescriptor(D);
4691 llvm::DIGlobalVariableExpression *GVE =
4692 DBuilder.createGlobalVariableExpression(
4693 DContext, Name, StringRef(), Unit, getLineNumber(D->getLocation()),
4694 Ty, false, false, nullptr, nullptr, nullptr, Align);
4695 Var->addDebugInfo(GVE);
4696}
4697
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004698llvm::DIScope *CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
David Blaikiebd483762013-05-20 04:58:53 +00004699 if (!LexicalBlockStack.empty())
Duncan P. N. Exon Smithfc8d9d92015-04-20 18:32:15 +00004700 return LexicalBlockStack.back();
Adrian Prantl5c8bd882015-09-11 17:23:08 +00004701 llvm::DIScope *Mod = getParentModuleOrNull(D);
4702 return getContextDescriptor(D, Mod ? Mod : TheCU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004703}
4704
David Blaikie9f88fe82013-04-22 06:13:21 +00004705void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
Amy Huang53539bb2020-01-13 15:54:54 -08004706 if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
David Blaikiebd483762013-05-20 04:58:53 +00004707 return;
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +00004708 const NamespaceDecl *NSDecl = UD.getNominatedNamespace();
Adrian McCarthyab1e7862016-07-21 18:43:20 +00004709 if (!NSDecl->isAnonymousNamespace() ||
4710 CGM.getCodeGenOpts().DebugExplicitImport) {
Adrian Prantl5649b0e2017-07-19 00:09:58 +00004711 auto Loc = UD.getLocation();
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +00004712 DBuilder.createImportedModule(
4713 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
Adrian Prantl5649b0e2017-07-19 00:09:58 +00004714 getOrCreateNamespace(NSDecl), getOrCreateFile(Loc), getLineNumber(Loc));
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +00004715 }
David Blaikie9f88fe82013-04-22 06:13:21 +00004716}
4717
David Blaikiebd483762013-05-20 04:58:53 +00004718void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
Amy Huang53539bb2020-01-13 15:54:54 -08004719 if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
David Blaikiebd483762013-05-20 04:58:53 +00004720 return;
4721 assert(UD.shadow_size() &&
4722 "We shouldn't be codegening an invalid UsingDecl containing no decls");
4723 // Emitting one decl is sufficient - debuggers can detect that this is an
4724 // overloaded name & provide lookup for all the overloads.
4725 const UsingShadowDecl &USD = **UD.shadow_begin();
David Blaikie2a58a182016-08-05 19:03:01 +00004726
4727 // FIXME: Skip functions with undeduced auto return type for now since we
4728 // don't currently have the plumbing for separate declarations & definitions
4729 // of free functions and mismatched types (auto in the declaration, concrete
4730 // return type in the definition)
4731 if (const auto *FD = dyn_cast<FunctionDecl>(USD.getUnderlyingDecl()))
4732 if (const auto *AT =
Simon Pilgrim7e38f0c2019-10-07 16:42:25 +00004733 FD->getType()->castAs<FunctionProtoType>()->getContainedAutoType())
David Blaikie2a58a182016-08-05 19:03:01 +00004734 if (AT->getDeducedType().isNull())
4735 return;
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004736 if (llvm::DINode *Target =
Adrian Prantl5649b0e2017-07-19 00:09:58 +00004737 getDeclarationOrDefinition(USD.getUnderlyingDecl())) {
4738 auto Loc = USD.getLocation();
David Blaikiebd483762013-05-20 04:58:53 +00004739 DBuilder.createImportedDeclaration(
4740 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
Adrian Prantl5649b0e2017-07-19 00:09:58 +00004741 getOrCreateFile(Loc), getLineNumber(Loc));
4742 }
David Blaikiebd483762013-05-20 04:58:53 +00004743}
4744
Adrian Prantlc4bb47e2015-06-30 17:39:51 +00004745void CGDebugInfo::EmitImportDecl(const ImportDecl &ID) {
David Blaikieaf09f4a2016-05-03 23:06:40 +00004746 if (CGM.getCodeGenOpts().getDebuggerTuning() != llvm::DebuggerKind::LLDB)
4747 return;
Adrian Prantl8a634c12015-12-18 19:44:31 +00004748 if (Module *M = ID.getImportedModule()) {
Reid Klecknerc915cb92020-02-27 18:13:54 -08004749 auto Info = ASTSourceDescriptor(*M);
Adrian Prantl5649b0e2017-07-19 00:09:58 +00004750 auto Loc = ID.getLocation();
Adrian Prantl8a634c12015-12-18 19:44:31 +00004751 DBuilder.createImportedDeclaration(
4752 getCurrentContextDescriptor(cast<Decl>(ID.getDeclContext())),
Adrian Prantl5649b0e2017-07-19 00:09:58 +00004753 getOrCreateModuleRef(Info, DebugTypeExtRefs), getOrCreateFile(Loc),
4754 getLineNumber(Loc));
Adrian Prantl8a634c12015-12-18 19:44:31 +00004755 }
Adrian Prantlc4bb47e2015-06-30 17:39:51 +00004756}
4757
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004758llvm::DIImportedEntity *
David Blaikief121b932013-05-20 22:50:41 +00004759CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
Amy Huang53539bb2020-01-13 15:54:54 -08004760 if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
Duncan P. N. Exon Smithdadc2b62015-04-21 18:43:54 +00004761 return nullptr;
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00004762 auto &VH = NamespaceAliasCache[&NA];
David Blaikief121b932013-05-20 22:50:41 +00004763 if (VH)
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004764 return cast<llvm::DIImportedEntity>(VH);
4765 llvm::DIImportedEntity *R;
Adrian Prantl5649b0e2017-07-19 00:09:58 +00004766 auto Loc = NA.getLocation();
David Majnemer58ed0f32016-07-17 00:39:12 +00004767 if (const auto *Underlying =
David Blaikief121b932013-05-20 22:50:41 +00004768 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
4769 // This could cache & dedup here rather than relying on metadata deduping.
David Blaikie551fb0a2014-04-06 06:30:03 +00004770 R = DBuilder.createImportedDeclaration(
David Blaikief121b932013-05-20 22:50:41 +00004771 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
Adrian Prantl5649b0e2017-07-19 00:09:58 +00004772 EmitNamespaceAlias(*Underlying), getOrCreateFile(Loc),
4773 getLineNumber(Loc), NA.getName());
David Blaikief121b932013-05-20 22:50:41 +00004774 else
David Blaikie551fb0a2014-04-06 06:30:03 +00004775 R = DBuilder.createImportedDeclaration(
David Blaikief121b932013-05-20 22:50:41 +00004776 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
Adrian Prantlddb8e062017-05-12 16:23:53 +00004777 getOrCreateNamespace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
Adrian Prantl5649b0e2017-07-19 00:09:58 +00004778 getOrCreateFile(Loc), getLineNumber(Loc), NA.getName());
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00004779 VH.reset(R);
David Blaikief121b932013-05-20 22:50:41 +00004780 return R;
4781}
4782
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004783llvm::DINamespace *
Adrian Prantlddb8e062017-05-12 16:23:53 +00004784CGDebugInfo::getOrCreateNamespace(const NamespaceDecl *NSDecl) {
4785 // Don't canonicalize the NamespaceDecl here: The DINamespace will be uniqued
4786 // if necessary, and this way multiple declarations of the same namespace in
4787 // different parent modules stay distinct.
4788 auto I = NamespaceCache.find(NSDecl);
Adrian Prantld8870552017-05-11 22:59:19 +00004789 if (I != NamespaceCache.end())
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004790 return cast<llvm::DINamespace>(I->second);
Eric Christopherb2a008c2013-05-16 00:45:12 +00004791
Adrian Prantl6ec370a2015-09-10 18:39:45 +00004792 llvm::DIScope *Context = getDeclContextDescriptor(NSDecl);
Adrian Prantld8870552017-05-11 22:59:19 +00004793 // Don't trust the context if it is a DIModule (see comment above).
Adrian Prantlddb8e062017-05-12 16:23:53 +00004794 llvm::DINamespace *NS =
4795 DBuilder.createNameSpace(Context, NSDecl->getName(), NSDecl->isInline());
4796 NamespaceCache[NSDecl].reset(NS);
Guy Benyei11169dd2012-12-18 14:30:41 +00004797 return NS;
4798}
4799
Adrian Prantla5206ce2015-09-22 23:26:43 +00004800void CGDebugInfo::setDwoId(uint64_t Signature) {
4801 assert(TheCU && "no main compile unit");
4802 TheCU->setDWOId(Signature);
4803}
4804
Guy Benyei11169dd2012-12-18 14:30:41 +00004805void CGDebugInfo::finalize() {
David Blaikie87dab872014-05-07 16:56:58 +00004806 // Creating types might create further types - invalidating the current
4807 // element and the size(), so don't cache/reference them.
4808 for (size_t i = 0; i != ObjCInterfaceCache.size(); ++i) {
4809 ObjCInterfaceCacheEntry E = ObjCInterfaceCache[i];
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004810 llvm::DIType *Ty = E.Type->getDecl()->getDefinition()
Duncan P. N. Exon Smith497d4d462015-04-11 19:05:04 +00004811 ? CreateTypeDefinition(E.Type, E.Unit)
4812 : E.Decl;
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004813 DBuilder.replaceTemporary(llvm::TempDIType(E.Decl), Ty);
David Blaikie87dab872014-05-07 16:56:58 +00004814 }
4815
Adrian Prantle0cabe22019-11-21 09:56:01 -08004816 // Add methods to interface.
4817 for (const auto &P : ObjCMethodCache) {
4818 if (P.second.empty())
4819 continue;
Jonas Devlieghered8ba8ae2018-06-27 17:31:59 +00004820
Adrian Prantle0cabe22019-11-21 09:56:01 -08004821 QualType QTy(P.first->getTypeForDecl(), 0);
4822 auto It = TypeCache.find(QTy.getAsOpaquePtr());
4823 assert(It != TypeCache.end());
Jonas Devlieghered8ba8ae2018-06-27 17:31:59 +00004824
Adrian Prantle0cabe22019-11-21 09:56:01 -08004825 llvm::DICompositeType *InterfaceDecl =
4826 cast<llvm::DICompositeType>(It->second);
Jonas Devlieghered8ba8ae2018-06-27 17:31:59 +00004827
Adrian Prantle0cabe22019-11-21 09:56:01 -08004828 auto CurElts = InterfaceDecl->getElements();
4829 SmallVector<llvm::Metadata *, 16> EltTys(CurElts.begin(), CurElts.end());
4830
4831 // For DWARF v4 or earlier, only add objc_direct methods.
4832 for (auto &SubprogramDirect : P.second)
4833 if (CGM.getCodeGenOpts().DwarfVersion >= 5 || SubprogramDirect.getInt())
4834 EltTys.push_back(SubprogramDirect.getPointer());
4835
4836 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
4837 DBuilder.replaceArrays(InterfaceDecl, Elements);
Jonas Devlieghered8ba8ae2018-06-27 17:31:59 +00004838 }
4839
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004840 for (const auto &P : ReplaceMap) {
4841 assert(P.second);
4842 auto *Ty = cast<llvm::DIType>(P.second);
Duncan P. N. Exon Smith4caa7f22015-04-16 01:00:56 +00004843 assert(Ty->isForwardDecl());
Eric Christopherb2a008c2013-05-16 00:45:12 +00004844
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004845 auto It = TypeCache.find(P.first);
4846 assert(It != TypeCache.end());
4847 assert(It->second);
Adrian Prantl73409ce2013-03-11 18:33:46 +00004848
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004849 DBuilder.replaceTemporary(llvm::TempDIType(Ty),
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004850 cast<llvm::DIType>(It->second));
Guy Benyei11169dd2012-12-18 14:30:41 +00004851 }
Adrian Prantl73409ce2013-03-11 18:33:46 +00004852
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004853 for (const auto &P : FwdDeclReplaceMap) {
4854 assert(P.second);
4855 llvm::TempMDNode FwdDecl(cast<llvm::MDNode>(P.second));
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00004856 llvm::Metadata *Repl;
Frederic Rissd253ed62014-11-18 03:40:51 +00004857
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004858 auto It = DeclCache.find(P.first);
Adrian Prantl97f76852014-12-19 01:02:11 +00004859 // If there has been no definition for the declaration, call RAUW
Frederic Rissd253ed62014-11-18 03:40:51 +00004860 // with ourselves, that will destroy the temporary MDNode and
4861 // replace it with a standard one, avoiding leaking memory.
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004862 if (It == DeclCache.end())
4863 Repl = P.second;
Frederic Rissd253ed62014-11-18 03:40:51 +00004864 else
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004865 Repl = It->second;
Frederic Rissdce60a72014-11-19 18:53:46 +00004866
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004867 if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(Repl))
4868 Repl = GVE->getVariable();
Duncan P. N. Exon Smithd899f6e2015-04-18 00:07:30 +00004869 DBuilder.replaceTemporary(std::move(FwdDecl), cast<llvm::MDNode>(Repl));
Frederic Rissd253ed62014-11-18 03:40:51 +00004870 }
4871
Adrian Prantl73409ce2013-03-11 18:33:46 +00004872 // We keep our own list of retained types, because we need to look
4873 // up the final type in the type cache.
Adrian Prantl3a884fa2015-08-27 22:56:46 +00004874 for (auto &RT : RetainedTypes)
Adrian Prantlad9a195e2015-08-27 21:21:19 +00004875 if (auto MD = TypeCache[RT])
4876 DBuilder.retainType(cast<llvm::DIType>(MD));
Adrian Prantl73409ce2013-03-11 18:33:46 +00004877
Guy Benyei11169dd2012-12-18 14:30:41 +00004878 DBuilder.finalize();
4879}
David Blaikie66088d52014-09-24 17:01:27 +00004880
4881void CGDebugInfo::EmitExplicitCastType(QualType Ty) {
Amy Huang53539bb2020-01-13 15:54:54 -08004882 if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
David Blaikie66088d52014-09-24 17:01:27 +00004883 return;
Duncan P. N. Exon Smith5043f912015-03-27 22:58:05 +00004884
Adrian Prantlc2a44ec2018-12-11 16:58:46 +00004885 if (auto *DieTy = getOrCreateType(Ty, TheCU->getFile()))
Duncan P. N. Exon Smith5043f912015-03-27 22:58:05 +00004886 // Don't ignore in case of explicit cast where it is referenced indirectly.
4887 DBuilder.retainType(DieTy);
David Blaikie66088d52014-09-24 17:01:27 +00004888}
Amara Emerson652795d2016-11-10 14:44:30 +00004889
4890llvm::DebugLoc CGDebugInfo::SourceLocToDebugLoc(SourceLocation Loc) {
4891 if (LexicalBlockStack.empty())
4892 return llvm::DebugLoc();
4893
4894 llvm::MDNode *Scope = LexicalBlockStack.back();
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004895 return llvm::DebugLoc::get(getLineNumber(Loc), getColumnNumber(Loc), Scope);
Amara Emerson652795d2016-11-10 14:44:30 +00004896}
Vedant Kumar5931b4e2018-10-05 20:37:17 +00004897
4898llvm::DINode::DIFlags CGDebugInfo::getCallSiteRelatedAttrs() const {
4899 // Call site-related attributes are only useful in optimized programs, and
4900 // when there's a possibility of debugging backtraces.
4901 if (!CGM.getLangOpts().Optimize || DebugKind == codegenoptions::NoDebugInfo ||
4902 DebugKind == codegenoptions::LocTrackingOnly)
4903 return llvm::DINode::FlagZero;
4904
4905 // Call site-related attributes are available in DWARF v5. Some debuggers,
4906 // while not fully DWARF v5-compliant, may accept these attributes as if they
4907 // were part of DWARF v4.
4908 bool SupportsDWARFv4Ext =
4909 CGM.getCodeGenOpts().DwarfVersion == 4 &&
Djordje Todorovic639d36b2019-06-26 09:38:09 +00004910 (CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB ||
Vedant Kumar568db782019-11-13 18:19:32 -08004911 CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::GDB);
Djordje Todorovic639d36b2019-06-26 09:38:09 +00004912
Djordje Todorovicd9b96212020-03-19 12:13:18 +01004913 if (!SupportsDWARFv4Ext && CGM.getCodeGenOpts().DwarfVersion < 5)
Vedant Kumar5931b4e2018-10-05 20:37:17 +00004914 return llvm::DINode::FlagZero;
4915
4916 return llvm::DINode::FlagAllCallsDescribed;
4917}