blob: da6cb458982ba19b8e1bfb65e50b61f2009d1cfd [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
Guy Benyei11169dd2012-12-18 14:30:41 +0000994 // Create the type.
Brock Wyma8557ec52018-05-22 12:41:19 +0000995 SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +0000996 llvm::DICompositeType *RetTy = DBuilder.createReplaceableCompositeType(
Peter Collingbourned251b0a2015-03-01 22:07:04 +0000997 getTagForRecord(RD), RDName, Ctx, DefUnit, Line, 0, Size, Align,
Brock Wyma8557ec52018-05-22 12:41:19 +0000998 llvm::DINode::FlagFwdDecl, Identifier);
Paul Robinson1787f812017-09-28 18:37:02 +0000999 if (CGM.getCodeGenOpts().DebugFwdTemplateParams)
1000 if (auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD))
1001 DBuilder.replaceArrays(RetTy, llvm::DINodeArray(),
1002 CollectCXXTemplateParams(TSpecial, DefUnit));
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001003 ReplaceMap.emplace_back(
1004 std::piecewise_construct, std::make_tuple(Ty),
1005 std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
David Blaikief427b002014-05-06 03:42:01 +00001006 return RetTy;
Guy Benyei11169dd2012-12-18 14:30:41 +00001007}
1008
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001009llvm::DIType *CGDebugInfo::CreatePointerLikeType(llvm::dwarf::Tag Tag,
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00001010 const Type *Ty,
1011 QualType PointeeTy,
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001012 llvm::DIFile *Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001013 // Bit size, align and offset of the type.
1014 // Size is always the size of a pointer. We can't use getTypeSize here
1015 // because that does not return the correct value for references.
Konstantin Zhuravlyovd1ba16e2017-03-08 23:56:48 +00001016 unsigned AddressSpace = CGM.getContext().getTargetAddressSpace(PointeeTy);
1017 uint64_t Size = CGM.getTarget().getPointerWidth(AddressSpace);
Victor Leschuka7ece032016-10-20 00:13:19 +00001018 auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
Konstantin Zhuravlyovd1ba16e2017-03-08 23:56:48 +00001019 Optional<unsigned> DWARFAddressSpace =
1020 CGM.getTarget().getDWARFAddressSpace(AddressSpace);
Guy Benyei11169dd2012-12-18 14:30:41 +00001021
Keno Fischer87842f32015-11-16 09:04:13 +00001022 if (Tag == llvm::dwarf::DW_TAG_reference_type ||
1023 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
1024 return DBuilder.createReferenceType(Tag, getOrCreateType(PointeeTy, Unit),
Konstantin Zhuravlyovd1ba16e2017-03-08 23:56:48 +00001025 Size, Align, DWARFAddressSpace);
Keno Fischer87842f32015-11-16 09:04:13 +00001026 else
1027 return DBuilder.createPointerType(getOrCreateType(PointeeTy, Unit), Size,
Konstantin Zhuravlyovd1ba16e2017-03-08 23:56:48 +00001028 Align, DWARFAddressSpace);
Guy Benyei11169dd2012-12-18 14:30:41 +00001029}
1030
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001031llvm::DIType *CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
1032 llvm::DIType *&Cache) {
Eric Christopherf8bc4d82013-07-18 00:52:50 +00001033 if (Cache)
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001034 return Cache;
David Blaikiefefc7f72013-05-21 17:58:54 +00001035 Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
Adrian Prantlc2a44ec2018-12-11 16:58:46 +00001036 TheCU, TheCU->getFile(), 0);
David Blaikiefefc7f72013-05-21 17:58:54 +00001037 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1038 Cache = DBuilder.createPointerType(Cache, Size);
1039 return Cache;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001040}
1041
Scott Linder58df0e42018-08-08 15:56:12 +00001042uint64_t CGDebugInfo::collectDefaultElementTypesForBlockPointer(
1043 const BlockPointerType *Ty, llvm::DIFile *Unit, llvm::DIDerivedType *DescTy,
1044 unsigned LineNo, SmallVectorImpl<llvm::Metadata *> &EltTys) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001045 QualType FType;
Guy Benyei11169dd2012-12-18 14:30:41 +00001046
Scott Linder58df0e42018-08-08 15:56:12 +00001047 // Advanced by calls to CreateMemberType in increments of FType, then
1048 // returned as the overall size of the default elements.
1049 uint64_t FieldOffset = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00001050
Scott Linder58df0e42018-08-08 15:56:12 +00001051 // Blocks in OpenCL have unique constraints which make the standard fields
1052 // redundant while requiring size and align fields for enqueue_kernel. See
1053 // initializeForBlockHeader in CGBlocks.cpp
Scott Linder2b5cf042018-07-30 20:31:11 +00001054 if (CGM.getLangOpts().OpenCL) {
1055 FType = CGM.getContext().IntTy;
1056 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
1057 EltTys.push_back(CreateMemberType(Unit, FType, "__align", &FieldOffset));
1058 } else {
1059 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1060 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
1061 FType = CGM.getContext().IntTy;
1062 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
1063 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
1064 FType = CGM.getContext().getPointerType(Ty->getPointeeType());
1065 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
1066 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
Scott Linder58df0e42018-08-08 15:56:12 +00001067 uint64_t FieldSize = CGM.getContext().getTypeSize(Ty);
1068 uint32_t FieldAlign = CGM.getContext().getTypeAlign(Ty);
Scott Linder2b5cf042018-07-30 20:31:11 +00001069 EltTys.push_back(DBuilder.createMemberType(
Scott Linder58df0e42018-08-08 15:56:12 +00001070 Unit, "__descriptor", nullptr, LineNo, FieldSize, FieldAlign,
1071 FieldOffset, llvm::DINode::FlagZero, DescTy));
Scott Lindera7c45682018-07-30 22:52:07 +00001072 FieldOffset += FieldSize;
Scott Linder2b5cf042018-07-30 20:31:11 +00001073 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001074
Scott Linder58df0e42018-08-08 15:56:12 +00001075 return FieldOffset;
1076}
1077
1078llvm::DIType *CGDebugInfo::CreateType(const BlockPointerType *Ty,
1079 llvm::DIFile *Unit) {
1080 SmallVector<llvm::Metadata *, 8> EltTys;
1081 QualType FType;
1082 uint64_t FieldOffset;
1083 llvm::DINodeArray Elements;
1084
1085 FieldOffset = 0;
1086 FType = CGM.getContext().UnsignedLongTy;
1087 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
1088 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
1089
1090 Elements = DBuilder.getOrCreateArray(EltTys);
1091 EltTys.clear();
1092
1093 llvm::DINode::DIFlags Flags = llvm::DINode::FlagAppleBlock;
1094
1095 auto *EltTy =
1096 DBuilder.createStructType(Unit, "__block_descriptor", nullptr, 0,
1097 FieldOffset, 0, Flags, nullptr, Elements);
1098
1099 // Bit size, align and offset of the type.
1100 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1101
1102 auto *DescTy = DBuilder.createPointerType(EltTy, Size);
1103
1104 FieldOffset = collectDefaultElementTypesForBlockPointer(Ty, Unit, DescTy,
1105 0, EltTys);
1106
Guy Benyei11169dd2012-12-18 14:30:41 +00001107 Elements = DBuilder.getOrCreateArray(EltTys);
1108
Adrian Prantl3d2c0512015-07-07 00:49:35 +00001109 // The __block_literal_generic structs are marked with a special
1110 // DW_AT_APPLE_BLOCK attribute and are an implementation detail only
1111 // the debugger needs to know about. To allow type uniquing, emit
1112 // them without a name or a location.
Scott Linder58df0e42018-08-08 15:56:12 +00001113 EltTy = DBuilder.createStructType(Unit, "", nullptr, 0, FieldOffset, 0,
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00001114 Flags, nullptr, Elements);
Guy Benyei11169dd2012-12-18 14:30:41 +00001115
Adrian Prantl3d2c0512015-07-07 00:49:35 +00001116 return DBuilder.createPointerType(EltTy, Size);
Guy Benyei11169dd2012-12-18 14:30:41 +00001117}
1118
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001119llvm::DIType *CGDebugInfo::CreateType(const TemplateSpecializationType *Ty,
1120 llvm::DIFile *Unit) {
David Blaikief1b382e2014-04-06 17:14:06 +00001121 assert(Ty->isTypeAlias());
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001122 llvm::DIType *Src = getOrCreateType(Ty->getAliasedType(), Unit);
David Blaikief1b382e2014-04-06 17:14:06 +00001123
David Blaikie8472fa62019-06-08 00:01:21 +00001124 auto *AliasDecl =
1125 cast<TypeAliasTemplateDecl>(Ty->getTemplateName().getAsTemplateDecl())
1126 ->getTemplatedDecl();
1127
1128 if (AliasDecl->hasAttr<NoDebugAttr>())
1129 return Src;
1130
David Blaikief1b382e2014-04-06 17:14:06 +00001131 SmallString<128> NS;
1132 llvm::raw_svector_ostream OS(NS);
Serge Pavlov03e672c2017-11-28 16:14:14 +00001133 Ty->getTemplateName().print(OS, getPrintingPolicy(), /*qualified*/ false);
1134 printTemplateArgumentList(OS, Ty->template_arguments(), getPrintingPolicy());
David Blaikief1b382e2014-04-06 17:14:06 +00001135
David Blaikief1b382e2014-04-06 17:14:06 +00001136 SourceLocation Loc = AliasDecl->getLocation();
Adrian Prantlb67dbce2015-09-11 18:45:02 +00001137 return DBuilder.createTypedef(Src, OS.str(), getOrCreateFile(Loc),
1138 getLineNumber(Loc),
Sam McCalld27a16e2019-11-18 15:53:22 +01001139 getDeclContextDescriptor(AliasDecl));
David Blaikief1b382e2014-04-06 17:14:06 +00001140}
1141
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001142llvm::DIType *CGDebugInfo::CreateType(const TypedefType *Ty,
1143 llvm::DIFile *Unit) {
David Blaikie8472fa62019-06-08 00:01:21 +00001144 llvm::DIType *Underlying =
1145 getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
1146
1147 if (Ty->getDecl()->hasAttr<NoDebugAttr>())
1148 return Underlying;
1149
Guy Benyei11169dd2012-12-18 14:30:41 +00001150 // We don't set size information, but do specify where the typedef was
1151 // declared.
Amjad Abouddc4531e2016-04-30 01:44:38 +00001152 SourceLocation Loc = Ty->getDecl()->getLocation();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001153
Sourabh Singh Tomarf1e39882019-12-03 09:29:54 +05301154 uint32_t Align = getDeclAlignIfRequired(Ty->getDecl(), CGM.getContext());
Duncan P. N. Exon Smith4078ad42015-04-16 16:36:45 +00001155 // Typedefs are derived from some other type.
Sam McCalld27a16e2019-11-18 15:53:22 +01001156 return DBuilder.createTypedef(Underlying, Ty->getDecl()->getName(),
1157 getOrCreateFile(Loc), getLineNumber(Loc),
Sourabh Singh Tomarf1e39882019-12-03 09:29:54 +05301158 getDeclContextDescriptor(Ty->getDecl()), Align);
Guy Benyei11169dd2012-12-18 14:30:41 +00001159}
1160
Reid Klecknerf00f8032016-06-08 20:41:54 +00001161static unsigned getDwarfCC(CallingConv CC) {
1162 switch (CC) {
1163 case CC_C:
1164 // Avoid emitting DW_AT_calling_convention if the C convention was used.
1165 return 0;
1166
1167 case CC_X86StdCall:
1168 return llvm::dwarf::DW_CC_BORLAND_stdcall;
1169 case CC_X86FastCall:
1170 return llvm::dwarf::DW_CC_BORLAND_msfastcall;
1171 case CC_X86ThisCall:
1172 return llvm::dwarf::DW_CC_BORLAND_thiscall;
1173 case CC_X86VectorCall:
1174 return llvm::dwarf::DW_CC_LLVM_vectorcall;
1175 case CC_X86Pascal:
1176 return llvm::dwarf::DW_CC_BORLAND_pascal;
Martin Storsjo022e7822017-07-17 20:49:45 +00001177 case CC_Win64:
Jonas Devliegheref0702682018-03-22 13:53:30 +00001178 return llvm::dwarf::DW_CC_LLVM_Win64;
Reid Klecknerf00f8032016-06-08 20:41:54 +00001179 case CC_X86_64SysV:
Jonas Devliegheref0702682018-03-22 13:53:30 +00001180 return llvm::dwarf::DW_CC_LLVM_X86_64SysV;
Reid Klecknerf00f8032016-06-08 20:41:54 +00001181 case CC_AAPCS:
Sander de Smalen44a22532018-11-26 16:38:37 +00001182 case CC_AArch64VectorCall:
Jonas Devliegheref0702682018-03-22 13:53:30 +00001183 return llvm::dwarf::DW_CC_LLVM_AAPCS;
Reid Klecknerf00f8032016-06-08 20:41:54 +00001184 case CC_AAPCS_VFP:
Jonas Devliegheref0702682018-03-22 13:53:30 +00001185 return llvm::dwarf::DW_CC_LLVM_AAPCS_VFP;
Reid Klecknerf00f8032016-06-08 20:41:54 +00001186 case CC_IntelOclBicc:
Jonas Devliegheref0702682018-03-22 13:53:30 +00001187 return llvm::dwarf::DW_CC_LLVM_IntelOclBicc;
Reid Klecknerf00f8032016-06-08 20:41:54 +00001188 case CC_SpirFunction:
Jonas Devliegheref0702682018-03-22 13:53:30 +00001189 return llvm::dwarf::DW_CC_LLVM_SpirFunction;
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00001190 case CC_OpenCLKernel:
Jonas Devliegheref0702682018-03-22 13:53:30 +00001191 return llvm::dwarf::DW_CC_LLVM_OpenCLKernel;
Reid Klecknerf00f8032016-06-08 20:41:54 +00001192 case CC_Swift:
Jonas Devliegheref0702682018-03-22 13:53:30 +00001193 return llvm::dwarf::DW_CC_LLVM_Swift;
Reid Klecknerf00f8032016-06-08 20:41:54 +00001194 case CC_PreserveMost:
Jonas Devliegheref0702682018-03-22 13:53:30 +00001195 return llvm::dwarf::DW_CC_LLVM_PreserveMost;
Reid Klecknerf00f8032016-06-08 20:41:54 +00001196 case CC_PreserveAll:
Jonas Devliegheref0702682018-03-22 13:53:30 +00001197 return llvm::dwarf::DW_CC_LLVM_PreserveAll;
Erich Keane757d3172016-11-02 18:29:35 +00001198 case CC_X86RegCall:
Jonas Devliegheref0702682018-03-22 13:53:30 +00001199 return llvm::dwarf::DW_CC_LLVM_X86RegCall;
Reid Klecknerf00f8032016-06-08 20:41:54 +00001200 }
1201 return 0;
1202}
1203
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001204llvm::DIType *CGDebugInfo::CreateType(const FunctionType *Ty,
1205 llvm::DIFile *Unit) {
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001206 SmallVector<llvm::Metadata *, 16> EltTys;
Guy Benyei11169dd2012-12-18 14:30:41 +00001207
1208 // Add the result type at least.
Alp Toker314cc812014-01-25 16:55:45 +00001209 EltTys.push_back(getOrCreateType(Ty->getReturnType(), Unit));
Guy Benyei11169dd2012-12-18 14:30:41 +00001210
1211 // Set up remainder of arguments if there is a prototype.
Adrian Prantl800faef2014-02-25 23:42:18 +00001212 // otherwise emit it as a variadic function.
Guy Benyei11169dd2012-12-18 14:30:41 +00001213 if (isa<FunctionNoProtoType>(Ty))
1214 EltTys.push_back(DBuilder.createUnspecifiedParameter());
David Majnemer58ed0f32016-07-17 00:39:12 +00001215 else if (const auto *FPT = dyn_cast<FunctionProtoType>(Ty)) {
1216 for (const QualType &ParamType : FPT->param_types())
1217 EltTys.push_back(getOrCreateType(ParamType, Unit));
Adrian Prantld45ba252014-02-25 19:38:11 +00001218 if (FPT->isVariadic())
1219 EltTys.push_back(DBuilder.createUnspecifiedParameter());
Guy Benyei11169dd2012-12-18 14:30:41 +00001220 }
1221
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001222 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
Leny Kholodov80c047d2016-09-06 10:48:04 +00001223 return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
Reid Klecknerf00f8032016-06-08 20:41:54 +00001224 getDwarfCC(Ty->getCallConv()));
Guy Benyei11169dd2012-12-18 14:30:41 +00001225}
1226
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001227/// Convert an AccessSpecifier into the corresponding DINode flag.
Adrian Prantl21361fb2014-08-29 22:44:27 +00001228/// As an optimization, return 0 if the access specifier equals the
1229/// default for the containing type.
Leny Kholodovdf050fd2016-09-06 17:06:14 +00001230static llvm::DINode::DIFlags getAccessFlag(AccessSpecifier Access,
1231 const RecordDecl *RD) {
Adrian Prantl21361fb2014-08-29 22:44:27 +00001232 AccessSpecifier Default = clang::AS_none;
1233 if (RD && RD->isClass())
1234 Default = clang::AS_private;
1235 else if (RD && (RD->isStruct() || RD->isUnion()))
1236 Default = clang::AS_public;
1237
1238 if (Access == Default)
Leny Kholodov80c047d2016-09-06 10:48:04 +00001239 return llvm::DINode::FlagZero;
Adrian Prantl21361fb2014-08-29 22:44:27 +00001240
Eric Christophere7b87e52014-10-26 23:40:33 +00001241 switch (Access) {
1242 case clang::AS_private:
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001243 return llvm::DINode::FlagPrivate;
Eric Christophere7b87e52014-10-26 23:40:33 +00001244 case clang::AS_protected:
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001245 return llvm::DINode::FlagProtected;
Eric Christophere7b87e52014-10-26 23:40:33 +00001246 case clang::AS_public:
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001247 return llvm::DINode::FlagPublic;
Eric Christophere7b87e52014-10-26 23:40:33 +00001248 case clang::AS_none:
Leny Kholodov80c047d2016-09-06 10:48:04 +00001249 return llvm::DINode::FlagZero;
Adrian Prantl21361fb2014-08-29 22:44:27 +00001250 }
1251 llvm_unreachable("unexpected access enumerator");
1252}
Guy Benyei11169dd2012-12-18 14:30:41 +00001253
David Majnemerb4b671e2016-06-30 03:01:59 +00001254llvm::DIType *CGDebugInfo::createBitFieldType(const FieldDecl *BitFieldDecl,
1255 llvm::DIScope *RecordTy,
1256 const RecordDecl *RD) {
1257 StringRef Name = BitFieldDecl->getName();
1258 QualType Ty = BitFieldDecl->getType();
1259 SourceLocation Loc = BitFieldDecl->getLocation();
1260 llvm::DIFile *VUnit = getOrCreateFile(Loc);
1261 llvm::DIType *DebugType = getOrCreateType(Ty, VUnit);
1262
1263 // Get the location for the field.
1264 llvm::DIFile *File = getOrCreateFile(Loc);
1265 unsigned Line = getLineNumber(Loc);
1266
1267 const CGBitFieldInfo &BitFieldInfo =
1268 CGM.getTypes().getCGRecordLayout(RD).getBitFieldInfo(BitFieldDecl);
1269 uint64_t SizeInBits = BitFieldInfo.Size;
1270 assert(SizeInBits > 0 && "found named 0-width bitfield");
David Majnemerb4b671e2016-06-30 03:01:59 +00001271 uint64_t StorageOffsetInBits =
1272 CGM.getContext().toBits(BitFieldInfo.StorageOffset);
Reid Kleckner06a4b2a2017-06-12 19:57:56 +00001273 uint64_t Offset = BitFieldInfo.Offset;
1274 // The bit offsets for big endian machines are reversed for big
1275 // endian target, compensate for that as the DIDerivedType requires
1276 // un-reversed offsets.
1277 if (CGM.getDataLayout().isBigEndian())
1278 Offset = BitFieldInfo.StorageSize - BitFieldInfo.Size - Offset;
1279 uint64_t OffsetInBits = StorageOffsetInBits + Offset;
Leny Kholodov80c047d2016-09-06 10:48:04 +00001280 llvm::DINode::DIFlags Flags = getAccessFlag(BitFieldDecl->getAccess(), RD);
David Majnemerb4b671e2016-06-30 03:01:59 +00001281 return DBuilder.createBitFieldMemberType(
Victor Leschuka7ece032016-10-20 00:13:19 +00001282 RecordTy, Name, File, Line, SizeInBits, OffsetInBits, StorageOffsetInBits,
1283 Flags, DebugType);
David Majnemerb4b671e2016-06-30 03:01:59 +00001284}
1285
1286llvm::DIType *
1287CGDebugInfo::createFieldType(StringRef name, QualType type, SourceLocation loc,
1288 AccessSpecifier AS, uint64_t offsetInBits,
Victor Leschuka7ece032016-10-20 00:13:19 +00001289 uint32_t AlignInBits, llvm::DIFile *tunit,
1290 llvm::DIScope *scope, const RecordDecl *RD) {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001291 llvm::DIType *debugType = getOrCreateType(type, tunit);
Guy Benyei11169dd2012-12-18 14:30:41 +00001292
1293 // Get the location for the field.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001294 llvm::DIFile *file = getOrCreateFile(loc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001295 unsigned line = getLineNumber(loc);
1296
David Majnemer34b57492014-07-30 01:30:47 +00001297 uint64_t SizeInBits = 0;
Victor Leschuka7ece032016-10-20 00:13:19 +00001298 auto Align = AlignInBits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001299 if (!type->isIncompleteArrayType()) {
David Majnemer34b57492014-07-30 01:30:47 +00001300 TypeInfo TI = CGM.getContext().getTypeInfo(type);
1301 SizeInBits = TI.Width;
Victor Leschuka7ece032016-10-20 00:13:19 +00001302 if (!Align)
1303 Align = getTypeAlignIfRequired(type, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00001304 }
1305
Leny Kholodov80c047d2016-09-06 10:48:04 +00001306 llvm::DINode::DIFlags flags = getAccessFlag(AS, RD);
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00001307 return DBuilder.createMemberType(scope, name, file, line, SizeInBits, Align,
1308 offsetInBits, flags, debugType);
Guy Benyei11169dd2012-12-18 14:30:41 +00001309}
1310
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001311void CGDebugInfo::CollectRecordLambdaFields(
1312 const CXXRecordDecl *CXXDecl, SmallVectorImpl<llvm::Metadata *> &elements,
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001313 llvm::DIType *RecordTy) {
Eric Christopher91a31902013-01-16 01:22:32 +00001314 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
1315 // has the name and the location of the variable so we should iterate over
1316 // both concurrently.
1317 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
1318 RecordDecl::field_iterator Field = CXXDecl->field_begin();
1319 unsigned fieldno = 0;
1320 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
Eric Christophere7b87e52014-10-26 23:40:33 +00001321 E = CXXDecl->captures_end();
1322 I != E; ++I, ++Field, ++fieldno) {
Benjamin Kramerf3ca26982014-05-10 16:31:55 +00001323 const LambdaCapture &C = *I;
Eric Christopher91a31902013-01-16 01:22:32 +00001324 if (C.capturesVariable()) {
David Majnemerb4b671e2016-06-30 03:01:59 +00001325 SourceLocation Loc = C.getLocation();
1326 assert(!Field->isBitField() && "lambdas don't have bitfield members!");
Eric Christopher91a31902013-01-16 01:22:32 +00001327 VarDecl *V = C.getCapturedVar();
Eric Christopher91a31902013-01-16 01:22:32 +00001328 StringRef VName = V->getName();
David Majnemerb4b671e2016-06-30 03:01:59 +00001329 llvm::DIFile *VUnit = getOrCreateFile(Loc);
Victor Leschuka7ece032016-10-20 00:13:19 +00001330 auto Align = getDeclAlignIfRequired(V, CGM.getContext());
David Majnemerb4b671e2016-06-30 03:01:59 +00001331 llvm::DIType *FieldType = createFieldType(
1332 VName, Field->getType(), Loc, Field->getAccess(),
Victor Leschuka7ece032016-10-20 00:13:19 +00001333 layout.getFieldOffset(fieldno), Align, VUnit, RecordTy, CXXDecl);
David Majnemerb4b671e2016-06-30 03:01:59 +00001334 elements.push_back(FieldType);
Alexey Bataev39c81e22014-08-28 04:28:19 +00001335 } else if (C.capturesThis()) {
Eric Christopher91a31902013-01-16 01:22:32 +00001336 // TODO: Need to handle 'this' in some way by probably renaming the
1337 // this of the lambda class and having a field member of 'this' or
1338 // by using AT_object_pointer for the function and having that be
1339 // used as 'this' for semantic references.
Eric Christopher91a31902013-01-16 01:22:32 +00001340 FieldDecl *f = *Field;
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001341 llvm::DIFile *VUnit = getOrCreateFile(f->getLocation());
Eric Christopher91a31902013-01-16 01:22:32 +00001342 QualType type = f->getType();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001343 llvm::DIType *fieldType = createFieldType(
David Majnemerb4b671e2016-06-30 03:01:59 +00001344 "this", type, f->getLocation(), f->getAccess(),
Eric Christophere7b87e52014-10-26 23:40:33 +00001345 layout.getFieldOffset(fieldno), VUnit, RecordTy, CXXDecl);
Eric Christopher91a31902013-01-16 01:22:32 +00001346
1347 elements.push_back(fieldType);
1348 }
1349 }
1350}
1351
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001352llvm::DIDerivedType *
1353CGDebugInfo::CreateRecordStaticField(const VarDecl *Var, llvm::DIType *RecordTy,
Duncan P. N. Exon Smithc09c5482015-04-20 21:17:26 +00001354 const RecordDecl *RD) {
Eric Christopher91a31902013-01-16 01:22:32 +00001355 // Create the descriptor for the static variable, with or without
1356 // constant initializers.
David Blaikie8e707bb2014-10-14 22:22:17 +00001357 Var = Var->getCanonicalDecl();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001358 llvm::DIFile *VUnit = getOrCreateFile(Var->getLocation());
1359 llvm::DIType *VTy = getOrCreateType(Var->getType(), VUnit);
Eric Christopher91a31902013-01-16 01:22:32 +00001360
Eric Christopher91a31902013-01-16 01:22:32 +00001361 unsigned LineNumber = getLineNumber(Var->getLocation());
1362 StringRef VName = Var->getName();
Craig Topper8a13c412014-05-21 05:09:00 +00001363 llvm::Constant *C = nullptr;
Eric Christopher91a31902013-01-16 01:22:32 +00001364 if (Var->getInit()) {
1365 const APValue *Value = Var->evaluateValue();
David Blaikied42917f2013-01-20 01:19:17 +00001366 if (Value) {
1367 if (Value->isInt())
1368 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
1369 if (Value->isFloat())
1370 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
1371 }
Eric Christopher91a31902013-01-16 01:22:32 +00001372 }
1373
Leny Kholodov80c047d2016-09-06 10:48:04 +00001374 llvm::DINode::DIFlags Flags = getAccessFlag(Var->getAccess(), RD);
Victor Leschuka7ece032016-10-20 00:13:19 +00001375 auto Align = getDeclAlignIfRequired(Var, CGM.getContext());
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001376 llvm::DIDerivedType *GV = DBuilder.createStaticMemberType(
Victor Leschuka7ece032016-10-20 00:13:19 +00001377 RecordTy, VName, VUnit, LineNumber, VTy, Flags, C, Align);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001378 StaticDataMemberCache[Var->getCanonicalDecl()].reset(GV);
David Blaikieae019462013-08-15 22:50:29 +00001379 return GV;
Eric Christopher91a31902013-01-16 01:22:32 +00001380}
1381
Eric Christophere7b87e52014-10-26 23:40:33 +00001382void CGDebugInfo::CollectRecordNormalField(
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001383 const FieldDecl *field, uint64_t OffsetInBits, llvm::DIFile *tunit,
1384 SmallVectorImpl<llvm::Metadata *> &elements, llvm::DIType *RecordTy,
Eric Christophere7b87e52014-10-26 23:40:33 +00001385 const RecordDecl *RD) {
Eric Christopher91a31902013-01-16 01:22:32 +00001386 StringRef name = field->getName();
1387 QualType type = field->getType();
1388
1389 // Ignore unnamed fields unless they're anonymous structs/unions.
1390 if (name.empty() && !type->isRecordType())
1391 return;
1392
David Majnemerb4b671e2016-06-30 03:01:59 +00001393 llvm::DIType *FieldType;
Eric Christopher91a31902013-01-16 01:22:32 +00001394 if (field->isBitField()) {
David Majnemerb4b671e2016-06-30 03:01:59 +00001395 FieldType = createBitFieldType(field, RecordTy, RD);
1396 } else {
Victor Leschuka7ece032016-10-20 00:13:19 +00001397 auto Align = getDeclAlignIfRequired(field, CGM.getContext());
David Majnemerb4b671e2016-06-30 03:01:59 +00001398 FieldType =
1399 createFieldType(name, type, field->getLocation(), field->getAccess(),
Victor Leschuka7ece032016-10-20 00:13:19 +00001400 OffsetInBits, Align, tunit, RecordTy, RD);
Eric Christopher91a31902013-01-16 01:22:32 +00001401 }
1402
David Majnemerb4b671e2016-06-30 03:01:59 +00001403 elements.push_back(FieldType);
Eric Christopher91a31902013-01-16 01:22:32 +00001404}
1405
Reid Klecknere2e82062017-08-08 20:30:14 +00001406void CGDebugInfo::CollectRecordNestedType(
1407 const TypeDecl *TD, SmallVectorImpl<llvm::Metadata *> &elements) {
1408 QualType Ty = CGM.getContext().getTypeDeclType(TD);
Reid Kleckner755220b2016-08-01 18:56:13 +00001409 // Injected class names are not considered nested records.
1410 if (isa<InjectedClassNameType>(Ty))
1411 return;
Reid Klecknere2e82062017-08-08 20:30:14 +00001412 SourceLocation Loc = TD->getLocation();
Adrian McCarthyab1e7862016-07-21 18:43:20 +00001413 llvm::DIType *nestedType = getOrCreateType(Ty, getOrCreateFile(Loc));
1414 elements.push_back(nestedType);
1415}
1416
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001417void CGDebugInfo::CollectRecordFields(
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001418 const RecordDecl *record, llvm::DIFile *tunit,
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001419 SmallVectorImpl<llvm::Metadata *> &elements,
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001420 llvm::DICompositeType *RecordTy) {
David Majnemer58ed0f32016-07-17 00:39:12 +00001421 const auto *CXXDecl = dyn_cast<CXXRecordDecl>(record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001422
Eric Christopher91a31902013-01-16 01:22:32 +00001423 if (CXXDecl && CXXDecl->isLambda())
1424 CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
1425 else {
1426 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001427
Eric Christopher91a31902013-01-16 01:22:32 +00001428 // Field number for non-static fields.
Eric Christopher0f7594372013-01-04 17:59:07 +00001429 unsigned fieldNo = 0;
Eric Christopher91a31902013-01-16 01:22:32 +00001430
Eric Christopher91a31902013-01-16 01:22:32 +00001431 // Static and non-static members should appear in the same order as
1432 // the corresponding declarations in the source program.
Aaron Ballman629afae2014-03-07 19:56:05 +00001433 for (const auto *I : record->decls())
1434 if (const auto *V = dyn_cast<VarDecl>(I)) {
Paul Robinsonb17327d2016-04-27 17:37:12 +00001435 if (V->hasAttr<NoDebugAttr>())
1436 continue;
Reid Kleckner891b2712018-07-20 20:55:00 +00001437
1438 // Skip variable template specializations when emitting CodeView. MSVC
1439 // doesn't emit them.
1440 if (CGM.getCodeGenOpts().EmitCodeView &&
1441 isa<VarTemplateSpecializationDecl>(V))
1442 continue;
1443
David Blaikie4f3b7362019-06-17 19:40:52 +00001444 if (isa<VarTemplatePartialSpecializationDecl>(V))
1445 continue;
1446
David Blaikiece763042013-08-20 21:49:21 +00001447 // Reuse the existing static member declaration if one exists
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001448 auto MI = StaticDataMemberCache.find(V->getCanonicalDecl());
David Blaikiece763042013-08-20 21:49:21 +00001449 if (MI != StaticDataMemberCache.end()) {
1450 assert(MI->second &&
1451 "Static data member declaration should still exist");
Duncan P. N. Exon Smithac346ba2015-07-24 18:05:58 +00001452 elements.push_back(MI->second);
Adrian Prantl21361fb2014-08-29 22:44:27 +00001453 } else {
1454 auto Field = CreateRecordStaticField(V, RecordTy, record);
1455 elements.push_back(Field);
1456 }
Aaron Ballman629afae2014-03-07 19:56:05 +00001457 } else if (const auto *field = dyn_cast<FieldDecl>(I)) {
Eric Christophere7b87e52014-10-26 23:40:33 +00001458 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo), tunit,
1459 elements, RecordTy, record);
Eric Christopher91a31902013-01-16 01:22:32 +00001460
1461 // Bump field number for next field.
1462 ++fieldNo;
Reid Kleckner891b2712018-07-20 20:55:00 +00001463 } else if (CGM.getCodeGenOpts().EmitCodeView) {
1464 // Debug info for nested types is included in the member list only for
1465 // CodeView.
Reid Klecknere2e82062017-08-08 20:30:14 +00001466 if (const auto *nestedType = dyn_cast<TypeDecl>(I))
1467 if (!nestedType->isImplicit() &&
1468 nestedType->getDeclContext() == record)
1469 CollectRecordNestedType(nestedType, elements);
1470 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001471 }
1472}
1473
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001474llvm::DISubroutineType *
Guy Benyei11169dd2012-12-18 14:30:41 +00001475CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
Awanish Pandeyc83602f2020-01-23 16:06:52 +05301476 llvm::DIFile *Unit, bool decl) {
David Blaikie7eb06852013-01-07 23:06:35 +00001477 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
David Blaikie2aaf0652013-01-07 22:24:59 +00001478 if (Method->isStatic())
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001479 return cast_or_null<llvm::DISubroutineType>(
Duncan P. N. Exon Smithc7551282015-04-06 23:21:33 +00001480 getOrCreateType(QualType(Func, 0), Unit));
Awanish Pandeyc83602f2020-01-23 16:06:52 +05301481 return getOrCreateInstanceMethodType(Method->getThisType(), Func, Unit, decl);
David Blaikie7eb06852013-01-07 23:06:35 +00001482}
David Blaikie2aaf0652013-01-07 22:24:59 +00001483
Awanish Pandeyc83602f2020-01-23 16:06:52 +05301484llvm::DISubroutineType *
1485CGDebugInfo::getOrCreateInstanceMethodType(QualType ThisPtr,
1486 const FunctionProtoType *Func,
1487 llvm::DIFile *Unit, bool decl) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001488 // Add "this" pointer.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001489 llvm::DITypeRefArray Args(
1490 cast<llvm::DISubroutineType>(getOrCreateType(QualType(Func, 0), Unit))
Duncan P. N. Exon Smithc7551282015-04-06 23:21:33 +00001491 ->getTypeArray());
Duncan P. N. Exon Smitha98fac62015-04-07 04:14:45 +00001492 assert(Args.size() && "Invalid number of arguments!");
Guy Benyei11169dd2012-12-18 14:30:41 +00001493
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001494 SmallVector<llvm::Metadata *, 16> Elts;
Guy Benyei11169dd2012-12-18 14:30:41 +00001495 // First element is always return type. For 'void' functions it is NULL.
Awanish Pandeyc83602f2020-01-23 16:06:52 +05301496 QualType temp = Func->getReturnType();
1497 if (temp->getTypeClass() == Type::Auto && decl)
1498 Elts.push_back(CreateType(cast<AutoType>(temp)));
1499 else
1500 Elts.push_back(Args[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001501
David Blaikie2aaf0652013-01-07 22:24:59 +00001502 // "this" pointer is always first argument.
David Blaikie7eb06852013-01-07 23:06:35 +00001503 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
David Blaikie2aaf0652013-01-07 22:24:59 +00001504 if (isa<ClassTemplateSpecializationDecl>(RD)) {
1505 // Create pointer type directly in this case.
1506 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
1507 QualType PointeeTy = ThisPtrTy->getPointeeType();
1508 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCallc8e01702013-04-16 22:48:15 +00001509 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
Victor Leschuka7ece032016-10-20 00:13:19 +00001510 auto Align = getTypeAlignIfRequired(ThisPtrTy, CGM.getContext());
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001511 llvm::DIType *PointeeType = getOrCreateType(PointeeTy, Unit);
1512 llvm::DIType *ThisPtrType =
Eric Christophere7b87e52014-10-26 23:40:33 +00001513 DBuilder.createPointerType(PointeeType, Size, Align);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001514 TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);
David Blaikie2aaf0652013-01-07 22:24:59 +00001515 // TODO: This and the artificial type below are misleading, the
1516 // types aren't artificial the argument is, but the current
1517 // metadata doesn't represent that.
1518 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1519 Elts.push_back(ThisPtrType);
1520 } else {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001521 llvm::DIType *ThisPtrType = getOrCreateType(ThisPtr, Unit);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001522 TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);
David Blaikie2aaf0652013-01-07 22:24:59 +00001523 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1524 Elts.push_back(ThisPtrType);
Guy Benyei11169dd2012-12-18 14:30:41 +00001525 }
1526
1527 // Copy rest of the arguments.
Duncan P. N. Exon Smitha98fac62015-04-07 04:14:45 +00001528 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1529 Elts.push_back(Args[i]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001530
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001531 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
Guy Benyei11169dd2012-12-18 14:30:41 +00001532
Leny Kholodov80c047d2016-09-06 10:48:04 +00001533 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
Adrian Prantl0630eb72013-12-18 21:48:18 +00001534 if (Func->getExtProtoInfo().RefQualifier == RQ_LValue)
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001535 Flags |= llvm::DINode::FlagLValueReference;
Adrian Prantl0630eb72013-12-18 21:48:18 +00001536 if (Func->getExtProtoInfo().RefQualifier == RQ_RValue)
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001537 Flags |= llvm::DINode::FlagRValueReference;
Adrian Prantl0630eb72013-12-18 21:48:18 +00001538
Reid Klecknerf00f8032016-06-08 20:41:54 +00001539 return DBuilder.createSubroutineType(EltTypeArray, Flags,
1540 getDwarfCC(Func->getCallConv()));
Guy Benyei11169dd2012-12-18 14:30:41 +00001541}
1542
Eric Christopherb2a008c2013-05-16 00:45:12 +00001543/// isFunctionLocalClass - Return true if CXXRecordDecl is defined
Guy Benyei11169dd2012-12-18 14:30:41 +00001544/// inside a function.
1545static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
David Majnemer58ed0f32016-07-17 00:39:12 +00001546 if (const auto *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
Guy Benyei11169dd2012-12-18 14:30:41 +00001547 return isFunctionLocalClass(NRD);
1548 if (isa<FunctionDecl>(RD->getDeclContext()))
1549 return true;
1550 return false;
1551}
1552
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001553llvm::DISubprogram *CGDebugInfo::CreateCXXMemberFunction(
1554 const CXXMethodDecl *Method, llvm::DIFile *Unit, llvm::DIType *RecordTy) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001555 bool IsCtorOrDtor =
Eric Christophere7b87e52014-10-26 23:40:33 +00001556 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
Eric Christopherb2a008c2013-05-16 00:45:12 +00001557
Guy Benyei11169dd2012-12-18 14:30:41 +00001558 StringRef MethodName = getFunctionName(Method);
Awanish Pandeyc83602f2020-01-23 16:06:52 +05301559 llvm::DISubroutineType *MethodTy = getOrCreateMethodType(Method, Unit, true);
Guy Benyei11169dd2012-12-18 14:30:41 +00001560
1561 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1562 // make sense to give a single ctor/dtor a linkage name.
1563 StringRef MethodLinkageName;
David Blaikie71647672016-04-12 21:22:48 +00001564 // FIXME: 'isFunctionLocalClass' seems like an arbitrary/unintentional
1565 // property to use here. It may've been intended to model "is non-external
1566 // type" but misses cases of non-function-local but non-external classes such
1567 // as those in anonymous namespaces as well as the reverse - external types
1568 // that are function local, such as those in (non-local) inline functions.
Guy Benyei11169dd2012-12-18 14:30:41 +00001569 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1570 MethodLinkageName = CGM.getMangledName(Method);
1571
1572 // Get the location for the method.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001573 llvm::DIFile *MethodDefUnit = nullptr;
David Blaikie7fceebf2013-08-19 03:37:48 +00001574 unsigned MethodLine = 0;
1575 if (!Method->isImplicit()) {
1576 MethodDefUnit = getOrCreateFile(Method->getLocation());
1577 MethodLine = getLineNumber(Method->getLocation());
1578 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001579
1580 // Collect virtual method info.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001581 llvm::DIType *ContainingType = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001582 unsigned VIndex = 0;
Leny Kholodov80c047d2016-09-06 10:48:04 +00001583 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
Paul Robinsoncda54212018-11-19 18:29:28 +00001584 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
Reid Kleckner0358cbf2016-07-01 02:41:25 +00001585 int ThisAdjustment = 0;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001586
Guy Benyei11169dd2012-12-18 14:30:41 +00001587 if (Method->isVirtual()) {
1588 if (Method->isPure())
Paul Robinsoncda54212018-11-19 18:29:28 +00001589 SPFlags |= llvm::DISubprogram::SPFlagPureVirtual;
Guy Benyei11169dd2012-12-18 14:30:41 +00001590 else
Paul Robinsoncda54212018-11-19 18:29:28 +00001591 SPFlags |= llvm::DISubprogram::SPFlagVirtual;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001592
Reid Kleckner216d0a12016-06-16 20:08:51 +00001593 if (CGM.getTarget().getCXXABI().isItaniumFamily()) {
1594 // It doesn't make sense to give a virtual destructor a vtable index,
1595 // since a single destructor has two entries in the vtable.
1596 if (!isa<CXXDestructorDecl>(Method))
1597 VIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(Method);
1598 } else {
1599 // Emit MS ABI vftable information. There is only one entry for the
1600 // deleting dtor.
1601 const auto *DD = dyn_cast<CXXDestructorDecl>(Method);
1602 GlobalDecl GD = DD ? GlobalDecl(DD, Dtor_Deleting) : GlobalDecl(Method);
Reid Klecknercbec0262018-04-02 20:00:39 +00001603 MethodVFTableLocation ML =
Reid Kleckner216d0a12016-06-16 20:08:51 +00001604 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD);
1605 VIndex = ML.Index;
Reid Klecknerc4871ed2016-06-22 18:34:45 +00001606
1607 // CodeView only records the vftable offset in the class that introduces
1608 // the virtual method. This is possible because, unlike Itanium, the MS
1609 // C++ ABI does not include all virtual methods from non-primary bases in
1610 // the vtable for the most derived class. For example, if C inherits from
1611 // A and B, C's primary vftable will not include B's virtual methods.
Benjamin Krameracfa3392017-12-17 23:52:45 +00001612 if (Method->size_overridden_methods() == 0)
Reid Klecknerc4871ed2016-06-22 18:34:45 +00001613 Flags |= llvm::DINode::FlagIntroducedVirtual;
1614
Reid Kleckner0358cbf2016-07-01 02:41:25 +00001615 // The 'this' adjustment accounts for both the virtual and non-virtual
1616 // portions of the adjustment. Presumably the debugger only uses it when
1617 // it knows the dynamic type of an object.
1618 ThisAdjustment = CGM.getCXXABI()
1619 .getVirtualFunctionPrologueThisAdjustment(GD)
1620 .getQuantity();
Reid Kleckner216d0a12016-06-16 20:08:51 +00001621 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001622 ContainingType = RecordTy;
1623 }
1624
Adrian Prantlf919be32019-10-29 09:20:14 -07001625 // We're checking for deleted C++ special member functions
1626 // [Ctors,Dtors, Copy/Move]
Sourabh Singh Tomar52ea3082019-11-02 01:28:40 +05301627 auto checkAttrDeleted = [&](const auto *Method) {
Adrian Prantlf919be32019-10-29 09:20:14 -07001628 if (Method->getCanonicalDecl()->isDeleted())
1629 SPFlags |= llvm::DISubprogram::SPFlagDeleted;
1630 };
1631
1632 switch (Method->getKind()) {
1633
1634 case Decl::CXXConstructor:
1635 case Decl::CXXDestructor:
1636 checkAttrDeleted(Method);
1637 break;
1638 case Decl::CXXMethod:
1639 if (Method->isCopyAssignmentOperator() ||
1640 Method->isMoveAssignmentOperator())
1641 checkAttrDeleted(Method);
1642 break;
1643 default:
1644 break;
1645 }
1646
Adrian Prantla9cfde12019-10-16 16:30:38 +00001647 if (Method->isNoReturn())
1648 Flags |= llvm::DINode::FlagNoReturn;
Adrian Prantlf919be32019-10-29 09:20:14 -07001649
Adrian McCarthyd91bf392017-09-13 20:53:55 +00001650 if (Method->isStatic())
1651 Flags |= llvm::DINode::FlagStaticMember;
Guy Benyei11169dd2012-12-18 14:30:41 +00001652 if (Method->isImplicit())
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001653 Flags |= llvm::DINode::FlagArtificial;
Adrian Prantl21361fb2014-08-29 22:44:27 +00001654 Flags |= getAccessFlag(Method->getAccess(), Method->getParent());
David Majnemer58ed0f32016-07-17 00:39:12 +00001655 if (const auto *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001656 if (CXXC->isExplicit())
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001657 Flags |= llvm::DINode::FlagExplicit;
David Majnemer58ed0f32016-07-17 00:39:12 +00001658 } else if (const auto *CXXC = dyn_cast<CXXConversionDecl>(Method)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001659 if (CXXC->isExplicit())
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001660 Flags |= llvm::DINode::FlagExplicit;
Guy Benyei11169dd2012-12-18 14:30:41 +00001661 }
1662 if (Method->hasPrototype())
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001663 Flags |= llvm::DINode::FlagPrototyped;
Adrian Prantl0630eb72013-12-18 21:48:18 +00001664 if (Method->getRefQualifier() == RQ_LValue)
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001665 Flags |= llvm::DINode::FlagLValueReference;
Adrian Prantl0630eb72013-12-18 21:48:18 +00001666 if (Method->getRefQualifier() == RQ_RValue)
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001667 Flags |= llvm::DINode::FlagRValueReference;
Paul Robinsoncda54212018-11-19 18:29:28 +00001668 if (CGM.getLangOpts().Optimize)
1669 SPFlags |= llvm::DISubprogram::SPFlagOptimized;
Guy Benyei11169dd2012-12-18 14:30:41 +00001670
Amy Huang651128f2020-01-03 16:28:48 -08001671 // In this debug mode, emit type info for a class when its constructor type
1672 // info is emitted.
1673 if (DebugKind == codegenoptions::DebugInfoConstructor)
1674 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
1675 completeClass(CD->getParent());
1676
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001677 llvm::DINodeArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1678 llvm::DISubprogram *SP = DBuilder.createMethod(
Eric Christophere7b87e52014-10-26 23:40:33 +00001679 RecordTy, MethodName, MethodLinkageName, MethodDefUnit, MethodLine,
Paul Robinsoncda54212018-11-19 18:29:28 +00001680 MethodTy, VIndex, ThisAdjustment, ContainingType, Flags, SPFlags,
Reid Kleckner0358cbf2016-07-01 02:41:25 +00001681 TParamsArray.get());
Eric Christopherb2a008c2013-05-16 00:45:12 +00001682
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001683 SPCache[Method->getCanonicalDecl()].reset(SP);
Guy Benyei11169dd2012-12-18 14:30:41 +00001684
1685 return SP;
1686}
1687
Eric Christophere7b87e52014-10-26 23:40:33 +00001688void CGDebugInfo::CollectCXXMemberFunctions(
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001689 const CXXRecordDecl *RD, llvm::DIFile *Unit,
1690 SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001691
1692 // Since we want more than just the individual member decls if we
1693 // have templated functions iterate over every declaration to gather
1694 // the functions.
Eric Christophere7b87e52014-10-26 23:40:33 +00001695 for (const auto *I : RD->decls()) {
David Blaikiefd580722014-10-06 05:18:55 +00001696 const auto *Method = dyn_cast<CXXMethodDecl>(I);
1697 // If the member is implicit, don't add it to the member list. This avoids
1698 // the member being added to type units by LLVM, while still allowing it
1699 // to be emitted into the type declaration/reference inside the compile
1700 // unit.
Paul Robinson6a7511b2015-06-25 17:50:43 +00001701 // Ditto 'nodebug' methods, for consistency with CodeGenFunction.cpp.
David Blaikie6dddfe32014-10-06 05:52:27 +00001702 // FIXME: Handle Using(Shadow?)Decls here to create
1703 // DW_TAG_imported_declarations inside the class for base decls brought into
1704 // derived classes. GDB doesn't seem to notice/leverage these when I tried
1705 // it, so I'm not rushing to fix this. (GCC seems to produce them, if
1706 // referenced)
Paul Robinson6a7511b2015-06-25 17:50:43 +00001707 if (!Method || Method->isImplicit() || Method->hasAttr<NoDebugAttr>())
David Blaikiefd580722014-10-06 05:18:55 +00001708 continue;
David Blaikie42edade2014-11-11 20:44:45 +00001709
Simon Pilgrim7e38f0c2019-10-07 16:42:25 +00001710 if (Method->getType()->castAs<FunctionProtoType>()->getContainedAutoType())
David Blaikie42edade2014-11-11 20:44:45 +00001711 continue;
1712
David Blaikiefd580722014-10-06 05:18:55 +00001713 // Reuse the existing member function declaration if it exists.
1714 // It may be associated with the declaration of the type & should be
1715 // reused as we're building the definition.
1716 //
1717 // This situation can arise in the vtable-based debug info reduction where
1718 // implicit members are emitted in a non-vtable TU.
1719 auto MI = SPCache.find(Method->getCanonicalDecl());
1720 EltTys.push_back(MI == SPCache.end()
1721 ? CreateCXXMemberFunction(Method, Unit, RecordTy)
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001722 : static_cast<llvm::Metadata *>(MI->second));
Guy Benyei11169dd2012-12-18 14:30:41 +00001723 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00001724}
Guy Benyei11169dd2012-12-18 14:30:41 +00001725
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001726void CGDebugInfo::CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile *Unit,
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001727 SmallVectorImpl<llvm::Metadata *> &EltTys,
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001728 llvm::DIType *RecordTy) {
Bob Haarmandff36732016-10-25 22:19:32 +00001729 llvm::DenseSet<CanonicalDeclPtr<const CXXRecordDecl>> SeenTypes;
1730 CollectCXXBasesAux(RD, Unit, EltTys, RecordTy, RD->bases(), SeenTypes,
1731 llvm::DINode::FlagZero);
Eric Christopherb2a008c2013-05-16 00:45:12 +00001732
Bob Haarmandff36732016-10-25 22:19:32 +00001733 // If we are generating CodeView debug info, we also need to emit records for
1734 // indirect virtual base classes.
1735 if (CGM.getCodeGenOpts().EmitCodeView) {
1736 CollectCXXBasesAux(RD, Unit, EltTys, RecordTy, RD->vbases(), SeenTypes,
1737 llvm::DINode::FlagIndirectVirtualBase);
1738 }
1739}
1740
1741void CGDebugInfo::CollectCXXBasesAux(
1742 const CXXRecordDecl *RD, llvm::DIFile *Unit,
1743 SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy,
1744 const CXXRecordDecl::base_class_const_range &Bases,
1745 llvm::DenseSet<CanonicalDeclPtr<const CXXRecordDecl>> &SeenTypes,
1746 llvm::DINode::DIFlags StartingFlags) {
1747 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1748 for (const auto &BI : Bases) {
David Majnemer58ed0f32016-07-17 00:39:12 +00001749 const auto *Base =
Simon Pilgrim1cd399c2019-10-03 11:22:48 +00001750 cast<CXXRecordDecl>(BI.getType()->castAs<RecordType>()->getDecl());
Bob Haarmandff36732016-10-25 22:19:32 +00001751 if (!SeenTypes.insert(Base).second)
1752 continue;
1753 auto *BaseTy = getOrCreateType(BI.getType(), Unit);
1754 llvm::DINode::DIFlags BFlags = StartingFlags;
1755 uint64_t BaseOffset;
Brock Wyma3db2b102018-05-14 21:21:22 +00001756 uint32_t VBPtrOffset = 0;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001757
Aaron Ballman574705e2014-03-13 15:41:46 +00001758 if (BI.isVirtual()) {
Reid Klecknerd3b23d62014-08-07 21:29:25 +00001759 if (CGM.getTarget().getCXXABI().isItaniumFamily()) {
1760 // virtual base offset offset is -ve. The code generator emits dwarf
1761 // expression where it expects +ve number.
Eric Christophere7b87e52014-10-26 23:40:33 +00001762 BaseOffset = 0 - CGM.getItaniumVTableContext()
1763 .getVirtualBaseOffsetOffset(RD, Base)
1764 .getQuantity();
Reid Klecknerd3b23d62014-08-07 21:29:25 +00001765 } else {
1766 // In the MS ABI, store the vbtable offset, which is analogous to the
1767 // vbase offset offset in Itanium.
1768 BaseOffset =
1769 4 * CGM.getMicrosoftVTableContext().getVBTableIndex(RD, Base);
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00001770 VBPtrOffset = CGM.getContext()
1771 .getASTRecordLayout(RD)
1772 .getVBPtrOffset()
1773 .getQuantity();
Reid Klecknerd3b23d62014-08-07 21:29:25 +00001774 }
Bob Haarmandff36732016-10-25 22:19:32 +00001775 BFlags |= llvm::DINode::FlagVirtual;
Guy Benyei11169dd2012-12-18 14:30:41 +00001776 } else
1777 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1778 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1779 // BI->isVirtual() and bits when not.
Eric Christopherb2a008c2013-05-16 00:45:12 +00001780
Adrian Prantl21361fb2014-08-29 22:44:27 +00001781 BFlags |= getAccessFlag(BI.getAccessSpecifier(), RD);
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00001782 llvm::DIType *DTy = DBuilder.createInheritance(RecordTy, BaseTy, BaseOffset,
1783 VBPtrOffset, BFlags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001784 EltTys.push_back(DTy);
1785 }
1786}
1787
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001788llvm::DINodeArray
Eric Christophere7b87e52014-10-26 23:40:33 +00001789CGDebugInfo::CollectTemplateParams(const TemplateParameterList *TPList,
1790 ArrayRef<TemplateArgument> TAList,
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001791 llvm::DIFile *Unit) {
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001792 SmallVector<llvm::Metadata *, 16> TemplateParams;
Guy Benyei11169dd2012-12-18 14:30:41 +00001793 for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1794 const TemplateArgument &TA = TAList[i];
David Blaikie47c11502013-06-22 18:59:18 +00001795 StringRef Name;
Awanish Pandey7a42bab2020-03-02 10:52:12 +05301796 bool defaultParameter = false;
David Blaikie47c11502013-06-22 18:59:18 +00001797 if (TPList)
1798 Name = TPList->getParam(i)->getName();
David Blaikie38079fd2013-05-10 21:53:14 +00001799 switch (TA.getKind()) {
1800 case TemplateArgument::Type: {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001801 llvm::DIType *TTy = getOrCreateType(TA.getAsType(), Unit);
Awanish Pandey7a42bab2020-03-02 10:52:12 +05301802
1803 if (TPList)
1804 if (auto *templateType =
1805 dyn_cast_or_null<TemplateTypeParmDecl>(TPList->getParam(i)))
1806 if (templateType->hasDefaultArgument())
1807 defaultParameter =
1808 templateType->getDefaultArgument() == TA.getAsType();
1809
1810 TemplateParams.push_back(DBuilder.createTemplateTypeParameter(
1811 TheCU, Name, TTy, defaultParameter));
1812
David Blaikie38079fd2013-05-10 21:53:14 +00001813 } break;
1814 case TemplateArgument::Integral: {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001815 llvm::DIType *TTy = getOrCreateType(TA.getIntegralType(), Unit);
Awanish Pandey7a42bab2020-03-02 10:52:12 +05301816 if (TPList && CGM.getCodeGenOpts().DwarfVersion >= 5)
1817 if (auto *templateType =
1818 dyn_cast_or_null<NonTypeTemplateParmDecl>(TPList->getParam(i)))
1819 if (templateType->hasDefaultArgument())
1820 defaultParameter =
1821 templateType->getDefaultArgument()->EvaluateKnownConstInt(
1822 CGM.getContext()) == TA.getAsIntegral();
1823
Duncan P. N. Exon Smithdadc2b62015-04-21 18:43:54 +00001824 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
Awanish Pandey7a42bab2020-03-02 10:52:12 +05301825 TheCU, Name, TTy, defaultParameter,
Duncan P. N. Exon Smithdadc2b62015-04-21 18:43:54 +00001826 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral())));
David Blaikie38079fd2013-05-10 21:53:14 +00001827 } break;
1828 case TemplateArgument::Declaration: {
1829 const ValueDecl *D = TA.getAsDecl();
David Blaikieb5c7e6a2014-10-18 02:21:26 +00001830 QualType T = TA.getParamTypeForDecl().getDesugaredType(CGM.getContext());
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001831 llvm::DIType *TTy = getOrCreateType(T, Unit);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001832 llvm::Constant *V = nullptr;
Michael Liao982cbb62019-03-06 21:16:27 +00001833 // Skip retrieve the value if that template parameter has cuda device
1834 // attribute, i.e. that value is not available at the host side.
1835 if (!CGM.getLangOpts().CUDA || CGM.getLangOpts().CUDAIsDevice ||
1836 !D->hasAttr<CUDADeviceAttr>()) {
1837 const CXXMethodDecl *MD;
1838 // Variable pointer template parameters have a value that is the address
1839 // of the variable.
1840 if (const auto *VD = dyn_cast<VarDecl>(D))
1841 V = CGM.GetAddrOfGlobalVar(VD);
1842 // Member function pointers have special support for building them,
1843 // though this is currently unsupported in LLVM CodeGen.
1844 else if ((MD = dyn_cast<CXXMethodDecl>(D)) && MD->isInstance())
1845 V = CGM.getCXXABI().EmitMemberFunctionPointer(MD);
1846 else if (const auto *FD = dyn_cast<FunctionDecl>(D))
1847 V = CGM.GetAddrOfFunction(FD);
1848 // Member data pointers have special handling too to compute the fixed
1849 // offset within the object.
1850 else if (const auto *MPT =
1851 dyn_cast<MemberPointerType>(T.getTypePtr())) {
1852 // These five lines (& possibly the above member function pointer
1853 // handling) might be able to be refactored to use similar code in
1854 // CodeGenModule::getMemberPointerConstant
1855 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
1856 CharUnits chars =
1857 CGM.getContext().toCharUnitsFromBits((int64_t)fieldOffset);
1858 V = CGM.getCXXABI().EmitMemberDataPointer(MPT, chars);
1859 }
Simon Pilgrimcfee2ef2019-10-16 10:38:49 +00001860 assert(V && "Failed to find template parameter pointer");
Michael Liao982cbb62019-03-06 21:16:27 +00001861 V = V->stripPointerCasts();
David Blaikie38079fd2013-05-10 21:53:14 +00001862 }
Duncan P. N. Exon Smithdadc2b62015-04-21 18:43:54 +00001863 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
Awanish Pandey7a42bab2020-03-02 10:52:12 +05301864 TheCU, Name, TTy, defaultParameter, cast_or_null<llvm::Constant>(V)));
David Blaikie38079fd2013-05-10 21:53:14 +00001865 } break;
1866 case TemplateArgument::NullPtr: {
1867 QualType T = TA.getNullPtrType();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001868 llvm::DIType *TTy = getOrCreateType(T, Unit);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001869 llvm::Constant *V = nullptr;
David Blaikie38079fd2013-05-10 21:53:14 +00001870 // Special case member data pointer null values since they're actually -1
1871 // instead of zero.
David Majnemer58ed0f32016-07-17 00:39:12 +00001872 if (const auto *MPT = dyn_cast<MemberPointerType>(T.getTypePtr()))
David Blaikie38079fd2013-05-10 21:53:14 +00001873 // But treat member function pointers as simple zero integers because
1874 // it's easier than having a special case in LLVM's CodeGen. If LLVM
1875 // CodeGen grows handling for values of non-null member function
1876 // pointers then perhaps we could remove this special case and rely on
1877 // EmitNullMemberPointer for member function pointers.
1878 if (MPT->isMemberDataPointer())
1879 V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
1880 if (!V)
1881 V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
Awanish Pandey7a42bab2020-03-02 10:52:12 +05301882 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
1883 TheCU, Name, TTy, defaultParameter, V));
David Blaikie38079fd2013-05-10 21:53:14 +00001884 } break;
Duncan P. N. Exon Smithdadc2b62015-04-21 18:43:54 +00001885 case TemplateArgument::Template:
1886 TemplateParams.push_back(DBuilder.createTemplateTemplateParameter(
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00001887 TheCU, Name, nullptr,
Duncan P. N. Exon Smithdadc2b62015-04-21 18:43:54 +00001888 TA.getAsTemplate().getAsTemplateDecl()->getQualifiedNameAsString()));
1889 break;
1890 case TemplateArgument::Pack:
1891 TemplateParams.push_back(DBuilder.createTemplateParameterPack(
1892 TheCU, Name, nullptr,
1893 CollectTemplateParams(nullptr, TA.getPackAsArray(), Unit)));
1894 break;
David Majnemer5559d472013-08-24 08:21:10 +00001895 case TemplateArgument::Expression: {
1896 const Expr *E = TA.getAsExpr();
1897 QualType T = E->getType();
David Majnemer922ad9f2014-10-24 19:49:04 +00001898 if (E->isGLValue())
1899 T = CGM.getContext().getLValueReferenceType(T);
John McCallde0fe072017-08-15 21:42:52 +00001900 llvm::Constant *V = ConstantEmitter(CGM).emitAbstract(E, T);
David Majnemer5559d472013-08-24 08:21:10 +00001901 assert(V && "Expression in template argument isn't constant");
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001902 llvm::DIType *TTy = getOrCreateType(T, Unit);
Duncan P. N. Exon Smithdadc2b62015-04-21 18:43:54 +00001903 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
Awanish Pandey7a42bab2020-03-02 10:52:12 +05301904 TheCU, Name, TTy, defaultParameter, V->stripPointerCasts()));
David Majnemer5559d472013-08-24 08:21:10 +00001905 } break;
David Blaikie2b93c542013-05-10 23:36:06 +00001906 // And the following should never occur:
David Blaikie38079fd2013-05-10 21:53:14 +00001907 case TemplateArgument::TemplateExpansion:
David Blaikie38079fd2013-05-10 21:53:14 +00001908 case TemplateArgument::Null:
1909 llvm_unreachable(
1910 "These argument types shouldn't exist in concrete types");
Guy Benyei11169dd2012-12-18 14:30:41 +00001911 }
1912 }
1913 return DBuilder.getOrCreateArray(TemplateParams);
1914}
1915
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001916llvm::DINodeArray
Duncan P. N. Exon Smith8e47da42015-04-21 20:07:29 +00001917CGDebugInfo::CollectFunctionTemplateParams(const FunctionDecl *FD,
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001918 llvm::DIFile *Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001919 if (FD->getTemplatedKind() ==
1920 FunctionDecl::TK_FunctionTemplateSpecialization) {
Eric Christophere7b87e52014-10-26 23:40:33 +00001921 const TemplateParameterList *TList = FD->getTemplateSpecializationInfo()
1922 ->getTemplate()
1923 ->getTemplateParameters();
David Blaikie47c11502013-06-22 18:59:18 +00001924 return CollectTemplateParams(
1925 TList, FD->getTemplateSpecializationArgs()->asArray(), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00001926 }
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001927 return llvm::DINodeArray();
Guy Benyei11169dd2012-12-18 14:30:41 +00001928}
1929
Matthew Voss20165362018-10-03 18:45:04 +00001930llvm::DINodeArray CGDebugInfo::CollectVarTemplateParams(const VarDecl *VL,
Reid Kleckner2dbd5d82019-05-02 17:45:54 +00001931 llvm::DIFile *Unit) {
1932 // Always get the full list of parameters, not just the ones from the
1933 // specialization. A partial specialization may have fewer parameters than
1934 // there are arguments.
1935 auto *TS = dyn_cast<VarTemplateSpecializationDecl>(VL);
1936 if (!TS)
1937 return llvm::DINodeArray();
1938 VarTemplateDecl *T = TS->getSpecializedTemplate();
1939 const TemplateParameterList *TList = T->getTemplateParameters();
1940 auto TA = TS->getTemplateArgs().asArray();
1941 return CollectTemplateParams(TList, TA, Unit);
Matthew Voss20165362018-10-03 18:45:04 +00001942}
1943
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001944llvm::DINodeArray CGDebugInfo::CollectCXXTemplateParams(
1945 const ClassTemplateSpecializationDecl *TSpecial, llvm::DIFile *Unit) {
Reid Kleckner2dbd5d82019-05-02 17:45:54 +00001946 // Always get the full list of parameters, not just the ones from the
1947 // specialization. A partial specialization may have fewer parameters than
1948 // there are arguments.
Adrian Prantl649f0302014-04-17 01:04:01 +00001949 TemplateParameterList *TPList =
Eric Christophere7b87e52014-10-26 23:40:33 +00001950 TSpecial->getSpecializedTemplate()->getTemplateParameters();
Adrian Prantl2c92e9c2014-04-17 00:30:48 +00001951 const TemplateArgumentList &TAList = TSpecial->getTemplateArgs();
David Blaikie47c11502013-06-22 18:59:18 +00001952 return CollectTemplateParams(TPList, TAList.asArray(), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00001953}
1954
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001955llvm::DIType *CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile *Unit) {
Duncan P. N. Exon Smithb7470232015-04-15 23:48:50 +00001956 if (VTablePtrType)
Guy Benyei11169dd2012-12-18 14:30:41 +00001957 return VTablePtrType;
1958
1959 ASTContext &Context = CGM.getContext();
1960
1961 /* Function type */
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001962 llvm::Metadata *STy = getOrCreateType(Context.IntTy, Unit);
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001963 llvm::DITypeRefArray SElements = DBuilder.getOrCreateTypeArray(STy);
Eric Christopher28a6db52015-10-15 06:56:08 +00001964 llvm::DIType *SubTy = DBuilder.createSubroutineType(SElements);
Guy Benyei11169dd2012-12-18 14:30:41 +00001965 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
Konstantin Zhuravlyovd1ba16e2017-03-08 23:56:48 +00001966 unsigned VtblPtrAddressSpace = CGM.getTarget().getVtblPtrAddressSpace();
1967 Optional<unsigned> DWARFAddressSpace =
1968 CGM.getTarget().getDWARFAddressSpace(VtblPtrAddressSpace);
1969
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00001970 llvm::DIType *vtbl_ptr_type = DBuilder.createPointerType(
1971 SubTy, Size, 0, DWARFAddressSpace, "__vtbl_ptr_type");
Guy Benyei11169dd2012-12-18 14:30:41 +00001972 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1973 return VTablePtrType;
1974}
1975
Guy Benyei11169dd2012-12-18 14:30:41 +00001976StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +00001977 // Copy the gdb compatible name on the side and use its reference.
1978 return internString("_vptr$", RD->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00001979}
1980
Reid Kleckner105c5652019-04-24 22:45:44 +00001981StringRef CGDebugInfo::getDynamicInitializerName(const VarDecl *VD,
1982 DynamicInitKind StubKind,
1983 llvm::Function *InitFn) {
1984 // If we're not emitting codeview, use the mangled name. For Itanium, this is
1985 // arbitrary.
Alexandre Ganeacaf31662019-11-15 16:21:17 -05001986 if (!CGM.getCodeGenOpts().EmitCodeView)
Reid Kleckner105c5652019-04-24 22:45:44 +00001987 return InitFn->getName();
1988
1989 // Print the normal qualified name for the variable, then break off the last
1990 // NNS, and add the appropriate other text. Clang always prints the global
1991 // variable name without template arguments, so we can use rsplit("::") and
1992 // then recombine the pieces.
1993 SmallString<128> QualifiedGV;
1994 StringRef Quals;
1995 StringRef GVName;
1996 {
1997 llvm::raw_svector_ostream OS(QualifiedGV);
1998 VD->printQualifiedName(OS, getPrintingPolicy());
1999 std::tie(Quals, GVName) = OS.str().rsplit("::");
2000 if (GVName.empty())
2001 std::swap(Quals, GVName);
2002 }
2003
2004 SmallString<128> InitName;
2005 llvm::raw_svector_ostream OS(InitName);
2006 if (!Quals.empty())
2007 OS << Quals << "::";
2008
2009 switch (StubKind) {
2010 case DynamicInitKind::NoStub:
2011 llvm_unreachable("not an initializer");
2012 case DynamicInitKind::Initializer:
2013 OS << "`dynamic initializer for '";
2014 break;
2015 case DynamicInitKind::AtExit:
2016 OS << "`dynamic atexit destructor for '";
2017 break;
2018 }
2019
2020 OS << GVName;
2021
2022 // Add any template specialization args.
2023 if (const auto *VTpl = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
2024 printTemplateArgumentList(OS, VTpl->getTemplateArgs().asArray(),
2025 getPrintingPolicy());
2026 }
2027
2028 OS << '\'';
2029
2030 return internString(OS.str());
2031}
2032
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002033void CGDebugInfo::CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile *Unit,
Reid Klecknerdc124992016-08-31 16:11:43 +00002034 SmallVectorImpl<llvm::Metadata *> &EltTys,
2035 llvm::DICompositeType *RecordTy) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002036 // If this class is not dynamic then there is not any vtable info to collect.
2037 if (!RD->isDynamicClass())
2038 return;
2039
Reid Kleckner59812422016-08-31 20:35:01 +00002040 // Don't emit any vtable shape or vptr info if this class doesn't have an
2041 // extendable vfptr. This can happen if the class doesn't have virtual
2042 // methods, or in the MS ABI if those virtual methods only come from virtually
2043 // inherited bases.
2044 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2045 if (!RL.hasExtendableVFPtr())
2046 return;
2047
Reid Klecknerdc124992016-08-31 16:11:43 +00002048 // CodeView needs to know how large the vtable of every dynamic class is, so
2049 // emit a special named pointer type into the element list. The vptr type
2050 // points to this type as well.
2051 llvm::DIType *VPtrTy = nullptr;
2052 bool NeedVTableShape = CGM.getCodeGenOpts().EmitCodeView &&
2053 CGM.getTarget().getCXXABI().isMicrosoft();
2054 if (NeedVTableShape) {
2055 uint64_t PtrWidth =
2056 CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
2057 const VTableLayout &VFTLayout =
2058 CGM.getMicrosoftVTableContext().getVFTableLayout(RD, CharUnits::Zero());
2059 unsigned VSlotCount =
Peter Collingbournee53683f2016-09-08 01:14:39 +00002060 VFTLayout.vtable_components().size() - CGM.getLangOpts().RTTIData;
Reid Klecknerdc124992016-08-31 16:11:43 +00002061 unsigned VTableWidth = PtrWidth * VSlotCount;
Konstantin Zhuravlyovd1ba16e2017-03-08 23:56:48 +00002062 unsigned VtblPtrAddressSpace = CGM.getTarget().getVtblPtrAddressSpace();
2063 Optional<unsigned> DWARFAddressSpace =
2064 CGM.getTarget().getDWARFAddressSpace(VtblPtrAddressSpace);
Reid Klecknerdc124992016-08-31 16:11:43 +00002065
2066 // Create a very wide void* type and insert it directly in the element list.
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00002067 llvm::DIType *VTableType = DBuilder.createPointerType(
2068 nullptr, VTableWidth, 0, DWARFAddressSpace, "__vtbl_ptr_type");
Reid Klecknerdc124992016-08-31 16:11:43 +00002069 EltTys.push_back(VTableType);
2070
2071 // The vptr is a pointer to this special vtable type.
2072 VPtrTy = DBuilder.createPointerType(VTableType, PtrWidth);
2073 }
2074
2075 // If there is a primary base then the artificial vptr member lives there.
Reid Klecknerdc124992016-08-31 16:11:43 +00002076 if (RL.getPrimaryBase())
2077 return;
2078
2079 if (!VPtrTy)
2080 VPtrTy = getOrCreateVTablePtrType(Unit);
2081
Guy Benyei11169dd2012-12-18 14:30:41 +00002082 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00002083 llvm::DIType *VPtrMember =
2084 DBuilder.createMemberType(Unit, getVTableName(RD), Unit, 0, Size, 0, 0,
2085 llvm::DINode::FlagArtificial, VPtrTy);
Reid Klecknerdc124992016-08-31 16:11:43 +00002086 EltTys.push_back(VPtrMember);
Guy Benyei11169dd2012-12-18 14:30:41 +00002087}
2088
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002089llvm::DIType *CGDebugInfo::getOrCreateRecordType(QualType RTy,
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00002090 SourceLocation Loc) {
Amy Huang53539bb2020-01-13 15:54:54 -08002091 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002092 llvm::DIType *T = getOrCreateType(RTy, getOrCreateFile(Loc));
Guy Benyei11169dd2012-12-18 14:30:41 +00002093 return T;
2094}
2095
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002096llvm::DIType *CGDebugInfo::getOrCreateInterfaceType(QualType D,
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00002097 SourceLocation Loc) {
Adrian Prantlad9a195e2015-08-27 21:21:19 +00002098 return getOrCreateStandaloneType(D, Loc);
2099}
2100
2101llvm::DIType *CGDebugInfo::getOrCreateStandaloneType(QualType D,
2102 SourceLocation Loc) {
Amy Huang53539bb2020-01-13 15:54:54 -08002103 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
Adrian Prantlad9a195e2015-08-27 21:21:19 +00002104 assert(!D.isNull() && "null type");
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002105 llvm::DIType *T = getOrCreateType(D, getOrCreateFile(Loc));
Adrian Prantlad9a195e2015-08-27 21:21:19 +00002106 assert(T && "could not create debug info for type");
Adrian Prantl3a884fa2015-08-27 22:56:46 +00002107
Adrian Prantl73409ce2013-03-11 18:33:46 +00002108 RetainedTypes.push_back(D.getAsOpaquePtr());
Guy Benyei11169dd2012-12-18 14:30:41 +00002109 return T;
2110}
2111
Amy Huang0d0334f2019-04-12 20:25:30 +00002112void CGDebugInfo::addHeapAllocSiteMetadata(llvm::Instruction *CI,
2113 QualType D,
2114 SourceLocation Loc) {
2115 llvm::MDNode *node;
2116 if (D.getTypePtr()->isVoidPointerType()) {
2117 node = llvm::MDNode::get(CGM.getLLVMContext(), None);
2118 } else {
2119 QualType PointeeTy = D.getTypePtr()->getPointeeType();
2120 node = getOrCreateType(PointeeTy, getOrCreateFile(Loc));
2121 }
Amy Huangfc79ab92019-04-23 21:12:58 +00002122
Amy Huang0d0334f2019-04-12 20:25:30 +00002123 CI->setMetadata("heapallocsite", node);
2124}
2125
David Blaikie483a9da2014-05-06 18:35:21 +00002126void CGDebugInfo::completeType(const EnumDecl *ED) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00002127 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
David Blaikie483a9da2014-05-06 18:35:21 +00002128 return;
2129 QualType Ty = CGM.getContext().getEnumType(ED);
Eric Christophere7b87e52014-10-26 23:40:33 +00002130 void *TyPtr = Ty.getAsOpaquePtr();
David Blaikie483a9da2014-05-06 18:35:21 +00002131 auto I = TypeCache.find(TyPtr);
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002132 if (I == TypeCache.end() || !cast<llvm::DIType>(I->second)->isForwardDecl())
David Blaikie483a9da2014-05-06 18:35:21 +00002133 return;
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002134 llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<EnumType>());
Duncan P. N. Exon Smith4caa7f22015-04-16 01:00:56 +00002135 assert(!Res->isForwardDecl());
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002136 TypeCache[TyPtr].reset(Res);
David Blaikie483a9da2014-05-06 18:35:21 +00002137}
2138
David Blaikieb2e86eb2013-08-15 20:49:17 +00002139void CGDebugInfo::completeType(const RecordDecl *RD) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00002140 if (DebugKind > codegenoptions::LimitedDebugInfo ||
David Blaikieb2e86eb2013-08-15 20:49:17 +00002141 !CGM.getLangOpts().CPlusPlus)
2142 completeRequiredType(RD);
2143}
2144
David Blaikieb11c8732017-01-30 06:36:08 +00002145/// Return true if the class or any of its methods are marked dllimport.
2146static bool isClassOrMethodDLLImport(const CXXRecordDecl *RD) {
2147 if (RD->hasAttr<DLLImportAttr>())
2148 return true;
2149 for (const CXXMethodDecl *MD : RD->methods())
2150 if (MD->hasAttr<DLLImportAttr>())
2151 return true;
2152 return false;
2153}
2154
Adrian Prantla43acdc2017-07-24 23:48:51 +00002155/// Does a type definition exist in an imported clang module?
2156static bool isDefinedInClangModule(const RecordDecl *RD) {
2157 // Only definitions that where imported from an AST file come from a module.
2158 if (!RD || !RD->isFromASTFile())
2159 return false;
2160 // Anonymous entities cannot be addressed. Treat them as not from module.
2161 if (!RD->isExternallyVisible() && RD->getName().empty())
2162 return false;
2163 if (auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD)) {
2164 if (!CXXDecl->isCompleteDefinition())
2165 return false;
Adrian Prantlba6fdc52018-10-24 00:06:02 +00002166 // Check wether RD is a template.
Adrian Prantla43acdc2017-07-24 23:48:51 +00002167 auto TemplateKind = CXXDecl->getTemplateSpecializationKind();
2168 if (TemplateKind != TSK_Undeclared) {
Adrian Prantlba6fdc52018-10-24 00:06:02 +00002169 // Unfortunately getOwningModule() isn't accurate enough to find the
2170 // owning module of a ClassTemplateSpecializationDecl that is inside a
2171 // namespace spanning multiple modules.
2172 bool Explicit = false;
2173 if (auto *TD = dyn_cast<ClassTemplateSpecializationDecl>(CXXDecl))
2174 Explicit = TD->isExplicitInstantiationOrSpecialization();
2175 if (!Explicit && CXXDecl->getEnclosingNamespaceContext())
2176 return false;
Adrian Prantla43acdc2017-07-24 23:48:51 +00002177 // This is a template, check the origin of the first member.
2178 if (CXXDecl->field_begin() == CXXDecl->field_end())
2179 return TemplateKind == TSK_ExplicitInstantiationDeclaration;
2180 if (!CXXDecl->field_begin()->isFromASTFile())
2181 return false;
2182 }
2183 }
2184 return true;
2185}
2186
David Blaikie6943dea2013-08-20 01:28:15 +00002187void CGDebugInfo::completeClassData(const RecordDecl *RD) {
David Blaikieb11c8732017-01-30 06:36:08 +00002188 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
2189 if (CXXRD->isDynamicClass() &&
2190 CGM.getVTableLinkage(CXXRD) ==
2191 llvm::GlobalValue::AvailableExternallyLinkage &&
2192 !isClassOrMethodDLLImport(CXXRD))
2193 return;
Adrian Prantla43acdc2017-07-24 23:48:51 +00002194
2195 if (DebugTypeExtRefs && isDefinedInClangModule(RD->getDefinition()))
2196 return;
2197
David Blaikieb11c8732017-01-30 06:36:08 +00002198 completeClass(RD);
2199}
2200
2201void CGDebugInfo::completeClass(const RecordDecl *RD) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00002202 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
Michael Gottesman349542b2013-08-19 18:46:16 +00002203 return;
David Blaikie6943dea2013-08-20 01:28:15 +00002204 QualType Ty = CGM.getContext().getRecordType(RD);
Eric Christophere7b87e52014-10-26 23:40:33 +00002205 void *TyPtr = Ty.getAsOpaquePtr();
David Blaikieef8a9512014-05-05 23:23:53 +00002206 auto I = TypeCache.find(TyPtr);
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002207 if (I != TypeCache.end() && !cast<llvm::DIType>(I->second)->isForwardDecl())
David Blaikieb2e86eb2013-08-15 20:49:17 +00002208 return;
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002209 llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<RecordType>());
Duncan P. N. Exon Smith4caa7f22015-04-16 01:00:56 +00002210 assert(!Res->isForwardDecl());
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002211 TypeCache[TyPtr].reset(Res);
David Blaikieb2e86eb2013-08-15 20:49:17 +00002212}
2213
David Blaikie0e716b42014-03-03 23:48:23 +00002214static bool hasExplicitMemberDefinition(CXXRecordDecl::method_iterator I,
2215 CXXRecordDecl::method_iterator End) {
David Majnemer58ed0f32016-07-17 00:39:12 +00002216 for (CXXMethodDecl *MD : llvm::make_range(I, End))
2217 if (FunctionDecl *Tmpl = MD->getInstantiatedFromMemberFunction())
David Blaikief7f21852014-03-04 03:08:14 +00002218 if (!Tmpl->isImplicit() && Tmpl->isThisDeclarationADefinition() &&
David Majnemer58ed0f32016-07-17 00:39:12 +00002219 !MD->getMemberSpecializationInfo()->isExplicitSpecialization())
David Blaikie0e716b42014-03-03 23:48:23 +00002220 return true;
2221 return false;
2222}
2223
Benjamin Kramer8c305922016-02-02 11:06:51 +00002224static bool shouldOmitDefinition(codegenoptions::DebugInfoKind DebugKind,
2225 bool DebugTypeExtRefs, const RecordDecl *RD,
David Blaikie0e716b42014-03-03 23:48:23 +00002226 const LangOptions &LangOpts) {
Adrian Prantl88d79172016-04-26 21:58:18 +00002227 if (DebugTypeExtRefs && isDefinedInClangModule(RD->getDefinition()))
Adrian Prantl43e00812016-01-19 23:42:53 +00002228 return true;
Adrian Prantl5c8bd882015-09-11 17:23:08 +00002229
David Blaikie1ac9c982017-04-11 21:13:37 +00002230 if (auto *ES = RD->getASTContext().getExternalSource())
2231 if (ES->hasExternalDefinitions(RD) == ExternalASTSource::EK_Always)
2232 return true;
2233
Benjamin Kramer8c305922016-02-02 11:06:51 +00002234 if (DebugKind > codegenoptions::LimitedDebugInfo)
David Blaikie0e716b42014-03-03 23:48:23 +00002235 return false;
2236
2237 if (!LangOpts.CPlusPlus)
2238 return false;
2239
2240 if (!RD->isCompleteDefinitionRequired())
2241 return true;
2242
David Majnemer58ed0f32016-07-17 00:39:12 +00002243 const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
David Blaikie0e716b42014-03-03 23:48:23 +00002244
2245 if (!CXXDecl)
2246 return false;
2247
Adrian McCarthy99242982016-08-16 22:11:18 +00002248 // Only emit complete debug info for a dynamic class when its vtable is
2249 // emitted. However, Microsoft debuggers don't resolve type information
Reid Klecknerc9404e12016-09-09 16:27:04 +00002250 // across DLL boundaries, so skip this optimization if the class or any of its
2251 // methods are marked dllimport. This isn't a complete solution, since objects
2252 // without any dllimport methods can be used in one DLL and constructed in
2253 // another, but it is the current behavior of LimitedDebugInfo.
Adrian McCarthy99242982016-08-16 22:11:18 +00002254 if (CXXDecl->hasDefinition() && CXXDecl->isDynamicClass() &&
Reid Klecknerc9404e12016-09-09 16:27:04 +00002255 !isClassOrMethodDLLImport(CXXDecl))
David Blaikie0e716b42014-03-03 23:48:23 +00002256 return true;
2257
Amy Huang651128f2020-01-03 16:28:48 -08002258 // In constructor debug mode, only emit debug info for a class when its
2259 // constructor is emitted. Skip this optimization if the class or any of
2260 // its methods are marked dllimport.
2261 if (DebugKind == codegenoptions::DebugInfoConstructor &&
2262 !CXXDecl->isLambda() && !isClassOrMethodDLLImport(CXXDecl)) {
2263 for (const auto *Ctor : CXXDecl->ctors()) {
2264 if (Ctor->isUserProvided())
2265 return true;
2266 }
2267 }
2268
David Blaikie0e716b42014-03-03 23:48:23 +00002269 TemplateSpecializationKind Spec = TSK_Undeclared;
David Majnemer58ed0f32016-07-17 00:39:12 +00002270 if (const auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD))
David Blaikie0e716b42014-03-03 23:48:23 +00002271 Spec = SD->getSpecializationKind();
2272
2273 if (Spec == TSK_ExplicitInstantiationDeclaration &&
2274 hasExplicitMemberDefinition(CXXDecl->method_begin(),
2275 CXXDecl->method_end()))
2276 return true;
2277
2278 return false;
2279}
2280
Reid Kleckner6c7b1c62016-09-13 00:01:23 +00002281void CGDebugInfo::completeRequiredType(const RecordDecl *RD) {
2282 if (shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD, CGM.getLangOpts()))
2283 return;
2284
2285 QualType Ty = CGM.getContext().getRecordType(RD);
2286 llvm::DIType *T = getTypeOrNull(Ty);
2287 if (T && T->isForwardDecl())
2288 completeClassData(RD);
2289}
2290
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002291llvm::DIType *CGDebugInfo::CreateType(const RecordType *Ty) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002292 RecordDecl *RD = Ty->getDecl();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002293 llvm::DIType *T = cast_or_null<llvm::DIType>(getTypeOrNull(QualType(Ty, 0)));
Adrian Prantl5c8bd882015-09-11 17:23:08 +00002294 if (T || shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD,
2295 CGM.getLangOpts())) {
David Blaikie3b1cc9b2013-09-06 06:45:04 +00002296 if (!T)
Adrian Prantl6ec370a2015-09-10 18:39:45 +00002297 T = getOrCreateRecordFwdDecl(Ty, getDeclContextDescriptor(RD));
David Blaikie3b1cc9b2013-09-06 06:45:04 +00002298 return T;
David Blaikiee36464c2013-06-05 05:32:23 +00002299 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002300
David Blaikieb2e86eb2013-08-15 20:49:17 +00002301 return CreateTypeDefinition(Ty);
2302}
2303
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002304llvm::DIType *CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) {
David Blaikieb2e86eb2013-08-15 20:49:17 +00002305 RecordDecl *RD = Ty->getDecl();
2306
Guy Benyei11169dd2012-12-18 14:30:41 +00002307 // Get overall information about the record type for the debug info.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002308 llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00002309
2310 // Records and classes and unions can all be recursive. To handle them, we
2311 // first generate a debug descriptor for the struct as a forward declaration.
2312 // Then (if it is a definition) we go through and get debug info for all of
2313 // its members. Finally, we create a descriptor for the complete type (which
2314 // may refer to the forward decl if the struct is recursive) and replace all
2315 // uses of the forward declaration with the final definition.
Duncan P. N. Exon Smithbd210e62015-07-24 20:34:41 +00002316 llvm::DICompositeType *FwdDecl = getOrCreateLimitedType(Ty, DefUnit);
Guy Benyei11169dd2012-12-18 14:30:41 +00002317
Adrian Prantl5f66bae2015-02-11 17:45:15 +00002318 const RecordDecl *D = RD->getDefinition();
2319 if (!D || !D->isCompleteDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00002320 return FwdDecl;
2321
David Majnemer58ed0f32016-07-17 00:39:12 +00002322 if (const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
David Blaikieadfbf992013-08-18 16:55:33 +00002323 CollectContainingType(CXXDecl, FwdDecl);
2324
Guy Benyei11169dd2012-12-18 14:30:41 +00002325 // Push the struct on region stack.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002326 LexicalBlockStack.emplace_back(&*FwdDecl);
2327 RegionMap[Ty->getDecl()].reset(FwdDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00002328
Guy Benyei11169dd2012-12-18 14:30:41 +00002329 // Convert all the elements.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002330 SmallVector<llvm::Metadata *, 16> EltTys;
David Blaikie6943dea2013-08-20 01:28:15 +00002331 // what about nested types?
Guy Benyei11169dd2012-12-18 14:30:41 +00002332
2333 // Note: The split of CXXDecl information here is intentional, the
2334 // gdb tests will depend on a certain ordering at printout. The debug
2335 // information offsets are still correct if we merge them all together
2336 // though.
David Majnemer58ed0f32016-07-17 00:39:12 +00002337 const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
Guy Benyei11169dd2012-12-18 14:30:41 +00002338 if (CXXDecl) {
2339 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
Reid Klecknerdc124992016-08-31 16:11:43 +00002340 CollectVTableInfo(CXXDecl, DefUnit, EltTys, FwdDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00002341 }
2342
Eric Christopher91a31902013-01-16 01:22:32 +00002343 // Collect data fields (including static variables and any initializers).
Guy Benyei11169dd2012-12-18 14:30:41 +00002344 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
Eric Christopher2df080e2013-10-11 18:16:51 +00002345 if (CXXDecl)
Guy Benyei11169dd2012-12-18 14:30:41 +00002346 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00002347
2348 LexicalBlockStack.pop_back();
2349 RegionMap.erase(Ty->getDecl());
2350
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002351 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
Duncan P. N. Exon Smithc8ee63e2014-12-18 00:48:56 +00002352 DBuilder.replaceArrays(FwdDecl, Elements);
Guy Benyei11169dd2012-12-18 14:30:41 +00002353
Adrian Prantl5f66bae2015-02-11 17:45:15 +00002354 if (FwdDecl->isTemporary())
Duncan P. N. Exon Smith4078ad42015-04-16 16:36:45 +00002355 FwdDecl =
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002356 llvm::MDNode::replaceWithPermanent(llvm::TempDICompositeType(FwdDecl));
Adrian Prantl5f66bae2015-02-11 17:45:15 +00002357
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002358 RegionMap[Ty->getDecl()].reset(FwdDecl);
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00002359 return FwdDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00002360}
2361
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002362llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectType *Ty,
2363 llvm::DIFile *Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002364 // Ignore protocols.
2365 return getOrCreateType(Ty->getBaseType(), Unit);
2366}
2367
Manman Rene6be26c2016-09-13 17:25:08 +00002368llvm::DIType *CGDebugInfo::CreateType(const ObjCTypeParamType *Ty,
2369 llvm::DIFile *Unit) {
2370 // Ignore protocols.
2371 SourceLocation Loc = Ty->getDecl()->getLocation();
2372
2373 // Use Typedefs to represent ObjCTypeParamType.
2374 return DBuilder.createTypedef(
2375 getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit),
2376 Ty->getDecl()->getName(), getOrCreateFile(Loc), getLineNumber(Loc),
Sam McCalld27a16e2019-11-18 15:53:22 +01002377 getDeclContextDescriptor(Ty->getDecl()));
Manman Rene6be26c2016-09-13 17:25:08 +00002378}
2379
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00002380/// \return true if Getter has the default name for the property PD.
2381static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,
2382 const ObjCMethodDecl *Getter) {
2383 assert(PD);
2384 if (!Getter)
2385 return true;
2386
2387 assert(Getter->getDeclName().isObjCZeroArgSelector());
2388 return PD->getName() ==
Eric Christophere7b87e52014-10-26 23:40:33 +00002389 Getter->getDeclName().getObjCSelector().getNameForSlot(0);
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00002390}
2391
2392/// \return true if Setter has the default name for the property PD.
2393static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,
2394 const ObjCMethodDecl *Setter) {
2395 assert(PD);
2396 if (!Setter)
2397 return true;
2398
2399 assert(Setter->getDeclName().isObjCOneArgSelector());
Adrian Prantla4ce9062013-06-07 22:29:12 +00002400 return SelectorTable::constructSetterName(PD->getName()) ==
Eric Christophere7b87e52014-10-26 23:40:33 +00002401 Setter->getDeclName().getObjCSelector().getNameForSlot(0);
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00002402}
2403
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002404llvm::DIType *CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
2405 llvm::DIFile *Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002406 ObjCInterfaceDecl *ID = Ty->getDecl();
2407 if (!ID)
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00002408 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00002409
Adrian Prantl50fd1a82016-04-20 23:59:32 +00002410 // Return a forward declaration if this type was imported from a clang module,
2411 // and this is not the compile unit with the implementation of the type (which
2412 // may contain hidden ivars).
2413 if (DebugTypeExtRefs && ID->isFromASTFile() && ID->getDefinition() &&
2414 !ID->getImplementation())
Adrian Prantl5c8bd882015-09-11 17:23:08 +00002415 return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
2416 ID->getName(),
2417 getDeclContextDescriptor(ID), Unit, 0);
2418
Guy Benyei11169dd2012-12-18 14:30:41 +00002419 // Get overall information about the record type for the debug info.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002420 llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00002421 unsigned Line = getLineNumber(ID->getLocation());
Duncan P. N. Exon Smith798d5652015-04-15 23:19:15 +00002422 auto RuntimeLang =
2423 static_cast<llvm::dwarf::SourceLanguage>(TheCU->getSourceLanguage());
Guy Benyei11169dd2012-12-18 14:30:41 +00002424
2425 // If this is just a forward declaration return a special forward-declaration
2426 // debug type since we won't be able to lay out the entire type.
2427 ObjCInterfaceDecl *Def = ID->getDefinition();
David Blaikieef8a9512014-05-05 23:23:53 +00002428 if (!Def || !Def->getImplementation()) {
Adrian Prantl42ce2d32015-10-01 16:57:02 +00002429 llvm::DIScope *Mod = getParentModuleOrNull(ID);
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002430 llvm::DIType *FwdDecl = DBuilder.createReplaceableCompositeType(
Adrian Prantl42ce2d32015-10-01 16:57:02 +00002431 llvm::dwarf::DW_TAG_structure_type, ID->getName(), Mod ? Mod : TheCU,
2432 DefUnit, Line, RuntimeLang);
David Blaikieef8a9512014-05-05 23:23:53 +00002433 ObjCInterfaceCache.push_back(ObjCInterfaceCacheEntry(Ty, FwdDecl, Unit));
Guy Benyei11169dd2012-12-18 14:30:41 +00002434 return FwdDecl;
2435 }
2436
David Blaikieef8a9512014-05-05 23:23:53 +00002437 return CreateTypeDefinition(Ty, Unit);
2438}
2439
Reid Klecknerc915cb92020-02-27 18:13:54 -08002440llvm::DIModule *CGDebugInfo::getOrCreateModuleRef(ASTSourceDescriptor Mod,
2441 bool CreateSkeletonCU) {
Adrian Prantleb66a262015-09-24 16:10:04 +00002442 // Use the Module pointer as the key into the cache. This is a
2443 // nullptr if the "Module" is a PCH, which is safe because we don't
2444 // support chained PCH debug info, so there can only be a single PCH.
2445 const Module *M = Mod.getModuleOrNull();
Adrian Prantl9e8ea352015-09-29 20:44:46 +00002446 auto ModRef = ModuleCache.find(M);
2447 if (ModRef != ModuleCache.end())
2448 return cast<llvm::DIModule>(ModRef->second);
Adrian Prantl2388ead2015-06-30 18:01:05 +00002449
2450 // Macro definitions that were defined with "-D" on the command line.
2451 SmallString<128> ConfigMacros;
2452 {
2453 llvm::raw_svector_ostream OS(ConfigMacros);
2454 const auto &PPOpts = CGM.getPreprocessorOpts();
2455 unsigned I = 0;
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002456 // Translate the macro definitions back into a command line.
Adrian Prantl2388ead2015-06-30 18:01:05 +00002457 for (auto &M : PPOpts.Macros) {
2458 if (++I > 1)
2459 OS << " ";
2460 const std::string &Macro = M.first;
2461 bool Undef = M.second;
2462 OS << "\"-" << (Undef ? 'U' : 'D');
2463 for (char c : Macro)
2464 switch (c) {
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00002465 case '\\':
2466 OS << "\\\\";
2467 break;
2468 case '"':
2469 OS << "\\\"";
2470 break;
2471 default:
2472 OS << c;
Adrian Prantl2388ead2015-06-30 18:01:05 +00002473 }
2474 OS << '\"';
Adrian Prantlc4bb47e2015-06-30 17:39:51 +00002475 }
Adrian Prantlc4bb47e2015-06-30 17:39:51 +00002476 }
Adrian Prantl66689202015-09-18 23:01:45 +00002477
Adrian Prantl835e6632015-09-24 16:10:10 +00002478 bool IsRootModule = M ? !M->Parent : true;
Adrian Prantl7b6b9a12019-02-08 23:15:42 +00002479 // When a module name is specified as -fmodule-name, that module gets a
2480 // clang::Module object, but it won't actually be built or imported; it will
2481 // be textual.
Adrian Prantle308e422019-02-15 20:24:26 +00002482 if (CreateSkeletonCU && IsRootModule && Mod.getASTFile().empty() && M)
2483 assert(StringRef(M->Name).startswith(CGM.getLangOpts().ModuleName) &&
Adrian Prantl7b6b9a12019-02-08 23:15:42 +00002484 "clang module without ASTFile must be specified by -fmodule-name");
2485
2486 if (CreateSkeletonCU && IsRootModule && !Mod.getASTFile().empty()) {
Adrian Prantlc96da8f2016-01-22 17:43:43 +00002487 // PCH files don't have a signature field in the control block,
2488 // but LLVM detects skeleton CUs by looking for a non-zero DWO id.
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002489 // We use the lower 64 bits for debug info.
2490 uint64_t Signature =
2491 Mod.getSignature()
2492 ? (uint64_t)Mod.getSignature()[1] << 32 | Mod.getSignature()[0]
2493 : ~1ULL;
Adrian Prantl66689202015-09-18 23:01:45 +00002494 llvm::DIBuilder DIB(CGM.getModule());
Adrian Prantl079c6dd2020-03-18 13:14:07 -07002495 SmallString<0> PCM;
Adrian Prantl43580a52020-03-18 13:15:14 -07002496 if (!llvm::sys::path::is_absolute(Mod.getASTFile()))
Adrian Prantl079c6dd2020-03-18 13:14:07 -07002497 PCM = Mod.getPath();
2498 llvm::sys::path::append(PCM, Mod.getASTFile());
Adrian Prantl43580a52020-03-18 13:15:14 -07002499 std::string RemappedPCM = remapDIPath(PCM);
2500 StringRef RelativePCM(RemappedPCM);
2501 StringRef CompDir = TheCU->getDirectory();
2502 if (RelativePCM.consume_front(CompDir))
2503 RelativePCM.consume_front(llvm::sys::path::get_separator());
Amjad Aboudfa9a17e2016-12-14 20:24:40 +00002504 DIB.createCompileUnit(TheCU->getSourceLanguage(),
Scott Lindera2fbcef2018-02-26 17:32:31 +00002505 // TODO: Support "Source" from external AST providers?
Adrian Prantl079c6dd2020-03-18 13:14:07 -07002506 DIB.createFile(Mod.getModuleName(), CompDir),
Adrian Prantl43580a52020-03-18 13:15:14 -07002507 TheCU->getProducer(), false, StringRef(), 0, RelativePCM,
Adrian Prantl079c6dd2020-03-18 13:14:07 -07002508 llvm::DICompileUnit::FullDebug, Signature);
Adrian Prantl66689202015-09-18 23:01:45 +00002509 DIB.finalize();
Adrian Prantl2f957ac2015-09-19 00:59:22 +00002510 }
Adrian Prantl7b6b9a12019-02-08 23:15:42 +00002511
Adrian Prantl835e6632015-09-24 16:10:10 +00002512 llvm::DIModule *Parent =
2513 IsRootModule ? nullptr
Reid Klecknerc915cb92020-02-27 18:13:54 -08002514 : getOrCreateModuleRef(ASTSourceDescriptor(*M->Parent),
2515 CreateSkeletonCU);
Adrian Prantleb66a262015-09-24 16:10:04 +00002516 llvm::DIModule *DIMod =
Adrian Prantl835e6632015-09-24 16:10:10 +00002517 DBuilder.createModule(Parent, Mod.getModuleName(), ConfigMacros,
Adrian Prantl7b303702020-01-14 13:37:04 -08002518 Mod.getPath());
Adrian Prantl9e8ea352015-09-29 20:44:46 +00002519 ModuleCache[M].reset(DIMod);
Adrian Prantleb66a262015-09-24 16:10:04 +00002520 return DIMod;
Adrian Prantlc4bb47e2015-06-30 17:39:51 +00002521}
2522
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002523llvm::DIType *CGDebugInfo::CreateTypeDefinition(const ObjCInterfaceType *Ty,
2524 llvm::DIFile *Unit) {
David Blaikieef8a9512014-05-05 23:23:53 +00002525 ObjCInterfaceDecl *ID = Ty->getDecl();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002526 llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
David Blaikieef8a9512014-05-05 23:23:53 +00002527 unsigned Line = getLineNumber(ID->getLocation());
Duncan P. N. Exon Smith798d5652015-04-15 23:19:15 +00002528 unsigned RuntimeLang = TheCU->getSourceLanguage();
Guy Benyei11169dd2012-12-18 14:30:41 +00002529
2530 // Bit size, align and offset of the type.
2531 uint64_t Size = CGM.getContext().getTypeSize(Ty);
Victor Leschuka7ece032016-10-20 00:13:19 +00002532 auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00002533
Leny Kholodov80c047d2016-09-06 10:48:04 +00002534 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
Guy Benyei11169dd2012-12-18 14:30:41 +00002535 if (ID->getImplementation())
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002536 Flags |= llvm::DINode::FlagObjcClassComplete;
Guy Benyei11169dd2012-12-18 14:30:41 +00002537
Adrian Prantlfd696112015-10-01 00:48:51 +00002538 llvm::DIScope *Mod = getParentModuleOrNull(ID);
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002539 llvm::DICompositeType *RealDecl = DBuilder.createStructType(
Adrian Prantlfd696112015-10-01 00:48:51 +00002540 Mod ? Mod : Unit, ID->getName(), DefUnit, Line, Size, Align, Flags,
2541 nullptr, llvm::DINodeArray(), RuntimeLang);
Guy Benyei11169dd2012-12-18 14:30:41 +00002542
David Blaikieef8a9512014-05-05 23:23:53 +00002543 QualType QTy(Ty, 0);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002544 TypeCache[QTy.getAsOpaquePtr()].reset(RealDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00002545
Eric Christopher35f1f9f2013-07-14 21:00:07 +00002546 // Push the struct on region stack.
Duncan P. N. Exon Smith4078ad42015-04-16 16:36:45 +00002547 LexicalBlockStack.emplace_back(RealDecl);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002548 RegionMap[Ty->getDecl()].reset(RealDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00002549
2550 // Convert all the elements.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002551 SmallVector<llvm::Metadata *, 16> EltTys;
Guy Benyei11169dd2012-12-18 14:30:41 +00002552
2553 ObjCInterfaceDecl *SClass = ID->getSuperClass();
2554 if (SClass) {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002555 llvm::DIType *SClassTy =
Eric Christophere7b87e52014-10-26 23:40:33 +00002556 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
Duncan P. N. Exon Smithb7470232015-04-15 23:48:50 +00002557 if (!SClassTy)
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00002558 return nullptr;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002559
Brock Wyma3db2b102018-05-14 21:21:22 +00002560 llvm::DIType *InhTag = DBuilder.createInheritance(RealDecl, SClassTy, 0, 0,
Leny Kholodovdf050fd2016-09-06 17:06:14 +00002561 llvm::DINode::FlagZero);
Guy Benyei11169dd2012-12-18 14:30:41 +00002562 EltTys.push_back(InhTag);
2563 }
2564
Eric Christopher35f1f9f2013-07-14 21:00:07 +00002565 // Create entries for all of the properties.
Nico Weber7123bca2015-12-04 19:14:14 +00002566 auto AddProperty = [&](const ObjCPropertyDecl *PD) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002567 SourceLocation Loc = PD->getLocation();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002568 llvm::DIFile *PUnit = getOrCreateFile(Loc);
Guy Benyei11169dd2012-12-18 14:30:41 +00002569 unsigned PLine = getLineNumber(Loc);
2570 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
2571 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
Eric Christophere7b87e52014-10-26 23:40:33 +00002572 llvm::MDNode *PropertyNode = DBuilder.createObjCProperty(
2573 PD->getName(), PUnit, PLine,
2574 hasDefaultGetterName(PD, Getter) ? ""
2575 : getSelectorName(PD->getGetterName()),
2576 hasDefaultSetterName(PD, Setter) ? ""
2577 : getSelectorName(PD->getSetterName()),
2578 PD->getPropertyAttributes(), getOrCreateType(PD->getType(), PUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00002579 EltTys.push_back(PropertyNode);
Nico Weber7123bca2015-12-04 19:14:14 +00002580 };
2581 {
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00002582 llvm::SmallPtrSet<const IdentifierInfo *, 16> PropertySet;
Nico Weberde059e12015-12-04 19:35:45 +00002583 for (const ObjCCategoryDecl *ClassExt : ID->known_extensions())
Manman Renefe1bac2016-01-27 20:00:32 +00002584 for (auto *PD : ClassExt->properties()) {
Nico Weberde059e12015-12-04 19:35:45 +00002585 PropertySet.insert(PD->getIdentifier());
2586 AddProperty(PD);
2587 }
Manman Renefe1bac2016-01-27 20:00:32 +00002588 for (const auto *PD : ID->properties()) {
Nico Weber7123bca2015-12-04 19:14:14 +00002589 // Don't emit duplicate metadata for properties that were already in a
2590 // class extension.
2591 if (!PropertySet.insert(PD->getIdentifier()).second)
2592 continue;
2593 AddProperty(PD);
2594 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002595 }
2596
2597 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
2598 unsigned FieldNo = 0;
2599 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
2600 Field = Field->getNextIvar(), ++FieldNo) {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002601 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
Duncan P. N. Exon Smithb7470232015-04-15 23:48:50 +00002602 if (!FieldTy)
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00002603 return nullptr;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002604
Guy Benyei11169dd2012-12-18 14:30:41 +00002605 StringRef FieldName = Field->getName();
2606
2607 // Ignore unnamed fields.
2608 if (FieldName.empty())
2609 continue;
2610
2611 // Get the location for the field.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002612 llvm::DIFile *FieldDefUnit = getOrCreateFile(Field->getLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00002613 unsigned FieldLine = getLineNumber(Field->getLocation());
2614 QualType FType = Field->getType();
2615 uint64_t FieldSize = 0;
Victor Leschuk802e4a52016-10-19 22:11:07 +00002616 uint32_t FieldAlign = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00002617
2618 if (!FType->isIncompleteArrayType()) {
2619
2620 // Bit size, align and offset of the type.
2621 FieldSize = Field->isBitField()
Eric Christopher35f1f9f2013-07-14 21:00:07 +00002622 ? Field->getBitWidthValue(CGM.getContext())
2623 : CGM.getContext().getTypeSize(FType);
Victor Leschuka7ece032016-10-20 00:13:19 +00002624 FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00002625 }
2626
2627 uint64_t FieldOffset;
2628 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
2629 // We don't know the runtime offset of an ivar if we're using the
2630 // non-fragile ABI. For bitfields, use the bit offset into the first
2631 // byte of storage of the bitfield. For other fields, use zero.
2632 if (Field->isBitField()) {
Eric Christophere7b87e52014-10-26 23:40:33 +00002633 FieldOffset =
2634 CGM.getObjCRuntime().ComputeBitfieldBitOffset(CGM, ID, Field);
Guy Benyei11169dd2012-12-18 14:30:41 +00002635 FieldOffset %= CGM.getContext().getCharWidth();
2636 } else {
2637 FieldOffset = 0;
2638 }
2639 } else {
2640 FieldOffset = RL.getFieldOffset(FieldNo);
2641 }
2642
Leny Kholodov80c047d2016-09-06 10:48:04 +00002643 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
Guy Benyei11169dd2012-12-18 14:30:41 +00002644 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002645 Flags = llvm::DINode::FlagProtected;
Guy Benyei11169dd2012-12-18 14:30:41 +00002646 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002647 Flags = llvm::DINode::FlagPrivate;
Adrian Prantl21361fb2014-08-29 22:44:27 +00002648 else if (Field->getAccessControl() == ObjCIvarDecl::Public)
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002649 Flags = llvm::DINode::FlagPublic;
Guy Benyei11169dd2012-12-18 14:30:41 +00002650
Craig Topper8a13c412014-05-21 05:09:00 +00002651 llvm::MDNode *PropertyNode = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00002652 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00002653 if (ObjCPropertyImplDecl *PImpD =
Eric Christophere7b87e52014-10-26 23:40:33 +00002654 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002655 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
Eric Christopherc0c5d462013-02-21 22:35:08 +00002656 SourceLocation Loc = PD->getLocation();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002657 llvm::DIFile *PUnit = getOrCreateFile(Loc);
Eric Christopherc0c5d462013-02-21 22:35:08 +00002658 unsigned PLine = getLineNumber(Loc);
Adrian Prantl901cc4a2019-11-08 09:24:31 -08002659 ObjCMethodDecl *Getter = PImpD->getGetterMethodDecl();
2660 ObjCMethodDecl *Setter = PImpD->getSetterMethodDecl();
Eric Christophere7b87e52014-10-26 23:40:33 +00002661 PropertyNode = DBuilder.createObjCProperty(
2662 PD->getName(), PUnit, PLine,
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00002663 hasDefaultGetterName(PD, Getter)
2664 ? ""
2665 : getSelectorName(PD->getGetterName()),
2666 hasDefaultSetterName(PD, Setter)
2667 ? ""
2668 : getSelectorName(PD->getSetterName()),
Eric Christophere7b87e52014-10-26 23:40:33 +00002669 PD->getPropertyAttributes(),
2670 getOrCreateType(PD->getType(), PUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00002671 }
2672 }
2673 }
Eric Christophere7b87e52014-10-26 23:40:33 +00002674 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit, FieldLine,
2675 FieldSize, FieldAlign, FieldOffset, Flags,
2676 FieldTy, PropertyNode);
Guy Benyei11169dd2012-12-18 14:30:41 +00002677 EltTys.push_back(FieldTy);
2678 }
2679
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002680 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
Duncan P. N. Exon Smithc8ee63e2014-12-18 00:48:56 +00002681 DBuilder.replaceArrays(RealDecl, Elements);
Adrian Prantla03a85a2013-03-06 22:03:30 +00002682
Guy Benyei11169dd2012-12-18 14:30:41 +00002683 LexicalBlockStack.pop_back();
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00002684 return RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00002685}
2686
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002687llvm::DIType *CGDebugInfo::CreateType(const VectorType *Ty,
2688 llvm::DIFile *Unit) {
2689 llvm::DIType *ElementTy = getOrCreateType(Ty->getElementType(), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00002690 int64_t Count = Ty->getNumElements();
Guy Benyei11169dd2012-12-18 14:30:41 +00002691
Sander de Smalen891af03a2018-02-03 13:55:59 +00002692 llvm::Metadata *Subscript;
2693 QualType QTy(Ty, 0);
2694 auto SizeExpr = SizeExprCache.find(QTy);
2695 if (SizeExpr != SizeExprCache.end())
2696 Subscript = DBuilder.getOrCreateSubrange(0, SizeExpr->getSecond());
2697 else
2698 Subscript = DBuilder.getOrCreateSubrange(0, Count ? Count : -1);
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002699 llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
Guy Benyei11169dd2012-12-18 14:30:41 +00002700
2701 uint64_t Size = CGM.getContext().getTypeSize(Ty);
Victor Leschuka7ece032016-10-20 00:13:19 +00002702 auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00002703
2704 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
2705}
2706
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002707llvm::DIType *CGDebugInfo::CreateType(const ArrayType *Ty, llvm::DIFile *Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002708 uint64_t Size;
Victor Leschuk802e4a52016-10-19 22:11:07 +00002709 uint32_t Align;
Guy Benyei11169dd2012-12-18 14:30:41 +00002710
2711 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
David Majnemer58ed0f32016-07-17 00:39:12 +00002712 if (const auto *VAT = dyn_cast<VariableArrayType>(Ty)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002713 Size = 0;
Victor Leschuka7ece032016-10-20 00:13:19 +00002714 Align = getTypeAlignIfRequired(CGM.getContext().getBaseElementType(VAT),
2715 CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00002716 } else if (Ty->isIncompleteArrayType()) {
2717 Size = 0;
2718 if (Ty->getElementType()->isIncompleteType())
2719 Align = 0;
2720 else
Victor Leschuka7ece032016-10-20 00:13:19 +00002721 Align = getTypeAlignIfRequired(Ty->getElementType(), CGM.getContext());
David Blaikief03b2e82013-05-09 20:48:12 +00002722 } else if (Ty->isIncompleteType()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002723 Size = 0;
2724 Align = 0;
2725 } else {
2726 // Size and align of the whole array, not the element type.
2727 Size = CGM.getContext().getTypeSize(Ty);
Victor Leschuka7ece032016-10-20 00:13:19 +00002728 Align = getTypeAlignIfRequired(Ty, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00002729 }
2730
2731 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
2732 // interior arrays, do we care? Why aren't nested arrays represented the
2733 // obvious/recursive way?
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002734 SmallVector<llvm::Metadata *, 8> Subscripts;
Guy Benyei11169dd2012-12-18 14:30:41 +00002735 QualType EltTy(Ty, 0);
2736 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
2737 // If the number of elements is known, then count is that number. Otherwise,
2738 // it's -1. This allows us to represent a subrange with an array of 0
2739 // elements, like this:
2740 //
2741 // struct foo {
2742 // int x[0];
2743 // };
Eric Christophere7b87e52014-10-26 23:40:33 +00002744 int64_t Count = -1; // Count == -1 is an unbounded array.
David Majnemer58ed0f32016-07-17 00:39:12 +00002745 if (const auto *CAT = dyn_cast<ConstantArrayType>(Ty))
Guy Benyei11169dd2012-12-18 14:30:41 +00002746 Count = CAT->getSize().getZExtValue();
David Blaikie87173f12016-08-22 17:49:56 +00002747 else if (const auto *VAT = dyn_cast<VariableArrayType>(Ty)) {
Eli Friedman01d6b962016-10-19 22:16:32 +00002748 if (Expr *Size = VAT->getSizeExpr()) {
Fangrui Song407659a2018-11-30 23:41:18 +00002749 Expr::EvalResult Result;
2750 if (Size->EvaluateAsInt(Result, CGM.getContext()))
2751 Count = Result.Val.getInt().getExtValue();
Eli Friedman01d6b962016-10-19 22:16:32 +00002752 }
David Blaikie87173f12016-08-22 17:49:56 +00002753 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00002754
Sander de Smalen891af03a2018-02-03 13:55:59 +00002755 auto SizeNode = SizeExprCache.find(EltTy);
2756 if (SizeNode != SizeExprCache.end())
2757 Subscripts.push_back(
2758 DBuilder.getOrCreateSubrange(0, SizeNode->getSecond()));
2759 else
2760 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
Guy Benyei11169dd2012-12-18 14:30:41 +00002761 EltTy = Ty->getElementType();
2762 }
2763
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002764 llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
Guy Benyei11169dd2012-12-18 14:30:41 +00002765
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00002766 return DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
2767 SubscriptArray);
Guy Benyei11169dd2012-12-18 14:30:41 +00002768}
2769
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002770llvm::DIType *CGDebugInfo::CreateType(const LValueReferenceType *Ty,
2771 llvm::DIFile *Unit) {
Eric Christophere7b87e52014-10-26 23:40:33 +00002772 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type, Ty,
2773 Ty->getPointeeType(), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00002774}
2775
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002776llvm::DIType *CGDebugInfo::CreateType(const RValueReferenceType *Ty,
2777 llvm::DIFile *Unit) {
Eric Christophere7b87e52014-10-26 23:40:33 +00002778 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type, Ty,
2779 Ty->getPointeeType(), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00002780}
2781
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002782llvm::DIType *CGDebugInfo::CreateType(const MemberPointerType *Ty,
2783 llvm::DIFile *U) {
Leny Kholodov80c047d2016-09-06 10:48:04 +00002784 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
Reid Klecknerfb727182016-06-17 22:27:59 +00002785 uint64_t Size = 0;
2786
2787 if (!Ty->isIncompleteType()) {
2788 Size = CGM.getContext().getTypeSize(Ty);
2789
2790 // Set the MS inheritance model. There is no flag for the unspecified model.
2791 if (CGM.getTarget().getCXXABI().isMicrosoft()) {
2792 switch (Ty->getMostRecentCXXRecordDecl()->getMSInheritanceModel()) {
Reid Klecknera9cc64e2019-11-15 18:49:32 -08002793 case MSInheritanceModel::Single:
Reid Klecknerfb727182016-06-17 22:27:59 +00002794 Flags |= llvm::DINode::FlagSingleInheritance;
2795 break;
Reid Klecknera9cc64e2019-11-15 18:49:32 -08002796 case MSInheritanceModel::Multiple:
Reid Klecknerfb727182016-06-17 22:27:59 +00002797 Flags |= llvm::DINode::FlagMultipleInheritance;
2798 break;
Reid Klecknera9cc64e2019-11-15 18:49:32 -08002799 case MSInheritanceModel::Virtual:
Reid Klecknerfb727182016-06-17 22:27:59 +00002800 Flags |= llvm::DINode::FlagVirtualInheritance;
2801 break;
Reid Klecknera9cc64e2019-11-15 18:49:32 -08002802 case MSInheritanceModel::Unspecified:
Reid Klecknerfb727182016-06-17 22:27:59 +00002803 break;
2804 }
2805 }
2806 }
2807
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002808 llvm::DIType *ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
David Majnemer5fd33e02015-04-24 01:25:08 +00002809 if (Ty->isMemberDataPointerType())
David Blaikie2c705ca2013-01-19 19:20:56 +00002810 return DBuilder.createMemberPointerType(
Reid Klecknerfb727182016-06-17 22:27:59 +00002811 getOrCreateType(Ty->getPointeeType(), U), ClassType, Size, /*Align=*/0,
2812 Flags);
Adrian Prantl0866acd2013-12-19 01:38:47 +00002813
2814 const FunctionProtoType *FPT =
Eric Christophere7b87e52014-10-26 23:40:33 +00002815 Ty->getPointeeType()->getAs<FunctionProtoType>();
2816 return DBuilder.createMemberPointerType(
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00002817 getOrCreateInstanceMethodType(
2818 CXXMethodDecl::getThisType(FPT, Ty->getMostRecentCXXRecordDecl()),
Awanish Pandeyc83602f2020-01-23 16:06:52 +05302819 FPT, U, false),
Reid Klecknerfb727182016-06-17 22:27:59 +00002820 ClassType, Size, /*Align=*/0, Flags);
Guy Benyei11169dd2012-12-18 14:30:41 +00002821}
2822
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002823llvm::DIType *CGDebugInfo::CreateType(const AtomicType *Ty, llvm::DIFile *U) {
Victor Leschuk0df190372016-10-31 19:09:47 +00002824 auto *FromTy = getOrCreateType(Ty->getValueType(), U);
2825 return DBuilder.createQualifiedType(llvm::dwarf::DW_TAG_atomic_type, FromTy);
Guy Benyei11169dd2012-12-18 14:30:41 +00002826}
2827
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00002828llvm::DIType *CGDebugInfo::CreateType(const PipeType *Ty, llvm::DIFile *U) {
Xiuli Pan9c14e282016-01-09 12:53:17 +00002829 return getOrCreateType(Ty->getElementType(), U);
2830}
2831
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002832llvm::DIType *CGDebugInfo::CreateEnumType(const EnumType *Ty) {
Manman Ren1b457022013-08-28 21:20:28 +00002833 const EnumDecl *ED = Ty->getDecl();
Adrian Prantl5c8bd882015-09-11 17:23:08 +00002834
Guy Benyei11169dd2012-12-18 14:30:41 +00002835 uint64_t Size = 0;
Victor Leschuk802e4a52016-10-19 22:11:07 +00002836 uint32_t Align = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00002837 if (!ED->getTypeForDecl()->isIncompleteType()) {
2838 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
Victor Leschuka7ece032016-10-20 00:13:19 +00002839 Align = getDeclAlignIfRequired(ED, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00002840 }
2841
Brock Wyma8557ec52018-05-22 12:41:19 +00002842 SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
Manman Rene0064d82013-08-29 23:19:58 +00002843
Adrian Prantl5c8bd882015-09-11 17:23:08 +00002844 bool isImportedFromModule =
2845 DebugTypeExtRefs && ED->isFromASTFile() && ED->getDefinition();
2846
Guy Benyei11169dd2012-12-18 14:30:41 +00002847 // If this is just a forward declaration, construct an appropriately
2848 // marked node and just return it.
Adrian Prantl5c8bd882015-09-11 17:23:08 +00002849 if (isImportedFromModule || !ED->getDefinition()) {
Adrian Prantl45946062016-02-23 19:30:08 +00002850 // Note that it is possible for enums to be created as part of
2851 // their own declcontext. In this case a FwdDecl will be created
2852 // twice. This doesn't cause a problem because both FwdDecls are
2853 // entered into the ReplaceMap: finalize() will replace the first
2854 // FwdDecl with the second and then replace the second with
2855 // complete type.
Amjad Abouddc4531e2016-04-30 01:44:38 +00002856 llvm::DIScope *EDContext = getDeclContextDescriptor(ED);
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002857 llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
Adrian Prantlff9d83c2016-02-08 17:03:28 +00002858 llvm::TempDIScope TmpContext(DBuilder.createReplaceableCompositeType(
2859 llvm::dwarf::DW_TAG_enumeration_type, "", TheCU, DefUnit, 0));
Adrian Prantla40030f2016-02-06 01:59:09 +00002860
Guy Benyei11169dd2012-12-18 14:30:41 +00002861 unsigned Line = getLineNumber(ED->getLocation());
2862 StringRef EDName = ED->getName();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002863 llvm::DIType *RetTy = DBuilder.createReplaceableCompositeType(
Adrian Prantl45946062016-02-23 19:30:08 +00002864 llvm::dwarf::DW_TAG_enumeration_type, EDName, EDContext, DefUnit, Line,
Brock Wyma8557ec52018-05-22 12:41:19 +00002865 0, Size, Align, llvm::DINode::FlagFwdDecl, Identifier);
Adrian Prantla40030f2016-02-06 01:59:09 +00002866
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002867 ReplaceMap.emplace_back(
2868 std::piecewise_construct, std::make_tuple(Ty),
2869 std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
David Blaikief427b002014-05-06 03:42:01 +00002870 return RetTy;
Guy Benyei11169dd2012-12-18 14:30:41 +00002871 }
2872
David Blaikie483a9da2014-05-06 18:35:21 +00002873 return CreateTypeDefinition(Ty);
2874}
2875
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002876llvm::DIType *CGDebugInfo::CreateTypeDefinition(const EnumType *Ty) {
David Blaikie483a9da2014-05-06 18:35:21 +00002877 const EnumDecl *ED = Ty->getDecl();
2878 uint64_t Size = 0;
Victor Leschuk802e4a52016-10-19 22:11:07 +00002879 uint32_t Align = 0;
David Blaikie483a9da2014-05-06 18:35:21 +00002880 if (!ED->getTypeForDecl()->isIncompleteType()) {
2881 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
Victor Leschuka7ece032016-10-20 00:13:19 +00002882 Align = getDeclAlignIfRequired(ED, CGM.getContext());
David Blaikie483a9da2014-05-06 18:35:21 +00002883 }
2884
Brock Wyma8557ec52018-05-22 12:41:19 +00002885 SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
David Blaikie483a9da2014-05-06 18:35:21 +00002886
Duncan P. N. Exon Smithdadc2b62015-04-21 18:43:54 +00002887 // Create elements for each enumerator.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002888 SmallVector<llvm::Metadata *, 16> Enumerators;
Guy Benyei11169dd2012-12-18 14:30:41 +00002889 ED = ED->getDefinition();
Momchil Velikov25f6be52018-02-12 16:12:52 +00002890 bool IsSigned = ED->getIntegerType()->isSignedIntegerType();
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00002891 for (const auto *Enum : ED->enumerators()) {
Momchil Velikov25f6be52018-02-12 16:12:52 +00002892 const auto &InitVal = Enum->getInitVal();
2893 auto Value = IsSigned ? InitVal.getSExtValue() : InitVal.getZExtValue();
2894 Enumerators.push_back(
2895 DBuilder.createEnumerator(Enum->getName(), Value, !IsSigned));
Guy Benyei11169dd2012-12-18 14:30:41 +00002896 }
2897
2898 // Return a CompositeType for the enum itself.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002899 llvm::DINodeArray EltArray = DBuilder.getOrCreateArray(Enumerators);
Guy Benyei11169dd2012-12-18 14:30:41 +00002900
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002901 llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00002902 unsigned Line = getLineNumber(ED->getLocation());
Amjad Abouddc4531e2016-04-30 01:44:38 +00002903 llvm::DIScope *EnumContext = getDeclContextDescriptor(ED);
Momchil Velikov25f6be52018-02-12 16:12:52 +00002904 llvm::DIType *ClassTy = getOrCreateType(ED->getIntegerType(), DefUnit);
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00002905 return DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit,
2906 Line, Size, Align, EltArray, ClassTy,
Paul Robinsonb1ce7c82019-01-08 16:28:11 +00002907 Identifier, ED->isScoped());
Guy Benyei11169dd2012-12-18 14:30:41 +00002908}
2909
Amjad Aboud546bc112017-02-09 22:07:24 +00002910llvm::DIMacro *CGDebugInfo::CreateMacro(llvm::DIMacroFile *Parent,
2911 unsigned MType, SourceLocation LineLoc,
2912 StringRef Name, StringRef Value) {
2913 unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(LineLoc);
2914 return DBuilder.createMacro(Parent, Line, MType, Name, Value);
2915}
2916
2917llvm::DIMacroFile *CGDebugInfo::CreateTempMacroFile(llvm::DIMacroFile *Parent,
2918 SourceLocation LineLoc,
2919 SourceLocation FileLoc) {
2920 llvm::DIFile *FName = getOrCreateFile(FileLoc);
2921 unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(LineLoc);
2922 return DBuilder.createTempMacroFile(Parent, Line, FName);
2923}
2924
David Blaikie05491062013-01-21 04:37:12 +00002925static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
2926 Qualifiers Quals;
Guy Benyei11169dd2012-12-18 14:30:41 +00002927 do {
Adrian Prantl179af902013-09-26 21:35:50 +00002928 Qualifiers InnerQuals = T.getLocalQualifiers();
2929 // Qualifiers::operator+() doesn't like it if you add a Qualifier
2930 // that is already there.
2931 Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals);
2932 Quals += InnerQuals;
Guy Benyei11169dd2012-12-18 14:30:41 +00002933 QualType LastT = T;
2934 switch (T->getTypeClass()) {
2935 default:
David Blaikie05491062013-01-21 04:37:12 +00002936 return C.getQualifiedType(T.getTypePtr(), Quals);
David Blaikief1b382e2014-04-06 17:14:06 +00002937 case Type::TemplateSpecialization: {
2938 const auto *Spec = cast<TemplateSpecializationType>(T);
2939 if (Spec->isTypeAlias())
2940 return C.getQualifiedType(T.getTypePtr(), Quals);
2941 T = Spec->desugar();
Eric Christophere7b87e52014-10-26 23:40:33 +00002942 break;
2943 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002944 case Type::TypeOfExpr:
2945 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
2946 break;
2947 case Type::TypeOf:
2948 T = cast<TypeOfType>(T)->getUnderlyingType();
2949 break;
2950 case Type::Decltype:
2951 T = cast<DecltypeType>(T)->getUnderlyingType();
2952 break;
2953 case Type::UnaryTransform:
2954 T = cast<UnaryTransformType>(T)->getUnderlyingType();
2955 break;
2956 case Type::Attributed:
2957 T = cast<AttributedType>(T)->getEquivalentType();
2958 break;
2959 case Type::Elaborated:
2960 T = cast<ElaboratedType>(T)->getNamedType();
2961 break;
2962 case Type::Paren:
2963 T = cast<ParenType>(T)->getInnerType();
2964 break;
Leonard Chanc72aaf62019-05-07 03:20:17 +00002965 case Type::MacroQualified:
2966 T = cast<MacroQualifiedType>(T)->getUnderlyingType();
2967 break;
David Blaikie05491062013-01-21 04:37:12 +00002968 case Type::SubstTemplateTypeParm:
Guy Benyei11169dd2012-12-18 14:30:41 +00002969 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
Guy Benyei11169dd2012-12-18 14:30:41 +00002970 break;
Richard Smitha0abc422017-02-22 00:13:14 +00002971 case Type::Auto:
2972 case Type::DeducedTemplateSpecialization: {
2973 QualType DT = cast<DeducedType>(T)->getDeducedType();
David Blaikie42edade2014-11-11 20:44:45 +00002974 assert(!DT.isNull() && "Undeduced types shouldn't reach here.");
David Blaikie22c460a02013-05-24 21:24:35 +00002975 T = DT;
Guy Benyei11169dd2012-12-18 14:30:41 +00002976 break;
2977 }
Jordan Rose303e2f12016-11-10 23:28:17 +00002978 case Type::Adjusted:
2979 case Type::Decayed:
2980 // Decayed and adjusted types use the adjusted type in LLVM and DWARF.
2981 T = cast<AdjustedType>(T)->getAdjustedType();
2982 break;
2983 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00002984
Guy Benyei11169dd2012-12-18 14:30:41 +00002985 assert(T != LastT && "Type unwrapping failed to unwrap!");
NAKAMURA Takumi3e0a3632013-01-21 10:51:28 +00002986 (void)LastT;
Guy Benyei11169dd2012-12-18 14:30:41 +00002987 } while (true);
2988}
2989
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002990llvm::DIType *CGDebugInfo::getTypeOrNull(QualType Ty) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002991
2992 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00002993 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Eric Christopherb2a008c2013-05-16 00:45:12 +00002994
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00002995 auto It = TypeCache.find(Ty.getAsOpaquePtr());
2996 if (It != TypeCache.end()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002997 // Verify that the debug info still exists.
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00002998 if (llvm::Metadata *V = It->second)
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002999 return cast<llvm::DIType>(V);
Guy Benyei11169dd2012-12-18 14:30:41 +00003000 }
3001
Duncan P. N. Exon Smithc7551282015-04-06 23:21:33 +00003002 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003003}
3004
David Blaikie0e716b42014-03-03 23:48:23 +00003005void CGDebugInfo::completeTemplateDefinition(
3006 const ClassTemplateSpecializationDecl &SD) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00003007 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
David Blaikie0856f662014-03-04 22:01:08 +00003008 return;
David Blaikie1ac9c982017-04-11 21:13:37 +00003009 completeUnusedClass(SD);
3010}
David Blaikie0856f662014-03-04 22:01:08 +00003011
David Blaikie1ac9c982017-04-11 21:13:37 +00003012void CGDebugInfo::completeUnusedClass(const CXXRecordDecl &D) {
3013 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
3014 return;
3015
3016 completeClassData(&D);
David Blaikie0e716b42014-03-03 23:48:23 +00003017 // In case this type has no member function definitions being emitted, ensure
3018 // it is retained
David Blaikie1ac9c982017-04-11 21:13:37 +00003019 RetainedTypes.push_back(CGM.getContext().getRecordType(&D).getAsOpaquePtr());
David Blaikie0e716b42014-03-03 23:48:23 +00003020}
3021
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003022llvm::DIType *CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile *Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003023 if (Ty.isNull())
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00003024 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003025
Luboš Luňák4f2104c2019-11-02 16:39:59 +01003026 llvm::TimeTraceScope TimeScope("DebugType", [&]() {
3027 std::string Name;
3028 llvm::raw_string_ostream OS(Name);
3029 Ty.print(OS, getPrintingPolicy());
3030 return Name;
3031 });
3032
Guy Benyei11169dd2012-12-18 14:30:41 +00003033 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00003034 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00003035
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00003036 if (auto *T = getTypeOrNull(Ty))
Guy Benyei11169dd2012-12-18 14:30:41 +00003037 return T;
3038
Adrian Prantlca844182015-09-11 17:23:03 +00003039 llvm::DIType *Res = CreateTypeNode(Ty, Unit);
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00003040 void *TyPtr = Ty.getAsOpaquePtr();
Adrian Prantl73409ce2013-03-11 18:33:46 +00003041
3042 // And update the type cache.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003043 TypeCache[TyPtr].reset(Res);
Guy Benyei11169dd2012-12-18 14:30:41 +00003044
Guy Benyei11169dd2012-12-18 14:30:41 +00003045 return Res;
3046}
3047
Adrian Prantl5c8bd882015-09-11 17:23:08 +00003048llvm::DIModule *CGDebugInfo::getParentModuleOrNull(const Decl *D) {
Adrian Prantl335f5c72015-10-02 17:36:14 +00003049 // A forward declaration inside a module header does not belong to the module.
3050 if (isa<RecordDecl>(D) && !cast<RecordDecl>(D)->getDefinition())
3051 return nullptr;
Adrian Prantl85d938a2015-09-21 17:48:37 +00003052 if (DebugTypeExtRefs && D->isFromASTFile()) {
3053 // Record a reference to an imported clang module or precompiled header.
3054 auto *Reader = CGM.getContext().getExternalSource();
3055 auto Idx = D->getOwningModuleID();
3056 auto Info = Reader->getSourceDescriptor(Idx);
3057 if (Info)
3058 return getOrCreateModuleRef(*Info, /*SkeletonCU=*/true);
3059 } else if (ClangModuleMap) {
Adrian Prantl9402cef2015-09-20 16:51:35 +00003060 // We are building a clang module or a precompiled header.
3061 //
3062 // TODO: When D is a CXXRecordDecl or a C++ Enum, the ODR applies
3063 // and it wouldn't be necessary to specify the parent scope
3064 // because the type is already unique by definition (it would look
3065 // like the output of -fno-standalone-debug). On the other hand,
3066 // the parent scope helps a consumer to quickly locate the object
3067 // file where the type's definition is located, so it might be
3068 // best to make this behavior a command line or debugger tuning
3069 // option.
Richard Smith54f04402017-05-18 02:29:20 +00003070 if (Module *M = D->getOwningModule()) {
Adrian Prantlaa5d08d2016-01-22 21:14:41 +00003071 // This is a (sub-)module.
Reid Klecknerc915cb92020-02-27 18:13:54 -08003072 auto Info = ASTSourceDescriptor(*M);
Adrian Prantl9402cef2015-09-20 16:51:35 +00003073 return getOrCreateModuleRef(Info, /*SkeletonCU=*/false);
Adrian Prantlaa5d08d2016-01-22 21:14:41 +00003074 } else {
3075 // This the precompiled header being built.
3076 return getOrCreateModuleRef(PCHDescriptor, /*SkeletonCU=*/false);
Adrian Prantl9402cef2015-09-20 16:51:35 +00003077 }
3078 }
Adrian Prantl5c8bd882015-09-11 17:23:08 +00003079
Adrian Prantl9402cef2015-09-20 16:51:35 +00003080 return nullptr;
Adrian Prantl5c8bd882015-09-11 17:23:08 +00003081}
3082
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003083llvm::DIType *CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile *Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003084 // Handle qualifiers, which recursively handles what they refer to.
3085 if (Ty.hasLocalQualifiers())
David Blaikie99dab3b2013-09-04 22:03:57 +00003086 return CreateQualifiedType(Ty, Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00003087
Guy Benyei11169dd2012-12-18 14:30:41 +00003088 // Work out details of type.
3089 switch (Ty->getTypeClass()) {
3090#define TYPE(Class, Base)
3091#define ABSTRACT_TYPE(Class, Base)
3092#define NON_CANONICAL_TYPE(Class, Base)
3093#define DEPENDENT_TYPE(Class, Base) case Type::Class:
John McCall36b12a82019-10-02 06:35:23 +00003094#include "clang/AST/TypeNodes.inc"
Guy Benyei11169dd2012-12-18 14:30:41 +00003095 llvm_unreachable("Dependent types cannot show up in debug information");
3096
3097 case Type::ExtVector:
3098 case Type::Vector:
3099 return CreateType(cast<VectorType>(Ty), Unit);
3100 case Type::ObjCObjectPointer:
3101 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
3102 case Type::ObjCObject:
3103 return CreateType(cast<ObjCObjectType>(Ty), Unit);
Manman Rene6be26c2016-09-13 17:25:08 +00003104 case Type::ObjCTypeParam:
3105 return CreateType(cast<ObjCTypeParamType>(Ty), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00003106 case Type::ObjCInterface:
3107 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
3108 case Type::Builtin:
3109 return CreateType(cast<BuiltinType>(Ty));
3110 case Type::Complex:
3111 return CreateType(cast<ComplexType>(Ty));
3112 case Type::Pointer:
3113 return CreateType(cast<PointerType>(Ty), Unit);
3114 case Type::BlockPointer:
3115 return CreateType(cast<BlockPointerType>(Ty), Unit);
3116 case Type::Typedef:
David Blaikie99dab3b2013-09-04 22:03:57 +00003117 return CreateType(cast<TypedefType>(Ty), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00003118 case Type::Record:
David Blaikie99dab3b2013-09-04 22:03:57 +00003119 return CreateType(cast<RecordType>(Ty));
Guy Benyei11169dd2012-12-18 14:30:41 +00003120 case Type::Enum:
Manman Ren1b457022013-08-28 21:20:28 +00003121 return CreateEnumType(cast<EnumType>(Ty));
Guy Benyei11169dd2012-12-18 14:30:41 +00003122 case Type::FunctionProto:
3123 case Type::FunctionNoProto:
3124 return CreateType(cast<FunctionType>(Ty), Unit);
3125 case Type::ConstantArray:
3126 case Type::VariableArray:
3127 case Type::IncompleteArray:
3128 return CreateType(cast<ArrayType>(Ty), Unit);
3129
3130 case Type::LValueReference:
3131 return CreateType(cast<LValueReferenceType>(Ty), Unit);
3132 case Type::RValueReference:
3133 return CreateType(cast<RValueReferenceType>(Ty), Unit);
3134
3135 case Type::MemberPointer:
3136 return CreateType(cast<MemberPointerType>(Ty), Unit);
3137
3138 case Type::Atomic:
3139 return CreateType(cast<AtomicType>(Ty), Unit);
3140
Xiuli Pan9c14e282016-01-09 12:53:17 +00003141 case Type::Pipe:
3142 return CreateType(cast<PipeType>(Ty), Unit);
3143
Guy Benyei11169dd2012-12-18 14:30:41 +00003144 case Type::TemplateSpecialization:
David Blaikief1b382e2014-04-06 17:14:06 +00003145 return CreateType(cast<TemplateSpecializationType>(Ty), Unit);
3146
David Blaikie42edade2014-11-11 20:44:45 +00003147 case Type::Auto:
David Blaikief1b382e2014-04-06 17:14:06 +00003148 case Type::Attributed:
Jordan Rose303e2f12016-11-10 23:28:17 +00003149 case Type::Adjusted:
3150 case Type::Decayed:
Richard Smith600b5262017-01-26 20:40:47 +00003151 case Type::DeducedTemplateSpecialization:
Guy Benyei11169dd2012-12-18 14:30:41 +00003152 case Type::Elaborated:
3153 case Type::Paren:
Leonard Chanc72aaf62019-05-07 03:20:17 +00003154 case Type::MacroQualified:
Guy Benyei11169dd2012-12-18 14:30:41 +00003155 case Type::SubstTemplateTypeParm:
3156 case Type::TypeOfExpr:
3157 case Type::TypeOf:
3158 case Type::Decltype:
3159 case Type::UnaryTransform:
David Blaikie66ed89d2013-07-13 21:08:08 +00003160 case Type::PackExpansion:
David Blaikie22c460a02013-05-24 21:24:35 +00003161 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003162 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00003163
David Blaikie42edade2014-11-11 20:44:45 +00003164 llvm_unreachable("type should have been unwrapped!");
Guy Benyei11169dd2012-12-18 14:30:41 +00003165}
3166
Duncan P. N. Exon Smithbd210e62015-07-24 20:34:41 +00003167llvm::DICompositeType *CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty,
3168 llvm::DIFile *Unit) {
David Blaikie4a2b5ef2013-08-12 22:24:20 +00003169 QualType QTy(Ty, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00003170
Duncan P. N. Exon Smithbd210e62015-07-24 20:34:41 +00003171 auto *T = cast_or_null<llvm::DICompositeType>(getTypeOrNull(QTy));
Guy Benyei11169dd2012-12-18 14:30:41 +00003172
3173 // We may have cached a forward decl when we could have created
3174 // a non-forward decl. Go ahead and create a non-forward decl
3175 // now.
Duncan P. N. Exon Smith4caa7f22015-04-16 01:00:56 +00003176 if (T && !T->isForwardDecl())
Eric Christophere7b87e52014-10-26 23:40:33 +00003177 return T;
Guy Benyei11169dd2012-12-18 14:30:41 +00003178
3179 // Otherwise create the type.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003180 llvm::DICompositeType *Res = CreateLimitedType(Ty);
David Blaikie8d5e1282013-08-20 21:03:29 +00003181
3182 // Propagate members from the declaration to the definition
3183 // CreateType(const RecordType*) will overwrite this with the members in the
3184 // correct order if the full type is needed.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003185 DBuilder.replaceArrays(Res, T ? T->getElements() : llvm::DINodeArray());
Guy Benyei11169dd2012-12-18 14:30:41 +00003186
Guy Benyei11169dd2012-12-18 14:30:41 +00003187 // And update the type cache.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003188 TypeCache[QTy.getAsOpaquePtr()].reset(Res);
Guy Benyei11169dd2012-12-18 14:30:41 +00003189 return Res;
3190}
3191
3192// TODO: Currently used for context chains when limiting debug info.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003193llvm::DICompositeType *CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003194 RecordDecl *RD = Ty->getDecl();
Eric Christopherb2a008c2013-05-16 00:45:12 +00003195
Guy Benyei11169dd2012-12-18 14:30:41 +00003196 // Get overall information about the record type for the debug info.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003197 llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00003198 unsigned Line = getLineNumber(RD->getLocation());
3199 StringRef RDName = getClassName(RD);
3200
Amjad Abouddc4531e2016-04-30 01:44:38 +00003201 llvm::DIScope *RDContext = getDeclContextDescriptor(RD);
Guy Benyei11169dd2012-12-18 14:30:41 +00003202
David Blaikied2785892013-08-18 17:36:19 +00003203 // If we ended up creating the type during the context chain construction,
3204 // just return that.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003205 auto *T = cast_or_null<llvm::DICompositeType>(
Duncan P. N. Exon Smithc7551282015-04-06 23:21:33 +00003206 getTypeOrNull(CGM.getContext().getRecordType(RD)));
Duncan P. N. Exon Smith4caa7f22015-04-16 01:00:56 +00003207 if (T && (!T->isForwardDecl() || !RD->getDefinition()))
Eric Christophere7b87e52014-10-26 23:40:33 +00003208 return T;
David Blaikied2785892013-08-18 17:36:19 +00003209
Adrian Prantl381e7552014-02-04 21:29:50 +00003210 // If this is just a forward or incomplete declaration, construct an
3211 // appropriately marked node and just return it.
3212 const RecordDecl *D = RD->getDefinition();
3213 if (!D || !D->isCompleteDefinition())
Manman Ren1b457022013-08-28 21:20:28 +00003214 return getOrCreateRecordFwdDecl(Ty, RDContext);
Guy Benyei11169dd2012-12-18 14:30:41 +00003215
3216 uint64_t Size = CGM.getContext().getTypeSize(Ty);
Victor Leschuka7ece032016-10-20 00:13:19 +00003217 auto Align = getDeclAlignIfRequired(D, CGM.getContext());
Eric Christopherb2a008c2013-05-16 00:45:12 +00003218
Brock Wyma8557ec52018-05-22 12:41:19 +00003219 SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
Manman Rene0064d82013-08-29 23:19:58 +00003220
Shafik Yaghmour528f5da2019-08-27 20:17:35 +00003221 // Explicitly record the calling convention and export symbols for C++
3222 // records.
Adrian Prantl6c5f03a2018-01-05 01:13:52 +00003223 auto Flags = llvm::DINode::FlagZero;
3224 if (auto CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3225 if (CGM.getCXXABI().getRecordArgABI(CXXRD) == CGCXXABI::RAA_Indirect)
3226 Flags |= llvm::DINode::FlagTypePassByReference;
3227 else
3228 Flags |= llvm::DINode::FlagTypePassByValue;
Aaron Smith044326c2018-07-23 20:49:07 +00003229
Aaron Smithfa7745b2019-04-11 20:24:54 +00003230 // Record if a C++ record is non-trivial type.
3231 if (!CXXRD->isTrivial())
Aaron Smithf0d27332019-02-26 03:49:05 +00003232 Flags |= llvm::DINode::FlagNonTrivial;
Shafik Yaghmour528f5da2019-08-27 20:17:35 +00003233
3234 // Record exports it symbols to the containing structure.
3235 if (CXXRD->isAnonymousStructOrUnion())
3236 Flags |= llvm::DINode::FlagExportSymbols;
Adrian Prantl6c5f03a2018-01-05 01:13:52 +00003237 }
3238
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003239 llvm::DICompositeType *RealDecl = DBuilder.createReplaceableCompositeType(
Leny Kholodov80c047d2016-09-06 10:48:04 +00003240 getTagForRecord(RD), RDName, RDContext, DefUnit, Line, 0, Size, Align,
Brock Wyma8557ec52018-05-22 12:41:19 +00003241 Flags, Identifier);
Guy Benyei11169dd2012-12-18 14:30:41 +00003242
Duncan P. N. Exon Smithf9521b02016-04-17 07:45:08 +00003243 // Elements of composite types usually have back to the type, creating
3244 // uniquing cycles. Distinct nodes are more efficient.
3245 switch (RealDecl->getTag()) {
3246 default:
3247 llvm_unreachable("invalid composite type tag");
3248
3249 case llvm::dwarf::DW_TAG_array_type:
3250 case llvm::dwarf::DW_TAG_enumeration_type:
3251 // Array elements and most enumeration elements don't have back references,
3252 // so they don't tend to be involved in uniquing cycles and there is some
3253 // chance of merging them when linking together two modules. Only make
3254 // them distinct if they are ODR-uniqued.
Brock Wyma8557ec52018-05-22 12:41:19 +00003255 if (Identifier.empty())
Duncan P. N. Exon Smithf9521b02016-04-17 07:45:08 +00003256 break;
Galina Kistanova0872d6c2017-06-03 06:30:46 +00003257 LLVM_FALLTHROUGH;
Duncan P. N. Exon Smithf9521b02016-04-17 07:45:08 +00003258
3259 case llvm::dwarf::DW_TAG_structure_type:
3260 case llvm::dwarf::DW_TAG_union_type:
3261 case llvm::dwarf::DW_TAG_class_type:
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00003262 // Immediately resolve to a distinct node.
Duncan P. N. Exon Smithf9521b02016-04-17 07:45:08 +00003263 RealDecl =
3264 llvm::MDNode::replaceWithDistinct(llvm::TempDICompositeType(RealDecl));
3265 break;
3266 }
3267
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003268 RegionMap[Ty->getDecl()].reset(RealDecl);
3269 TypeCache[QualType(Ty, 0).getAsOpaquePtr()].reset(RealDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00003270
David Majnemer58ed0f32016-07-17 00:39:12 +00003271 if (const auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD))
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003272 DBuilder.replaceArrays(RealDecl, llvm::DINodeArray(),
Duncan P. N. Exon Smithc8ee63e2014-12-18 00:48:56 +00003273 CollectCXXTemplateParams(TSpecial, DefUnit));
David Blaikie952dac32013-08-15 22:42:12 +00003274 return RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00003275}
3276
David Blaikieadfbf992013-08-18 16:55:33 +00003277void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD,
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003278 llvm::DICompositeType *RealDecl) {
David Blaikieadfbf992013-08-18 16:55:33 +00003279 // A class's primary base or the class itself contains the vtable.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003280 llvm::DICompositeType *ContainingType = nullptr;
David Blaikieadfbf992013-08-18 16:55:33 +00003281 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
3282 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
Alp Tokerd4733632013-12-05 04:47:09 +00003283 // Seek non-virtual primary base root.
David Blaikieadfbf992013-08-18 16:55:33 +00003284 while (1) {
3285 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
3286 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
3287 if (PBT && !BRL.isPrimaryBaseVirtual())
3288 PBase = PBT;
3289 else
3290 break;
3291 }
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003292 ContainingType = cast<llvm::DICompositeType>(
David Blaikieadfbf992013-08-18 16:55:33 +00003293 getOrCreateType(QualType(PBase->getTypeForDecl(), 0),
3294 getOrCreateFile(RD->getLocation())));
3295 } else if (RD->isDynamicClass())
3296 ContainingType = RealDecl;
3297
Duncan P. N. Exon Smithc8ee63e2014-12-18 00:48:56 +00003298 DBuilder.replaceVTableHolder(RealDecl, ContainingType);
David Blaikieadfbf992013-08-18 16:55:33 +00003299}
3300
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003301llvm::DIType *CGDebugInfo::CreateMemberType(llvm::DIFile *Unit, QualType FType,
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00003302 StringRef Name, uint64_t *Offset) {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003303 llvm::DIType *FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00003304 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
Victor Leschuka7ece032016-10-20 00:13:19 +00003305 auto FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext());
Leny Kholodovdf050fd2016-09-06 17:06:14 +00003306 llvm::DIType *Ty =
3307 DBuilder.createMemberType(Unit, Name, Unit, 0, FieldSize, FieldAlign,
3308 *Offset, llvm::DINode::FlagZero, FieldTy);
Guy Benyei11169dd2012-12-18 14:30:41 +00003309 *Offset += FieldSize;
3310 return Ty;
3311}
3312
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003313void CGDebugInfo::collectFunctionDeclProps(GlobalDecl GD, llvm::DIFile *Unit,
Duncan P. N. Exon Smith8e47da42015-04-21 20:07:29 +00003314 StringRef &Name,
3315 StringRef &LinkageName,
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003316 llvm::DIScope *&FDContext,
3317 llvm::DINodeArray &TParamsArray,
Leny Kholodov80c047d2016-09-06 10:48:04 +00003318 llvm::DINode::DIFlags &Flags) {
David Majnemer58ed0f32016-07-17 00:39:12 +00003319 const auto *FD = cast<FunctionDecl>(GD.getDecl());
Frederic Riss9db79f12014-11-18 03:40:46 +00003320 Name = getFunctionName(FD);
3321 // Use mangled name as linkage name for C/C++ functions.
3322 if (FD->hasPrototype()) {
3323 LinkageName = CGM.getMangledName(GD);
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003324 Flags |= llvm::DINode::FlagPrototyped;
Frederic Riss9db79f12014-11-18 03:40:46 +00003325 }
3326 // No need to replicate the linkage name if it isn't different from the
3327 // subprogram name, no need to have it at all unless coverage is enabled or
Dehao Chenb3a70de2017-01-19 00:44:21 +00003328 // debug is set to more than just line tables or extra debug info is needed.
Benjamin Kramer8c305922016-02-02 11:06:51 +00003329 if (LinkageName == Name || (!CGM.getCodeGenOpts().EmitGcovArcs &&
3330 !CGM.getCodeGenOpts().EmitGcovNotes &&
Dehao Chenb3a70de2017-01-19 00:44:21 +00003331 !CGM.getCodeGenOpts().DebugInfoForProfiling &&
Benjamin Kramer8c305922016-02-02 11:06:51 +00003332 DebugKind <= codegenoptions::DebugLineTablesOnly))
Frederic Riss9db79f12014-11-18 03:40:46 +00003333 LinkageName = StringRef();
3334
Amy Huang53539bb2020-01-13 15:54:54 -08003335 if (CGM.getCodeGenOpts().hasReducedDebugInfo()) {
Frederic Riss9db79f12014-11-18 03:40:46 +00003336 if (const NamespaceDecl *NSDecl =
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00003337 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
Adrian Prantlddb8e062017-05-12 16:23:53 +00003338 FDContext = getOrCreateNamespace(NSDecl);
Frederic Riss9db79f12014-11-18 03:40:46 +00003339 else if (const RecordDecl *RDecl =
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00003340 dyn_cast_or_null<RecordDecl>(FD->getDeclContext())) {
Adrian Prantl5c8bd882015-09-11 17:23:08 +00003341 llvm::DIScope *Mod = getParentModuleOrNull(RDecl);
3342 FDContext = getContextDescriptor(RDecl, Mod ? Mod : TheCU);
3343 }
Adrian Prantlfd5ac8a2016-08-17 16:20:32 +00003344 // Check if it is a noreturn-marked function
3345 if (FD->isNoReturn())
3346 Flags |= llvm::DINode::FlagNoReturn;
Frederic Riss9db79f12014-11-18 03:40:46 +00003347 // Collect template parameters.
3348 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
3349 }
3350}
3351
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003352void CGDebugInfo::collectVarDeclProps(const VarDecl *VD, llvm::DIFile *&Unit,
Frederic Riss9db79f12014-11-18 03:40:46 +00003353 unsigned &LineNo, QualType &T,
3354 StringRef &Name, StringRef &LinkageName,
Matthew Voss20165362018-10-03 18:45:04 +00003355 llvm::MDTuple *&TemplateParameters,
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003356 llvm::DIScope *&VDContext) {
Frederic Riss9db79f12014-11-18 03:40:46 +00003357 Unit = getOrCreateFile(VD->getLocation());
3358 LineNo = getLineNumber(VD->getLocation());
3359
3360 setLocation(VD->getLocation());
3361
3362 T = VD->getType();
3363 if (T->isIncompleteArrayType()) {
3364 // CodeGen turns int[] into int[1] so we'll do the same here.
3365 llvm::APInt ConstVal(32, 1);
3366 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3367
Richard Smith772e2662019-10-04 01:25:59 +00003368 T = CGM.getContext().getConstantArrayType(ET, ConstVal, nullptr,
3369 ArrayType::Normal, 0);
Frederic Riss9db79f12014-11-18 03:40:46 +00003370 }
3371
3372 Name = VD->getName();
3373 if (VD->getDeclContext() && !isa<FunctionDecl>(VD->getDeclContext()) &&
3374 !isa<ObjCMethodDecl>(VD->getDeclContext()))
3375 LinkageName = CGM.getMangledName(VD);
3376 if (LinkageName == Name)
3377 LinkageName = StringRef();
3378
Matthew Voss20165362018-10-03 18:45:04 +00003379 if (isa<VarTemplateSpecializationDecl>(VD)) {
3380 llvm::DINodeArray parameterNodes = CollectVarTemplateParams(VD, &*Unit);
3381 TemplateParameters = parameterNodes.get();
3382 } else {
3383 TemplateParameters = nullptr;
3384 }
3385
Frederic Riss9db79f12014-11-18 03:40:46 +00003386 // Since we emit declarations (DW_AT_members) for static members, place the
3387 // definition of those static members in the namespace they were declared in
3388 // in the source code (the lexical decl context).
3389 // FIXME: Generalize this for even non-member global variables where the
3390 // declaration and definition may have different lexical decl contexts, once
3391 // we have support for emitting declarations of (non-member) global variables.
Saleem Abdulrasoolcd187f02015-02-28 00:13:13 +00003392 const DeclContext *DC = VD->isStaticDataMember() ? VD->getLexicalDeclContext()
3393 : VD->getDeclContext();
3394 // When a record type contains an in-line initialization of a static data
3395 // member, and the record type is marked as __declspec(dllexport), an implicit
3396 // definition of the member will be created in the record context. DWARF
3397 // doesn't seem to have a nice way to describe this in a form that consumers
3398 // are likely to understand, so fake the "normal" situation of a definition
3399 // outside the class by putting it in the global scope.
3400 if (DC->isRecord())
3401 DC = CGM.getContext().getTranslationUnitDecl();
Adrian Prantl5c8bd882015-09-11 17:23:08 +00003402
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00003403 llvm::DIScope *Mod = getParentModuleOrNull(VD);
3404 VDContext = getContextDescriptor(cast<Decl>(DC), Mod ? Mod : TheCU);
Frederic Riss9db79f12014-11-18 03:40:46 +00003405}
3406
Adrian Prantlb7acfc02017-02-27 21:30:05 +00003407llvm::DISubprogram *CGDebugInfo::getFunctionFwdDeclOrStub(GlobalDecl GD,
3408 bool Stub) {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003409 llvm::DINodeArray TParamsArray;
Frederic Rissd253ed62014-11-18 03:40:51 +00003410 StringRef Name, LinkageName;
Leny Kholodov80c047d2016-09-06 10:48:04 +00003411 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
Paul Robinsoncda54212018-11-19 18:29:28 +00003412 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
Adrian Prantlb7acfc02017-02-27 21:30:05 +00003413 SourceLocation Loc = GD.getDecl()->getLocation();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003414 llvm::DIFile *Unit = getOrCreateFile(Loc);
3415 llvm::DIScope *DContext = Unit;
Frederic Rissd253ed62014-11-18 03:40:51 +00003416 unsigned Line = getLineNumber(Loc);
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00003417 collectFunctionDeclProps(GD, Unit, Name, LinkageName, DContext, TParamsArray,
3418 Flags);
Simon Pilgrimcfee2ef2019-10-16 10:38:49 +00003419 auto *FD = cast<FunctionDecl>(GD.getDecl());
Adrian Prantlb7acfc02017-02-27 21:30:05 +00003420
Frederic Rissd253ed62014-11-18 03:40:51 +00003421 // Build function type.
3422 SmallVector<QualType, 16> ArgTypes;
Simon Pilgrimcfee2ef2019-10-16 10:38:49 +00003423 for (const ParmVarDecl *Parm : FD->parameters())
3424 ArgTypes.push_back(Parm->getType());
3425
Reid Klecknerf00f8032016-06-08 20:41:54 +00003426 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
3427 QualType FnType = CGM.getContext().getFunctionType(
3428 FD->getReturnType(), ArgTypes, FunctionProtoType::ExtProtoInfo(CC));
Paul Robinsoncda54212018-11-19 18:29:28 +00003429 if (!FD->isExternallyVisible())
3430 SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;
3431 if (CGM.getLangOpts().Optimize)
3432 SPFlags |= llvm::DISubprogram::SPFlagOptimized;
3433
Adrian Prantlb7acfc02017-02-27 21:30:05 +00003434 if (Stub) {
Vedant Kumar5931b4e2018-10-05 20:37:17 +00003435 Flags |= getCallSiteRelatedAttrs();
Paul Robinsoncda54212018-11-19 18:29:28 +00003436 SPFlags |= llvm::DISubprogram::SPFlagDefinition;
Adrian Prantlb7acfc02017-02-27 21:30:05 +00003437 return DBuilder.createFunction(
3438 DContext, Name, LinkageName, Unit, Line,
Paul Robinsoncda54212018-11-19 18:29:28 +00003439 getOrCreateFunctionType(GD.getDecl(), FnType, Unit), 0, Flags, SPFlags,
Adrian Prantlb7acfc02017-02-27 21:30:05 +00003440 TParamsArray.get(), getFunctionDeclaration(FD));
3441 }
3442
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003443 llvm::DISubprogram *SP = DBuilder.createTempFunctionFwdDecl(
Duncan P. N. Exon Smithebad0aa2015-04-07 16:50:49 +00003444 DContext, Name, LinkageName, Unit, Line,
Paul Robinsoncda54212018-11-19 18:29:28 +00003445 getOrCreateFunctionType(GD.getDecl(), FnType, Unit), 0, Flags, SPFlags,
Duncan P. N. Exon Smithebad0aa2015-04-07 16:50:49 +00003446 TParamsArray.get(), getFunctionDeclaration(FD));
George Burgess IV00f70bd2018-03-01 05:43:23 +00003447 const FunctionDecl *CanonDecl = FD->getCanonicalDecl();
Duncan P. N. Exon Smith4078ad42015-04-16 16:36:45 +00003448 FwdDeclReplaceMap.emplace_back(std::piecewise_construct,
3449 std::make_tuple(CanonDecl),
3450 std::make_tuple(SP));
Frederic Rissd253ed62014-11-18 03:40:51 +00003451 return SP;
3452}
3453
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00003454llvm::DISubprogram *CGDebugInfo::getFunctionForwardDeclaration(GlobalDecl GD) {
Adrian Prantlb7acfc02017-02-27 21:30:05 +00003455 return getFunctionFwdDeclOrStub(GD, /* Stub = */ false);
3456}
3457
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00003458llvm::DISubprogram *CGDebugInfo::getFunctionStub(GlobalDecl GD) {
Adrian Prantlb7acfc02017-02-27 21:30:05 +00003459 return getFunctionFwdDeclOrStub(GD, /* Stub = */ true);
3460}
3461
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003462llvm::DIGlobalVariable *
Frederic Rissd253ed62014-11-18 03:40:51 +00003463CGDebugInfo::getGlobalVariableForwardDeclaration(const VarDecl *VD) {
3464 QualType T;
3465 StringRef Name, LinkageName;
3466 SourceLocation Loc = VD->getLocation();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003467 llvm::DIFile *Unit = getOrCreateFile(Loc);
3468 llvm::DIScope *DContext = Unit;
Frederic Rissd253ed62014-11-18 03:40:51 +00003469 unsigned Line = getLineNumber(Loc);
Matthew Voss20165362018-10-03 18:45:04 +00003470 llvm::MDTuple *TemplateParameters = nullptr;
Frederic Rissd253ed62014-11-18 03:40:51 +00003471
Matthew Voss20165362018-10-03 18:45:04 +00003472 collectVarDeclProps(VD, Unit, Line, T, Name, LinkageName, TemplateParameters,
3473 DContext);
Victor Leschuka7ece032016-10-20 00:13:19 +00003474 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
Duncan P. N. Exon Smithdadc2b62015-04-21 18:43:54 +00003475 auto *GV = DBuilder.createTempGlobalVariableFwdDecl(
3476 DContext, Name, LinkageName, Unit, Line, getOrCreateType(T, Unit),
Matthew Voss20165362018-10-03 18:45:04 +00003477 !VD->isExternallyVisible(), nullptr, TemplateParameters, Align);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003478 FwdDeclReplaceMap.emplace_back(
3479 std::piecewise_construct,
3480 std::make_tuple(cast<VarDecl>(VD->getCanonicalDecl())),
3481 std::make_tuple(static_cast<llvm::Metadata *>(GV)));
Frederic Rissd253ed62014-11-18 03:40:51 +00003482 return GV;
3483}
3484
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003485llvm::DINode *CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
David Blaikiebd483762013-05-20 04:58:53 +00003486 // We only need a declaration (not a definition) of the type - so use whatever
3487 // we would otherwise do to get a type for a pointee. (forward declarations in
3488 // limited debug info, full definitions (if the type definition is available)
3489 // in unlimited debug info)
David Majnemer58ed0f32016-07-17 00:39:12 +00003490 if (const auto *TD = dyn_cast<TypeDecl>(D))
David Blaikie6b7d060c2013-08-12 23:14:36 +00003491 return getOrCreateType(CGM.getContext().getTypeDeclType(TD),
David Blaikie99dab3b2013-09-04 22:03:57 +00003492 getOrCreateFile(TD->getLocation()));
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003493 auto I = DeclCache.find(D->getCanonicalDecl());
Frederic Rissd253ed62014-11-18 03:40:51 +00003494
Adrian Prantl5f4740d2016-12-20 02:10:02 +00003495 if (I != DeclCache.end()) {
3496 auto N = I->second;
3497 if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(N))
3498 return GVE->getVariable();
3499 return dyn_cast_or_null<llvm::DINode>(N);
3500 }
Frederic Rissd253ed62014-11-18 03:40:51 +00003501
3502 // No definition for now. Emit a forward definition that might be
3503 // merged with a potential upcoming definition.
David Majnemer58ed0f32016-07-17 00:39:12 +00003504 if (const auto *FD = dyn_cast<FunctionDecl>(D))
Frederic Rissd253ed62014-11-18 03:40:51 +00003505 return getFunctionForwardDeclaration(FD);
3506 else if (const auto *VD = dyn_cast<VarDecl>(D))
3507 return getGlobalVariableForwardDeclaration(VD);
3508
Duncan P. N. Exon Smith4078ad42015-04-16 16:36:45 +00003509 return nullptr;
David Blaikiebd483762013-05-20 04:58:53 +00003510}
3511
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003512llvm::DISubprogram *CGDebugInfo::getFunctionDeclaration(const Decl *D) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00003513 if (!D || DebugKind <= codegenoptions::DebugLineTablesOnly)
Duncan P. N. Exon Smitha7fbcbf2015-04-20 22:09:57 +00003514 return nullptr;
David Blaikie18cfbc52013-06-22 00:09:36 +00003515
David Majnemer58ed0f32016-07-17 00:39:12 +00003516 const auto *FD = dyn_cast<FunctionDecl>(D);
Eric Christophere7b87e52014-10-26 23:40:33 +00003517 if (!FD)
Duncan P. N. Exon Smitha7fbcbf2015-04-20 22:09:57 +00003518 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003519
3520 // Setup context.
Adrian Prantl6ec370a2015-09-10 18:39:45 +00003521 auto *S = getDeclContextDescriptor(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00003522
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003523 auto MI = SPCache.find(FD->getCanonicalDecl());
David Blaikiefd07c602013-08-09 17:20:05 +00003524 if (MI == SPCache.end()) {
David Majnemer58ed0f32016-07-17 00:39:12 +00003525 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {
Duncan P. N. Exon Smithc09c5482015-04-20 21:17:26 +00003526 return CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()),
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003527 cast<llvm::DICompositeType>(S));
David Blaikiefd07c602013-08-09 17:20:05 +00003528 }
3529 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003530 if (MI != SPCache.end()) {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003531 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
Duncan P. N. Exon Smith87afdeb2015-04-14 03:24:14 +00003532 if (SP && !SP->isDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00003533 return SP;
3534 }
3535
Aaron Ballman86c93902014-03-06 23:45:36 +00003536 for (auto NextFD : FD->redecls()) {
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003537 auto MI = SPCache.find(NextFD->getCanonicalDecl());
Guy Benyei11169dd2012-12-18 14:30:41 +00003538 if (MI != SPCache.end()) {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003539 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
Duncan P. N. Exon Smith87afdeb2015-04-14 03:24:14 +00003540 if (SP && !SP->isDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00003541 return SP;
3542 }
3543 }
Duncan P. N. Exon Smitha7fbcbf2015-04-20 22:09:57 +00003544 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003545}
3546
Adrian Prantl901cc4a2019-11-08 09:24:31 -08003547llvm::DISubprogram *CGDebugInfo::getObjCMethodDeclaration(
3548 const Decl *D, llvm::DISubroutineType *FnType, unsigned LineNo,
3549 llvm::DINode::DIFlags Flags, llvm::DISubprogram::DISPFlags SPFlags) {
3550 if (!D || DebugKind <= codegenoptions::DebugLineTablesOnly)
3551 return nullptr;
3552
Adrian Prantle0cabe22019-11-21 09:56:01 -08003553 const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
3554 if (!OMD)
3555 return nullptr;
3556
3557 if (CGM.getCodeGenOpts().DwarfVersion < 5 && !OMD->isDirectMethod())
Adrian Prantl901cc4a2019-11-08 09:24:31 -08003558 return nullptr;
3559
Raphael Isemannccfab8e2019-12-17 09:36:57 +01003560 if (OMD->isDirectMethod())
3561 SPFlags |= llvm::DISubprogram::SPFlagObjCDirect;
3562
Adrian Prantl901cc4a2019-11-08 09:24:31 -08003563 // Starting with DWARF V5 method declarations are emitted as children of
3564 // the interface type.
Adrian Prantl901cc4a2019-11-08 09:24:31 -08003565 auto *ID = dyn_cast_or_null<ObjCInterfaceDecl>(D->getDeclContext());
3566 if (!ID)
3567 ID = OMD->getClassInterface();
3568 if (!ID)
3569 return nullptr;
3570 QualType QTy(ID->getTypeForDecl(), 0);
3571 auto It = TypeCache.find(QTy.getAsOpaquePtr());
3572 if (It == TypeCache.end())
3573 return nullptr;
3574 auto *InterfaceType = cast<llvm::DICompositeType>(It->second);
3575 llvm::DISubprogram *FD = DBuilder.createFunction(
3576 InterfaceType, getObjCMethodName(OMD), StringRef(),
3577 InterfaceType->getFile(), LineNo, FnType, LineNo, Flags, SPFlags);
3578 DBuilder.finalizeSubprogram(FD);
Adrian Prantle0cabe22019-11-21 09:56:01 -08003579 ObjCMethodCache[ID].push_back({FD, OMD->isDirectMethod()});
Adrian Prantl901cc4a2019-11-08 09:24:31 -08003580 return FD;
3581}
3582
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00003583// getOrCreateFunctionType - Construct type. If it is a c++ method, include
Guy Benyei11169dd2012-12-18 14:30:41 +00003584// implicit parameter "this".
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003585llvm::DISubroutineType *CGDebugInfo::getOrCreateFunctionType(const Decl *D,
Duncan P. N. Exon Smith4078ad42015-04-16 16:36:45 +00003586 QualType FnType,
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003587 llvm::DIFile *F) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00003588 if (!D || DebugKind <= codegenoptions::DebugLineTablesOnly)
Duncan P. N. Exon Smitha7fbcbf2015-04-20 22:09:57 +00003589 // Create fake but valid subroutine type. Otherwise -verify would fail, and
3590 // subprogram DIE will miss DW_AT_decl_file and DW_AT_decl_line fields.
Eric Christopher28a6db52015-10-15 06:56:08 +00003591 return DBuilder.createSubroutineType(DBuilder.getOrCreateTypeArray(None));
Guy Benyei11169dd2012-12-18 14:30:41 +00003592
David Majnemer58ed0f32016-07-17 00:39:12 +00003593 if (const auto *Method = dyn_cast<CXXMethodDecl>(D))
Awanish Pandeyc83602f2020-01-23 16:06:52 +05303594 return getOrCreateMethodType(Method, F, false);
Reid Klecknerf00f8032016-06-08 20:41:54 +00003595
3596 const auto *FTy = FnType->getAs<FunctionType>();
3597 CallingConv CC = FTy ? FTy->getCallConv() : CallingConv::CC_C;
3598
David Majnemer58ed0f32016-07-17 00:39:12 +00003599 if (const auto *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003600 // Add "self" and "_cmd"
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003601 SmallVector<llvm::Metadata *, 16> Elts;
Guy Benyei11169dd2012-12-18 14:30:41 +00003602
3603 // First element is always return type. For 'void' functions it is NULL.
Alp Toker314cc812014-01-25 16:55:45 +00003604 QualType ResultTy = OMethod->getReturnType();
Adrian Prantl5f360102013-05-22 21:37:49 +00003605
3606 // Replace the instancetype keyword with the actual type.
3607 if (ResultTy == CGM.getContext().getObjCInstanceType())
3608 ResultTy = CGM.getContext().getPointerType(
Eric Christophere7b87e52014-10-26 23:40:33 +00003609 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
Adrian Prantl5f360102013-05-22 21:37:49 +00003610
Adrian Prantl7bec9032013-05-10 21:08:31 +00003611 Elts.push_back(getOrCreateType(ResultTy, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00003612 // "self" pointer is always first argument.
Adrian Prantl748a6cd2015-09-08 20:41:52 +00003613 QualType SelfDeclTy;
3614 if (auto *SelfDecl = OMethod->getSelfDecl())
3615 SelfDeclTy = SelfDecl->getType();
3616 else if (auto *FPT = dyn_cast<FunctionProtoType>(FnType))
3617 if (FPT->getNumParams() > 1)
3618 SelfDeclTy = FPT->getParamType(0);
3619 if (!SelfDeclTy.isNull())
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00003620 Elts.push_back(
3621 CreateSelfType(SelfDeclTy, getOrCreateType(SelfDeclTy, F)));
Guy Benyei11169dd2012-12-18 14:30:41 +00003622 // "_cmd" pointer is always second argument.
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00003623 Elts.push_back(DBuilder.createArtificialType(
Adrian Prantl748a6cd2015-09-08 20:41:52 +00003624 getOrCreateType(CGM.getContext().getObjCSelType(), F)));
Guy Benyei11169dd2012-12-18 14:30:41 +00003625 // Get rest of the arguments.
David Majnemer59f77922016-06-24 04:05:48 +00003626 for (const auto *PI : OMethod->parameters())
Aaron Ballman43b68be2014-03-07 17:50:17 +00003627 Elts.push_back(getOrCreateType(PI->getType(), F));
Frederic Riss787d9d62014-08-12 04:42:23 +00003628 // Variadic methods need a special marker at the end of the type list.
3629 if (OMethod->isVariadic())
3630 Elts.push_back(DBuilder.createUnspecifiedParameter());
Guy Benyei11169dd2012-12-18 14:30:41 +00003631
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003632 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
Leny Kholodov80c047d2016-09-06 10:48:04 +00003633 return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
3634 getDwarfCC(CC));
Guy Benyei11169dd2012-12-18 14:30:41 +00003635 }
Adrian Prantld45ba252014-02-25 19:38:11 +00003636
Adrian Prantl800faef2014-02-25 23:42:18 +00003637 // Handle variadic function types; they need an additional
3638 // unspecified parameter.
David Majnemer58ed0f32016-07-17 00:39:12 +00003639 if (const auto *FD = dyn_cast<FunctionDecl>(D))
Adrian Prantld45ba252014-02-25 19:38:11 +00003640 if (FD->isVariadic()) {
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003641 SmallVector<llvm::Metadata *, 16> EltTys;
Adrian Prantld45ba252014-02-25 19:38:11 +00003642 EltTys.push_back(getOrCreateType(FD->getReturnType(), F));
David Majnemer58ed0f32016-07-17 00:39:12 +00003643 if (const auto *FPT = dyn_cast<FunctionProtoType>(FnType))
3644 for (QualType ParamType : FPT->param_types())
3645 EltTys.push_back(getOrCreateType(ParamType, F));
Adrian Prantld45ba252014-02-25 19:38:11 +00003646 EltTys.push_back(DBuilder.createUnspecifiedParameter());
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003647 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
Leny Kholodov80c047d2016-09-06 10:48:04 +00003648 return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
3649 getDwarfCC(CC));
Adrian Prantld45ba252014-02-25 19:38:11 +00003650 }
3651
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003652 return cast<llvm::DISubroutineType>(getOrCreateType(FnType, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00003653}
3654
Eric Christophere7b87e52014-10-26 23:40:33 +00003655void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, SourceLocation Loc,
3656 SourceLocation ScopeLoc, QualType FnType,
Brock Wyma94ece8f2018-04-16 16:53:57 +00003657 llvm::Function *Fn, bool CurFuncIsThunk,
3658 CGBuilderTy &Builder) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003659
3660 StringRef Name;
3661 StringRef LinkageName;
3662
3663 FnBeginRegionCount.push_back(LexicalBlockStack.size());
3664
3665 const Decl *D = GD.getDecl();
Craig Topper8a13c412014-05-21 05:09:00 +00003666 bool HasDecl = (D != nullptr);
Eric Christopher885c41b2014-04-01 22:25:28 +00003667
Leny Kholodov80c047d2016-09-06 10:48:04 +00003668 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
Paul Robinsoncda54212018-11-19 18:29:28 +00003669 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003670 llvm::DIFile *Unit = getOrCreateFile(Loc);
3671 llvm::DIScope *FDContext = Unit;
3672 llvm::DINodeArray TParamsArray;
Guy Benyei11169dd2012-12-18 14:30:41 +00003673 if (!HasDecl) {
3674 // Use llvm function name.
David Blaikieebe87e12013-08-27 23:57:18 +00003675 LinkageName = Fn->getName();
David Majnemer58ed0f32016-07-17 00:39:12 +00003676 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Duncan P. N. Exon Smitha7fbcbf2015-04-20 22:09:57 +00003677 // If there is a subprogram for this function available then use it.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003678 auto FI = SPCache.find(FD->getCanonicalDecl());
Guy Benyei11169dd2012-12-18 14:30:41 +00003679 if (FI != SPCache.end()) {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003680 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
Duncan P. N. Exon Smith87afdeb2015-04-14 03:24:14 +00003681 if (SP && SP->isDefinition()) {
Duncan P. N. Exon Smithd899f6e2015-04-18 00:07:30 +00003682 LexicalBlockStack.emplace_back(SP);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003683 RegionMap[D].reset(SP);
Guy Benyei11169dd2012-12-18 14:30:41 +00003684 return;
3685 }
3686 }
Frederic Riss9db79f12014-11-18 03:40:46 +00003687 collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
3688 TParamsArray, Flags);
David Majnemer58ed0f32016-07-17 00:39:12 +00003689 } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003690 Name = getObjCMethodName(OMD);
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003691 Flags |= llvm::DINode::FlagPrototyped;
Reid Kleckner105c5652019-04-24 22:45:44 +00003692 } else if (isa<VarDecl>(D) &&
3693 GD.getDynamicInitKind() != DynamicInitKind::NoStub) {
3694 // This is a global initializer or atexit destructor for a global variable.
3695 Name = getDynamicInitializerName(cast<VarDecl>(D), GD.getDynamicInitKind(),
3696 Fn);
Guy Benyei11169dd2012-12-18 14:30:41 +00003697 } else {
Guy Benyei11169dd2012-12-18 14:30:41 +00003698 Name = Fn->getName();
shafik428583d2020-02-05 10:39:35 -08003699
Michael Liao318d0ed2020-02-06 12:19:55 -05003700 if (isa<BlockDecl>(D))
shafik428583d2020-02-05 10:39:35 -08003701 LinkageName = Name;
3702
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003703 Flags |= llvm::DINode::FlagPrototyped;
Guy Benyei11169dd2012-12-18 14:30:41 +00003704 }
David Majnemer58ed0f32016-07-17 00:39:12 +00003705 if (Name.startswith("\01"))
Guy Benyei11169dd2012-12-18 14:30:41 +00003706 Name = Name.substr(1);
3707
Alexandre Ganeacaf31662019-11-15 16:21:17 -05003708 if (!HasDecl || D->isImplicit() || D->hasAttr<ArtificialAttr>()) {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003709 Flags |= llvm::DINode::FlagArtificial;
Adrian Prantldb763572016-11-09 21:43:51 +00003710 // Artificial functions should not silently reuse CurLoc.
3711 CurLoc = SourceLocation();
Adrian Prantl42d71b92014-04-10 23:21:53 +00003712 }
Brock Wyma94ece8f2018-04-16 16:53:57 +00003713
3714 if (CurFuncIsThunk)
3715 Flags |= llvm::DINode::FlagThunk;
3716
Paul Robinsoncda54212018-11-19 18:29:28 +00003717 if (Fn->hasLocalLinkage())
3718 SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;
3719 if (CGM.getLangOpts().Optimize)
3720 SPFlags |= llvm::DISubprogram::SPFlagOptimized;
3721
Vedant Kumar5931b4e2018-10-05 20:37:17 +00003722 llvm::DINode::DIFlags FlagsForDef = Flags | getCallSiteRelatedAttrs();
Paul Robinsoncda54212018-11-19 18:29:28 +00003723 llvm::DISubprogram::DISPFlags SPFlagsForDef =
3724 SPFlags | llvm::DISubprogram::SPFlagDefinition;
Vedant Kumar5931b4e2018-10-05 20:37:17 +00003725
Adrian Prantl42d71b92014-04-10 23:21:53 +00003726 unsigned LineNo = getLineNumber(Loc);
3727 unsigned ScopeLine = getLineNumber(ScopeLoc);
Adrian Prantl901cc4a2019-11-08 09:24:31 -08003728 llvm::DISubroutineType *DIFnType = getOrCreateFunctionType(D, FnType, Unit);
3729 llvm::DISubprogram *Decl = nullptr;
3730 if (D)
3731 Decl = isa<ObjCMethodDecl>(D)
3732 ? getObjCMethodDeclaration(D, DIFnType, LineNo, Flags, SPFlags)
3733 : getFunctionDeclaration(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00003734
Eric Christopher8018e412014-03-27 18:50:35 +00003735 // FIXME: The function declaration we're constructing here is mostly reusing
3736 // declarations from CXXMethodDecl and not constructing new ones for arbitrary
3737 // FunctionDecls. When/if we fix this we can have FDContext be TheCU/null for
3738 // all subprograms instead of the actual context since subprogram definitions
3739 // are emitted as CU level entities by the backend.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003740 llvm::DISubprogram *SP = DBuilder.createFunction(
Adrian Prantl901cc4a2019-11-08 09:24:31 -08003741 FDContext, Name, LinkageName, Unit, LineNo, DIFnType, ScopeLine,
3742 FlagsForDef, SPFlagsForDef, TParamsArray.get(), Decl);
Peter Collingbourne0900fe02015-11-05 22:04:14 +00003743 Fn->setSubprogram(SP);
Frederic Rissb1ab28c2014-11-05 19:19:04 +00003744 // We might get here with a VarDecl in the case we're generating
3745 // code for the initialization of globals. Do not record these decls
3746 // as they will overwrite the actual VarDecl Decl in the cache.
3747 if (HasDecl && isa<FunctionDecl>(D))
David Majnemer58ed0f32016-07-17 00:39:12 +00003748 DeclCache[D->getCanonicalDecl()].reset(SP);
Guy Benyei11169dd2012-12-18 14:30:41 +00003749
Adrian Prantlbebb8932014-03-21 21:01:58 +00003750 // Push the function onto the lexical block stack.
Duncan P. N. Exon Smithd899f6e2015-04-18 00:07:30 +00003751 LexicalBlockStack.emplace_back(SP);
Adrian Prantlbebb8932014-03-21 21:01:58 +00003752
Guy Benyei11169dd2012-12-18 14:30:41 +00003753 if (HasDecl)
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003754 RegionMap[D].reset(SP);
Guy Benyei11169dd2012-12-18 14:30:41 +00003755}
3756
Vedant Kumar8bd52142019-07-11 19:28:07 +00003757void CGDebugInfo::EmitFunctionDecl(GlobalDecl GD, SourceLocation Loc,
3758 QualType FnType, llvm::Function *Fn) {
Adrian Prantl748a6cd2015-09-08 20:41:52 +00003759 StringRef Name;
3760 StringRef LinkageName;
3761
3762 const Decl *D = GD.getDecl();
3763 if (!D)
Vedant Kumar8bd52142019-07-11 19:28:07 +00003764 return;
Adrian Prantl748a6cd2015-09-08 20:41:52 +00003765
Luboš Luňák4f2104c2019-11-02 16:39:59 +01003766 llvm::TimeTraceScope TimeScope("DebugFunction", [&]() {
3767 std::string Name;
3768 llvm::raw_string_ostream OS(Name);
3769 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
3770 ND->getNameForDiagnostic(OS, getPrintingPolicy(),
3771 /*Qualified=*/true);
3772 return Name;
3773 });
3774
Leny Kholodov80c047d2016-09-06 10:48:04 +00003775 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
Adrian Prantl748a6cd2015-09-08 20:41:52 +00003776 llvm::DIFile *Unit = getOrCreateFile(Loc);
Vedant Kumar8bd52142019-07-11 19:28:07 +00003777 bool IsDeclForCallSite = Fn ? true : false;
Djordje Todorovic0f651682019-06-27 06:44:44 +00003778 llvm::DIScope *FDContext =
3779 IsDeclForCallSite ? Unit : getDeclContextDescriptor(D);
Adrian Prantl748a6cd2015-09-08 20:41:52 +00003780 llvm::DINodeArray TParamsArray;
3781 if (isa<FunctionDecl>(D)) {
3782 // If there is a DISubprogram for this function available then use it.
3783 collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
3784 TParamsArray, Flags);
David Majnemer58ed0f32016-07-17 00:39:12 +00003785 } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) {
Adrian Prantl748a6cd2015-09-08 20:41:52 +00003786 Name = getObjCMethodName(OMD);
3787 Flags |= llvm::DINode::FlagPrototyped;
3788 } else {
3789 llvm_unreachable("not a function or ObjC method");
3790 }
3791 if (!Name.empty() && Name[0] == '\01')
3792 Name = Name.substr(1);
3793
3794 if (D->isImplicit()) {
3795 Flags |= llvm::DINode::FlagArtificial;
3796 // Artificial functions without a location should not silently reuse CurLoc.
3797 if (Loc.isInvalid())
3798 CurLoc = SourceLocation();
3799 }
3800 unsigned LineNo = getLineNumber(Loc);
3801 unsigned ScopeLine = 0;
Paul Robinsoncda54212018-11-19 18:29:28 +00003802 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
3803 if (CGM.getLangOpts().Optimize)
3804 SPFlags |= llvm::DISubprogram::SPFlagOptimized;
Adrian Prantl748a6cd2015-09-08 20:41:52 +00003805
Djordje Todorovic0f651682019-06-27 06:44:44 +00003806 llvm::DISubprogram *SP = DBuilder.createFunction(
Adrian Prantle76bda52016-04-15 15:55:45 +00003807 FDContext, Name, LinkageName, Unit, LineNo,
Paul Robinsoncda54212018-11-19 18:29:28 +00003808 getOrCreateFunctionType(D, FnType, Unit), ScopeLine, Flags, SPFlags,
Djordje Todorovic0f651682019-06-27 06:44:44 +00003809 TParamsArray.get(), getFunctionDeclaration(D));
Vedant Kumar8bd52142019-07-11 19:28:07 +00003810
3811 if (IsDeclForCallSite)
3812 Fn->setSubprogram(SP);
3813
Djordje Todorovic0f651682019-06-27 06:44:44 +00003814 DBuilder.retainType(SP);
3815}
3816
3817void CGDebugInfo::EmitFuncDeclForCallSite(llvm::CallBase *CallOrInvoke,
3818 QualType CalleeType,
3819 const FunctionDecl *CalleeDecl) {
Vedant Kumar568db782019-11-13 18:19:32 -08003820 if (!CallOrInvoke)
Djordje Todorovic0f651682019-06-27 06:44:44 +00003821 return;
Djordje Todorovic0f651682019-06-27 06:44:44 +00003822 auto *Func = CallOrInvoke->getCalledFunction();
3823 if (!Func)
3824 return;
Vedant Kumar568db782019-11-13 18:19:32 -08003825 if (Func->getSubprogram())
3826 return;
3827
3828 // Do not emit a declaration subprogram for a builtin or if call site info
3829 // isn't required. Also, elide declarations for functions with reserved names,
3830 // as call site-related features aren't interesting in this case (& also, the
3831 // compiler may emit calls to these functions without debug locations, which
3832 // makes the verifier complain).
3833 if (CalleeDecl->getBuiltinID() != 0 ||
3834 getCallSiteRelatedAttrs() == llvm::DINode::FlagZero)
3835 return;
3836 if (const auto *Id = CalleeDecl->getIdentifier())
3837 if (Id->isReservedName())
3838 return;
Djordje Todorovic0f651682019-06-27 06:44:44 +00003839
3840 // If there is no DISubprogram attached to the function being called,
3841 // create the one describing the function in order to have complete
3842 // call site debug info.
Vedant Kumar8bd52142019-07-11 19:28:07 +00003843 if (!CalleeDecl->isStatic() && !CalleeDecl->isInlined())
Michael Liao4cf01ed2020-03-18 01:43:20 -04003844 EmitFunctionDecl(CalleeDecl, CalleeDecl->getLocation(), CalleeType, Func);
Adrian Prantl748a6cd2015-09-08 20:41:52 +00003845}
3846
Adrian Prantlb7acfc02017-02-27 21:30:05 +00003847void CGDebugInfo::EmitInlineFunctionStart(CGBuilderTy &Builder, GlobalDecl GD) {
3848 const auto *FD = cast<FunctionDecl>(GD.getDecl());
3849 // If there is a subprogram for this function available then use it.
3850 auto FI = SPCache.find(FD->getCanonicalDecl());
3851 llvm::DISubprogram *SP = nullptr;
3852 if (FI != SPCache.end())
3853 SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
Adrian Prantl8040a212017-08-23 21:24:12 +00003854 if (!SP || !SP->isDefinition())
Adrian Prantlb7acfc02017-02-27 21:30:05 +00003855 SP = getFunctionStub(GD);
3856 FnBeginRegionCount.push_back(LexicalBlockStack.size());
3857 LexicalBlockStack.emplace_back(SP);
3858 setInlinedAt(Builder.getCurrentDebugLocation());
3859 EmitLocation(Builder, FD->getLocation());
3860}
3861
3862void CGDebugInfo::EmitInlineFunctionEnd(CGBuilderTy &Builder) {
3863 assert(CurInlinedAt && "unbalanced inline scope stack");
Keno Fischer41d4b4e2017-06-01 21:14:03 +00003864 EmitFunctionEnd(Builder, nullptr);
Adrian Prantlb7acfc02017-02-27 21:30:05 +00003865 setInlinedAt(llvm::DebugLoc(CurInlinedAt).getInlinedAt());
3866}
3867
Calixte Denizetfcd661d2018-09-24 18:24:18 +00003868void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003869 // Update our current location
3870 setLocation(Loc);
3871
Adrian Prantl42ab39f2018-11-09 21:17:38 +00003872 if (CurLoc.isInvalid() || CurLoc.isMacroID() || LexicalBlockStack.empty())
Eric Christophere7b87e52014-10-26 23:40:33 +00003873 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00003874
Adrian Prantle83b1302014-01-07 22:05:52 +00003875 llvm::MDNode *Scope = LexicalBlockStack.back();
Calixte Denizetfcd661d2018-09-24 18:24:18 +00003876 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(
3877 getLineNumber(CurLoc), getColumnNumber(CurLoc), Scope, CurInlinedAt));
Guy Benyei11169dd2012-12-18 14:30:41 +00003878}
3879
Guy Benyei11169dd2012-12-18 14:30:41 +00003880void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
Duncan P. N. Exon Smitha66e3052014-12-09 19:22:40 +00003881 llvm::MDNode *Back = nullptr;
3882 if (!LexicalBlockStack.empty())
3883 Back = LexicalBlockStack.back().get();
Duncan P. N. Exon Smithd899f6e2015-04-18 00:07:30 +00003884 LexicalBlockStack.emplace_back(DBuilder.createLexicalBlock(
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003885 cast<llvm::DIScope>(Back), getOrCreateFile(CurLoc), getLineNumber(CurLoc),
Duncan P. N. Exon Smithd899f6e2015-04-18 00:07:30 +00003886 getColumnNumber(CurLoc)));
Guy Benyei11169dd2012-12-18 14:30:41 +00003887}
3888
Konstantin Zhuravlyov2b4917f2017-03-09 18:06:23 +00003889void CGDebugInfo::AppendAddressSpaceXDeref(
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00003890 unsigned AddressSpace, SmallVectorImpl<int64_t> &Expr) const {
Konstantin Zhuravlyov2b4917f2017-03-09 18:06:23 +00003891 Optional<unsigned> DWARFAddressSpace =
3892 CGM.getTarget().getDWARFAddressSpace(AddressSpace);
3893 if (!DWARFAddressSpace)
3894 return;
3895
3896 Expr.push_back(llvm::dwarf::DW_OP_constu);
3897 Expr.push_back(DWARFAddressSpace.getValue());
3898 Expr.push_back(llvm::dwarf::DW_OP_swap);
3899 Expr.push_back(llvm::dwarf::DW_OP_xderef);
3900}
3901
Eric Christopher0fdcb312013-05-16 00:52:20 +00003902void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
3903 SourceLocation Loc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003904 // Set our current location.
3905 setLocation(Loc);
3906
Guy Benyei11169dd2012-12-18 14:30:41 +00003907 // Emit a line table change for the current location inside the new scope.
Adrian Prantlb7acfc02017-02-27 21:30:05 +00003908 Builder.SetCurrentDebugLocation(
3909 llvm::DebugLoc::get(getLineNumber(Loc), getColumnNumber(Loc),
3910 LexicalBlockStack.back(), CurInlinedAt));
David Blaikie60a877b2014-10-22 19:34:33 +00003911
Benjamin Kramer8c305922016-02-02 11:06:51 +00003912 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
David Blaikie60a877b2014-10-22 19:34:33 +00003913 return;
3914
3915 // Create a new lexical block and push it on the stack.
3916 CreateLexicalBlock(Loc);
Guy Benyei11169dd2012-12-18 14:30:41 +00003917}
3918
Eric Christopher0fdcb312013-05-16 00:52:20 +00003919void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
3920 SourceLocation Loc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003921 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
3922
3923 // Provide an entry in the line table for the end of the block.
Calixte Denizetfcd661d2018-09-24 18:24:18 +00003924 EmitLocation(Builder, Loc);
Guy Benyei11169dd2012-12-18 14:30:41 +00003925
Benjamin Kramer8c305922016-02-02 11:06:51 +00003926 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
David Blaikie60a877b2014-10-22 19:34:33 +00003927 return;
3928
Guy Benyei11169dd2012-12-18 14:30:41 +00003929 LexicalBlockStack.pop_back();
3930}
3931
Keno Fischer41d4b4e2017-06-01 21:14:03 +00003932void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder, llvm::Function *Fn) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003933 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
3934 unsigned RCount = FnBeginRegionCount.back();
3935 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
3936
3937 // Pop all regions for this function.
David Blaikie60a877b2014-10-22 19:34:33 +00003938 while (LexicalBlockStack.size() != RCount) {
3939 // Provide an entry in the line table for the end of the block.
Calixte Denizetfcd661d2018-09-24 18:24:18 +00003940 EmitLocation(Builder, CurLoc);
David Blaikie60a877b2014-10-22 19:34:33 +00003941 LexicalBlockStack.pop_back();
3942 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003943 FnBeginRegionCount.pop_back();
Keno Fischer41d4b4e2017-06-01 21:14:03 +00003944
3945 if (Fn && Fn->getSubprogram())
3946 DBuilder.finalizeSubprogram(Fn->getSubprogram());
Guy Benyei11169dd2012-12-18 14:30:41 +00003947}
3948
Adrian Prantl05a623e2018-09-10 16:14:28 +00003949CGDebugInfo::BlockByRefType
3950CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
3951 uint64_t *XOffset) {
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003952 SmallVector<llvm::Metadata *, 5> EltTys;
Guy Benyei11169dd2012-12-18 14:30:41 +00003953 QualType FType;
3954 uint64_t FieldSize, FieldOffset;
Victor Leschuk802e4a52016-10-19 22:11:07 +00003955 uint32_t FieldAlign;
Eric Christopherb2a008c2013-05-16 00:45:12 +00003956
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003957 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
Eric Christopherb2a008c2013-05-16 00:45:12 +00003958 QualType Type = VD->getType();
Guy Benyei11169dd2012-12-18 14:30:41 +00003959
3960 FieldOffset = 0;
3961 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
3962 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
3963 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
3964 FType = CGM.getContext().IntTy;
3965 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
3966 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
3967
3968 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
3969 if (HasCopyAndDispose) {
3970 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
Eric Christophere7b87e52014-10-26 23:40:33 +00003971 EltTys.push_back(
3972 CreateMemberType(Unit, FType, "__copy_helper", &FieldOffset));
3973 EltTys.push_back(
3974 CreateMemberType(Unit, FType, "__destroy_helper", &FieldOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00003975 }
3976 bool HasByrefExtendedLayout;
3977 Qualifiers::ObjCLifetime Lifetime;
Eric Christophere7b87e52014-10-26 23:40:33 +00003978 if (CGM.getContext().getByrefLifetime(Type, Lifetime,
3979 HasByrefExtendedLayout) &&
3980 HasByrefExtendedLayout) {
Adrian Prantlead2ba42013-07-23 00:12:14 +00003981 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
Eric Christophere7b87e52014-10-26 23:40:33 +00003982 EltTys.push_back(
3983 CreateMemberType(Unit, FType, "__byref_variable_layout", &FieldOffset));
Adrian Prantlead2ba42013-07-23 00:12:14 +00003984 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00003985
Guy Benyei11169dd2012-12-18 14:30:41 +00003986 CharUnits Align = CGM.getContext().getDeclAlign(VD);
3987 if (Align > CGM.getContext().toCharUnitsFromBits(
Eric Christophere7b87e52014-10-26 23:40:33 +00003988 CGM.getTarget().getPointerAlign(0))) {
3989 CharUnits FieldOffsetInBytes =
3990 CGM.getContext().toCharUnitsFromBits(FieldOffset);
Rui Ueyama83aa9792016-01-14 21:00:27 +00003991 CharUnits AlignedOffsetInBytes = FieldOffsetInBytes.alignTo(Align);
Eric Christophere7b87e52014-10-26 23:40:33 +00003992 CharUnits NumPaddingBytes = AlignedOffsetInBytes - FieldOffsetInBytes;
Eric Christopherb2a008c2013-05-16 00:45:12 +00003993
Guy Benyei11169dd2012-12-18 14:30:41 +00003994 if (NumPaddingBytes.isPositive()) {
3995 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
Richard Smith772e2662019-10-04 01:25:59 +00003996 FType = CGM.getContext().getConstantArrayType(
3997 CGM.getContext().CharTy, pad, nullptr, ArrayType::Normal, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00003998 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
3999 }
4000 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00004001
Guy Benyei11169dd2012-12-18 14:30:41 +00004002 FType = Type;
Adrian Prantl05a623e2018-09-10 16:14:28 +00004003 llvm::DIType *WrappedTy = getOrCreateType(FType, Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00004004 FieldSize = CGM.getContext().getTypeSize(FType);
4005 FieldAlign = CGM.getContext().toBits(Align);
4006
Eric Christopherb2a008c2013-05-16 00:45:12 +00004007 *XOffset = FieldOffset;
Adrian Prantl05a623e2018-09-10 16:14:28 +00004008 llvm::DIType *FieldTy = DBuilder.createMemberType(
4009 Unit, VD->getName(), Unit, 0, FieldSize, FieldAlign, FieldOffset,
4010 llvm::DINode::FlagZero, WrappedTy);
Guy Benyei11169dd2012-12-18 14:30:41 +00004011 EltTys.push_back(FieldTy);
4012 FieldOffset += FieldSize;
Eric Christopherb2a008c2013-05-16 00:45:12 +00004013
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004014 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
Adrian Prantl05a623e2018-09-10 16:14:28 +00004015 return {DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0,
4016 llvm::DINode::FlagZero, nullptr, Elements),
4017 WrappedTy};
Guy Benyei11169dd2012-12-18 14:30:41 +00004018}
4019
Sander de Smalen891af03a2018-02-03 13:55:59 +00004020llvm::DILocalVariable *CGDebugInfo::EmitDeclare(const VarDecl *VD,
4021 llvm::Value *Storage,
4022 llvm::Optional<unsigned> ArgNo,
Amy Huang7fac5c82019-06-20 17:15:21 +00004023 CGBuilderTy &Builder,
4024 const bool UsePointerValue) {
Amy Huang53539bb2020-01-13 15:54:54 -08004025 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00004026 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
Paul Robinsonafd2dde2016-06-16 00:42:36 +00004027 if (VD->hasAttr<NoDebugAttr>())
Sander de Smalen891af03a2018-02-03 13:55:59 +00004028 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004029
David Blaikie7fceebf2013-08-19 03:37:48 +00004030 bool Unwritten =
4031 VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) &&
4032 cast<Decl>(VD->getDeclContext())->isImplicit());
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004033 llvm::DIFile *Unit = nullptr;
David Blaikie7fceebf2013-08-19 03:37:48 +00004034 if (!Unwritten)
4035 Unit = getOrCreateFile(VD->getLocation());
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004036 llvm::DIType *Ty;
Guy Benyei11169dd2012-12-18 14:30:41 +00004037 uint64_t XOffset = 0;
4038 if (VD->hasAttr<BlocksAttr>())
Adrian Prantl05a623e2018-09-10 16:14:28 +00004039 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset).WrappedType;
Eric Christopherb2a008c2013-05-16 00:45:12 +00004040 else
Guy Benyei11169dd2012-12-18 14:30:41 +00004041 Ty = getOrCreateType(VD->getType(), Unit);
4042
4043 // If there is no debug info for this type then do not emit debug info
4044 // for this variable.
4045 if (!Ty)
Sander de Smalen891af03a2018-02-03 13:55:59 +00004046 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004047
Guy Benyei11169dd2012-12-18 14:30:41 +00004048 // Get location information.
David Blaikie7fceebf2013-08-19 03:37:48 +00004049 unsigned Line = 0;
4050 unsigned Column = 0;
4051 if (!Unwritten) {
4052 Line = getLineNumber(VD->getLocation());
4053 Column = getColumnNumber(VD->getLocation());
4054 }
Konstantin Zhuravlyov2b4917f2017-03-09 18:06:23 +00004055 SmallVector<int64_t, 13> Expr;
Leny Kholodov80c047d2016-09-06 10:48:04 +00004056 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
Guy Benyei11169dd2012-12-18 14:30:41 +00004057 if (VD->isImplicit())
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004058 Flags |= llvm::DINode::FlagArtificial;
Victor Leschuka7ece032016-10-20 00:13:19 +00004059
4060 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
4061
Konstantin Zhuravlyov2b4917f2017-03-09 18:06:23 +00004062 unsigned AddressSpace = CGM.getContext().getTargetAddressSpace(VD->getType());
4063 AppendAddressSpaceXDeref(AddressSpace, Expr);
4064
Alexey Bataev24f710182017-06-09 13:55:08 +00004065 // If this is implicit parameter of CXXThis or ObjCSelf kind, then give it an
4066 // object pointer flag.
Alexey Bataev56223232017-06-09 13:40:18 +00004067 if (const auto *IPD = dyn_cast<ImplicitParamDecl>(VD)) {
4068 if (IPD->getParameterKind() == ImplicitParamDecl::CXXThis ||
4069 IPD->getParameterKind() == ImplicitParamDecl::ObjCSelf)
4070 Flags |= llvm::DINode::FlagObjectPointer;
4071 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004072
Adrian Prantlc3782a12017-04-18 01:22:01 +00004073 // Note: Older versions of clang used to emit byval references with an extra
4074 // DW_OP_deref, because they referenced the IR arg directly instead of
4075 // referencing an alloca. Newer versions of LLVM don't treat allocas
4076 // differently from other function arguments when used in a dbg.declare.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004077 auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
Guy Benyei11169dd2012-12-18 14:30:41 +00004078 StringRef Name = VD->getName();
4079 if (!Name.empty()) {
4080 if (VD->hasAttr<BlocksAttr>()) {
Adrian Prantlc3782a12017-04-18 01:22:01 +00004081 // Here, we need an offset *into* the alloca.
Guy Benyei11169dd2012-12-18 14:30:41 +00004082 CharUnits offset = CharUnits::fromQuantity(32);
Florian Hahn3dbcced2017-06-13 18:06:15 +00004083 Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
Guy Benyei11169dd2012-12-18 14:30:41 +00004084 // offset of __forwarding field
4085 offset = CGM.getContext().toCharUnitsFromBits(
Eric Christophere7b87e52014-10-26 23:40:33 +00004086 CGM.getTarget().getPointerWidth(0));
Adrian Prantl7c6f9442015-01-19 17:51:58 +00004087 Expr.push_back(offset.getQuantity());
4088 Expr.push_back(llvm::dwarf::DW_OP_deref);
Florian Hahn3dbcced2017-06-13 18:06:15 +00004089 Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
Guy Benyei11169dd2012-12-18 14:30:41 +00004090 // offset of x field
4091 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
Adrian Prantl7c6f9442015-01-19 17:51:58 +00004092 Expr.push_back(offset.getQuantity());
Adrian Prantlc3782a12017-04-18 01:22:01 +00004093 }
David Majnemer58ed0f32016-07-17 00:39:12 +00004094 } else if (const auto *RT = dyn_cast<RecordType>(VD->getType())) {
Adrian Prantl0d820892015-04-29 15:05:50 +00004095 // If VD is an anonymous union then Storage represents value for
4096 // all union fields.
George Burgess IV00f70bd2018-03-01 05:43:23 +00004097 const RecordDecl *RD = RT->getDecl();
Adrian Prantl0d820892015-04-29 15:05:50 +00004098 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
Adrian Prantl00820ab2015-04-29 16:52:31 +00004099 // GDB has trouble finding local variables in anonymous unions, so we emit
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004100 // artificial local variables for each of the members.
Adrian Prantl00820ab2015-04-29 16:52:31 +00004101 //
4102 // FIXME: Remove this code as soon as GDB supports this.
4103 // The debug info verifier in LLVM operates based on the assumption that a
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004104 // variable has the same size as its storage and we had to disable the
4105 // check for artificial variables.
Adrian Prantl0d820892015-04-29 15:05:50 +00004106 for (const auto *Field : RD->fields()) {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004107 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
Adrian Prantl0d820892015-04-29 15:05:50 +00004108 StringRef FieldName = Field->getName();
4109
4110 // Ignore unnamed fields. Do not ignore unnamed records.
4111 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
4112 continue;
4113
4114 // Use VarDecl's Tag, Scope and Line number.
Victor Leschuka7ece032016-10-20 00:13:19 +00004115 auto FieldAlign = getDeclAlignIfRequired(Field, CGM.getContext());
Duncan P. N. Exon Smithe4306542015-07-31 17:56:14 +00004116 auto *D = DBuilder.createAutoVariable(
4117 Scope, FieldName, Unit, Line, FieldTy, CGM.getLangOpts().Optimize,
Victor Leschuka7ece032016-10-20 00:13:19 +00004118 Flags | llvm::DINode::FlagArtificial, FieldAlign);
Adrian Prantl0d820892015-04-29 15:05:50 +00004119
4120 // Insert an llvm.dbg.declare into the current block.
Adrian Prantlb7acfc02017-02-27 21:30:05 +00004121 DBuilder.insertDeclare(
4122 Storage, D, DBuilder.createExpression(Expr),
4123 llvm::DebugLoc::get(Line, Column, Scope, CurInlinedAt),
4124 Builder.GetInsertBlock());
Adrian Prantl0d820892015-04-29 15:05:50 +00004125 }
Adrian Prantl0d820892015-04-29 15:05:50 +00004126 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004127 }
David Blaikiea76a7c92013-01-05 05:58:35 +00004128
Amy Huang7fac5c82019-06-20 17:15:21 +00004129 // Clang stores the sret pointer provided by the caller in a static alloca.
4130 // Use DW_OP_deref to tell the debugger to load the pointer and treat it as
4131 // the address of the variable.
4132 if (UsePointerValue) {
4133 assert(std::find(Expr.begin(), Expr.end(), llvm::dwarf::DW_OP_deref) ==
4134 Expr.end() &&
4135 "Debug info already contains DW_OP_deref.");
4136 Expr.push_back(llvm::dwarf::DW_OP_deref);
4137 }
4138
David Blaikiea76a7c92013-01-05 05:58:35 +00004139 // Create the descriptor for the variable.
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004140 auto *D = ArgNo ? DBuilder.createParameterVariable(
4141 Scope, Name, *ArgNo, Unit, Line, Ty,
4142 CGM.getLangOpts().Optimize, Flags)
4143 : DBuilder.createAutoVariable(Scope, Name, Unit, Line, Ty,
4144 CGM.getLangOpts().Optimize,
4145 Flags, Align);
David Blaikiea76a7c92013-01-05 05:58:35 +00004146
4147 // Insert an llvm.dbg.declare into the current block.
Duncan P. N. Exon Smithfe88b482015-04-15 21:18:30 +00004148 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
Adrian Prantlb7acfc02017-02-27 21:30:05 +00004149 llvm::DebugLoc::get(Line, Column, Scope, CurInlinedAt),
Duncan P. N. Exon Smithfe88b482015-04-15 21:18:30 +00004150 Builder.GetInsertBlock());
Sander de Smalen891af03a2018-02-03 13:55:59 +00004151
4152 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00004153}
4154
Sander de Smalen891af03a2018-02-03 13:55:59 +00004155llvm::DILocalVariable *
4156CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD, llvm::Value *Storage,
Amy Huang7fac5c82019-06-20 17:15:21 +00004157 CGBuilderTy &Builder,
4158 const bool UsePointerValue) {
Amy Huang53539bb2020-01-13 15:54:54 -08004159 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
Amy Huang7fac5c82019-06-20 17:15:21 +00004160 return EmitDeclare(VD, Storage, llvm::None, Builder, UsePointerValue);
Guy Benyei11169dd2012-12-18 14:30:41 +00004161}
4162
Hsiangkai Wang35751492019-01-24 05:34:29 +00004163void CGDebugInfo::EmitLabel(const LabelDecl *D, CGBuilderTy &Builder) {
Amy Huang53539bb2020-01-13 15:54:54 -08004164 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
Hsiangkai Wang35751492019-01-24 05:34:29 +00004165 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4166
4167 if (D->hasAttr<NoDebugAttr>())
4168 return;
4169
4170 auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
4171 llvm::DIFile *Unit = getOrCreateFile(D->getLocation());
4172
4173 // Get location information.
4174 unsigned Line = getLineNumber(D->getLocation());
4175 unsigned Column = getColumnNumber(D->getLocation());
4176
4177 StringRef Name = D->getName();
4178
4179 // Create the descriptor for the label.
4180 auto *L =
4181 DBuilder.createLabel(Scope, Name, Unit, Line, CGM.getLangOpts().Optimize);
4182
4183 // Insert an llvm.dbg.label into the current block.
4184 DBuilder.insertLabel(L,
4185 llvm::DebugLoc::get(Line, Column, Scope, CurInlinedAt),
4186 Builder.GetInsertBlock());
4187}
4188
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004189llvm::DIType *CGDebugInfo::CreateSelfType(const QualType &QualTy,
4190 llvm::DIType *Ty) {
4191 llvm::DIType *CachedTy = getTypeOrNull(QualTy);
Eric Christophere7b87e52014-10-26 23:40:33 +00004192 if (CachedTy)
4193 Ty = CachedTy;
Adrian Prantlde17db32013-03-29 19:20:29 +00004194 return DBuilder.createObjectPointerType(Ty);
4195}
4196
Eric Christophere7b87e52014-10-26 23:40:33 +00004197void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(
4198 const VarDecl *VD, llvm::Value *Storage, CGBuilderTy &Builder,
Adrian Prantl88eec392014-11-21 00:35:25 +00004199 const CGBlockInfo &blockInfo, llvm::Instruction *InsertPoint) {
Amy Huang53539bb2020-01-13 15:54:54 -08004200 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00004201 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
Eric Christopherb2a008c2013-05-16 00:45:12 +00004202
Craig Topper8a13c412014-05-21 05:09:00 +00004203 if (Builder.GetInsertBlock() == nullptr)
Guy Benyei11169dd2012-12-18 14:30:41 +00004204 return;
Paul Robinsonafd2dde2016-06-16 00:42:36 +00004205 if (VD->hasAttr<NoDebugAttr>())
4206 return;
Eric Christopherb2a008c2013-05-16 00:45:12 +00004207
Guy Benyei11169dd2012-12-18 14:30:41 +00004208 bool isByRef = VD->hasAttr<BlocksAttr>();
Eric Christopherb2a008c2013-05-16 00:45:12 +00004209
Guy Benyei11169dd2012-12-18 14:30:41 +00004210 uint64_t XOffset = 0;
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004211 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
4212 llvm::DIType *Ty;
Guy Benyei11169dd2012-12-18 14:30:41 +00004213 if (isByRef)
Adrian Prantl05a623e2018-09-10 16:14:28 +00004214 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset).WrappedType;
Eric Christopherb2a008c2013-05-16 00:45:12 +00004215 else
Guy Benyei11169dd2012-12-18 14:30:41 +00004216 Ty = getOrCreateType(VD->getType(), Unit);
4217
4218 // Self is passed along as an implicit non-arg variable in a
4219 // block. Mark it as the object pointer.
Alexey Bataev56223232017-06-09 13:40:18 +00004220 if (const auto *IPD = dyn_cast<ImplicitParamDecl>(VD))
4221 if (IPD->getParameterKind() == ImplicitParamDecl::ObjCSelf)
4222 Ty = CreateSelfType(VD->getType(), Ty);
Guy Benyei11169dd2012-12-18 14:30:41 +00004223
4224 // Get location information.
4225 unsigned Line = getLineNumber(VD->getLocation());
4226 unsigned Column = getColumnNumber(VD->getLocation());
4227
4228 const llvm::DataLayout &target = CGM.getDataLayout();
4229
4230 CharUnits offset = CharUnits::fromQuantity(
Eric Christophere7b87e52014-10-26 23:40:33 +00004231 target.getStructLayout(blockInfo.StructureType)
Guy Benyei11169dd2012-12-18 14:30:41 +00004232 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
4233
Duncan P. N. Exon Smithf3dc4292014-10-01 20:26:18 +00004234 SmallVector<int64_t, 9> addr;
Adrian Prantlc3782a12017-04-18 01:22:01 +00004235 addr.push_back(llvm::dwarf::DW_OP_deref);
Florian Hahn3dbcced2017-06-13 18:06:15 +00004236 addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
Duncan P. N. Exon Smithf3dc4292014-10-01 20:26:18 +00004237 addr.push_back(offset.getQuantity());
Guy Benyei11169dd2012-12-18 14:30:41 +00004238 if (isByRef) {
Duncan P. N. Exon Smithf3dc4292014-10-01 20:26:18 +00004239 addr.push_back(llvm::dwarf::DW_OP_deref);
Florian Hahn3dbcced2017-06-13 18:06:15 +00004240 addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
Guy Benyei11169dd2012-12-18 14:30:41 +00004241 // offset of __forwarding field
Eric Christophere7b87e52014-10-26 23:40:33 +00004242 offset =
4243 CGM.getContext().toCharUnitsFromBits(target.getPointerSizeInBits(0));
Duncan P. N. Exon Smithf3dc4292014-10-01 20:26:18 +00004244 addr.push_back(offset.getQuantity());
4245 addr.push_back(llvm::dwarf::DW_OP_deref);
Florian Hahn3dbcced2017-06-13 18:06:15 +00004246 addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
Guy Benyei11169dd2012-12-18 14:30:41 +00004247 // offset of x field
4248 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
Duncan P. N. Exon Smithf3dc4292014-10-01 20:26:18 +00004249 addr.push_back(offset.getQuantity());
Guy Benyei11169dd2012-12-18 14:30:41 +00004250 }
4251
4252 // Create the descriptor for the variable.
Victor Leschuka7ece032016-10-20 00:13:19 +00004253 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
Duncan P. N. Exon Smithe4306542015-07-31 17:56:14 +00004254 auto *D = DBuilder.createAutoVariable(
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004255 cast<llvm::DILocalScope>(LexicalBlockStack.back()), VD->getName(), Unit,
Victor Leschuka7ece032016-10-20 00:13:19 +00004256 Line, Ty, false, llvm::DINode::FlagZero, Align);
Adrian Prantl0f6df002013-03-29 19:20:35 +00004257
Guy Benyei11169dd2012-12-18 14:30:41 +00004258 // Insert an llvm.dbg.declare into the current block.
Adrian Prantlb7acfc02017-02-27 21:30:05 +00004259 auto DL =
4260 llvm::DebugLoc::get(Line, Column, LexicalBlockStack.back(), CurInlinedAt);
Adrian Prantlc3782a12017-04-18 01:22:01 +00004261 auto *Expr = DBuilder.createExpression(addr);
Duncan P. N. Exon Smithfe88b482015-04-15 21:18:30 +00004262 if (InsertPoint)
Adrian Prantlc3782a12017-04-18 01:22:01 +00004263 DBuilder.insertDeclare(Storage, D, Expr, DL, InsertPoint);
Duncan P. N. Exon Smithfe88b482015-04-15 21:18:30 +00004264 else
Adrian Prantlc3782a12017-04-18 01:22:01 +00004265 DBuilder.insertDeclare(Storage, D, Expr, DL, Builder.GetInsertBlock());
Guy Benyei11169dd2012-12-18 14:30:41 +00004266}
4267
Guy Benyei11169dd2012-12-18 14:30:41 +00004268void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
4269 unsigned ArgNo,
4270 CGBuilderTy &Builder) {
Amy Huang53539bb2020-01-13 15:54:54 -08004271 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
Duncan P. N. Exon Smithe4306542015-07-31 17:56:14 +00004272 EmitDeclare(VD, AI, ArgNo, Builder);
Guy Benyei11169dd2012-12-18 14:30:41 +00004273}
4274
4275namespace {
Eric Christophere7b87e52014-10-26 23:40:33 +00004276struct BlockLayoutChunk {
4277 uint64_t OffsetInBits;
4278 const BlockDecl::Capture *Capture;
4279};
4280bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
4281 return l.OffsetInBits < r.OffsetInBits;
4282}
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004283} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00004284
Scott Linder58df0e42018-08-08 15:56:12 +00004285void CGDebugInfo::collectDefaultFieldsForBlockLiteralDeclare(
4286 const CGBlockInfo &Block, const ASTContext &Context, SourceLocation Loc,
4287 const llvm::StructLayout &BlockLayout, llvm::DIFile *Unit,
4288 SmallVectorImpl<llvm::Metadata *> &Fields) {
4289 // Blocks in OpenCL have unique constraints which make the standard fields
4290 // redundant while requiring size and align fields for enqueue_kernel. See
4291 // initializeForBlockHeader in CGBlocks.cpp
4292 if (CGM.getLangOpts().OpenCL) {
4293 Fields.push_back(createFieldType("__size", Context.IntTy, Loc, AS_public,
4294 BlockLayout.getElementOffsetInBits(0),
4295 Unit, Unit));
4296 Fields.push_back(createFieldType("__align", Context.IntTy, Loc, AS_public,
4297 BlockLayout.getElementOffsetInBits(1),
4298 Unit, Unit));
4299 } else {
4300 Fields.push_back(createFieldType("__isa", Context.VoidPtrTy, Loc, AS_public,
4301 BlockLayout.getElementOffsetInBits(0),
4302 Unit, Unit));
4303 Fields.push_back(createFieldType("__flags", Context.IntTy, Loc, AS_public,
4304 BlockLayout.getElementOffsetInBits(1),
4305 Unit, Unit));
4306 Fields.push_back(
4307 createFieldType("__reserved", Context.IntTy, Loc, AS_public,
4308 BlockLayout.getElementOffsetInBits(2), Unit, Unit));
4309 auto *FnTy = Block.getBlockExpr()->getFunctionType();
4310 auto FnPtrType = CGM.getContext().getPointerType(FnTy->desugar());
4311 Fields.push_back(createFieldType("__FuncPtr", FnPtrType, Loc, AS_public,
4312 BlockLayout.getElementOffsetInBits(3),
4313 Unit, Unit));
4314 Fields.push_back(createFieldType(
4315 "__descriptor",
4316 Context.getPointerType(Block.NeedsCopyDispose
4317 ? Context.getBlockDescriptorExtendedType()
4318 : Context.getBlockDescriptorType()),
4319 Loc, AS_public, BlockLayout.getElementOffsetInBits(4), Unit, Unit));
4320 }
4321}
4322
Guy Benyei11169dd2012-12-18 14:30:41 +00004323void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
Adrian Prantl356347b2017-10-26 20:08:52 +00004324 StringRef Name,
David Blaikie77bbb5f2014-08-08 17:10:14 +00004325 unsigned ArgNo,
Adrian Prantl356347b2017-10-26 20:08:52 +00004326 llvm::AllocaInst *Alloca,
Guy Benyei11169dd2012-12-18 14:30:41 +00004327 CGBuilderTy &Builder) {
Amy Huang53539bb2020-01-13 15:54:54 -08004328 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00004329 ASTContext &C = CGM.getContext();
4330 const BlockDecl *blockDecl = block.getBlockDecl();
4331
4332 // Collect some general information about the block's location.
4333 SourceLocation loc = blockDecl->getCaretLocation();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004334 llvm::DIFile *tunit = getOrCreateFile(loc);
Guy Benyei11169dd2012-12-18 14:30:41 +00004335 unsigned line = getLineNumber(loc);
4336 unsigned column = getColumnNumber(loc);
Eric Christopherb2a008c2013-05-16 00:45:12 +00004337
Guy Benyei11169dd2012-12-18 14:30:41 +00004338 // Build the debug-info type for the block literal.
Adrian Prantl6ec370a2015-09-10 18:39:45 +00004339 getDeclContextDescriptor(blockDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00004340
4341 const llvm::StructLayout *blockLayout =
Eric Christophere7b87e52014-10-26 23:40:33 +00004342 CGM.getDataLayout().getStructLayout(block.StructureType);
Guy Benyei11169dd2012-12-18 14:30:41 +00004343
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00004344 SmallVector<llvm::Metadata *, 16> fields;
Scott Linder58df0e42018-08-08 15:56:12 +00004345 collectDefaultFieldsForBlockLiteralDeclare(block, C, loc, *blockLayout, tunit,
4346 fields);
Guy Benyei11169dd2012-12-18 14:30:41 +00004347
4348 // We want to sort the captures by offset, not because DWARF
4349 // requires this, but because we're paranoid about debuggers.
4350 SmallVector<BlockLayoutChunk, 8> chunks;
4351
4352 // 'this' capture.
4353 if (blockDecl->capturesCXXThis()) {
4354 BlockLayoutChunk chunk;
4355 chunk.OffsetInBits =
Eric Christophere7b87e52014-10-26 23:40:33 +00004356 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
Craig Topper8a13c412014-05-21 05:09:00 +00004357 chunk.Capture = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004358 chunks.push_back(chunk);
4359 }
4360
4361 // Variable captures.
Aaron Ballman9371dd22014-03-14 18:34:04 +00004362 for (const auto &capture : blockDecl->captures()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004363 const VarDecl *variable = capture.getVariable();
4364 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
4365
4366 // Ignore constant captures.
4367 if (captureInfo.isConstant())
4368 continue;
4369
4370 BlockLayoutChunk chunk;
4371 chunk.OffsetInBits =
Eric Christophere7b87e52014-10-26 23:40:33 +00004372 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
Guy Benyei11169dd2012-12-18 14:30:41 +00004373 chunk.Capture = &capture;
4374 chunks.push_back(chunk);
4375 }
4376
4377 // Sort by offset.
4378 llvm::array_pod_sort(chunks.begin(), chunks.end());
4379
David Majnemer58ed0f32016-07-17 00:39:12 +00004380 for (const BlockLayoutChunk &Chunk : chunks) {
4381 uint64_t offsetInBits = Chunk.OffsetInBits;
4382 const BlockDecl::Capture *capture = Chunk.Capture;
Guy Benyei11169dd2012-12-18 14:30:41 +00004383
4384 // If we have a null capture, this must be the C++ 'this' capture.
4385 if (!capture) {
Adrian Prantl2526fca2016-04-18 23:48:16 +00004386 QualType type;
4387 if (auto *Method =
4388 cast_or_null<CXXMethodDecl>(blockDecl->getNonClosureContext()))
Brian Gesiak5488ab42019-01-11 01:54:53 +00004389 type = Method->getThisType();
Adrian Prantl2526fca2016-04-18 23:48:16 +00004390 else if (auto *RDecl = dyn_cast<CXXRecordDecl>(blockDecl->getParent()))
4391 type = QualType(RDecl->getTypeForDecl(), 0);
4392 else
4393 llvm_unreachable("unexpected block declcontext");
Guy Benyei11169dd2012-12-18 14:30:41 +00004394
David Majnemerb4b671e2016-06-30 03:01:59 +00004395 fields.push_back(createFieldType("this", type, loc, AS_public,
Guy Benyei11169dd2012-12-18 14:30:41 +00004396 offsetInBits, tunit, tunit));
4397 continue;
4398 }
4399
4400 const VarDecl *variable = capture->getVariable();
4401 StringRef name = variable->getName();
4402
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004403 llvm::DIType *fieldType;
Guy Benyei11169dd2012-12-18 14:30:41 +00004404 if (capture->isByRef()) {
David Majnemer34b57492014-07-30 01:30:47 +00004405 TypeInfo PtrInfo = C.getTypeInfo(C.VoidPtrTy);
Victor Leschuka7ece032016-10-20 00:13:19 +00004406 auto Align = PtrInfo.AlignIsRequired ? PtrInfo.Align : 0;
Adrian Prantl05a623e2018-09-10 16:14:28 +00004407 // FIXME: This recomputes the layout of the BlockByRefWrapper.
Guy Benyei11169dd2012-12-18 14:30:41 +00004408 uint64_t xoffset;
Adrian Prantl05a623e2018-09-10 16:14:28 +00004409 fieldType =
4410 EmitTypeForVarWithBlocksAttr(variable, &xoffset).BlockByRefWrapper;
David Majnemer34b57492014-07-30 01:30:47 +00004411 fieldType = DBuilder.createPointerType(fieldType, PtrInfo.Width);
Victor Leschuka7ece032016-10-20 00:13:19 +00004412 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
4413 PtrInfo.Width, Align, offsetInBits,
4414 llvm::DINode::FlagZero, fieldType);
Guy Benyei11169dd2012-12-18 14:30:41 +00004415 } else {
Victor Leschuka7ece032016-10-20 00:13:19 +00004416 auto Align = getDeclAlignIfRequired(variable, CGM.getContext());
David Majnemerb4b671e2016-06-30 03:01:59 +00004417 fieldType = createFieldType(name, variable->getType(), loc, AS_public,
Victor Leschuka7ece032016-10-20 00:13:19 +00004418 offsetInBits, Align, tunit, tunit);
Guy Benyei11169dd2012-12-18 14:30:41 +00004419 }
4420 fields.push_back(fieldType);
4421 }
4422
4423 SmallString<36> typeName;
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004424 llvm::raw_svector_ostream(typeName)
4425 << "__block_literal_" << CGM.getUniqueBlockCount();
Guy Benyei11169dd2012-12-18 14:30:41 +00004426
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004427 llvm::DINodeArray fieldsArray = DBuilder.getOrCreateArray(fields);
Guy Benyei11169dd2012-12-18 14:30:41 +00004428
Leny Kholodovdf050fd2016-09-06 17:06:14 +00004429 llvm::DIType *type =
4430 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
Victor Leschuka7ece032016-10-20 00:13:19 +00004431 CGM.getContext().toBits(block.BlockSize), 0,
Leny Kholodovdf050fd2016-09-06 17:06:14 +00004432 llvm::DINode::FlagZero, nullptr, fieldsArray);
Guy Benyei11169dd2012-12-18 14:30:41 +00004433 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
4434
4435 // Get overall information about the block.
Leny Kholodov80c047d2016-09-06 10:48:04 +00004436 llvm::DINode::DIFlags flags = llvm::DINode::FlagArtificial;
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004437 auto *scope = cast<llvm::DILocalScope>(LexicalBlockStack.back());
Guy Benyei11169dd2012-12-18 14:30:41 +00004438
4439 // Create the descriptor for the parameter.
Duncan P. N. Exon Smithe4306542015-07-31 17:56:14 +00004440 auto *debugVar = DBuilder.createParameterVariable(
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004441 scope, Name, ArgNo, tunit, line, type, CGM.getLangOpts().Optimize, flags);
Adrian Prantl51936dd2013-03-14 17:53:33 +00004442
Adrian Prantl616bef42013-03-14 21:52:59 +00004443 // Insert an llvm.dbg.declare into the current block.
Adrian Prantl356347b2017-10-26 20:08:52 +00004444 DBuilder.insertDeclare(Alloca, debugVar, DBuilder.createExpression(),
Adrian Prantlb7acfc02017-02-27 21:30:05 +00004445 llvm::DebugLoc::get(line, column, scope, CurInlinedAt),
Duncan P. N. Exon Smithfe88b482015-04-15 21:18:30 +00004446 Builder.GetInsertBlock());
Guy Benyei11169dd2012-12-18 14:30:41 +00004447}
4448
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004449llvm::DIDerivedType *
David Blaikie6943dea2013-08-20 01:28:15 +00004450CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) {
Amy Huangdd3a9ca2019-05-30 22:04:11 +00004451 if (!D || !D->isStaticDataMember())
Duncan P. N. Exon Smithc09c5482015-04-20 21:17:26 +00004452 return nullptr;
Saleem Abdulrasoolcd187f02015-02-28 00:13:13 +00004453
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00004454 auto MI = StaticDataMemberCache.find(D->getCanonicalDecl());
David Blaikie6943dea2013-08-20 01:28:15 +00004455 if (MI != StaticDataMemberCache.end()) {
4456 assert(MI->second && "Static data member declaration should still exist");
Duncan P. N. Exon Smithac346ba2015-07-24 18:05:58 +00004457 return MI->second;
Evgeniy Stepanov37b3f732013-08-16 10:35:31 +00004458 }
David Blaikiece763042013-08-20 21:49:21 +00004459
4460 // If the member wasn't found in the cache, lazily construct and add it to the
4461 // type (used when a limited form of the type is emitted).
Adrian Prantl21361fb2014-08-29 22:44:27 +00004462 auto DC = D->getDeclContext();
Adrian Prantl6ec370a2015-09-10 18:39:45 +00004463 auto *Ctxt = cast<llvm::DICompositeType>(getDeclContextDescriptor(D));
Adrian Prantl21361fb2014-08-29 22:44:27 +00004464 return CreateRecordStaticField(D, Ctxt, cast<RecordDecl>(DC));
David Blaikie6943dea2013-08-20 01:28:15 +00004465}
4466
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004467llvm::DIGlobalVariableExpression *CGDebugInfo::CollectAnonRecordDecls(
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004468 const RecordDecl *RD, llvm::DIFile *Unit, unsigned LineNo,
4469 StringRef LinkageName, llvm::GlobalVariable *Var, llvm::DIScope *DContext) {
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004470 llvm::DIGlobalVariableExpression *GVE = nullptr;
Eric Christophercab9fae2014-04-10 05:20:00 +00004471
4472 for (const auto *Field : RD->fields()) {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004473 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
Eric Christophercab9fae2014-04-10 05:20:00 +00004474 StringRef FieldName = Field->getName();
4475
4476 // Ignore unnamed fields, but recurse into anonymous records.
4477 if (FieldName.empty()) {
David Majnemer58ed0f32016-07-17 00:39:12 +00004478 if (const auto *RT = dyn_cast<RecordType>(Field->getType()))
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004479 GVE = CollectAnonRecordDecls(RT->getDecl(), Unit, LineNo, LinkageName,
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004480 Var, DContext);
Eric Christophercab9fae2014-04-10 05:20:00 +00004481 continue;
4482 }
4483 // Use VarDecl's Tag, Scope and Line number.
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004484 GVE = DBuilder.createGlobalVariableExpression(
4485 DContext, FieldName, LinkageName, Unit, LineNo, FieldTy,
4486 Var->hasLocalLinkage());
4487 Var->addDebugInfo(GVE);
Eric Christophercab9fae2014-04-10 05:20:00 +00004488 }
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004489 return GVE;
Eric Christophercab9fae2014-04-10 05:20:00 +00004490}
4491
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00004492void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
Guy Benyei11169dd2012-12-18 14:30:41 +00004493 const VarDecl *D) {
Amy Huang53539bb2020-01-13 15:54:54 -08004494 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
Paul Robinsonb17327d2016-04-27 17:37:12 +00004495 if (D->hasAttr<NoDebugAttr>())
4496 return;
Adrian Prantl338ef7a2016-11-09 00:42:03 +00004497
Luboš Luňák4f2104c2019-11-02 16:39:59 +01004498 llvm::TimeTraceScope TimeScope("DebugGlobalVariable", [&]() {
4499 std::string Name;
4500 llvm::raw_string_ostream OS(Name);
4501 D->getNameForDiagnostic(OS, getPrintingPolicy(),
4502 /*Qualified=*/true);
4503 return Name;
4504 });
4505
Adrian Prantl338ef7a2016-11-09 00:42:03 +00004506 // If we already created a DIGlobalVariable for this declaration, just attach
4507 // it to the llvm::GlobalVariable.
4508 auto Cached = DeclCache.find(D->getCanonicalDecl());
4509 if (Cached != DeclCache.end())
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004510 return Var->addDebugInfo(
4511 cast<llvm::DIGlobalVariableExpression>(Cached->second));
Adrian Prantl338ef7a2016-11-09 00:42:03 +00004512
Guy Benyei11169dd2012-12-18 14:30:41 +00004513 // Create global variable debug descriptor.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004514 llvm::DIFile *Unit = nullptr;
4515 llvm::DIScope *DContext = nullptr;
Frederic Riss9db79f12014-11-18 03:40:46 +00004516 unsigned LineNo;
4517 StringRef DeclName, LinkageName;
4518 QualType T;
Matthew Voss20165362018-10-03 18:45:04 +00004519 llvm::MDTuple *TemplateParameters = nullptr;
4520 collectVarDeclProps(D, Unit, LineNo, T, DeclName, LinkageName,
4521 TemplateParameters, DContext);
Eric Christophercab9fae2014-04-10 05:20:00 +00004522
4523 // Attempt to store one global variable for the declaration - even if we
4524 // emit a lot of fields.
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004525 llvm::DIGlobalVariableExpression *GVE = nullptr;
Eric Christophercab9fae2014-04-10 05:20:00 +00004526
4527 // If this is an anonymous union then we'll want to emit a global
4528 // variable for each member of the anonymous union so that it's possible
4529 // to find the name of any field in the union.
4530 if (T->isUnionType() && DeclName.empty()) {
Reid Kleckner43ecd7c2015-11-20 17:41:12 +00004531 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
Eric Christophere7b87e52014-10-26 23:40:33 +00004532 assert(RD->isAnonymousStructOrUnion() &&
4533 "unnamed non-anonymous struct or union?");
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004534 GVE = CollectAnonRecordDecls(RD, Unit, LineNo, LinkageName, Var, DContext);
Eric Christophercab9fae2014-04-10 05:20:00 +00004535 } else {
Victor Leschuka7ece032016-10-20 00:13:19 +00004536 auto Align = getDeclAlignIfRequired(D, CGM.getContext());
Konstantin Zhuravlyov2b4917f2017-03-09 18:06:23 +00004537
4538 SmallVector<int64_t, 4> Expr;
4539 unsigned AddressSpace =
4540 CGM.getContext().getTargetAddressSpace(D->getType());
Alexey Bataev1a9e05d2019-02-05 19:45:57 +00004541 if (CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) {
4542 if (D->hasAttr<CUDASharedAttr>())
4543 AddressSpace =
4544 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared);
4545 else if (D->hasAttr<CUDAConstantAttr>())
4546 AddressSpace =
4547 CGM.getContext().getTargetAddressSpace(LangAS::cuda_constant);
4548 }
Konstantin Zhuravlyov2b4917f2017-03-09 18:06:23 +00004549 AppendAddressSpaceXDeref(AddressSpace, Expr);
4550
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004551 GVE = DBuilder.createGlobalVariableExpression(
Eric Christophercab9fae2014-04-10 05:20:00 +00004552 DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),
Yonghong Songe3d8ee32019-11-22 08:45:37 -08004553 Var->hasLocalLinkage(), true,
Konstantin Zhuravlyov2b4917f2017-03-09 18:06:23 +00004554 Expr.empty() ? nullptr : DBuilder.createExpression(Expr),
Matthew Voss20165362018-10-03 18:45:04 +00004555 getOrCreateStaticDataMemberDeclarationOrNull(D), TemplateParameters,
4556 Align);
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004557 Var->addDebugInfo(GVE);
Eric Christophercab9fae2014-04-10 05:20:00 +00004558 }
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004559 DeclCache[D->getCanonicalDecl()].reset(GVE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004560}
4561
Peter Collingbourneeeb56ab2016-09-13 01:13:19 +00004562void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD, const APValue &Init) {
Amy Huang53539bb2020-01-13 15:54:54 -08004563 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
Paul Robinsonb17327d2016-04-27 17:37:12 +00004564 if (VD->hasAttr<NoDebugAttr>())
4565 return;
Luboš Luňák4f2104c2019-11-02 16:39:59 +01004566 llvm::TimeTraceScope TimeScope("DebugConstGlobalVariable", [&]() {
4567 std::string Name;
4568 llvm::raw_string_ostream OS(Name);
4569 VD->getNameForDiagnostic(OS, getPrintingPolicy(),
4570 /*Qualified=*/true);
4571 return Name;
4572 });
4573
Victor Leschuka7ece032016-10-20 00:13:19 +00004574 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00004575 // Create the descriptor for the variable.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004576 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00004577 StringRef Name = VD->getName();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004578 llvm::DIType *Ty = getOrCreateType(VD->getType(), Unit);
Amy Huang63305c82019-05-22 15:48:59 +00004579
David Majnemer58ed0f32016-07-17 00:39:12 +00004580 if (const auto *ECD = dyn_cast<EnumConstantDecl>(VD)) {
4581 const auto *ED = cast<EnumDecl>(ECD->getDeclContext());
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00004582 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
Amy Huangdd3a9ca2019-05-30 22:04:11 +00004583
Yuanfang Chen48c6fad2019-09-04 20:58:15 +00004584 if (CGM.getCodeGenOpts().EmitCodeView) {
4585 // If CodeView, emit enums as global variables, unless they are defined
4586 // inside a class. We do this because MSVC doesn't emit S_CONSTANTs for
4587 // enums in classes, and because it is difficult to attach this scope
4588 // information to the global variable.
4589 if (isa<RecordDecl>(ED->getDeclContext()))
4590 return;
4591 } else {
4592 // If not CodeView, emit DW_TAG_enumeration_type if necessary. For
4593 // example: for "enum { ZERO };", a DW_TAG_enumeration_type is created the
4594 // first time `ZERO` is referenced in a function.
4595 llvm::DIType *EDTy =
4596 getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
4597 assert (EDTy->getTag() == llvm::dwarf::DW_TAG_enumeration_type);
4598 (void)EDTy;
Amy Huangdd3a9ca2019-05-30 22:04:11 +00004599 return;
Yuanfang Chen48c6fad2019-09-04 20:58:15 +00004600 }
Amy Huang63305c82019-05-22 15:48:59 +00004601 }
4602
Amy Huang325003b2019-05-29 21:45:34 +00004603 llvm::DIScope *DContext = nullptr;
4604
4605 // Do not emit separate definitions for function local consts.
David Blaikiea15565562014-04-04 20:56:17 +00004606 if (isa<FunctionDecl>(VD->getDeclContext()))
4607 return;
Amy Huang325003b2019-05-29 21:45:34 +00004608
4609 // Emit definition for static members in CodeView.
David Blaikiebb113912014-04-05 07:23:17 +00004610 VD = cast<ValueDecl>(VD->getCanonicalDecl());
Amy Huangdd3a9ca2019-05-30 22:04:11 +00004611 auto *VarD = dyn_cast<VarDecl>(VD);
4612 if (VarD && VarD->isStaticDataMember()) {
David Blaikieaf080852014-11-21 00:20:58 +00004613 auto *RD = cast<RecordDecl>(VarD->getDeclContext());
Adrian Prantl6ec370a2015-09-10 18:39:45 +00004614 getDeclContextDescriptor(VarD);
David Blaikie423eb5a2014-11-19 19:42:40 +00004615 // Ensure that the type is retained even though it's otherwise unreferenced.
Duncan P. N. Exon Smith383f8412016-04-23 21:08:27 +00004616 //
4617 // FIXME: This is probably unnecessary, since Ty should reference RD
4618 // through its scope.
David Blaikie423eb5a2014-11-19 19:42:40 +00004619 RetainedTypes.push_back(
David Blaikieaf080852014-11-21 00:20:58 +00004620 CGM.getContext().getRecordType(RD).getAsOpaquePtr());
David Blaikie423eb5a2014-11-19 19:42:40 +00004621
Amy Huang325003b2019-05-29 21:45:34 +00004622 if (!CGM.getCodeGenOpts().EmitCodeView)
4623 return;
4624
4625 // Use the global scope for static members.
4626 DContext = getContextDescriptor(
4627 cast<Decl>(CGM.getContext().getTranslationUnitDecl()), TheCU);
4628 } else {
4629 DContext = getDeclContextDescriptor(VD);
4630 }
David Blaikieaf080852014-11-21 00:20:58 +00004631
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00004632 auto &GV = DeclCache[VD];
4633 if (GV)
David Blaikiebb113912014-04-05 07:23:17 +00004634 return;
Peter Collingbourneeeb56ab2016-09-13 01:13:19 +00004635 llvm::DIExpression *InitExpr = nullptr;
Peter Collingbourneb7013632016-12-16 22:10:52 +00004636 if (CGM.getContext().getTypeSize(VD->getType()) <= 64) {
4637 // FIXME: Add a representation for integer constants wider than 64 bits.
4638 if (Init.isInt())
4639 InitExpr =
4640 DBuilder.createConstantValueExpression(Init.getInt().getExtValue());
4641 else if (Init.isFloat())
4642 InitExpr = DBuilder.createConstantValueExpression(
4643 Init.getFloat().bitcastToAPInt().getZExtValue());
4644 }
Matthew Voss20165362018-10-03 18:45:04 +00004645
4646 llvm::MDTuple *TemplateParameters = nullptr;
4647
4648 if (isa<VarTemplateSpecializationDecl>(VD))
4649 if (VarD) {
4650 llvm::DINodeArray parameterNodes = CollectVarTemplateParams(VarD, &*Unit);
4651 TemplateParameters = parameterNodes.get();
4652 }
4653
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004654 GV.reset(DBuilder.createGlobalVariableExpression(
David Blaikie506a7452014-04-05 07:46:57 +00004655 DContext, Name, StringRef(), Unit, getLineNumber(VD->getLocation()), Ty,
Yonghong Songe3d8ee32019-11-22 08:45:37 -08004656 true, true, InitExpr, getOrCreateStaticDataMemberDeclarationOrNull(VarD),
Matthew Voss20165362018-10-03 18:45:04 +00004657 TemplateParameters, Align));
David Blaikiebd483762013-05-20 04:58:53 +00004658}
4659
Yonghong Songe3d8ee32019-11-22 08:45:37 -08004660void CGDebugInfo::EmitExternalVariable(llvm::GlobalVariable *Var,
4661 const VarDecl *D) {
Amy Huang53539bb2020-01-13 15:54:54 -08004662 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
Yonghong Songe3d8ee32019-11-22 08:45:37 -08004663 if (D->hasAttr<NoDebugAttr>())
4664 return;
4665
4666 auto Align = getDeclAlignIfRequired(D, CGM.getContext());
4667 llvm::DIFile *Unit = getOrCreateFile(D->getLocation());
4668 StringRef Name = D->getName();
4669 llvm::DIType *Ty = getOrCreateType(D->getType(), Unit);
4670
4671 llvm::DIScope *DContext = getDeclContextDescriptor(D);
4672 llvm::DIGlobalVariableExpression *GVE =
4673 DBuilder.createGlobalVariableExpression(
4674 DContext, Name, StringRef(), Unit, getLineNumber(D->getLocation()),
4675 Ty, false, false, nullptr, nullptr, nullptr, Align);
4676 Var->addDebugInfo(GVE);
4677}
4678
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004679llvm::DIScope *CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
David Blaikiebd483762013-05-20 04:58:53 +00004680 if (!LexicalBlockStack.empty())
Duncan P. N. Exon Smithfc8d9d92015-04-20 18:32:15 +00004681 return LexicalBlockStack.back();
Adrian Prantl5c8bd882015-09-11 17:23:08 +00004682 llvm::DIScope *Mod = getParentModuleOrNull(D);
4683 return getContextDescriptor(D, Mod ? Mod : TheCU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004684}
4685
David Blaikie9f88fe82013-04-22 06:13:21 +00004686void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
Amy Huang53539bb2020-01-13 15:54:54 -08004687 if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
David Blaikiebd483762013-05-20 04:58:53 +00004688 return;
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +00004689 const NamespaceDecl *NSDecl = UD.getNominatedNamespace();
Adrian McCarthyab1e7862016-07-21 18:43:20 +00004690 if (!NSDecl->isAnonymousNamespace() ||
4691 CGM.getCodeGenOpts().DebugExplicitImport) {
Adrian Prantl5649b0e2017-07-19 00:09:58 +00004692 auto Loc = UD.getLocation();
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +00004693 DBuilder.createImportedModule(
4694 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
Adrian Prantl5649b0e2017-07-19 00:09:58 +00004695 getOrCreateNamespace(NSDecl), getOrCreateFile(Loc), getLineNumber(Loc));
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +00004696 }
David Blaikie9f88fe82013-04-22 06:13:21 +00004697}
4698
David Blaikiebd483762013-05-20 04:58:53 +00004699void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
Amy Huang53539bb2020-01-13 15:54:54 -08004700 if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
David Blaikiebd483762013-05-20 04:58:53 +00004701 return;
4702 assert(UD.shadow_size() &&
4703 "We shouldn't be codegening an invalid UsingDecl containing no decls");
4704 // Emitting one decl is sufficient - debuggers can detect that this is an
4705 // overloaded name & provide lookup for all the overloads.
4706 const UsingShadowDecl &USD = **UD.shadow_begin();
David Blaikie2a58a182016-08-05 19:03:01 +00004707
4708 // FIXME: Skip functions with undeduced auto return type for now since we
4709 // don't currently have the plumbing for separate declarations & definitions
4710 // of free functions and mismatched types (auto in the declaration, concrete
4711 // return type in the definition)
4712 if (const auto *FD = dyn_cast<FunctionDecl>(USD.getUnderlyingDecl()))
4713 if (const auto *AT =
Simon Pilgrim7e38f0c2019-10-07 16:42:25 +00004714 FD->getType()->castAs<FunctionProtoType>()->getContainedAutoType())
David Blaikie2a58a182016-08-05 19:03:01 +00004715 if (AT->getDeducedType().isNull())
4716 return;
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004717 if (llvm::DINode *Target =
Adrian Prantl5649b0e2017-07-19 00:09:58 +00004718 getDeclarationOrDefinition(USD.getUnderlyingDecl())) {
4719 auto Loc = USD.getLocation();
David Blaikiebd483762013-05-20 04:58:53 +00004720 DBuilder.createImportedDeclaration(
4721 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
Adrian Prantl5649b0e2017-07-19 00:09:58 +00004722 getOrCreateFile(Loc), getLineNumber(Loc));
4723 }
David Blaikiebd483762013-05-20 04:58:53 +00004724}
4725
Adrian Prantlc4bb47e2015-06-30 17:39:51 +00004726void CGDebugInfo::EmitImportDecl(const ImportDecl &ID) {
David Blaikieaf09f4a2016-05-03 23:06:40 +00004727 if (CGM.getCodeGenOpts().getDebuggerTuning() != llvm::DebuggerKind::LLDB)
4728 return;
Adrian Prantl8a634c12015-12-18 19:44:31 +00004729 if (Module *M = ID.getImportedModule()) {
Reid Klecknerc915cb92020-02-27 18:13:54 -08004730 auto Info = ASTSourceDescriptor(*M);
Adrian Prantl5649b0e2017-07-19 00:09:58 +00004731 auto Loc = ID.getLocation();
Adrian Prantl8a634c12015-12-18 19:44:31 +00004732 DBuilder.createImportedDeclaration(
4733 getCurrentContextDescriptor(cast<Decl>(ID.getDeclContext())),
Adrian Prantl5649b0e2017-07-19 00:09:58 +00004734 getOrCreateModuleRef(Info, DebugTypeExtRefs), getOrCreateFile(Loc),
4735 getLineNumber(Loc));
Adrian Prantl8a634c12015-12-18 19:44:31 +00004736 }
Adrian Prantlc4bb47e2015-06-30 17:39:51 +00004737}
4738
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004739llvm::DIImportedEntity *
David Blaikief121b932013-05-20 22:50:41 +00004740CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
Amy Huang53539bb2020-01-13 15:54:54 -08004741 if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
Duncan P. N. Exon Smithdadc2b62015-04-21 18:43:54 +00004742 return nullptr;
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00004743 auto &VH = NamespaceAliasCache[&NA];
David Blaikief121b932013-05-20 22:50:41 +00004744 if (VH)
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004745 return cast<llvm::DIImportedEntity>(VH);
4746 llvm::DIImportedEntity *R;
Adrian Prantl5649b0e2017-07-19 00:09:58 +00004747 auto Loc = NA.getLocation();
David Majnemer58ed0f32016-07-17 00:39:12 +00004748 if (const auto *Underlying =
David Blaikief121b932013-05-20 22:50:41 +00004749 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
4750 // This could cache & dedup here rather than relying on metadata deduping.
David Blaikie551fb0a2014-04-06 06:30:03 +00004751 R = DBuilder.createImportedDeclaration(
David Blaikief121b932013-05-20 22:50:41 +00004752 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
Adrian Prantl5649b0e2017-07-19 00:09:58 +00004753 EmitNamespaceAlias(*Underlying), getOrCreateFile(Loc),
4754 getLineNumber(Loc), NA.getName());
David Blaikief121b932013-05-20 22:50:41 +00004755 else
David Blaikie551fb0a2014-04-06 06:30:03 +00004756 R = DBuilder.createImportedDeclaration(
David Blaikief121b932013-05-20 22:50:41 +00004757 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
Adrian Prantlddb8e062017-05-12 16:23:53 +00004758 getOrCreateNamespace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
Adrian Prantl5649b0e2017-07-19 00:09:58 +00004759 getOrCreateFile(Loc), getLineNumber(Loc), NA.getName());
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00004760 VH.reset(R);
David Blaikief121b932013-05-20 22:50:41 +00004761 return R;
4762}
4763
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004764llvm::DINamespace *
Adrian Prantlddb8e062017-05-12 16:23:53 +00004765CGDebugInfo::getOrCreateNamespace(const NamespaceDecl *NSDecl) {
4766 // Don't canonicalize the NamespaceDecl here: The DINamespace will be uniqued
4767 // if necessary, and this way multiple declarations of the same namespace in
4768 // different parent modules stay distinct.
4769 auto I = NamespaceCache.find(NSDecl);
Adrian Prantld8870552017-05-11 22:59:19 +00004770 if (I != NamespaceCache.end())
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004771 return cast<llvm::DINamespace>(I->second);
Eric Christopherb2a008c2013-05-16 00:45:12 +00004772
Adrian Prantl6ec370a2015-09-10 18:39:45 +00004773 llvm::DIScope *Context = getDeclContextDescriptor(NSDecl);
Adrian Prantld8870552017-05-11 22:59:19 +00004774 // Don't trust the context if it is a DIModule (see comment above).
Adrian Prantlddb8e062017-05-12 16:23:53 +00004775 llvm::DINamespace *NS =
4776 DBuilder.createNameSpace(Context, NSDecl->getName(), NSDecl->isInline());
4777 NamespaceCache[NSDecl].reset(NS);
Guy Benyei11169dd2012-12-18 14:30:41 +00004778 return NS;
4779}
4780
Adrian Prantla5206ce2015-09-22 23:26:43 +00004781void CGDebugInfo::setDwoId(uint64_t Signature) {
4782 assert(TheCU && "no main compile unit");
4783 TheCU->setDWOId(Signature);
4784}
4785
Guy Benyei11169dd2012-12-18 14:30:41 +00004786void CGDebugInfo::finalize() {
David Blaikie87dab872014-05-07 16:56:58 +00004787 // Creating types might create further types - invalidating the current
4788 // element and the size(), so don't cache/reference them.
4789 for (size_t i = 0; i != ObjCInterfaceCache.size(); ++i) {
4790 ObjCInterfaceCacheEntry E = ObjCInterfaceCache[i];
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004791 llvm::DIType *Ty = E.Type->getDecl()->getDefinition()
Duncan P. N. Exon Smith497d4d462015-04-11 19:05:04 +00004792 ? CreateTypeDefinition(E.Type, E.Unit)
4793 : E.Decl;
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004794 DBuilder.replaceTemporary(llvm::TempDIType(E.Decl), Ty);
David Blaikie87dab872014-05-07 16:56:58 +00004795 }
4796
Adrian Prantle0cabe22019-11-21 09:56:01 -08004797 // Add methods to interface.
4798 for (const auto &P : ObjCMethodCache) {
4799 if (P.second.empty())
4800 continue;
Jonas Devlieghered8ba8ae2018-06-27 17:31:59 +00004801
Adrian Prantle0cabe22019-11-21 09:56:01 -08004802 QualType QTy(P.first->getTypeForDecl(), 0);
4803 auto It = TypeCache.find(QTy.getAsOpaquePtr());
4804 assert(It != TypeCache.end());
Jonas Devlieghered8ba8ae2018-06-27 17:31:59 +00004805
Adrian Prantle0cabe22019-11-21 09:56:01 -08004806 llvm::DICompositeType *InterfaceDecl =
4807 cast<llvm::DICompositeType>(It->second);
Jonas Devlieghered8ba8ae2018-06-27 17:31:59 +00004808
Adrian Prantle0cabe22019-11-21 09:56:01 -08004809 auto CurElts = InterfaceDecl->getElements();
4810 SmallVector<llvm::Metadata *, 16> EltTys(CurElts.begin(), CurElts.end());
4811
4812 // For DWARF v4 or earlier, only add objc_direct methods.
4813 for (auto &SubprogramDirect : P.second)
4814 if (CGM.getCodeGenOpts().DwarfVersion >= 5 || SubprogramDirect.getInt())
4815 EltTys.push_back(SubprogramDirect.getPointer());
4816
4817 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
4818 DBuilder.replaceArrays(InterfaceDecl, Elements);
Jonas Devlieghered8ba8ae2018-06-27 17:31:59 +00004819 }
4820
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004821 for (const auto &P : ReplaceMap) {
4822 assert(P.second);
4823 auto *Ty = cast<llvm::DIType>(P.second);
Duncan P. N. Exon Smith4caa7f22015-04-16 01:00:56 +00004824 assert(Ty->isForwardDecl());
Eric Christopherb2a008c2013-05-16 00:45:12 +00004825
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004826 auto It = TypeCache.find(P.first);
4827 assert(It != TypeCache.end());
4828 assert(It->second);
Adrian Prantl73409ce2013-03-11 18:33:46 +00004829
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004830 DBuilder.replaceTemporary(llvm::TempDIType(Ty),
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004831 cast<llvm::DIType>(It->second));
Guy Benyei11169dd2012-12-18 14:30:41 +00004832 }
Adrian Prantl73409ce2013-03-11 18:33:46 +00004833
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004834 for (const auto &P : FwdDeclReplaceMap) {
4835 assert(P.second);
4836 llvm::TempMDNode FwdDecl(cast<llvm::MDNode>(P.second));
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00004837 llvm::Metadata *Repl;
Frederic Rissd253ed62014-11-18 03:40:51 +00004838
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004839 auto It = DeclCache.find(P.first);
Adrian Prantl97f76852014-12-19 01:02:11 +00004840 // If there has been no definition for the declaration, call RAUW
Frederic Rissd253ed62014-11-18 03:40:51 +00004841 // with ourselves, that will destroy the temporary MDNode and
4842 // replace it with a standard one, avoiding leaking memory.
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004843 if (It == DeclCache.end())
4844 Repl = P.second;
Frederic Rissd253ed62014-11-18 03:40:51 +00004845 else
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004846 Repl = It->second;
Frederic Rissdce60a72014-11-19 18:53:46 +00004847
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004848 if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(Repl))
4849 Repl = GVE->getVariable();
Duncan P. N. Exon Smithd899f6e2015-04-18 00:07:30 +00004850 DBuilder.replaceTemporary(std::move(FwdDecl), cast<llvm::MDNode>(Repl));
Frederic Rissd253ed62014-11-18 03:40:51 +00004851 }
4852
Adrian Prantl73409ce2013-03-11 18:33:46 +00004853 // We keep our own list of retained types, because we need to look
4854 // up the final type in the type cache.
Adrian Prantl3a884fa2015-08-27 22:56:46 +00004855 for (auto &RT : RetainedTypes)
Adrian Prantlad9a195e2015-08-27 21:21:19 +00004856 if (auto MD = TypeCache[RT])
4857 DBuilder.retainType(cast<llvm::DIType>(MD));
Adrian Prantl73409ce2013-03-11 18:33:46 +00004858
Guy Benyei11169dd2012-12-18 14:30:41 +00004859 DBuilder.finalize();
4860}
David Blaikie66088d52014-09-24 17:01:27 +00004861
4862void CGDebugInfo::EmitExplicitCastType(QualType Ty) {
Amy Huang53539bb2020-01-13 15:54:54 -08004863 if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
David Blaikie66088d52014-09-24 17:01:27 +00004864 return;
Duncan P. N. Exon Smith5043f912015-03-27 22:58:05 +00004865
Adrian Prantlc2a44ec2018-12-11 16:58:46 +00004866 if (auto *DieTy = getOrCreateType(Ty, TheCU->getFile()))
Duncan P. N. Exon Smith5043f912015-03-27 22:58:05 +00004867 // Don't ignore in case of explicit cast where it is referenced indirectly.
4868 DBuilder.retainType(DieTy);
David Blaikie66088d52014-09-24 17:01:27 +00004869}
Amara Emerson652795d2016-11-10 14:44:30 +00004870
4871llvm::DebugLoc CGDebugInfo::SourceLocToDebugLoc(SourceLocation Loc) {
4872 if (LexicalBlockStack.empty())
4873 return llvm::DebugLoc();
4874
4875 llvm::MDNode *Scope = LexicalBlockStack.back();
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004876 return llvm::DebugLoc::get(getLineNumber(Loc), getColumnNumber(Loc), Scope);
Amara Emerson652795d2016-11-10 14:44:30 +00004877}
Vedant Kumar5931b4e2018-10-05 20:37:17 +00004878
4879llvm::DINode::DIFlags CGDebugInfo::getCallSiteRelatedAttrs() const {
4880 // Call site-related attributes are only useful in optimized programs, and
4881 // when there's a possibility of debugging backtraces.
4882 if (!CGM.getLangOpts().Optimize || DebugKind == codegenoptions::NoDebugInfo ||
4883 DebugKind == codegenoptions::LocTrackingOnly)
4884 return llvm::DINode::FlagZero;
4885
4886 // Call site-related attributes are available in DWARF v5. Some debuggers,
4887 // while not fully DWARF v5-compliant, may accept these attributes as if they
4888 // were part of DWARF v4.
4889 bool SupportsDWARFv4Ext =
4890 CGM.getCodeGenOpts().DwarfVersion == 4 &&
Djordje Todorovic639d36b2019-06-26 09:38:09 +00004891 (CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB ||
Vedant Kumar568db782019-11-13 18:19:32 -08004892 CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::GDB);
Djordje Todorovic639d36b2019-06-26 09:38:09 +00004893
Djordje Todorovicd9b96212020-03-19 12:13:18 +01004894 if (!SupportsDWARFv4Ext && CGM.getCodeGenOpts().DwarfVersion < 5)
Vedant Kumar5931b4e2018-10-05 20:37:17 +00004895 return llvm::DINode::FlagZero;
4896
4897 return llvm::DINode::FlagAllCallsDescribed;
4898}