blob: 9a6204b5bda0dc47df66ed4294378b5f547e24e7 [file] [log] [blame]
Guy Benyei11169dd2012-12-18 14:30:41 +00001//===--- CGDebugInfo.cpp - Emit Debug Information for a Module ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the debug information generation while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGDebugInfo.h"
15#include "CGBlocks.h"
David Blaikie38079fd2013-05-10 21:53:14 +000016#include "CGCXXABI.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000017#include "CGObjCRuntime.h"
Bob Haarmandff36732016-10-25 22:19:32 +000018#include "CGRecordLayout.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000019#include "CodeGenFunction.h"
20#include "CodeGenModule.h"
John McCallde0fe072017-08-15 21:42:52 +000021#include "ConstantEmitter.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000022#include "clang/AST/ASTContext.h"
23#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"
Guy Benyei11169dd2012-12-18 14:30:41 +000049using namespace clang;
50using namespace clang::CodeGen;
51
Victor Leschuka7ece032016-10-20 00:13:19 +000052static uint32_t getTypeAlignIfRequired(const Type *Ty, const ASTContext &Ctx) {
53 auto TI = Ctx.getTypeInfo(Ty);
54 return TI.AlignIsRequired ? TI.Align : 0;
55}
56
57static uint32_t getTypeAlignIfRequired(QualType Ty, const ASTContext &Ctx) {
58 return getTypeAlignIfRequired(Ty.getTypePtr(), Ctx);
59}
60
61static uint32_t getDeclAlignIfRequired(const Decl *D, const ASTContext &Ctx) {
62 return D->hasAttr<AlignedAttr>() ? D->getMaxAlignment() : 0;
63}
64
Guy Benyei11169dd2012-12-18 14:30:41 +000065CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
Eric Christopher324bbbd2013-07-14 21:12:44 +000066 : CGM(CGM), DebugKind(CGM.getCodeGenOpts().getDebugInfo()),
Adrian Prantl6b21ab22015-08-27 19:46:20 +000067 DebugTypeExtRefs(CGM.getCodeGenOpts().DebugTypeExtRefs),
Eric Christopher324bbbd2013-07-14 21:12:44 +000068 DBuilder(CGM.getModule()) {
Saleem Abdulrasool436256a2015-10-12 20:21:08 +000069 for (const auto &KV : CGM.getCodeGenOpts().DebugPrefixMap)
70 DebugPrefixMap[KV.first] = KV.second;
Guy Benyei11169dd2012-12-18 14:30:41 +000071 CreateCompileUnit();
72}
73
74CGDebugInfo::~CGDebugInfo() {
75 assert(LexicalBlockStack.empty() &&
76 "Region stack mismatch, stack not empty!");
77}
78
David Blaikie66e41972015-01-14 07:38:27 +000079ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF,
Calixte Denizetfcd661d2018-09-24 18:24:18 +000080 SourceLocation TemporaryLocation)
David Blaikied7057d92015-08-12 23:49:57 +000081 : CGF(&CGF) {
Calixte Denizetfcd661d2018-09-24 18:24:18 +000082 init(TemporaryLocation);
David Blaikie9b479662015-01-25 01:19:10 +000083}
84
Adrian Prantl39428e72015-02-03 18:40:42 +000085ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF,
Adrian Prantl95b24e92015-02-03 20:00:54 +000086 bool DefaultToEmpty,
Calixte Denizetfcd661d2018-09-24 18:24:18 +000087 SourceLocation TemporaryLocation)
David Blaikied7057d92015-08-12 23:49:57 +000088 : CGF(&CGF) {
Calixte Denizetfcd661d2018-09-24 18:24:18 +000089 init(TemporaryLocation, DefaultToEmpty);
Adrian Prantl39428e72015-02-03 18:40:42 +000090}
91
92void ApplyDebugLocation::init(SourceLocation TemporaryLocation,
Calixte Denizetfcd661d2018-09-24 18:24:18 +000093 bool DefaultToEmpty) {
David Blaikied7057d92015-08-12 23:49:57 +000094 auto *DI = CGF->getDebugInfo();
95 if (!DI) {
96 CGF = nullptr;
97 return;
David Blaikie66e41972015-01-14 07:38:27 +000098 }
David Blaikied7057d92015-08-12 23:49:57 +000099
100 OriginalLocation = CGF->Builder.getCurrentDebugLocation();
Bob Haarmanc6c9b8f2017-09-11 22:11:57 +0000101
102 if (OriginalLocation && !DI->CGM.getExpressionLocationsEnabled())
103 return;
104
David Blaikied7057d92015-08-12 23:49:57 +0000105 if (TemporaryLocation.isValid()) {
Calixte Denizetfcd661d2018-09-24 18:24:18 +0000106 DI->EmitLocation(CGF->Builder, TemporaryLocation);
David Blaikied7057d92015-08-12 23:49:57 +0000107 return;
108 }
109
110 if (DefaultToEmpty) {
111 CGF->Builder.SetCurrentDebugLocation(llvm::DebugLoc());
112 return;
113 }
114
115 // Construct a location that has a valid scope, but no line info.
116 assert(!DI->LexicalBlockStack.empty());
Adrian Prantlb7acfc02017-02-27 21:30:05 +0000117 CGF->Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(
118 0, 0, DI->LexicalBlockStack.back(), DI->getInlinedAt()));
Adrian Prantl2e0637f2013-07-18 00:28:02 +0000119}
120
David Blaikie9b479662015-01-25 01:19:10 +0000121ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, const Expr *E)
David Blaikied7057d92015-08-12 23:49:57 +0000122 : CGF(&CGF) {
David Blaikie9b479662015-01-25 01:19:10 +0000123 init(E->getExprLoc());
124}
125
David Blaikie66e41972015-01-14 07:38:27 +0000126ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, llvm::DebugLoc Loc)
David Blaikied7057d92015-08-12 23:49:57 +0000127 : CGF(&CGF) {
128 if (!CGF.getDebugInfo()) {
129 this->CGF = nullptr;
130 return;
David Blaikie66e41972015-01-14 07:38:27 +0000131 }
David Blaikied7057d92015-08-12 23:49:57 +0000132 OriginalLocation = CGF.Builder.getCurrentDebugLocation();
133 if (Loc)
134 CGF.Builder.SetCurrentDebugLocation(std::move(Loc));
David Blaikie66e41972015-01-14 07:38:27 +0000135}
136
137ApplyDebugLocation::~ApplyDebugLocation() {
138 // Query CGF so the location isn't overwritten when location updates are
139 // temporarily disabled (for C++ default function arguments)
David Blaikied7057d92015-08-12 23:49:57 +0000140 if (CGF)
141 CGF->Builder.SetCurrentDebugLocation(std::move(OriginalLocation));
David Blaikie66e41972015-01-14 07:38:27 +0000142}
143
Adrian Prantlb7acfc02017-02-27 21:30:05 +0000144ApplyInlineDebugLocation::ApplyInlineDebugLocation(CodeGenFunction &CGF,
145 GlobalDecl InlinedFn)
146 : CGF(&CGF) {
147 if (!CGF.getDebugInfo()) {
148 this->CGF = nullptr;
149 return;
150 }
151 auto &DI = *CGF.getDebugInfo();
152 SavedLocation = DI.getLocation();
153 assert((DI.getInlinedAt() ==
154 CGF.Builder.getCurrentDebugLocation()->getInlinedAt()) &&
155 "CGDebugInfo and IRBuilder are out of sync");
156
157 DI.EmitInlineFunctionStart(CGF.Builder, InlinedFn);
158}
159
160ApplyInlineDebugLocation::~ApplyInlineDebugLocation() {
161 if (!CGF)
162 return;
163 auto &DI = *CGF->getDebugInfo();
164 DI.EmitInlineFunctionEnd(CGF->Builder);
165 DI.EmitLocation(CGF->Builder, SavedLocation);
166}
167
Guy Benyei11169dd2012-12-18 14:30:41 +0000168void CGDebugInfo::setLocation(SourceLocation Loc) {
169 // If the new location isn't valid return.
Eric Christophere7b87e52014-10-26 23:40:33 +0000170 if (Loc.isInvalid())
171 return;
Guy Benyei11169dd2012-12-18 14:30:41 +0000172
173 CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc);
174
175 // If we've changed files in the middle of a lexical scope go ahead
176 // and create a new lexical scope with file node if it's different
177 // from the one in the scope.
Eric Christophere7b87e52014-10-26 23:40:33 +0000178 if (LexicalBlockStack.empty())
179 return;
Guy Benyei11169dd2012-12-18 14:30:41 +0000180
181 SourceManager &SM = CGM.getContext().getSourceManager();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +0000182 auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
Guy Benyei11169dd2012-12-18 14:30:41 +0000183 PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
Adrian Prantl212c1042018-12-06 18:44:50 +0000184 if (PCLoc.isInvalid() || Scope->getFile() == getOrCreateFile(CurLoc))
Guy Benyei11169dd2012-12-18 14:30:41 +0000185 return;
186
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +0000187 if (auto *LBF = dyn_cast<llvm::DILexicalBlockFile>(Scope)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000188 LexicalBlockStack.pop_back();
Duncan P. N. Exon Smithd899f6e2015-04-18 00:07:30 +0000189 LexicalBlockStack.emplace_back(DBuilder.createLexicalBlockFile(
190 LBF->getScope(), getOrCreateFile(CurLoc)));
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +0000191 } else if (isa<llvm::DILexicalBlock>(Scope) ||
192 isa<llvm::DISubprogram>(Scope)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000193 LexicalBlockStack.pop_back();
Duncan P. N. Exon Smithd899f6e2015-04-18 00:07:30 +0000194 LexicalBlockStack.emplace_back(
195 DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000196 }
197}
198
Adrian Prantl6ec370a2015-09-10 18:39:45 +0000199llvm::DIScope *CGDebugInfo::getDeclContextDescriptor(const Decl *D) {
Adrian Prantl5c8bd882015-09-11 17:23:08 +0000200 llvm::DIScope *Mod = getParentModuleOrNull(D);
201 return getContextDescriptor(cast<Decl>(D->getDeclContext()),
202 Mod ? Mod : TheCU);
Adrian Prantl6ec370a2015-09-10 18:39:45 +0000203}
204
205llvm::DIScope *CGDebugInfo::getContextDescriptor(const Decl *Context,
206 llvm::DIScope *Default) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000207 if (!Context)
Adrian Prantl6ec370a2015-09-10 18:39:45 +0000208 return Default;
Guy Benyei11169dd2012-12-18 14:30:41 +0000209
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +0000210 auto I = RegionMap.find(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +0000211 if (I != RegionMap.end()) {
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +0000212 llvm::Metadata *V = I->second;
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +0000213 return dyn_cast_or_null<llvm::DIScope>(V);
Guy Benyei11169dd2012-12-18 14:30:41 +0000214 }
215
216 // Check namespace.
Adrian Prantlddb8e062017-05-12 16:23:53 +0000217 if (const auto *NSDecl = dyn_cast<NamespaceDecl>(Context))
218 return getOrCreateNamespace(NSDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +0000219
David Majnemer58ed0f32016-07-17 00:39:12 +0000220 if (const auto *RDecl = dyn_cast<RecordDecl>(Context))
David Blaikiebfa52742013-04-19 06:56:38 +0000221 if (!RDecl->isDependentType())
222 return getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
Eric Christophere7b87e52014-10-26 23:40:33 +0000223 getOrCreateMainFile());
Adrian Prantl6ec370a2015-09-10 18:39:45 +0000224 return Default;
Guy Benyei11169dd2012-12-18 14:30:41 +0000225}
226
Reid Kleckner59d12202017-08-08 01:33:53 +0000227PrintingPolicy CGDebugInfo::getPrintingPolicy() const {
228 PrintingPolicy PP = CGM.getContext().getPrintingPolicy();
229
230 // If we're emitting codeview, it's important to try to match MSVC's naming so
231 // that visualizers written for MSVC will trigger for our class names. In
232 // particular, we can't have spaces between arguments of standard templates
233 // like basic_string and vector.
234 if (CGM.getCodeGenOpts().EmitCodeView)
235 PP.MSVCFormatting = true;
236
Adrian Prantl56acd5a2018-12-05 18:37:44 +0000237 // Apply -fdebug-prefix-map.
238 PP.RemapFilePaths = true;
239 PP.remapPath = [this](StringRef Path) { return remapDIPath(Path); };
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() << ')';
Adrian Prantlb39fc142013-05-17 23:58:45 +0000296 } else if (isa<ObjCProtocolDecl>(DC)) {
Adrian Prantl6e785ec2013-05-17 23:49:10 +0000297 // We can extract the type of the class from the self pointer.
Eric Christophere7b87e52014-10-26 23:40:33 +0000298 if (ImplicitParamDecl *SelfDecl = OMD->getSelfDecl()) {
Adrian Prantl6e785ec2013-05-17 23:49:10 +0000299 QualType ClassTy =
Eric Christophere7b87e52014-10-26 23:40:33 +0000300 cast<ObjCObjectPointerType>(SelfDecl->getType())->getPointeeType();
Adrian Prantl6e785ec2013-05-17 23:49:10 +0000301 ClassTy.print(OS, PrintingPolicy(LangOptions()));
302 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000303 }
304 OS << ' ' << OMD->getSelector().getAsString() << ']';
305
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +0000306 return internString(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +0000307}
308
Guy Benyei11169dd2012-12-18 14:30:41 +0000309StringRef CGDebugInfo::getSelectorName(Selector S) {
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +0000310 return internString(S.getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +0000311}
312
Eric Christophere7b87e52014-10-26 23:40:33 +0000313StringRef CGDebugInfo::getClassName(const RecordDecl *RD) {
David Majnemerbc5976a2016-07-01 23:12:54 +0000314 if (isa<ClassTemplateSpecializationDecl>(RD)) {
315 SmallString<128> Name;
David Blaikie65813a32014-04-02 18:21:09 +0000316 llvm::raw_svector_ostream OS(Name);
Reid Kleckner59d12202017-08-08 01:33:53 +0000317 RD->getNameForDiagnostic(OS, getPrintingPolicy(),
David Blaikie65813a32014-04-02 18:21:09 +0000318 /*Qualified*/ false);
David Majnemerbc5976a2016-07-01 23:12:54 +0000319
320 // Copy this name on the side and use its reference.
321 return internString(Name);
Benjamin Kramer9170e912013-02-22 15:46:01 +0000322 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000323
David Majnemerbc5976a2016-07-01 23:12:54 +0000324 // quick optimization to avoid having to intern strings that are already
325 // stored reliably elsewhere
326 if (const IdentifierInfo *II = RD->getIdentifier())
327 return II->getName();
328
329 // The CodeView printer in LLVM wants to see the names of unnamed types: it is
330 // used to reconstruct the fully qualified type names.
331 if (CGM.getCodeGenOpts().EmitCodeView) {
332 if (const TypedefNameDecl *D = RD->getTypedefNameForAnonDecl()) {
333 assert(RD->getDeclContext() == D->getDeclContext() &&
334 "Typedef should not be in another decl context!");
335 assert(D->getDeclName().getAsIdentifierInfo() &&
336 "Typedef was not named!");
337 return D->getDeclName().getAsIdentifierInfo()->getName();
338 }
339
340 if (CGM.getLangOpts().CPlusPlus) {
341 StringRef Name;
342
343 ASTContext &Context = CGM.getContext();
344 if (const DeclaratorDecl *DD = Context.getDeclaratorForUnnamedTagDecl(RD))
345 // Anonymous types without a name for linkage purposes have their
346 // declarator mangled in if they have one.
347 Name = DD->getName();
348 else if (const TypedefNameDecl *TND =
349 Context.getTypedefNameForUnnamedTagDecl(RD))
350 // Anonymous types without a name for linkage purposes have their
351 // associate typedef mangled in if they have one.
352 Name = TND->getName();
353
354 if (!Name.empty()) {
355 SmallString<256> UnnamedType("<unnamed-type-");
356 UnnamedType += Name;
357 UnnamedType += '>';
358 return internString(UnnamedType);
359 }
360 }
361 }
362
363 return StringRef();
Guy Benyei11169dd2012-12-18 14:30:41 +0000364}
365
Scott Linder94834f12018-02-12 19:47:05 +0000366Optional<llvm::DIFile::ChecksumKind>
Amjad Aboude2aab8c2016-12-25 10:12:27 +0000367CGDebugInfo::computeChecksum(FileID FID, SmallString<32> &Checksum) const {
368 Checksum.clear();
369
Paul Robinson76178632018-05-25 22:35:59 +0000370 if (!CGM.getCodeGenOpts().EmitCodeView &&
371 CGM.getCodeGenOpts().DwarfVersion < 5)
Scott Linder94834f12018-02-12 19:47:05 +0000372 return None;
Amjad Aboude2aab8c2016-12-25 10:12:27 +0000373
374 SourceManager &SM = CGM.getContext().getSourceManager();
375 bool Invalid;
Paul Robinson76178632018-05-25 22:35:59 +0000376 llvm::MemoryBuffer *MemBuffer = SM.getBuffer(FID, &Invalid);
377 if (Invalid)
Scott Linder94834f12018-02-12 19:47:05 +0000378 return None;
Amjad Aboude2aab8c2016-12-25 10:12:27 +0000379
380 llvm::MD5 Hash;
381 llvm::MD5::MD5Result Result;
382
383 Hash.update(MemBuffer->getBuffer());
384 Hash.final(Result);
385
386 Hash.stringifyResult(Result, Checksum);
387 return llvm::DIFile::CSK_MD5;
388}
389
Jonas Devlieghere9ef49652018-06-28 10:56:40 +0000390Optional<StringRef> CGDebugInfo::getSource(const SourceManager &SM,
391 FileID FID) {
Scott Lindera2fbcef2018-02-26 17:32:31 +0000392 if (!CGM.getCodeGenOpts().EmbedSource)
393 return None;
394
395 bool SourceInvalid = false;
396 StringRef Source = SM.getBufferData(FID, &SourceInvalid);
397
398 if (SourceInvalid)
399 return None;
400
401 return Source;
402}
403
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +0000404llvm::DIFile *CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000405 if (!Loc.isValid())
406 // If Location is not valid then use main input file.
Scott Linder39ceac12018-02-26 16:31:08 +0000407 return getOrCreateMainFile();
Guy Benyei11169dd2012-12-18 14:30:41 +0000408
409 SourceManager &SM = CGM.getContext().getSourceManager();
410 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
411
Adrian Prantl212c1042018-12-06 18:44:50 +0000412 StringRef FileName = PLoc.getFilename();
413 if (PLoc.isInvalid() || FileName.empty())
Guy Benyei11169dd2012-12-18 14:30:41 +0000414 // If the location is not valid then use main input file.
Scott Linder39ceac12018-02-26 16:31:08 +0000415 return getOrCreateMainFile();
Guy Benyei11169dd2012-12-18 14:30:41 +0000416
417 // Cache the results.
Adrian Prantl212c1042018-12-06 18:44:50 +0000418 auto It = DIFileCache.find(FileName.data());
Guy Benyei11169dd2012-12-18 14:30:41 +0000419
Jonas Devlieghere9ef49652018-06-28 10:56:40 +0000420 if (It != DIFileCache.end()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000421 // Verify that the information still exists.
Jonas Devlieghere9ef49652018-06-28 10:56:40 +0000422 if (llvm::Metadata *V = It->second)
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +0000423 return cast<llvm::DIFile>(V);
Guy Benyei11169dd2012-12-18 14:30:41 +0000424 }
425
Amjad Aboude2aab8c2016-12-25 10:12:27 +0000426 SmallString<32> Checksum;
Scott Linder94834f12018-02-12 19:47:05 +0000427 Optional<llvm::DIFile::ChecksumKind> CSKind =
Amjad Aboude2aab8c2016-12-25 10:12:27 +0000428 computeChecksum(SM.getFileID(Loc), Checksum);
Scott Linder94834f12018-02-12 19:47:05 +0000429 Optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo;
430 if (CSKind)
431 CSInfo.emplace(*CSKind, Checksum);
Amjad Aboude2aab8c2016-12-25 10:12:27 +0000432
Adrian Prantl212c1042018-12-06 18:44:50 +0000433 StringRef Dir;
434 StringRef File;
435 std::string RemappedFile = remapDIPath(FileName);
436 std::string CurDir = remapDIPath(getCurrentDirname());
437 SmallString<128> DirBuf;
438 SmallString<128> FileBuf;
439 if (llvm::sys::path::is_absolute(RemappedFile)) {
440 // Strip the common prefix (if it is more than just "/") from current
441 // directory and FileName for a more space-efficient encoding.
442 auto FileIt = llvm::sys::path::begin(RemappedFile);
443 auto FileE = llvm::sys::path::end(RemappedFile);
444 auto CurDirIt = llvm::sys::path::begin(CurDir);
445 auto CurDirE = llvm::sys::path::end(CurDir);
446 for (; CurDirIt != CurDirE && *CurDirIt == *FileIt; ++CurDirIt, ++FileIt)
447 llvm::sys::path::append(DirBuf, *CurDirIt);
448 if (std::distance(llvm::sys::path::begin(CurDir), CurDirIt) == 1) {
449 // The common prefix only the root; stripping it would cause
450 // LLVM diagnostic locations to be more confusing.
451 Dir = {};
452 File = RemappedFile;
453 } else {
454 for (; FileIt != FileE; ++FileIt)
455 llvm::sys::path::append(FileBuf, *FileIt);
456 Dir = DirBuf;
457 File = FileBuf;
458 }
459 } else {
460 Dir = CurDir;
461 File = RemappedFile;
462 }
463 llvm::DIFile *F =
464 DBuilder.createFile(File, Dir, CSInfo,
465 getSource(SM, SM.getFileID(Loc)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000466
Adrian Prantl212c1042018-12-06 18:44:50 +0000467 DIFileCache[FileName.data()].reset(F);
Guy Benyei11169dd2012-12-18 14:30:41 +0000468 return F;
469}
470
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +0000471llvm::DIFile *CGDebugInfo::getOrCreateMainFile() {
Scott Lindera2fbcef2018-02-26 17:32:31 +0000472 return DBuilder.createFile(
Jonas Devlieghere9ef49652018-06-28 10:56:40 +0000473 remapDIPath(TheCU->getFilename()), remapDIPath(TheCU->getDirectory()),
Scott Lindera2fbcef2018-02-26 17:32:31 +0000474 TheCU->getFile()->getChecksum(),
475 CGM.getCodeGenOpts().EmbedSource ? TheCU->getSource() : None);
Saleem Abdulrasool436256a2015-10-12 20:21:08 +0000476}
477
478std::string CGDebugInfo::remapDIPath(StringRef Path) const {
479 for (const auto &Entry : DebugPrefixMap)
480 if (Path.startswith(Entry.first))
481 return (Twine(Entry.second) + Path.substr(Entry.first.size())).str();
482 return Path.str();
Guy Benyei11169dd2012-12-18 14:30:41 +0000483}
484
Guy Benyei11169dd2012-12-18 14:30:41 +0000485unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
486 if (Loc.isInvalid() && CurLoc.isInvalid())
487 return 0;
488 SourceManager &SM = CGM.getContext().getSourceManager();
489 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
Eric Christophere7b87e52014-10-26 23:40:33 +0000490 return PLoc.isValid() ? PLoc.getLine() : 0;
Guy Benyei11169dd2012-12-18 14:30:41 +0000491}
492
Adrian Prantlc7822422013-03-12 20:43:25 +0000493unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000494 // We may not want column information at all.
Adrian Prantlc7822422013-03-12 20:43:25 +0000495 if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo)
Guy Benyei11169dd2012-12-18 14:30:41 +0000496 return 0;
497
498 // If the location is invalid then use the current column.
499 if (Loc.isInvalid() && CurLoc.isInvalid())
500 return 0;
501 SourceManager &SM = CGM.getContext().getSourceManager();
502 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
Eric Christophere7b87e52014-10-26 23:40:33 +0000503 return PLoc.isValid() ? PLoc.getColumn() : 0;
Guy Benyei11169dd2012-12-18 14:30:41 +0000504}
505
506StringRef CGDebugInfo::getCurrentDirname() {
507 if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
508 return CGM.getCodeGenOpts().DebugCompilationDir;
509
510 if (!CWDName.empty())
511 return CWDName;
512 SmallString<256> CWD;
513 llvm::sys::fs::current_path(CWD);
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +0000514 return CWDName = internString(CWD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000515}
516
Guy Benyei11169dd2012-12-18 14:30:41 +0000517void CGDebugInfo::CreateCompileUnit() {
Amjad Aboude2aab8c2016-12-25 10:12:27 +0000518 SmallString<32> Checksum;
Scott Linder94834f12018-02-12 19:47:05 +0000519 Optional<llvm::DIFile::ChecksumKind> CSKind;
520 Optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo;
Guy Benyei11169dd2012-12-18 14:30:41 +0000521
David Blaikieaabde052014-05-14 00:29:00 +0000522 // Should we be asking the SourceManager for the main file name, instead of
523 // accepting it as an argument? This just causes the main file name to
524 // mismatch with source locations and create extra lexical scopes or
525 // mismatched debug info (a CU with a DW_AT_file of "-", because that's what
526 // the driver passed, but functions/other things have DW_AT_file of "<stdin>"
527 // because that's what the SourceManager says)
528
Guy Benyei11169dd2012-12-18 14:30:41 +0000529 // Get absolute path name.
530 SourceManager &SM = CGM.getContext().getSourceManager();
531 std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
532 if (MainFileName.empty())
David Blaikieaabde052014-05-14 00:29:00 +0000533 MainFileName = "<stdin>";
Guy Benyei11169dd2012-12-18 14:30:41 +0000534
535 // The main file name provided via the "-main-file-name" option contains just
536 // the file name itself with no path information. This file name may have had
537 // a relative path, so we look into the actual file entry for the main
538 // file to determine the real absolute path for the file.
539 std::string MainFileDir;
540 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
Saleem Abdulrasool436256a2015-10-12 20:21:08 +0000541 MainFileDir = remapDIPath(MainFile->getDir()->getName());
Yaron Keren9fb7e902013-10-21 20:07:37 +0000542 if (MainFileDir != ".") {
Eric Christopher0a1301f2014-02-26 02:49:36 +0000543 llvm::SmallString<1024> MainFileDirSS(MainFileDir);
544 llvm::sys::path::append(MainFileDirSS, MainFileName);
545 MainFileName = MainFileDirSS.str();
Yaron Keren9fb7e902013-10-21 20:07:37 +0000546 }
Taewook Oh0fb5b782017-08-16 19:36:24 +0000547 // If the main file name provided is identical to the input file name, and
548 // if the input file is a preprocessed source, use the module name for
549 // debug info. The module name comes from the name specified in the first
550 // linemarker if the input is a preprocessed source.
551 if (MainFile->getName() == MainFileName &&
552 FrontendOptions::getInputKindForExtension(
553 MainFile->getName().rsplit('.').second)
554 .isPreprocessed())
555 MainFileName = CGM.getModule().getName().str();
556
Amjad Aboude2aab8c2016-12-25 10:12:27 +0000557 CSKind = computeChecksum(SM.getMainFileID(), Checksum);
Guy Benyei11169dd2012-12-18 14:30:41 +0000558 }
559
Ed Masteda706022014-05-07 12:49:30 +0000560 llvm::dwarf::SourceLanguage LangTag;
Guy Benyei11169dd2012-12-18 14:30:41 +0000561 const LangOptions &LO = CGM.getLangOpts();
562 if (LO.CPlusPlus) {
Erik Pilkingtonfa983902018-10-30 20:31:30 +0000563 if (LO.ObjC)
Guy Benyei11169dd2012-12-18 14:30:41 +0000564 LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
565 else
566 LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
Erik Pilkingtonfa983902018-10-30 20:31:30 +0000567 } else if (LO.ObjC) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000568 LangTag = llvm::dwarf::DW_LANG_ObjC;
Pirama Arumuga Nainara7484c92016-06-21 21:35:11 +0000569 } else if (LO.RenderScript) {
570 LangTag = llvm::dwarf::DW_LANG_GOOGLE_RenderScript;
Guy Benyei11169dd2012-12-18 14:30:41 +0000571 } else if (LO.C99) {
572 LangTag = llvm::dwarf::DW_LANG_C99;
573 } else {
574 LangTag = llvm::dwarf::DW_LANG_C89;
575 }
576
577 std::string Producer = getClangFullVersion();
578
579 // Figure out which version of the ObjC runtime we have.
580 unsigned RuntimeVers = 0;
Erik Pilkingtonfa983902018-10-30 20:31:30 +0000581 if (LO.ObjC)
Guy Benyei11169dd2012-12-18 14:30:41 +0000582 RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
583
Adrian Prantl826824e2016-04-08 22:43:06 +0000584 llvm::DICompileUnit::DebugEmissionKind EmissionKind;
585 switch (DebugKind) {
586 case codegenoptions::NoDebugInfo:
587 case codegenoptions::LocTrackingOnly:
588 EmissionKind = llvm::DICompileUnit::NoDebug;
589 break;
590 case codegenoptions::DebugLineTablesOnly:
591 EmissionKind = llvm::DICompileUnit::LineTablesOnly;
592 break;
Alexey Bataev80e1b5e2018-08-31 13:56:14 +0000593 case codegenoptions::DebugDirectivesOnly:
594 EmissionKind = llvm::DICompileUnit::DebugDirectivesOnly;
595 break;
Adrian Prantl826824e2016-04-08 22:43:06 +0000596 case codegenoptions::LimitedDebugInfo:
597 case codegenoptions::FullDebugInfo:
598 EmissionKind = llvm::DICompileUnit::FullDebug;
599 break;
600 }
601
Scott Linder94834f12018-02-12 19:47:05 +0000602 if (CSKind)
603 CSInfo.emplace(*CSKind, Checksum);
604
Guy Benyei11169dd2012-12-18 14:30:41 +0000605 // Create new compile unit.
Guy Benyei11169dd2012-12-18 14:30:41 +0000606 // FIXME - Eliminate TheCU.
Adrian Prantlb4423022017-08-04 23:08:57 +0000607 auto &CGOpts = CGM.getCodeGenOpts();
Eric Christophere4200a22014-02-27 01:25:08 +0000608 TheCU = DBuilder.createCompileUnit(
David Blaikie81503552017-04-21 23:35:36 +0000609 LangTag,
610 DBuilder.createFile(remapDIPath(MainFileName),
Jonas Devlieghere9ef49652018-06-28 10:56:40 +0000611 remapDIPath(getCurrentDirname()), CSInfo,
Scott Lindera2fbcef2018-02-26 17:32:31 +0000612 getSource(SM, SM.getMainFileID())),
Mikhail Maltsev4a4e7a32018-04-23 10:08:46 +0000613 CGOpts.EmitVersionIdentMetadata ? Producer : "",
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +0000614 LO.Optimize || CGOpts.PrepareForLTO || CGOpts.PrepareForThinLTO,
Adrian Prantlb4423022017-08-04 23:08:57 +0000615 CGOpts.DwarfDebugFlags, RuntimeVers,
George Rimar91829ee2018-11-14 09:22:16 +0000616 (CGOpts.getSplitDwarfMode() != CodeGenOptions::NoFission)
617 ? ""
618 : CGOpts.SplitDwarfFile,
619 EmissionKind, 0 /* DWOid */, CGOpts.SplitDwarfInlining,
620 CGOpts.DebugInfoForProfiling,
David Blaikie9982bb82018-08-16 23:56:32 +0000621 CGM.getTarget().getTriple().isNVPTX()
622 ? llvm::DICompileUnit::DebugNameTableKind::None
David Blaikie65864522018-08-20 20:14:08 +0000623 : static_cast<llvm::DICompileUnit::DebugNameTableKind>(
David Blaikie27692de2018-11-13 20:08:13 +0000624 CGOpts.DebugNameTable),
625 CGOpts.DebugRangesBaseAddress);
Guy Benyei11169dd2012-12-18 14:30:41 +0000626}
627
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +0000628llvm::DIType *CGDebugInfo::CreateType(const BuiltinType *BT) {
Ed Masteda706022014-05-07 12:49:30 +0000629 llvm::dwarf::TypeKind Encoding;
Guy Benyei11169dd2012-12-18 14:30:41 +0000630 StringRef BTName;
631 switch (BT->getKind()) {
632#define BUILTIN_TYPE(Id, SingletonId)
Eric Christophere7b87e52014-10-26 23:40:33 +0000633#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
Guy Benyei11169dd2012-12-18 14:30:41 +0000634#include "clang/AST/BuiltinTypes.def"
635 case BuiltinType::Dependent:
636 llvm_unreachable("Unexpected builtin type");
637 case BuiltinType::NullPtr:
Peter Collingbourne5c5e6172013-06-27 22:51:01 +0000638 return DBuilder.createNullPtrType();
Guy Benyei11169dd2012-12-18 14:30:41 +0000639 case BuiltinType::Void:
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +0000640 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000641 case BuiltinType::ObjCClass:
David Blaikief427b002014-05-06 03:42:01 +0000642 if (!ClassTy)
643 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
644 "objc_class", TheCU,
645 getOrCreateMainFile(), 0);
Guy Benyei11169dd2012-12-18 14:30:41 +0000646 return ClassTy;
647 case BuiltinType::ObjCId: {
648 // typedef struct objc_class *Class;
649 // typedef struct objc_object {
650 // Class isa;
651 // } *id;
652
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000653 if (ObjTy)
Guy Benyei11169dd2012-12-18 14:30:41 +0000654 return ObjTy;
655
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000656 if (!ClassTy)
Guy Benyei11169dd2012-12-18 14:30:41 +0000657 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
658 "objc_class", TheCU,
659 getOrCreateMainFile(), 0);
660
661 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
Eric Christopherb2a008c2013-05-16 00:45:12 +0000662
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +0000663 auto *ISATy = DBuilder.createPointerType(ClassTy, Size);
Guy Benyei11169dd2012-12-18 14:30:41 +0000664
Leny Kholodovdf050fd2016-09-06 17:06:14 +0000665 ObjTy = DBuilder.createStructType(
666 TheCU, "objc_object", getOrCreateMainFile(), 0, 0, 0,
667 llvm::DINode::FlagZero, nullptr, llvm::DINodeArray());
Guy Benyei11169dd2012-12-18 14:30:41 +0000668
Duncan P. N. Exon Smithc8ee63e2014-12-18 00:48:56 +0000669 DBuilder.replaceArrays(
Leny Kholodovdf050fd2016-09-06 17:06:14 +0000670 ObjTy, DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
671 ObjTy, "isa", getOrCreateMainFile(), 0, Size, 0, 0,
672 llvm::DINode::FlagZero, ISATy)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000673 return ObjTy;
674 }
675 case BuiltinType::ObjCSel: {
David Blaikief427b002014-05-06 03:42:01 +0000676 if (!SelTy)
677 SelTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
678 "objc_selector", TheCU,
679 getOrCreateMainFile(), 0);
Guy Benyei11169dd2012-12-18 14:30:41 +0000680 return SelTy;
681 }
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000682
Jonas Devlieghere9ef49652018-06-28 10:56:40 +0000683#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
684 case BuiltinType::Id: \
685 return getOrCreateStructPtrType("opencl_" #ImgType "_" #Suffix "_t", \
Alexey Bader954ba212016-04-08 13:40:33 +0000686 SingletonId);
Alexey Baderb62f1442016-04-13 08:33:41 +0000687#include "clang/Basic/OpenCLImageTypes.def"
Guy Benyei61054192013-02-07 10:55:47 +0000688 case BuiltinType::OCLSampler:
Jonas Devlieghere9ef49652018-06-28 10:56:40 +0000689 return getOrCreateStructPtrType("opencl_sampler_t", OCLSamplerDITy);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +0000690 case BuiltinType::OCLEvent:
Eric Christophere7b87e52014-10-26 23:40:33 +0000691 return getOrCreateStructPtrType("opencl_event_t", OCLEventDITy);
Alexey Bader9c8453f2015-09-15 11:18:52 +0000692 case BuiltinType::OCLClkEvent:
693 return getOrCreateStructPtrType("opencl_clk_event_t", OCLClkEventDITy);
694 case BuiltinType::OCLQueue:
695 return getOrCreateStructPtrType("opencl_queue_t", OCLQueueDITy);
Alexey Bader9c8453f2015-09-15 11:18:52 +0000696 case BuiltinType::OCLReserveID:
697 return getOrCreateStructPtrType("opencl_reserve_id_t", OCLReserveIDDITy);
Andrew Savonichev3fee3512018-11-08 11:25:41 +0000698#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
699 case BuiltinType::Id: \
700 return getOrCreateStructPtrType("opencl_" #ExtType, Id##Ty);
701#include "clang/Basic/OpenCLExtensionTypes.def"
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000702
Guy Benyei11169dd2012-12-18 14:30:41 +0000703 case BuiltinType::UChar:
Eric Christophere7b87e52014-10-26 23:40:33 +0000704 case BuiltinType::Char_U:
705 Encoding = llvm::dwarf::DW_ATE_unsigned_char;
706 break;
Guy Benyei11169dd2012-12-18 14:30:41 +0000707 case BuiltinType::Char_S:
Eric Christophere7b87e52014-10-26 23:40:33 +0000708 case BuiltinType::SChar:
709 Encoding = llvm::dwarf::DW_ATE_signed_char;
710 break;
Richard Smith3a8244d2018-05-01 05:02:45 +0000711 case BuiltinType::Char8:
Guy Benyei11169dd2012-12-18 14:30:41 +0000712 case BuiltinType::Char16:
Eric Christophere7b87e52014-10-26 23:40:33 +0000713 case BuiltinType::Char32:
714 Encoding = llvm::dwarf::DW_ATE_UTF;
715 break;
Guy Benyei11169dd2012-12-18 14:30:41 +0000716 case BuiltinType::UShort:
717 case BuiltinType::UInt:
718 case BuiltinType::UInt128:
719 case BuiltinType::ULong:
720 case BuiltinType::WChar_U:
Eric Christophere7b87e52014-10-26 23:40:33 +0000721 case BuiltinType::ULongLong:
722 Encoding = llvm::dwarf::DW_ATE_unsigned;
723 break;
Guy Benyei11169dd2012-12-18 14:30:41 +0000724 case BuiltinType::Short:
725 case BuiltinType::Int:
726 case BuiltinType::Int128:
727 case BuiltinType::Long:
728 case BuiltinType::WChar_S:
Eric Christophere7b87e52014-10-26 23:40:33 +0000729 case BuiltinType::LongLong:
730 Encoding = llvm::dwarf::DW_ATE_signed;
731 break;
732 case BuiltinType::Bool:
733 Encoding = llvm::dwarf::DW_ATE_boolean;
734 break;
Guy Benyei11169dd2012-12-18 14:30:41 +0000735 case BuiltinType::Half:
736 case BuiltinType::Float:
737 case BuiltinType::LongDouble:
Sjoerd Meijercc623ad2017-09-08 15:15:00 +0000738 case BuiltinType::Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +0000739 case BuiltinType::Float128:
Eric Christophere7b87e52014-10-26 23:40:33 +0000740 case BuiltinType::Double:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +0000741 // FIXME: For targets where long double and __float128 have the same size,
742 // they are currently indistinguishable in the debugger without some
743 // special treatment. However, there is currently no consensus on encoding
744 // and this should be updated once a DWARF encoding exists for distinct
745 // floating point types of the same size.
Eric Christophere7b87e52014-10-26 23:40:33 +0000746 Encoding = llvm::dwarf::DW_ATE_float;
747 break;
Leonard Chanf921d852018-06-04 16:07:52 +0000748 case BuiltinType::ShortAccum:
749 case BuiltinType::Accum:
750 case BuiltinType::LongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +0000751 case BuiltinType::ShortFract:
752 case BuiltinType::Fract:
753 case BuiltinType::LongFract:
754 case BuiltinType::SatShortFract:
755 case BuiltinType::SatFract:
756 case BuiltinType::SatLongFract:
757 case BuiltinType::SatShortAccum:
758 case BuiltinType::SatAccum:
759 case BuiltinType::SatLongAccum:
Leonard Chanf921d852018-06-04 16:07:52 +0000760 Encoding = llvm::dwarf::DW_ATE_signed_fixed;
761 break;
762 case BuiltinType::UShortAccum:
763 case BuiltinType::UAccum:
764 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +0000765 case BuiltinType::UShortFract:
766 case BuiltinType::UFract:
767 case BuiltinType::ULongFract:
768 case BuiltinType::SatUShortAccum:
769 case BuiltinType::SatUAccum:
770 case BuiltinType::SatULongAccum:
771 case BuiltinType::SatUShortFract:
772 case BuiltinType::SatUFract:
773 case BuiltinType::SatULongFract:
Leonard Chanf921d852018-06-04 16:07:52 +0000774 Encoding = llvm::dwarf::DW_ATE_unsigned_fixed;
775 break;
Guy Benyei11169dd2012-12-18 14:30:41 +0000776 }
777
778 switch (BT->getKind()) {
Eric Christophere7b87e52014-10-26 23:40:33 +0000779 case BuiltinType::Long:
780 BTName = "long int";
781 break;
782 case BuiltinType::LongLong:
783 BTName = "long long int";
784 break;
785 case BuiltinType::ULong:
786 BTName = "long unsigned int";
787 break;
788 case BuiltinType::ULongLong:
789 BTName = "long long unsigned int";
790 break;
Guy Benyei11169dd2012-12-18 14:30:41 +0000791 default:
792 BTName = BT->getName(CGM.getLangOpts());
793 break;
794 }
Victor Leschuka7ece032016-10-20 00:13:19 +0000795 // Bit size and offset of the type.
Guy Benyei11169dd2012-12-18 14:30:41 +0000796 uint64_t Size = CGM.getContext().getTypeSize(BT);
Victor Leschuka7ece032016-10-20 00:13:19 +0000797 return DBuilder.createBasicType(BTName, Size, Encoding);
Guy Benyei11169dd2012-12-18 14:30:41 +0000798}
799
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +0000800llvm::DIType *CGDebugInfo::CreateType(const ComplexType *Ty) {
Victor Leschuka7ece032016-10-20 00:13:19 +0000801 // Bit size and offset of the type.
Ed Masteda706022014-05-07 12:49:30 +0000802 llvm::dwarf::TypeKind Encoding = llvm::dwarf::DW_ATE_complex_float;
Guy Benyei11169dd2012-12-18 14:30:41 +0000803 if (Ty->isComplexIntegerType())
804 Encoding = llvm::dwarf::DW_ATE_lo_user;
805
806 uint64_t Size = CGM.getContext().getTypeSize(Ty);
Victor Leschuka7ece032016-10-20 00:13:19 +0000807 return DBuilder.createBasicType("complex", Size, Encoding);
Guy Benyei11169dd2012-12-18 14:30:41 +0000808}
809
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +0000810llvm::DIType *CGDebugInfo::CreateQualifiedType(QualType Ty,
811 llvm::DIFile *Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000812 QualifierCollector Qc;
813 const Type *T = Qc.strip(Ty);
814
815 // Ignore these qualifiers for now.
816 Qc.removeObjCGCAttr();
817 Qc.removeAddressSpace();
818 Qc.removeObjCLifetime();
819
820 // We will create one Derived type for one qualifier and recurse to handle any
821 // additional ones.
Ed Masteda706022014-05-07 12:49:30 +0000822 llvm::dwarf::Tag Tag;
Guy Benyei11169dd2012-12-18 14:30:41 +0000823 if (Qc.hasConst()) {
824 Tag = llvm::dwarf::DW_TAG_const_type;
825 Qc.removeConst();
826 } else if (Qc.hasVolatile()) {
827 Tag = llvm::dwarf::DW_TAG_volatile_type;
828 Qc.removeVolatile();
829 } else if (Qc.hasRestrict()) {
830 Tag = llvm::dwarf::DW_TAG_restrict_type;
831 Qc.removeRestrict();
832 } else {
833 assert(Qc.empty() && "Unknown type qualifier for debug info");
834 return getOrCreateType(QualType(T, 0), Unit);
835 }
836
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +0000837 auto *FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +0000838
839 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
840 // CVR derived types.
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +0000841 return DBuilder.createQualifiedType(Tag, FromTy);
Guy Benyei11169dd2012-12-18 14:30:41 +0000842}
843
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +0000844llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
845 llvm::DIFile *Unit) {
Fariborz Jahanian65f1fa12013-02-21 20:42:11 +0000846
847 // The frontend treats 'id' as a typedef to an ObjCObjectType,
848 // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
849 // debug info, we want to emit 'id' in both cases.
850 if (Ty->isObjCQualifiedIdType())
Eric Christophere7b87e52014-10-26 23:40:33 +0000851 return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
Fariborz Jahanian65f1fa12013-02-21 20:42:11 +0000852
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +0000853 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
854 Ty->getPointeeType(), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +0000855}
856
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +0000857llvm::DIType *CGDebugInfo::CreateType(const PointerType *Ty,
858 llvm::DIFile *Unit) {
Eric Christopherb2a008c2013-05-16 00:45:12 +0000859 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +0000860 Ty->getPointeeType(), Unit);
861}
862
Adrian Prantlc6f91a22015-06-15 23:18:16 +0000863/// \return whether a C++ mangling exists for the type defined by TD.
864static bool hasCXXMangling(const TagDecl *TD, llvm::DICompileUnit *TheCU) {
865 switch (TheCU->getSourceLanguage()) {
866 case llvm::dwarf::DW_LANG_C_plus_plus:
867 return true;
868 case llvm::dwarf::DW_LANG_ObjC_plus_plus:
869 return isa<CXXRecordDecl>(TD) || isa<EnumDecl>(TD);
870 default:
871 return false;
872 }
873}
874
Reid Kleckner59320fc2018-08-17 20:59:52 +0000875// Determines if the debug info for this tag declaration needs a type
876// identifier. The purpose of the unique identifier is to deduplicate type
877// information for identical types across TUs. Because of the C++ one definition
878// rule (ODR), it is valid to assume that the type is defined the same way in
879// every TU and its debug info is equivalent.
880//
881// C does not have the ODR, and it is common for codebases to contain multiple
882// different definitions of a struct with the same name in different TUs.
883// Therefore, if the type doesn't have a C++ mangling, don't give it an
884// identifer. Type information in C is smaller and simpler than C++ type
885// information, so the increase in debug info size is negligible.
886//
887// If the type is not externally visible, it should be unique to the current TU,
888// and should not need an identifier to participate in type deduplication.
889// However, when emitting CodeView, the format internally uses these
890// unique type name identifers for references between debug info. For example,
891// the method of a class in an anonymous namespace uses the identifer to refer
892// to its parent class. The Microsoft C++ ABI attempts to provide unique names
893// for such types, so when emitting CodeView, always use identifiers for C++
894// types. This may create problems when attempting to emit CodeView when the MS
895// C++ ABI is not in use.
Jonas Devlieghere9ef49652018-06-28 10:56:40 +0000896static bool needsTypeIdentifier(const TagDecl *TD, CodeGenModule &CGM,
Brock Wyma8557ec52018-05-22 12:41:19 +0000897 llvm::DICompileUnit *TheCU) {
898 // We only add a type identifier for types with C++ name mangling.
899 if (!hasCXXMangling(TD, TheCU))
900 return false;
901
Brock Wyma8557ec52018-05-22 12:41:19 +0000902 // Externally visible types with C++ mangling need a type identifier.
903 if (TD->isExternallyVisible())
904 return true;
905
Reid Kleckner59320fc2018-08-17 20:59:52 +0000906 // CodeView types with C++ mangling need a type identifier.
907 if (CGM.getCodeGenOpts().EmitCodeView)
908 return true;
909
Brock Wyma8557ec52018-05-22 12:41:19 +0000910 return false;
911}
912
Reid Kleckner59320fc2018-08-17 20:59:52 +0000913// Returns a unique type identifier string if one exists, or an empty string.
Jonas Devlieghere9ef49652018-06-28 10:56:40 +0000914static SmallString<256> getTypeIdentifier(const TagType *Ty, CodeGenModule &CGM,
Brock Wyma8557ec52018-05-22 12:41:19 +0000915 llvm::DICompileUnit *TheCU) {
916 SmallString<256> Identifier;
Manman Rene0064d82013-08-29 23:19:58 +0000917 const TagDecl *TD = Ty->getDecl();
Adrian Prantlc6f91a22015-06-15 23:18:16 +0000918
Brock Wyma8557ec52018-05-22 12:41:19 +0000919 if (!needsTypeIdentifier(TD, CGM, TheCU))
920 return Identifier;
Adrian Prantlc6f91a22015-06-15 23:18:16 +0000921
Manman Rene0064d82013-08-29 23:19:58 +0000922 // TODO: This is using the RTTI name. Is there a better way to get
923 // a unique string for a type?
Brock Wyma8557ec52018-05-22 12:41:19 +0000924 llvm::raw_svector_ostream Out(Identifier);
Manman Rene0064d82013-08-29 23:19:58 +0000925 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(QualType(Ty, 0), Out);
Brock Wyma8557ec52018-05-22 12:41:19 +0000926 return Identifier;
Manman Rene0064d82013-08-29 23:19:58 +0000927}
928
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +0000929/// \return the appropriate DWARF tag for a composite type.
Adrian Prantl5f66bae2015-02-11 17:45:15 +0000930static llvm::dwarf::Tag getTagForRecord(const RecordDecl *RD) {
Jonas Devlieghere9ef49652018-06-28 10:56:40 +0000931 llvm::dwarf::Tag Tag;
Adrian Prantl5f66bae2015-02-11 17:45:15 +0000932 if (RD->isStruct() || RD->isInterface())
933 Tag = llvm::dwarf::DW_TAG_structure_type;
934 else if (RD->isUnion())
935 Tag = llvm::dwarf::DW_TAG_union_type;
936 else {
937 // FIXME: This could be a struct type giving a default visibility different
938 // than C++ class type, but needs llvm metadata changes first.
939 assert(RD->isClass());
940 Tag = llvm::dwarf::DW_TAG_class_type;
941 }
942 return Tag;
943}
944
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +0000945llvm::DICompositeType *
Manman Ren1b457022013-08-28 21:20:28 +0000946CGDebugInfo::getOrCreateRecordFwdDecl(const RecordType *Ty,
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +0000947 llvm::DIScope *Ctx) {
Manman Ren1b457022013-08-28 21:20:28 +0000948 const RecordDecl *RD = Ty->getDecl();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +0000949 if (llvm::DIType *T = getTypeOrNull(CGM.getContext().getRecordType(RD)))
950 return cast<llvm::DICompositeType>(T);
951 llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +0000952 unsigned Line = getLineNumber(RD->getLocation());
953 StringRef RDName = getClassName(RD);
954
Peter Collingbourned251b0a2015-03-01 22:07:04 +0000955 uint64_t Size = 0;
Victor Leschuk802e4a52016-10-19 22:11:07 +0000956 uint32_t Align = 0;
Peter Collingbourned251b0a2015-03-01 22:07:04 +0000957
Guy Benyei11169dd2012-12-18 14:30:41 +0000958 // Create the type.
Brock Wyma8557ec52018-05-22 12:41:19 +0000959 SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +0000960 llvm::DICompositeType *RetTy = DBuilder.createReplaceableCompositeType(
Peter Collingbourned251b0a2015-03-01 22:07:04 +0000961 getTagForRecord(RD), RDName, Ctx, DefUnit, Line, 0, Size, Align,
Brock Wyma8557ec52018-05-22 12:41:19 +0000962 llvm::DINode::FlagFwdDecl, Identifier);
Paul Robinson1787f812017-09-28 18:37:02 +0000963 if (CGM.getCodeGenOpts().DebugFwdTemplateParams)
964 if (auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD))
965 DBuilder.replaceArrays(RetTy, llvm::DINodeArray(),
966 CollectCXXTemplateParams(TSpecial, DefUnit));
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +0000967 ReplaceMap.emplace_back(
968 std::piecewise_construct, std::make_tuple(Ty),
969 std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
David Blaikief427b002014-05-06 03:42:01 +0000970 return RetTy;
Guy Benyei11169dd2012-12-18 14:30:41 +0000971}
972
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +0000973llvm::DIType *CGDebugInfo::CreatePointerLikeType(llvm::dwarf::Tag Tag,
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +0000974 const Type *Ty,
975 QualType PointeeTy,
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +0000976 llvm::DIFile *Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000977 // Bit size, align and offset of the type.
978 // Size is always the size of a pointer. We can't use getTypeSize here
979 // because that does not return the correct value for references.
Konstantin Zhuravlyovd1ba16e2017-03-08 23:56:48 +0000980 unsigned AddressSpace = CGM.getContext().getTargetAddressSpace(PointeeTy);
981 uint64_t Size = CGM.getTarget().getPointerWidth(AddressSpace);
Victor Leschuka7ece032016-10-20 00:13:19 +0000982 auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
Konstantin Zhuravlyovd1ba16e2017-03-08 23:56:48 +0000983 Optional<unsigned> DWARFAddressSpace =
984 CGM.getTarget().getDWARFAddressSpace(AddressSpace);
Guy Benyei11169dd2012-12-18 14:30:41 +0000985
Keno Fischer87842f32015-11-16 09:04:13 +0000986 if (Tag == llvm::dwarf::DW_TAG_reference_type ||
987 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
988 return DBuilder.createReferenceType(Tag, getOrCreateType(PointeeTy, Unit),
Konstantin Zhuravlyovd1ba16e2017-03-08 23:56:48 +0000989 Size, Align, DWARFAddressSpace);
Keno Fischer87842f32015-11-16 09:04:13 +0000990 else
991 return DBuilder.createPointerType(getOrCreateType(PointeeTy, Unit), Size,
Konstantin Zhuravlyovd1ba16e2017-03-08 23:56:48 +0000992 Align, DWARFAddressSpace);
Guy Benyei11169dd2012-12-18 14:30:41 +0000993}
994
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +0000995llvm::DIType *CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
996 llvm::DIType *&Cache) {
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000997 if (Cache)
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000998 return Cache;
David Blaikiefefc7f72013-05-21 17:58:54 +0000999 Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
1000 TheCU, getOrCreateMainFile(), 0);
1001 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1002 Cache = DBuilder.createPointerType(Cache, Size);
1003 return Cache;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001004}
1005
Scott Linder58df0e42018-08-08 15:56:12 +00001006uint64_t CGDebugInfo::collectDefaultElementTypesForBlockPointer(
1007 const BlockPointerType *Ty, llvm::DIFile *Unit, llvm::DIDerivedType *DescTy,
1008 unsigned LineNo, SmallVectorImpl<llvm::Metadata *> &EltTys) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001009 QualType FType;
Guy Benyei11169dd2012-12-18 14:30:41 +00001010
Scott Linder58df0e42018-08-08 15:56:12 +00001011 // Advanced by calls to CreateMemberType in increments of FType, then
1012 // returned as the overall size of the default elements.
1013 uint64_t FieldOffset = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00001014
Scott Linder58df0e42018-08-08 15:56:12 +00001015 // Blocks in OpenCL have unique constraints which make the standard fields
1016 // redundant while requiring size and align fields for enqueue_kernel. See
1017 // initializeForBlockHeader in CGBlocks.cpp
Scott Linder2b5cf042018-07-30 20:31:11 +00001018 if (CGM.getLangOpts().OpenCL) {
1019 FType = CGM.getContext().IntTy;
1020 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
1021 EltTys.push_back(CreateMemberType(Unit, FType, "__align", &FieldOffset));
1022 } else {
1023 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1024 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
1025 FType = CGM.getContext().IntTy;
1026 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
1027 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
1028 FType = CGM.getContext().getPointerType(Ty->getPointeeType());
1029 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
1030 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
Scott Linder58df0e42018-08-08 15:56:12 +00001031 uint64_t FieldSize = CGM.getContext().getTypeSize(Ty);
1032 uint32_t FieldAlign = CGM.getContext().getTypeAlign(Ty);
Scott Linder2b5cf042018-07-30 20:31:11 +00001033 EltTys.push_back(DBuilder.createMemberType(
Scott Linder58df0e42018-08-08 15:56:12 +00001034 Unit, "__descriptor", nullptr, LineNo, FieldSize, FieldAlign,
1035 FieldOffset, llvm::DINode::FlagZero, DescTy));
Scott Lindera7c45682018-07-30 22:52:07 +00001036 FieldOffset += FieldSize;
Scott Linder2b5cf042018-07-30 20:31:11 +00001037 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001038
Scott Linder58df0e42018-08-08 15:56:12 +00001039 return FieldOffset;
1040}
1041
1042llvm::DIType *CGDebugInfo::CreateType(const BlockPointerType *Ty,
1043 llvm::DIFile *Unit) {
1044 SmallVector<llvm::Metadata *, 8> EltTys;
1045 QualType FType;
1046 uint64_t FieldOffset;
1047 llvm::DINodeArray Elements;
1048
1049 FieldOffset = 0;
1050 FType = CGM.getContext().UnsignedLongTy;
1051 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
1052 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
1053
1054 Elements = DBuilder.getOrCreateArray(EltTys);
1055 EltTys.clear();
1056
1057 llvm::DINode::DIFlags Flags = llvm::DINode::FlagAppleBlock;
1058
1059 auto *EltTy =
1060 DBuilder.createStructType(Unit, "__block_descriptor", nullptr, 0,
1061 FieldOffset, 0, Flags, nullptr, Elements);
1062
1063 // Bit size, align and offset of the type.
1064 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1065
1066 auto *DescTy = DBuilder.createPointerType(EltTy, Size);
1067
1068 FieldOffset = collectDefaultElementTypesForBlockPointer(Ty, Unit, DescTy,
1069 0, EltTys);
1070
Guy Benyei11169dd2012-12-18 14:30:41 +00001071 Elements = DBuilder.getOrCreateArray(EltTys);
1072
Adrian Prantl3d2c0512015-07-07 00:49:35 +00001073 // The __block_literal_generic structs are marked with a special
1074 // DW_AT_APPLE_BLOCK attribute and are an implementation detail only
1075 // the debugger needs to know about. To allow type uniquing, emit
1076 // them without a name or a location.
Scott Linder58df0e42018-08-08 15:56:12 +00001077 EltTy = DBuilder.createStructType(Unit, "", nullptr, 0, FieldOffset, 0,
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00001078 Flags, nullptr, Elements);
Guy Benyei11169dd2012-12-18 14:30:41 +00001079
Adrian Prantl3d2c0512015-07-07 00:49:35 +00001080 return DBuilder.createPointerType(EltTy, Size);
Guy Benyei11169dd2012-12-18 14:30:41 +00001081}
1082
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001083llvm::DIType *CGDebugInfo::CreateType(const TemplateSpecializationType *Ty,
1084 llvm::DIFile *Unit) {
David Blaikief1b382e2014-04-06 17:14:06 +00001085 assert(Ty->isTypeAlias());
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001086 llvm::DIType *Src = getOrCreateType(Ty->getAliasedType(), Unit);
David Blaikief1b382e2014-04-06 17:14:06 +00001087
1088 SmallString<128> NS;
1089 llvm::raw_svector_ostream OS(NS);
Serge Pavlov03e672c2017-11-28 16:14:14 +00001090 Ty->getTemplateName().print(OS, getPrintingPolicy(), /*qualified*/ false);
1091 printTemplateArgumentList(OS, Ty->template_arguments(), getPrintingPolicy());
David Blaikief1b382e2014-04-06 17:14:06 +00001092
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00001093 auto *AliasDecl =
1094 cast<TypeAliasTemplateDecl>(Ty->getTemplateName().getAsTemplateDecl())
1095 ->getTemplatedDecl();
David Blaikief1b382e2014-04-06 17:14:06 +00001096
1097 SourceLocation Loc = AliasDecl->getLocation();
Adrian Prantlb67dbce2015-09-11 18:45:02 +00001098 return DBuilder.createTypedef(Src, OS.str(), getOrCreateFile(Loc),
1099 getLineNumber(Loc),
1100 getDeclContextDescriptor(AliasDecl));
David Blaikief1b382e2014-04-06 17:14:06 +00001101}
1102
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001103llvm::DIType *CGDebugInfo::CreateType(const TypedefType *Ty,
1104 llvm::DIFile *Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001105 // We don't set size information, but do specify where the typedef was
1106 // declared.
Amjad Abouddc4531e2016-04-30 01:44:38 +00001107 SourceLocation Loc = Ty->getDecl()->getLocation();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001108
Duncan P. N. Exon Smith4078ad42015-04-16 16:36:45 +00001109 // Typedefs are derived from some other type.
1110 return DBuilder.createTypedef(
1111 getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit),
1112 Ty->getDecl()->getName(), getOrCreateFile(Loc), getLineNumber(Loc),
Amjad Abouddc4531e2016-04-30 01:44:38 +00001113 getDeclContextDescriptor(Ty->getDecl()));
Guy Benyei11169dd2012-12-18 14:30:41 +00001114}
1115
Reid Klecknerf00f8032016-06-08 20:41:54 +00001116static unsigned getDwarfCC(CallingConv CC) {
1117 switch (CC) {
1118 case CC_C:
1119 // Avoid emitting DW_AT_calling_convention if the C convention was used.
1120 return 0;
1121
1122 case CC_X86StdCall:
1123 return llvm::dwarf::DW_CC_BORLAND_stdcall;
1124 case CC_X86FastCall:
1125 return llvm::dwarf::DW_CC_BORLAND_msfastcall;
1126 case CC_X86ThisCall:
1127 return llvm::dwarf::DW_CC_BORLAND_thiscall;
1128 case CC_X86VectorCall:
1129 return llvm::dwarf::DW_CC_LLVM_vectorcall;
1130 case CC_X86Pascal:
1131 return llvm::dwarf::DW_CC_BORLAND_pascal;
Martin Storsjo022e7822017-07-17 20:49:45 +00001132 case CC_Win64:
Jonas Devliegheref0702682018-03-22 13:53:30 +00001133 return llvm::dwarf::DW_CC_LLVM_Win64;
Reid Klecknerf00f8032016-06-08 20:41:54 +00001134 case CC_X86_64SysV:
Jonas Devliegheref0702682018-03-22 13:53:30 +00001135 return llvm::dwarf::DW_CC_LLVM_X86_64SysV;
Reid Klecknerf00f8032016-06-08 20:41:54 +00001136 case CC_AAPCS:
Sander de Smalen44a22532018-11-26 16:38:37 +00001137 case CC_AArch64VectorCall:
Jonas Devliegheref0702682018-03-22 13:53:30 +00001138 return llvm::dwarf::DW_CC_LLVM_AAPCS;
Reid Klecknerf00f8032016-06-08 20:41:54 +00001139 case CC_AAPCS_VFP:
Jonas Devliegheref0702682018-03-22 13:53:30 +00001140 return llvm::dwarf::DW_CC_LLVM_AAPCS_VFP;
Reid Klecknerf00f8032016-06-08 20:41:54 +00001141 case CC_IntelOclBicc:
Jonas Devliegheref0702682018-03-22 13:53:30 +00001142 return llvm::dwarf::DW_CC_LLVM_IntelOclBicc;
Reid Klecknerf00f8032016-06-08 20:41:54 +00001143 case CC_SpirFunction:
Jonas Devliegheref0702682018-03-22 13:53:30 +00001144 return llvm::dwarf::DW_CC_LLVM_SpirFunction;
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00001145 case CC_OpenCLKernel:
Jonas Devliegheref0702682018-03-22 13:53:30 +00001146 return llvm::dwarf::DW_CC_LLVM_OpenCLKernel;
Reid Klecknerf00f8032016-06-08 20:41:54 +00001147 case CC_Swift:
Jonas Devliegheref0702682018-03-22 13:53:30 +00001148 return llvm::dwarf::DW_CC_LLVM_Swift;
Reid Klecknerf00f8032016-06-08 20:41:54 +00001149 case CC_PreserveMost:
Jonas Devliegheref0702682018-03-22 13:53:30 +00001150 return llvm::dwarf::DW_CC_LLVM_PreserveMost;
Reid Klecknerf00f8032016-06-08 20:41:54 +00001151 case CC_PreserveAll:
Jonas Devliegheref0702682018-03-22 13:53:30 +00001152 return llvm::dwarf::DW_CC_LLVM_PreserveAll;
Erich Keane757d3172016-11-02 18:29:35 +00001153 case CC_X86RegCall:
Jonas Devliegheref0702682018-03-22 13:53:30 +00001154 return llvm::dwarf::DW_CC_LLVM_X86RegCall;
Reid Klecknerf00f8032016-06-08 20:41:54 +00001155 }
1156 return 0;
1157}
1158
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001159llvm::DIType *CGDebugInfo::CreateType(const FunctionType *Ty,
1160 llvm::DIFile *Unit) {
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001161 SmallVector<llvm::Metadata *, 16> EltTys;
Guy Benyei11169dd2012-12-18 14:30:41 +00001162
1163 // Add the result type at least.
Alp Toker314cc812014-01-25 16:55:45 +00001164 EltTys.push_back(getOrCreateType(Ty->getReturnType(), Unit));
Guy Benyei11169dd2012-12-18 14:30:41 +00001165
1166 // Set up remainder of arguments if there is a prototype.
Adrian Prantl800faef2014-02-25 23:42:18 +00001167 // otherwise emit it as a variadic function.
Guy Benyei11169dd2012-12-18 14:30:41 +00001168 if (isa<FunctionNoProtoType>(Ty))
1169 EltTys.push_back(DBuilder.createUnspecifiedParameter());
David Majnemer58ed0f32016-07-17 00:39:12 +00001170 else if (const auto *FPT = dyn_cast<FunctionProtoType>(Ty)) {
1171 for (const QualType &ParamType : FPT->param_types())
1172 EltTys.push_back(getOrCreateType(ParamType, Unit));
Adrian Prantld45ba252014-02-25 19:38:11 +00001173 if (FPT->isVariadic())
1174 EltTys.push_back(DBuilder.createUnspecifiedParameter());
Guy Benyei11169dd2012-12-18 14:30:41 +00001175 }
1176
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001177 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
Leny Kholodov80c047d2016-09-06 10:48:04 +00001178 return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
Reid Klecknerf00f8032016-06-08 20:41:54 +00001179 getDwarfCC(Ty->getCallConv()));
Guy Benyei11169dd2012-12-18 14:30:41 +00001180}
1181
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001182/// Convert an AccessSpecifier into the corresponding DINode flag.
Adrian Prantl21361fb2014-08-29 22:44:27 +00001183/// As an optimization, return 0 if the access specifier equals the
1184/// default for the containing type.
Leny Kholodovdf050fd2016-09-06 17:06:14 +00001185static llvm::DINode::DIFlags getAccessFlag(AccessSpecifier Access,
1186 const RecordDecl *RD) {
Adrian Prantl21361fb2014-08-29 22:44:27 +00001187 AccessSpecifier Default = clang::AS_none;
1188 if (RD && RD->isClass())
1189 Default = clang::AS_private;
1190 else if (RD && (RD->isStruct() || RD->isUnion()))
1191 Default = clang::AS_public;
1192
1193 if (Access == Default)
Leny Kholodov80c047d2016-09-06 10:48:04 +00001194 return llvm::DINode::FlagZero;
Adrian Prantl21361fb2014-08-29 22:44:27 +00001195
Eric Christophere7b87e52014-10-26 23:40:33 +00001196 switch (Access) {
1197 case clang::AS_private:
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001198 return llvm::DINode::FlagPrivate;
Eric Christophere7b87e52014-10-26 23:40:33 +00001199 case clang::AS_protected:
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001200 return llvm::DINode::FlagProtected;
Eric Christophere7b87e52014-10-26 23:40:33 +00001201 case clang::AS_public:
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001202 return llvm::DINode::FlagPublic;
Eric Christophere7b87e52014-10-26 23:40:33 +00001203 case clang::AS_none:
Leny Kholodov80c047d2016-09-06 10:48:04 +00001204 return llvm::DINode::FlagZero;
Adrian Prantl21361fb2014-08-29 22:44:27 +00001205 }
1206 llvm_unreachable("unexpected access enumerator");
1207}
Guy Benyei11169dd2012-12-18 14:30:41 +00001208
David Majnemerb4b671e2016-06-30 03:01:59 +00001209llvm::DIType *CGDebugInfo::createBitFieldType(const FieldDecl *BitFieldDecl,
1210 llvm::DIScope *RecordTy,
1211 const RecordDecl *RD) {
1212 StringRef Name = BitFieldDecl->getName();
1213 QualType Ty = BitFieldDecl->getType();
1214 SourceLocation Loc = BitFieldDecl->getLocation();
1215 llvm::DIFile *VUnit = getOrCreateFile(Loc);
1216 llvm::DIType *DebugType = getOrCreateType(Ty, VUnit);
1217
1218 // Get the location for the field.
1219 llvm::DIFile *File = getOrCreateFile(Loc);
1220 unsigned Line = getLineNumber(Loc);
1221
1222 const CGBitFieldInfo &BitFieldInfo =
1223 CGM.getTypes().getCGRecordLayout(RD).getBitFieldInfo(BitFieldDecl);
1224 uint64_t SizeInBits = BitFieldInfo.Size;
1225 assert(SizeInBits > 0 && "found named 0-width bitfield");
David Majnemerb4b671e2016-06-30 03:01:59 +00001226 uint64_t StorageOffsetInBits =
1227 CGM.getContext().toBits(BitFieldInfo.StorageOffset);
Reid Kleckner06a4b2a2017-06-12 19:57:56 +00001228 uint64_t Offset = BitFieldInfo.Offset;
1229 // The bit offsets for big endian machines are reversed for big
1230 // endian target, compensate for that as the DIDerivedType requires
1231 // un-reversed offsets.
1232 if (CGM.getDataLayout().isBigEndian())
1233 Offset = BitFieldInfo.StorageSize - BitFieldInfo.Size - Offset;
1234 uint64_t OffsetInBits = StorageOffsetInBits + Offset;
Leny Kholodov80c047d2016-09-06 10:48:04 +00001235 llvm::DINode::DIFlags Flags = getAccessFlag(BitFieldDecl->getAccess(), RD);
David Majnemerb4b671e2016-06-30 03:01:59 +00001236 return DBuilder.createBitFieldMemberType(
Victor Leschuka7ece032016-10-20 00:13:19 +00001237 RecordTy, Name, File, Line, SizeInBits, OffsetInBits, StorageOffsetInBits,
1238 Flags, DebugType);
David Majnemerb4b671e2016-06-30 03:01:59 +00001239}
1240
1241llvm::DIType *
1242CGDebugInfo::createFieldType(StringRef name, QualType type, SourceLocation loc,
1243 AccessSpecifier AS, uint64_t offsetInBits,
Victor Leschuka7ece032016-10-20 00:13:19 +00001244 uint32_t AlignInBits, llvm::DIFile *tunit,
1245 llvm::DIScope *scope, const RecordDecl *RD) {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001246 llvm::DIType *debugType = getOrCreateType(type, tunit);
Guy Benyei11169dd2012-12-18 14:30:41 +00001247
1248 // Get the location for the field.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001249 llvm::DIFile *file = getOrCreateFile(loc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001250 unsigned line = getLineNumber(loc);
1251
David Majnemer34b57492014-07-30 01:30:47 +00001252 uint64_t SizeInBits = 0;
Victor Leschuka7ece032016-10-20 00:13:19 +00001253 auto Align = AlignInBits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001254 if (!type->isIncompleteArrayType()) {
David Majnemer34b57492014-07-30 01:30:47 +00001255 TypeInfo TI = CGM.getContext().getTypeInfo(type);
1256 SizeInBits = TI.Width;
Victor Leschuka7ece032016-10-20 00:13:19 +00001257 if (!Align)
1258 Align = getTypeAlignIfRequired(type, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00001259 }
1260
Leny Kholodov80c047d2016-09-06 10:48:04 +00001261 llvm::DINode::DIFlags flags = getAccessFlag(AS, RD);
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00001262 return DBuilder.createMemberType(scope, name, file, line, SizeInBits, Align,
1263 offsetInBits, flags, debugType);
Guy Benyei11169dd2012-12-18 14:30:41 +00001264}
1265
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001266void CGDebugInfo::CollectRecordLambdaFields(
1267 const CXXRecordDecl *CXXDecl, SmallVectorImpl<llvm::Metadata *> &elements,
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001268 llvm::DIType *RecordTy) {
Eric Christopher91a31902013-01-16 01:22:32 +00001269 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
1270 // has the name and the location of the variable so we should iterate over
1271 // both concurrently.
1272 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
1273 RecordDecl::field_iterator Field = CXXDecl->field_begin();
1274 unsigned fieldno = 0;
1275 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
Eric Christophere7b87e52014-10-26 23:40:33 +00001276 E = CXXDecl->captures_end();
1277 I != E; ++I, ++Field, ++fieldno) {
Benjamin Kramerf3ca26982014-05-10 16:31:55 +00001278 const LambdaCapture &C = *I;
Eric Christopher91a31902013-01-16 01:22:32 +00001279 if (C.capturesVariable()) {
David Majnemerb4b671e2016-06-30 03:01:59 +00001280 SourceLocation Loc = C.getLocation();
1281 assert(!Field->isBitField() && "lambdas don't have bitfield members!");
Eric Christopher91a31902013-01-16 01:22:32 +00001282 VarDecl *V = C.getCapturedVar();
Eric Christopher91a31902013-01-16 01:22:32 +00001283 StringRef VName = V->getName();
David Majnemerb4b671e2016-06-30 03:01:59 +00001284 llvm::DIFile *VUnit = getOrCreateFile(Loc);
Victor Leschuka7ece032016-10-20 00:13:19 +00001285 auto Align = getDeclAlignIfRequired(V, CGM.getContext());
David Majnemerb4b671e2016-06-30 03:01:59 +00001286 llvm::DIType *FieldType = createFieldType(
1287 VName, Field->getType(), Loc, Field->getAccess(),
Victor Leschuka7ece032016-10-20 00:13:19 +00001288 layout.getFieldOffset(fieldno), Align, VUnit, RecordTy, CXXDecl);
David Majnemerb4b671e2016-06-30 03:01:59 +00001289 elements.push_back(FieldType);
Alexey Bataev39c81e22014-08-28 04:28:19 +00001290 } else if (C.capturesThis()) {
Eric Christopher91a31902013-01-16 01:22:32 +00001291 // TODO: Need to handle 'this' in some way by probably renaming the
1292 // this of the lambda class and having a field member of 'this' or
1293 // by using AT_object_pointer for the function and having that be
1294 // used as 'this' for semantic references.
Eric Christopher91a31902013-01-16 01:22:32 +00001295 FieldDecl *f = *Field;
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001296 llvm::DIFile *VUnit = getOrCreateFile(f->getLocation());
Eric Christopher91a31902013-01-16 01:22:32 +00001297 QualType type = f->getType();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001298 llvm::DIType *fieldType = createFieldType(
David Majnemerb4b671e2016-06-30 03:01:59 +00001299 "this", type, f->getLocation(), f->getAccess(),
Eric Christophere7b87e52014-10-26 23:40:33 +00001300 layout.getFieldOffset(fieldno), VUnit, RecordTy, CXXDecl);
Eric Christopher91a31902013-01-16 01:22:32 +00001301
1302 elements.push_back(fieldType);
1303 }
1304 }
1305}
1306
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001307llvm::DIDerivedType *
1308CGDebugInfo::CreateRecordStaticField(const VarDecl *Var, llvm::DIType *RecordTy,
Duncan P. N. Exon Smithc09c5482015-04-20 21:17:26 +00001309 const RecordDecl *RD) {
Eric Christopher91a31902013-01-16 01:22:32 +00001310 // Create the descriptor for the static variable, with or without
1311 // constant initializers.
David Blaikie8e707bb2014-10-14 22:22:17 +00001312 Var = Var->getCanonicalDecl();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001313 llvm::DIFile *VUnit = getOrCreateFile(Var->getLocation());
1314 llvm::DIType *VTy = getOrCreateType(Var->getType(), VUnit);
Eric Christopher91a31902013-01-16 01:22:32 +00001315
Eric Christopher91a31902013-01-16 01:22:32 +00001316 unsigned LineNumber = getLineNumber(Var->getLocation());
1317 StringRef VName = Var->getName();
Craig Topper8a13c412014-05-21 05:09:00 +00001318 llvm::Constant *C = nullptr;
Eric Christopher91a31902013-01-16 01:22:32 +00001319 if (Var->getInit()) {
1320 const APValue *Value = Var->evaluateValue();
David Blaikied42917f2013-01-20 01:19:17 +00001321 if (Value) {
1322 if (Value->isInt())
1323 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
1324 if (Value->isFloat())
1325 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
1326 }
Eric Christopher91a31902013-01-16 01:22:32 +00001327 }
1328
Leny Kholodov80c047d2016-09-06 10:48:04 +00001329 llvm::DINode::DIFlags Flags = getAccessFlag(Var->getAccess(), RD);
Victor Leschuka7ece032016-10-20 00:13:19 +00001330 auto Align = getDeclAlignIfRequired(Var, CGM.getContext());
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001331 llvm::DIDerivedType *GV = DBuilder.createStaticMemberType(
Victor Leschuka7ece032016-10-20 00:13:19 +00001332 RecordTy, VName, VUnit, LineNumber, VTy, Flags, C, Align);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001333 StaticDataMemberCache[Var->getCanonicalDecl()].reset(GV);
David Blaikieae019462013-08-15 22:50:29 +00001334 return GV;
Eric Christopher91a31902013-01-16 01:22:32 +00001335}
1336
Eric Christophere7b87e52014-10-26 23:40:33 +00001337void CGDebugInfo::CollectRecordNormalField(
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001338 const FieldDecl *field, uint64_t OffsetInBits, llvm::DIFile *tunit,
1339 SmallVectorImpl<llvm::Metadata *> &elements, llvm::DIType *RecordTy,
Eric Christophere7b87e52014-10-26 23:40:33 +00001340 const RecordDecl *RD) {
Eric Christopher91a31902013-01-16 01:22:32 +00001341 StringRef name = field->getName();
1342 QualType type = field->getType();
1343
1344 // Ignore unnamed fields unless they're anonymous structs/unions.
1345 if (name.empty() && !type->isRecordType())
1346 return;
1347
David Majnemerb4b671e2016-06-30 03:01:59 +00001348 llvm::DIType *FieldType;
Eric Christopher91a31902013-01-16 01:22:32 +00001349 if (field->isBitField()) {
David Majnemerb4b671e2016-06-30 03:01:59 +00001350 FieldType = createBitFieldType(field, RecordTy, RD);
1351 } else {
Victor Leschuka7ece032016-10-20 00:13:19 +00001352 auto Align = getDeclAlignIfRequired(field, CGM.getContext());
David Majnemerb4b671e2016-06-30 03:01:59 +00001353 FieldType =
1354 createFieldType(name, type, field->getLocation(), field->getAccess(),
Victor Leschuka7ece032016-10-20 00:13:19 +00001355 OffsetInBits, Align, tunit, RecordTy, RD);
Eric Christopher91a31902013-01-16 01:22:32 +00001356 }
1357
David Majnemerb4b671e2016-06-30 03:01:59 +00001358 elements.push_back(FieldType);
Eric Christopher91a31902013-01-16 01:22:32 +00001359}
1360
Reid Klecknere2e82062017-08-08 20:30:14 +00001361void CGDebugInfo::CollectRecordNestedType(
1362 const TypeDecl *TD, SmallVectorImpl<llvm::Metadata *> &elements) {
1363 QualType Ty = CGM.getContext().getTypeDeclType(TD);
Reid Kleckner755220b2016-08-01 18:56:13 +00001364 // Injected class names are not considered nested records.
1365 if (isa<InjectedClassNameType>(Ty))
1366 return;
Reid Klecknere2e82062017-08-08 20:30:14 +00001367 SourceLocation Loc = TD->getLocation();
Adrian McCarthyab1e7862016-07-21 18:43:20 +00001368 llvm::DIType *nestedType = getOrCreateType(Ty, getOrCreateFile(Loc));
1369 elements.push_back(nestedType);
1370}
1371
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001372void CGDebugInfo::CollectRecordFields(
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001373 const RecordDecl *record, llvm::DIFile *tunit,
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001374 SmallVectorImpl<llvm::Metadata *> &elements,
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001375 llvm::DICompositeType *RecordTy) {
David Majnemer58ed0f32016-07-17 00:39:12 +00001376 const auto *CXXDecl = dyn_cast<CXXRecordDecl>(record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001377
Eric Christopher91a31902013-01-16 01:22:32 +00001378 if (CXXDecl && CXXDecl->isLambda())
1379 CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
1380 else {
1381 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001382
Eric Christopher91a31902013-01-16 01:22:32 +00001383 // Field number for non-static fields.
Eric Christopher0f7594372013-01-04 17:59:07 +00001384 unsigned fieldNo = 0;
Eric Christopher91a31902013-01-16 01:22:32 +00001385
Eric Christopher91a31902013-01-16 01:22:32 +00001386 // Static and non-static members should appear in the same order as
1387 // the corresponding declarations in the source program.
Aaron Ballman629afae2014-03-07 19:56:05 +00001388 for (const auto *I : record->decls())
1389 if (const auto *V = dyn_cast<VarDecl>(I)) {
Paul Robinsonb17327d2016-04-27 17:37:12 +00001390 if (V->hasAttr<NoDebugAttr>())
1391 continue;
Reid Kleckner891b2712018-07-20 20:55:00 +00001392
1393 // Skip variable template specializations when emitting CodeView. MSVC
1394 // doesn't emit them.
1395 if (CGM.getCodeGenOpts().EmitCodeView &&
1396 isa<VarTemplateSpecializationDecl>(V))
1397 continue;
1398
David Blaikiece763042013-08-20 21:49:21 +00001399 // Reuse the existing static member declaration if one exists
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001400 auto MI = StaticDataMemberCache.find(V->getCanonicalDecl());
David Blaikiece763042013-08-20 21:49:21 +00001401 if (MI != StaticDataMemberCache.end()) {
1402 assert(MI->second &&
1403 "Static data member declaration should still exist");
Duncan P. N. Exon Smithac346ba2015-07-24 18:05:58 +00001404 elements.push_back(MI->second);
Adrian Prantl21361fb2014-08-29 22:44:27 +00001405 } else {
1406 auto Field = CreateRecordStaticField(V, RecordTy, record);
1407 elements.push_back(Field);
1408 }
Aaron Ballman629afae2014-03-07 19:56:05 +00001409 } else if (const auto *field = dyn_cast<FieldDecl>(I)) {
Eric Christophere7b87e52014-10-26 23:40:33 +00001410 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo), tunit,
1411 elements, RecordTy, record);
Eric Christopher91a31902013-01-16 01:22:32 +00001412
1413 // Bump field number for next field.
1414 ++fieldNo;
Reid Kleckner891b2712018-07-20 20:55:00 +00001415 } else if (CGM.getCodeGenOpts().EmitCodeView) {
1416 // Debug info for nested types is included in the member list only for
1417 // CodeView.
Reid Klecknere2e82062017-08-08 20:30:14 +00001418 if (const auto *nestedType = dyn_cast<TypeDecl>(I))
1419 if (!nestedType->isImplicit() &&
1420 nestedType->getDeclContext() == record)
1421 CollectRecordNestedType(nestedType, elements);
1422 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001423 }
1424}
1425
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001426llvm::DISubroutineType *
Guy Benyei11169dd2012-12-18 14:30:41 +00001427CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001428 llvm::DIFile *Unit) {
David Blaikie7eb06852013-01-07 23:06:35 +00001429 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
David Blaikie2aaf0652013-01-07 22:24:59 +00001430 if (Method->isStatic())
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001431 return cast_or_null<llvm::DISubroutineType>(
Duncan P. N. Exon Smithc7551282015-04-06 23:21:33 +00001432 getOrCreateType(QualType(Func, 0), Unit));
David Blaikie7eb06852013-01-07 23:06:35 +00001433 return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()),
1434 Func, Unit);
1435}
David Blaikie2aaf0652013-01-07 22:24:59 +00001436
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001437llvm::DISubroutineType *CGDebugInfo::getOrCreateInstanceMethodType(
1438 QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile *Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001439 // Add "this" pointer.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001440 llvm::DITypeRefArray Args(
1441 cast<llvm::DISubroutineType>(getOrCreateType(QualType(Func, 0), Unit))
Duncan P. N. Exon Smithc7551282015-04-06 23:21:33 +00001442 ->getTypeArray());
Duncan P. N. Exon Smitha98fac62015-04-07 04:14:45 +00001443 assert(Args.size() && "Invalid number of arguments!");
Guy Benyei11169dd2012-12-18 14:30:41 +00001444
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001445 SmallVector<llvm::Metadata *, 16> Elts;
Guy Benyei11169dd2012-12-18 14:30:41 +00001446
1447 // First element is always return type. For 'void' functions it is NULL.
Duncan P. N. Exon Smith37328582015-04-07 18:41:26 +00001448 Elts.push_back(Args[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001449
David Blaikie2aaf0652013-01-07 22:24:59 +00001450 // "this" pointer is always first argument.
David Blaikie7eb06852013-01-07 23:06:35 +00001451 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
David Blaikie2aaf0652013-01-07 22:24:59 +00001452 if (isa<ClassTemplateSpecializationDecl>(RD)) {
1453 // Create pointer type directly in this case.
1454 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
1455 QualType PointeeTy = ThisPtrTy->getPointeeType();
1456 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCallc8e01702013-04-16 22:48:15 +00001457 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
Victor Leschuka7ece032016-10-20 00:13:19 +00001458 auto Align = getTypeAlignIfRequired(ThisPtrTy, CGM.getContext());
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001459 llvm::DIType *PointeeType = getOrCreateType(PointeeTy, Unit);
1460 llvm::DIType *ThisPtrType =
Eric Christophere7b87e52014-10-26 23:40:33 +00001461 DBuilder.createPointerType(PointeeType, Size, Align);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001462 TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);
David Blaikie2aaf0652013-01-07 22:24:59 +00001463 // TODO: This and the artificial type below are misleading, the
1464 // types aren't artificial the argument is, but the current
1465 // metadata doesn't represent that.
1466 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1467 Elts.push_back(ThisPtrType);
1468 } else {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001469 llvm::DIType *ThisPtrType = getOrCreateType(ThisPtr, Unit);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001470 TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);
David Blaikie2aaf0652013-01-07 22:24:59 +00001471 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1472 Elts.push_back(ThisPtrType);
Guy Benyei11169dd2012-12-18 14:30:41 +00001473 }
1474
1475 // Copy rest of the arguments.
Duncan P. N. Exon Smitha98fac62015-04-07 04:14:45 +00001476 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1477 Elts.push_back(Args[i]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001478
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001479 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
Guy Benyei11169dd2012-12-18 14:30:41 +00001480
Leny Kholodov80c047d2016-09-06 10:48:04 +00001481 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
Adrian Prantl0630eb72013-12-18 21:48:18 +00001482 if (Func->getExtProtoInfo().RefQualifier == RQ_LValue)
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001483 Flags |= llvm::DINode::FlagLValueReference;
Adrian Prantl0630eb72013-12-18 21:48:18 +00001484 if (Func->getExtProtoInfo().RefQualifier == RQ_RValue)
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001485 Flags |= llvm::DINode::FlagRValueReference;
Adrian Prantl0630eb72013-12-18 21:48:18 +00001486
Reid Klecknerf00f8032016-06-08 20:41:54 +00001487 return DBuilder.createSubroutineType(EltTypeArray, Flags,
1488 getDwarfCC(Func->getCallConv()));
Guy Benyei11169dd2012-12-18 14:30:41 +00001489}
1490
Eric Christopherb2a008c2013-05-16 00:45:12 +00001491/// isFunctionLocalClass - Return true if CXXRecordDecl is defined
Guy Benyei11169dd2012-12-18 14:30:41 +00001492/// inside a function.
1493static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
David Majnemer58ed0f32016-07-17 00:39:12 +00001494 if (const auto *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
Guy Benyei11169dd2012-12-18 14:30:41 +00001495 return isFunctionLocalClass(NRD);
1496 if (isa<FunctionDecl>(RD->getDeclContext()))
1497 return true;
1498 return false;
1499}
1500
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001501llvm::DISubprogram *CGDebugInfo::CreateCXXMemberFunction(
1502 const CXXMethodDecl *Method, llvm::DIFile *Unit, llvm::DIType *RecordTy) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001503 bool IsCtorOrDtor =
Eric Christophere7b87e52014-10-26 23:40:33 +00001504 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
Eric Christopherb2a008c2013-05-16 00:45:12 +00001505
Guy Benyei11169dd2012-12-18 14:30:41 +00001506 StringRef MethodName = getFunctionName(Method);
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001507 llvm::DISubroutineType *MethodTy = getOrCreateMethodType(Method, Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00001508
1509 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1510 // make sense to give a single ctor/dtor a linkage name.
1511 StringRef MethodLinkageName;
David Blaikie71647672016-04-12 21:22:48 +00001512 // FIXME: 'isFunctionLocalClass' seems like an arbitrary/unintentional
1513 // property to use here. It may've been intended to model "is non-external
1514 // type" but misses cases of non-function-local but non-external classes such
1515 // as those in anonymous namespaces as well as the reverse - external types
1516 // that are function local, such as those in (non-local) inline functions.
Guy Benyei11169dd2012-12-18 14:30:41 +00001517 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1518 MethodLinkageName = CGM.getMangledName(Method);
1519
1520 // Get the location for the method.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001521 llvm::DIFile *MethodDefUnit = nullptr;
David Blaikie7fceebf2013-08-19 03:37:48 +00001522 unsigned MethodLine = 0;
1523 if (!Method->isImplicit()) {
1524 MethodDefUnit = getOrCreateFile(Method->getLocation());
1525 MethodLine = getLineNumber(Method->getLocation());
1526 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001527
1528 // Collect virtual method info.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001529 llvm::DIType *ContainingType = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001530 unsigned VIndex = 0;
Leny Kholodov80c047d2016-09-06 10:48:04 +00001531 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
Paul Robinsoncda54212018-11-19 18:29:28 +00001532 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
Reid Kleckner0358cbf2016-07-01 02:41:25 +00001533 int ThisAdjustment = 0;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001534
Guy Benyei11169dd2012-12-18 14:30:41 +00001535 if (Method->isVirtual()) {
1536 if (Method->isPure())
Paul Robinsoncda54212018-11-19 18:29:28 +00001537 SPFlags |= llvm::DISubprogram::SPFlagPureVirtual;
Guy Benyei11169dd2012-12-18 14:30:41 +00001538 else
Paul Robinsoncda54212018-11-19 18:29:28 +00001539 SPFlags |= llvm::DISubprogram::SPFlagVirtual;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001540
Reid Kleckner216d0a12016-06-16 20:08:51 +00001541 if (CGM.getTarget().getCXXABI().isItaniumFamily()) {
1542 // It doesn't make sense to give a virtual destructor a vtable index,
1543 // since a single destructor has two entries in the vtable.
1544 if (!isa<CXXDestructorDecl>(Method))
1545 VIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(Method);
1546 } else {
1547 // Emit MS ABI vftable information. There is only one entry for the
1548 // deleting dtor.
1549 const auto *DD = dyn_cast<CXXDestructorDecl>(Method);
1550 GlobalDecl GD = DD ? GlobalDecl(DD, Dtor_Deleting) : GlobalDecl(Method);
Reid Klecknercbec0262018-04-02 20:00:39 +00001551 MethodVFTableLocation ML =
Reid Kleckner216d0a12016-06-16 20:08:51 +00001552 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD);
1553 VIndex = ML.Index;
Reid Klecknerc4871ed2016-06-22 18:34:45 +00001554
1555 // CodeView only records the vftable offset in the class that introduces
1556 // the virtual method. This is possible because, unlike Itanium, the MS
1557 // C++ ABI does not include all virtual methods from non-primary bases in
1558 // the vtable for the most derived class. For example, if C inherits from
1559 // A and B, C's primary vftable will not include B's virtual methods.
Benjamin Krameracfa3392017-12-17 23:52:45 +00001560 if (Method->size_overridden_methods() == 0)
Reid Klecknerc4871ed2016-06-22 18:34:45 +00001561 Flags |= llvm::DINode::FlagIntroducedVirtual;
1562
Reid Kleckner0358cbf2016-07-01 02:41:25 +00001563 // The 'this' adjustment accounts for both the virtual and non-virtual
1564 // portions of the adjustment. Presumably the debugger only uses it when
1565 // it knows the dynamic type of an object.
1566 ThisAdjustment = CGM.getCXXABI()
1567 .getVirtualFunctionPrologueThisAdjustment(GD)
1568 .getQuantity();
Reid Kleckner216d0a12016-06-16 20:08:51 +00001569 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001570 ContainingType = RecordTy;
1571 }
1572
Adrian McCarthyd91bf392017-09-13 20:53:55 +00001573 if (Method->isStatic())
1574 Flags |= llvm::DINode::FlagStaticMember;
Guy Benyei11169dd2012-12-18 14:30:41 +00001575 if (Method->isImplicit())
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001576 Flags |= llvm::DINode::FlagArtificial;
Adrian Prantl21361fb2014-08-29 22:44:27 +00001577 Flags |= getAccessFlag(Method->getAccess(), Method->getParent());
David Majnemer58ed0f32016-07-17 00:39:12 +00001578 if (const auto *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001579 if (CXXC->isExplicit())
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001580 Flags |= llvm::DINode::FlagExplicit;
David Majnemer58ed0f32016-07-17 00:39:12 +00001581 } else if (const auto *CXXC = dyn_cast<CXXConversionDecl>(Method)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001582 if (CXXC->isExplicit())
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001583 Flags |= llvm::DINode::FlagExplicit;
Guy Benyei11169dd2012-12-18 14:30:41 +00001584 }
1585 if (Method->hasPrototype())
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001586 Flags |= llvm::DINode::FlagPrototyped;
Adrian Prantl0630eb72013-12-18 21:48:18 +00001587 if (Method->getRefQualifier() == RQ_LValue)
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001588 Flags |= llvm::DINode::FlagLValueReference;
Adrian Prantl0630eb72013-12-18 21:48:18 +00001589 if (Method->getRefQualifier() == RQ_RValue)
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001590 Flags |= llvm::DINode::FlagRValueReference;
Paul Robinsoncda54212018-11-19 18:29:28 +00001591 if (CGM.getLangOpts().Optimize)
1592 SPFlags |= llvm::DISubprogram::SPFlagOptimized;
Guy Benyei11169dd2012-12-18 14:30:41 +00001593
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001594 llvm::DINodeArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1595 llvm::DISubprogram *SP = DBuilder.createMethod(
Eric Christophere7b87e52014-10-26 23:40:33 +00001596 RecordTy, MethodName, MethodLinkageName, MethodDefUnit, MethodLine,
Paul Robinsoncda54212018-11-19 18:29:28 +00001597 MethodTy, VIndex, ThisAdjustment, ContainingType, Flags, SPFlags,
Reid Kleckner0358cbf2016-07-01 02:41:25 +00001598 TParamsArray.get());
Eric Christopherb2a008c2013-05-16 00:45:12 +00001599
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001600 SPCache[Method->getCanonicalDecl()].reset(SP);
Guy Benyei11169dd2012-12-18 14:30:41 +00001601
1602 return SP;
1603}
1604
Eric Christophere7b87e52014-10-26 23:40:33 +00001605void CGDebugInfo::CollectCXXMemberFunctions(
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001606 const CXXRecordDecl *RD, llvm::DIFile *Unit,
1607 SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001608
1609 // Since we want more than just the individual member decls if we
1610 // have templated functions iterate over every declaration to gather
1611 // the functions.
Eric Christophere7b87e52014-10-26 23:40:33 +00001612 for (const auto *I : RD->decls()) {
David Blaikiefd580722014-10-06 05:18:55 +00001613 const auto *Method = dyn_cast<CXXMethodDecl>(I);
1614 // If the member is implicit, don't add it to the member list. This avoids
1615 // the member being added to type units by LLVM, while still allowing it
1616 // to be emitted into the type declaration/reference inside the compile
1617 // unit.
Paul Robinson6a7511b2015-06-25 17:50:43 +00001618 // Ditto 'nodebug' methods, for consistency with CodeGenFunction.cpp.
David Blaikie6dddfe32014-10-06 05:52:27 +00001619 // FIXME: Handle Using(Shadow?)Decls here to create
1620 // DW_TAG_imported_declarations inside the class for base decls brought into
1621 // derived classes. GDB doesn't seem to notice/leverage these when I tried
1622 // it, so I'm not rushing to fix this. (GCC seems to produce them, if
1623 // referenced)
Paul Robinson6a7511b2015-06-25 17:50:43 +00001624 if (!Method || Method->isImplicit() || Method->hasAttr<NoDebugAttr>())
David Blaikiefd580722014-10-06 05:18:55 +00001625 continue;
David Blaikie42edade2014-11-11 20:44:45 +00001626
1627 if (Method->getType()->getAs<FunctionProtoType>()->getContainedAutoType())
1628 continue;
1629
David Blaikiefd580722014-10-06 05:18:55 +00001630 // Reuse the existing member function declaration if it exists.
1631 // It may be associated with the declaration of the type & should be
1632 // reused as we're building the definition.
1633 //
1634 // This situation can arise in the vtable-based debug info reduction where
1635 // implicit members are emitted in a non-vtable TU.
1636 auto MI = SPCache.find(Method->getCanonicalDecl());
1637 EltTys.push_back(MI == SPCache.end()
1638 ? CreateCXXMemberFunction(Method, Unit, RecordTy)
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001639 : static_cast<llvm::Metadata *>(MI->second));
Guy Benyei11169dd2012-12-18 14:30:41 +00001640 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00001641}
Guy Benyei11169dd2012-12-18 14:30:41 +00001642
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001643void CGDebugInfo::CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile *Unit,
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001644 SmallVectorImpl<llvm::Metadata *> &EltTys,
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001645 llvm::DIType *RecordTy) {
Bob Haarmandff36732016-10-25 22:19:32 +00001646 llvm::DenseSet<CanonicalDeclPtr<const CXXRecordDecl>> SeenTypes;
1647 CollectCXXBasesAux(RD, Unit, EltTys, RecordTy, RD->bases(), SeenTypes,
1648 llvm::DINode::FlagZero);
Eric Christopherb2a008c2013-05-16 00:45:12 +00001649
Bob Haarmandff36732016-10-25 22:19:32 +00001650 // If we are generating CodeView debug info, we also need to emit records for
1651 // indirect virtual base classes.
1652 if (CGM.getCodeGenOpts().EmitCodeView) {
1653 CollectCXXBasesAux(RD, Unit, EltTys, RecordTy, RD->vbases(), SeenTypes,
1654 llvm::DINode::FlagIndirectVirtualBase);
1655 }
1656}
1657
1658void CGDebugInfo::CollectCXXBasesAux(
1659 const CXXRecordDecl *RD, llvm::DIFile *Unit,
1660 SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy,
1661 const CXXRecordDecl::base_class_const_range &Bases,
1662 llvm::DenseSet<CanonicalDeclPtr<const CXXRecordDecl>> &SeenTypes,
1663 llvm::DINode::DIFlags StartingFlags) {
1664 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1665 for (const auto &BI : Bases) {
David Majnemer58ed0f32016-07-17 00:39:12 +00001666 const auto *Base =
Eric Christophere7b87e52014-10-26 23:40:33 +00001667 cast<CXXRecordDecl>(BI.getType()->getAs<RecordType>()->getDecl());
Bob Haarmandff36732016-10-25 22:19:32 +00001668 if (!SeenTypes.insert(Base).second)
1669 continue;
1670 auto *BaseTy = getOrCreateType(BI.getType(), Unit);
1671 llvm::DINode::DIFlags BFlags = StartingFlags;
1672 uint64_t BaseOffset;
Brock Wyma3db2b102018-05-14 21:21:22 +00001673 uint32_t VBPtrOffset = 0;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001674
Aaron Ballman574705e2014-03-13 15:41:46 +00001675 if (BI.isVirtual()) {
Reid Klecknerd3b23d62014-08-07 21:29:25 +00001676 if (CGM.getTarget().getCXXABI().isItaniumFamily()) {
1677 // virtual base offset offset is -ve. The code generator emits dwarf
1678 // expression where it expects +ve number.
Eric Christophere7b87e52014-10-26 23:40:33 +00001679 BaseOffset = 0 - CGM.getItaniumVTableContext()
1680 .getVirtualBaseOffsetOffset(RD, Base)
1681 .getQuantity();
Reid Klecknerd3b23d62014-08-07 21:29:25 +00001682 } else {
1683 // In the MS ABI, store the vbtable offset, which is analogous to the
1684 // vbase offset offset in Itanium.
1685 BaseOffset =
1686 4 * CGM.getMicrosoftVTableContext().getVBTableIndex(RD, Base);
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00001687 VBPtrOffset = CGM.getContext()
1688 .getASTRecordLayout(RD)
1689 .getVBPtrOffset()
1690 .getQuantity();
Reid Klecknerd3b23d62014-08-07 21:29:25 +00001691 }
Bob Haarmandff36732016-10-25 22:19:32 +00001692 BFlags |= llvm::DINode::FlagVirtual;
Guy Benyei11169dd2012-12-18 14:30:41 +00001693 } else
1694 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1695 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1696 // BI->isVirtual() and bits when not.
Eric Christopherb2a008c2013-05-16 00:45:12 +00001697
Adrian Prantl21361fb2014-08-29 22:44:27 +00001698 BFlags |= getAccessFlag(BI.getAccessSpecifier(), RD);
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00001699 llvm::DIType *DTy = DBuilder.createInheritance(RecordTy, BaseTy, BaseOffset,
1700 VBPtrOffset, BFlags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001701 EltTys.push_back(DTy);
1702 }
1703}
1704
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001705llvm::DINodeArray
Eric Christophere7b87e52014-10-26 23:40:33 +00001706CGDebugInfo::CollectTemplateParams(const TemplateParameterList *TPList,
1707 ArrayRef<TemplateArgument> TAList,
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001708 llvm::DIFile *Unit) {
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001709 SmallVector<llvm::Metadata *, 16> TemplateParams;
Guy Benyei11169dd2012-12-18 14:30:41 +00001710 for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1711 const TemplateArgument &TA = TAList[i];
David Blaikie47c11502013-06-22 18:59:18 +00001712 StringRef Name;
1713 if (TPList)
1714 Name = TPList->getParam(i)->getName();
David Blaikie38079fd2013-05-10 21:53:14 +00001715 switch (TA.getKind()) {
1716 case TemplateArgument::Type: {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001717 llvm::DIType *TTy = getOrCreateType(TA.getAsType(), Unit);
Duncan P. N. Exon Smithdadc2b62015-04-21 18:43:54 +00001718 TemplateParams.push_back(
1719 DBuilder.createTemplateTypeParameter(TheCU, Name, TTy));
David Blaikie38079fd2013-05-10 21:53:14 +00001720 } break;
1721 case TemplateArgument::Integral: {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001722 llvm::DIType *TTy = getOrCreateType(TA.getIntegralType(), Unit);
Duncan P. N. Exon Smithdadc2b62015-04-21 18:43:54 +00001723 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
1724 TheCU, Name, TTy,
1725 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral())));
David Blaikie38079fd2013-05-10 21:53:14 +00001726 } break;
1727 case TemplateArgument::Declaration: {
1728 const ValueDecl *D = TA.getAsDecl();
David Blaikieb5c7e6a2014-10-18 02:21:26 +00001729 QualType T = TA.getParamTypeForDecl().getDesugaredType(CGM.getContext());
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001730 llvm::DIType *TTy = getOrCreateType(T, Unit);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001731 llvm::Constant *V = nullptr;
David Blaikie1a83db42014-10-20 18:56:54 +00001732 const CXXMethodDecl *MD;
David Blaikie38079fd2013-05-10 21:53:14 +00001733 // Variable pointer template parameters have a value that is the address
1734 // of the variable.
David Blaikie952a9b12014-10-17 18:00:12 +00001735 if (const auto *VD = dyn_cast<VarDecl>(D))
David Blaikie38079fd2013-05-10 21:53:14 +00001736 V = CGM.GetAddrOfGlobalVar(VD);
1737 // Member function pointers have special support for building them, though
1738 // this is currently unsupported in LLVM CodeGen.
David Blaikie1a83db42014-10-20 18:56:54 +00001739 else if ((MD = dyn_cast<CXXMethodDecl>(D)) && MD->isInstance())
David Majnemere2be95b2015-06-23 07:31:01 +00001740 V = CGM.getCXXABI().EmitMemberFunctionPointer(MD);
David Blaikie952a9b12014-10-17 18:00:12 +00001741 else if (const auto *FD = dyn_cast<FunctionDecl>(D))
David Blaikied900f982013-05-13 06:57:50 +00001742 V = CGM.GetAddrOfFunction(FD);
David Blaikie38079fd2013-05-10 21:53:14 +00001743 // Member data pointers have special handling too to compute the fixed
1744 // offset within the object.
David Blaikie952a9b12014-10-17 18:00:12 +00001745 else if (const auto *MPT = dyn_cast<MemberPointerType>(T.getTypePtr())) {
David Blaikie38079fd2013-05-10 21:53:14 +00001746 // These five lines (& possibly the above member function pointer
1747 // handling) might be able to be refactored to use similar code in
1748 // CodeGenModule::getMemberPointerConstant
1749 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
1750 CharUnits chars =
Eric Christophere7b87e52014-10-26 23:40:33 +00001751 CGM.getContext().toCharUnitsFromBits((int64_t)fieldOffset);
David Blaikie952a9b12014-10-17 18:00:12 +00001752 V = CGM.getCXXABI().EmitMemberDataPointer(MPT, chars);
David Blaikie38079fd2013-05-10 21:53:14 +00001753 }
Duncan P. N. Exon Smithdadc2b62015-04-21 18:43:54 +00001754 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
1755 TheCU, Name, TTy,
1756 cast_or_null<llvm::Constant>(V->stripPointerCasts())));
David Blaikie38079fd2013-05-10 21:53:14 +00001757 } break;
1758 case TemplateArgument::NullPtr: {
1759 QualType T = TA.getNullPtrType();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001760 llvm::DIType *TTy = getOrCreateType(T, Unit);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001761 llvm::Constant *V = nullptr;
David Blaikie38079fd2013-05-10 21:53:14 +00001762 // Special case member data pointer null values since they're actually -1
1763 // instead of zero.
David Majnemer58ed0f32016-07-17 00:39:12 +00001764 if (const auto *MPT = dyn_cast<MemberPointerType>(T.getTypePtr()))
David Blaikie38079fd2013-05-10 21:53:14 +00001765 // But treat member function pointers as simple zero integers because
1766 // it's easier than having a special case in LLVM's CodeGen. If LLVM
1767 // CodeGen grows handling for values of non-null member function
1768 // pointers then perhaps we could remove this special case and rely on
1769 // EmitNullMemberPointer for member function pointers.
1770 if (MPT->isMemberDataPointer())
1771 V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
1772 if (!V)
1773 V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00001774 TemplateParams.push_back(
1775 DBuilder.createTemplateValueParameter(TheCU, Name, TTy, V));
David Blaikie38079fd2013-05-10 21:53:14 +00001776 } break;
Duncan P. N. Exon Smithdadc2b62015-04-21 18:43:54 +00001777 case TemplateArgument::Template:
1778 TemplateParams.push_back(DBuilder.createTemplateTemplateParameter(
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00001779 TheCU, Name, nullptr,
Duncan P. N. Exon Smithdadc2b62015-04-21 18:43:54 +00001780 TA.getAsTemplate().getAsTemplateDecl()->getQualifiedNameAsString()));
1781 break;
1782 case TemplateArgument::Pack:
1783 TemplateParams.push_back(DBuilder.createTemplateParameterPack(
1784 TheCU, Name, nullptr,
1785 CollectTemplateParams(nullptr, TA.getPackAsArray(), Unit)));
1786 break;
David Majnemer5559d472013-08-24 08:21:10 +00001787 case TemplateArgument::Expression: {
1788 const Expr *E = TA.getAsExpr();
1789 QualType T = E->getType();
David Majnemer922ad9f2014-10-24 19:49:04 +00001790 if (E->isGLValue())
1791 T = CGM.getContext().getLValueReferenceType(T);
John McCallde0fe072017-08-15 21:42:52 +00001792 llvm::Constant *V = ConstantEmitter(CGM).emitAbstract(E, T);
David Majnemer5559d472013-08-24 08:21:10 +00001793 assert(V && "Expression in template argument isn't constant");
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001794 llvm::DIType *TTy = getOrCreateType(T, Unit);
Duncan P. N. Exon Smithdadc2b62015-04-21 18:43:54 +00001795 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
David Majnemer58ed0f32016-07-17 00:39:12 +00001796 TheCU, Name, TTy, V->stripPointerCasts()));
David Majnemer5559d472013-08-24 08:21:10 +00001797 } break;
David Blaikie2b93c542013-05-10 23:36:06 +00001798 // And the following should never occur:
David Blaikie38079fd2013-05-10 21:53:14 +00001799 case TemplateArgument::TemplateExpansion:
David Blaikie38079fd2013-05-10 21:53:14 +00001800 case TemplateArgument::Null:
1801 llvm_unreachable(
1802 "These argument types shouldn't exist in concrete types");
Guy Benyei11169dd2012-12-18 14:30:41 +00001803 }
1804 }
1805 return DBuilder.getOrCreateArray(TemplateParams);
1806}
1807
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001808llvm::DINodeArray
Duncan P. N. Exon Smith8e47da42015-04-21 20:07:29 +00001809CGDebugInfo::CollectFunctionTemplateParams(const FunctionDecl *FD,
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001810 llvm::DIFile *Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001811 if (FD->getTemplatedKind() ==
1812 FunctionDecl::TK_FunctionTemplateSpecialization) {
Eric Christophere7b87e52014-10-26 23:40:33 +00001813 const TemplateParameterList *TList = FD->getTemplateSpecializationInfo()
1814 ->getTemplate()
1815 ->getTemplateParameters();
David Blaikie47c11502013-06-22 18:59:18 +00001816 return CollectTemplateParams(
1817 TList, FD->getTemplateSpecializationArgs()->asArray(), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00001818 }
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001819 return llvm::DINodeArray();
Guy Benyei11169dd2012-12-18 14:30:41 +00001820}
1821
Matthew Voss20165362018-10-03 18:45:04 +00001822llvm::DINodeArray CGDebugInfo::CollectVarTemplateParams(const VarDecl *VL,
1823 llvm::DIFile *Unit) {
1824 if (auto *TS = dyn_cast<VarTemplateSpecializationDecl>(VL)) {
1825 auto T = TS->getSpecializedTemplateOrPartial();
1826 auto TA = TS->getTemplateArgs().asArray();
1827 // Collect parameters for a partial specialization
1828 if (T.is<VarTemplatePartialSpecializationDecl *>()) {
1829 const TemplateParameterList *TList =
1830 T.get<VarTemplatePartialSpecializationDecl *>()
1831 ->getTemplateParameters();
1832 return CollectTemplateParams(TList, TA, Unit);
1833 }
1834
1835 // Collect parameters for an explicit specialization
1836 if (T.is<VarTemplateDecl *>()) {
1837 const TemplateParameterList *TList = T.get<VarTemplateDecl *>()
1838 ->getTemplateParameters();
1839 return CollectTemplateParams(TList, TA, Unit);
1840 }
1841 }
1842 return llvm::DINodeArray();
1843}
1844
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001845llvm::DINodeArray CGDebugInfo::CollectCXXTemplateParams(
1846 const ClassTemplateSpecializationDecl *TSpecial, llvm::DIFile *Unit) {
Adrian Prantl649f0302014-04-17 01:04:01 +00001847 // Always get the full list of parameters, not just the ones from
1848 // the specialization.
1849 TemplateParameterList *TPList =
Eric Christophere7b87e52014-10-26 23:40:33 +00001850 TSpecial->getSpecializedTemplate()->getTemplateParameters();
Adrian Prantl2c92e9c2014-04-17 00:30:48 +00001851 const TemplateArgumentList &TAList = TSpecial->getTemplateArgs();
David Blaikie47c11502013-06-22 18:59:18 +00001852 return CollectTemplateParams(TPList, TAList.asArray(), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00001853}
1854
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001855llvm::DIType *CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile *Unit) {
Duncan P. N. Exon Smithb7470232015-04-15 23:48:50 +00001856 if (VTablePtrType)
Guy Benyei11169dd2012-12-18 14:30:41 +00001857 return VTablePtrType;
1858
1859 ASTContext &Context = CGM.getContext();
1860
1861 /* Function type */
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001862 llvm::Metadata *STy = getOrCreateType(Context.IntTy, Unit);
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001863 llvm::DITypeRefArray SElements = DBuilder.getOrCreateTypeArray(STy);
Eric Christopher28a6db52015-10-15 06:56:08 +00001864 llvm::DIType *SubTy = DBuilder.createSubroutineType(SElements);
Guy Benyei11169dd2012-12-18 14:30:41 +00001865 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
Konstantin Zhuravlyovd1ba16e2017-03-08 23:56:48 +00001866 unsigned VtblPtrAddressSpace = CGM.getTarget().getVtblPtrAddressSpace();
1867 Optional<unsigned> DWARFAddressSpace =
1868 CGM.getTarget().getDWARFAddressSpace(VtblPtrAddressSpace);
1869
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00001870 llvm::DIType *vtbl_ptr_type = DBuilder.createPointerType(
1871 SubTy, Size, 0, DWARFAddressSpace, "__vtbl_ptr_type");
Guy Benyei11169dd2012-12-18 14:30:41 +00001872 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1873 return VTablePtrType;
1874}
1875
Guy Benyei11169dd2012-12-18 14:30:41 +00001876StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +00001877 // Copy the gdb compatible name on the side and use its reference.
1878 return internString("_vptr$", RD->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00001879}
1880
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001881void CGDebugInfo::CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile *Unit,
Reid Klecknerdc124992016-08-31 16:11:43 +00001882 SmallVectorImpl<llvm::Metadata *> &EltTys,
1883 llvm::DICompositeType *RecordTy) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001884 // If this class is not dynamic then there is not any vtable info to collect.
1885 if (!RD->isDynamicClass())
1886 return;
1887
Reid Kleckner59812422016-08-31 20:35:01 +00001888 // Don't emit any vtable shape or vptr info if this class doesn't have an
1889 // extendable vfptr. This can happen if the class doesn't have virtual
1890 // methods, or in the MS ABI if those virtual methods only come from virtually
1891 // inherited bases.
1892 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1893 if (!RL.hasExtendableVFPtr())
1894 return;
1895
Reid Klecknerdc124992016-08-31 16:11:43 +00001896 // CodeView needs to know how large the vtable of every dynamic class is, so
1897 // emit a special named pointer type into the element list. The vptr type
1898 // points to this type as well.
1899 llvm::DIType *VPtrTy = nullptr;
1900 bool NeedVTableShape = CGM.getCodeGenOpts().EmitCodeView &&
1901 CGM.getTarget().getCXXABI().isMicrosoft();
1902 if (NeedVTableShape) {
1903 uint64_t PtrWidth =
1904 CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1905 const VTableLayout &VFTLayout =
1906 CGM.getMicrosoftVTableContext().getVFTableLayout(RD, CharUnits::Zero());
1907 unsigned VSlotCount =
Peter Collingbournee53683f2016-09-08 01:14:39 +00001908 VFTLayout.vtable_components().size() - CGM.getLangOpts().RTTIData;
Reid Klecknerdc124992016-08-31 16:11:43 +00001909 unsigned VTableWidth = PtrWidth * VSlotCount;
Konstantin Zhuravlyovd1ba16e2017-03-08 23:56:48 +00001910 unsigned VtblPtrAddressSpace = CGM.getTarget().getVtblPtrAddressSpace();
1911 Optional<unsigned> DWARFAddressSpace =
1912 CGM.getTarget().getDWARFAddressSpace(VtblPtrAddressSpace);
Reid Klecknerdc124992016-08-31 16:11:43 +00001913
1914 // Create a very wide void* type and insert it directly in the element list.
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00001915 llvm::DIType *VTableType = DBuilder.createPointerType(
1916 nullptr, VTableWidth, 0, DWARFAddressSpace, "__vtbl_ptr_type");
Reid Klecknerdc124992016-08-31 16:11:43 +00001917 EltTys.push_back(VTableType);
1918
1919 // The vptr is a pointer to this special vtable type.
1920 VPtrTy = DBuilder.createPointerType(VTableType, PtrWidth);
1921 }
1922
1923 // If there is a primary base then the artificial vptr member lives there.
Reid Klecknerdc124992016-08-31 16:11:43 +00001924 if (RL.getPrimaryBase())
1925 return;
1926
1927 if (!VPtrTy)
1928 VPtrTy = getOrCreateVTablePtrType(Unit);
1929
Guy Benyei11169dd2012-12-18 14:30:41 +00001930 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00001931 llvm::DIType *VPtrMember =
1932 DBuilder.createMemberType(Unit, getVTableName(RD), Unit, 0, Size, 0, 0,
1933 llvm::DINode::FlagArtificial, VPtrTy);
Reid Klecknerdc124992016-08-31 16:11:43 +00001934 EltTys.push_back(VPtrMember);
Guy Benyei11169dd2012-12-18 14:30:41 +00001935}
1936
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001937llvm::DIType *CGDebugInfo::getOrCreateRecordType(QualType RTy,
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00001938 SourceLocation Loc) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00001939 assert(DebugKind >= codegenoptions::LimitedDebugInfo);
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001940 llvm::DIType *T = getOrCreateType(RTy, getOrCreateFile(Loc));
Guy Benyei11169dd2012-12-18 14:30:41 +00001941 return T;
1942}
1943
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001944llvm::DIType *CGDebugInfo::getOrCreateInterfaceType(QualType D,
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00001945 SourceLocation Loc) {
Adrian Prantlad9a195e2015-08-27 21:21:19 +00001946 return getOrCreateStandaloneType(D, Loc);
1947}
1948
1949llvm::DIType *CGDebugInfo::getOrCreateStandaloneType(QualType D,
1950 SourceLocation Loc) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00001951 assert(DebugKind >= codegenoptions::LimitedDebugInfo);
Adrian Prantlad9a195e2015-08-27 21:21:19 +00001952 assert(!D.isNull() && "null type");
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001953 llvm::DIType *T = getOrCreateType(D, getOrCreateFile(Loc));
Adrian Prantlad9a195e2015-08-27 21:21:19 +00001954 assert(T && "could not create debug info for type");
Adrian Prantl3a884fa2015-08-27 22:56:46 +00001955
Adrian Prantl73409ce2013-03-11 18:33:46 +00001956 RetainedTypes.push_back(D.getAsOpaquePtr());
Guy Benyei11169dd2012-12-18 14:30:41 +00001957 return T;
1958}
1959
David Blaikie483a9da2014-05-06 18:35:21 +00001960void CGDebugInfo::completeType(const EnumDecl *ED) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00001961 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
David Blaikie483a9da2014-05-06 18:35:21 +00001962 return;
1963 QualType Ty = CGM.getContext().getEnumType(ED);
Eric Christophere7b87e52014-10-26 23:40:33 +00001964 void *TyPtr = Ty.getAsOpaquePtr();
David Blaikie483a9da2014-05-06 18:35:21 +00001965 auto I = TypeCache.find(TyPtr);
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001966 if (I == TypeCache.end() || !cast<llvm::DIType>(I->second)->isForwardDecl())
David Blaikie483a9da2014-05-06 18:35:21 +00001967 return;
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001968 llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<EnumType>());
Duncan P. N. Exon Smith4caa7f22015-04-16 01:00:56 +00001969 assert(!Res->isForwardDecl());
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001970 TypeCache[TyPtr].reset(Res);
David Blaikie483a9da2014-05-06 18:35:21 +00001971}
1972
David Blaikieb2e86eb2013-08-15 20:49:17 +00001973void CGDebugInfo::completeType(const RecordDecl *RD) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00001974 if (DebugKind > codegenoptions::LimitedDebugInfo ||
David Blaikieb2e86eb2013-08-15 20:49:17 +00001975 !CGM.getLangOpts().CPlusPlus)
1976 completeRequiredType(RD);
1977}
1978
David Blaikieb11c8732017-01-30 06:36:08 +00001979/// Return true if the class or any of its methods are marked dllimport.
1980static bool isClassOrMethodDLLImport(const CXXRecordDecl *RD) {
1981 if (RD->hasAttr<DLLImportAttr>())
1982 return true;
1983 for (const CXXMethodDecl *MD : RD->methods())
1984 if (MD->hasAttr<DLLImportAttr>())
1985 return true;
1986 return false;
1987}
1988
Adrian Prantla43acdc2017-07-24 23:48:51 +00001989/// Does a type definition exist in an imported clang module?
1990static bool isDefinedInClangModule(const RecordDecl *RD) {
1991 // Only definitions that where imported from an AST file come from a module.
1992 if (!RD || !RD->isFromASTFile())
1993 return false;
1994 // Anonymous entities cannot be addressed. Treat them as not from module.
1995 if (!RD->isExternallyVisible() && RD->getName().empty())
1996 return false;
1997 if (auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD)) {
1998 if (!CXXDecl->isCompleteDefinition())
1999 return false;
Adrian Prantlba6fdc52018-10-24 00:06:02 +00002000 // Check wether RD is a template.
Adrian Prantla43acdc2017-07-24 23:48:51 +00002001 auto TemplateKind = CXXDecl->getTemplateSpecializationKind();
2002 if (TemplateKind != TSK_Undeclared) {
Adrian Prantlba6fdc52018-10-24 00:06:02 +00002003 // Unfortunately getOwningModule() isn't accurate enough to find the
2004 // owning module of a ClassTemplateSpecializationDecl that is inside a
2005 // namespace spanning multiple modules.
2006 bool Explicit = false;
2007 if (auto *TD = dyn_cast<ClassTemplateSpecializationDecl>(CXXDecl))
2008 Explicit = TD->isExplicitInstantiationOrSpecialization();
2009 if (!Explicit && CXXDecl->getEnclosingNamespaceContext())
2010 return false;
Adrian Prantla43acdc2017-07-24 23:48:51 +00002011 // This is a template, check the origin of the first member.
2012 if (CXXDecl->field_begin() == CXXDecl->field_end())
2013 return TemplateKind == TSK_ExplicitInstantiationDeclaration;
2014 if (!CXXDecl->field_begin()->isFromASTFile())
2015 return false;
2016 }
2017 }
2018 return true;
2019}
2020
David Blaikie6943dea2013-08-20 01:28:15 +00002021void CGDebugInfo::completeClassData(const RecordDecl *RD) {
David Blaikieb11c8732017-01-30 06:36:08 +00002022 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
2023 if (CXXRD->isDynamicClass() &&
2024 CGM.getVTableLinkage(CXXRD) ==
2025 llvm::GlobalValue::AvailableExternallyLinkage &&
2026 !isClassOrMethodDLLImport(CXXRD))
2027 return;
Adrian Prantla43acdc2017-07-24 23:48:51 +00002028
2029 if (DebugTypeExtRefs && isDefinedInClangModule(RD->getDefinition()))
2030 return;
2031
David Blaikieb11c8732017-01-30 06:36:08 +00002032 completeClass(RD);
2033}
2034
2035void CGDebugInfo::completeClass(const RecordDecl *RD) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00002036 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
Michael Gottesman349542b2013-08-19 18:46:16 +00002037 return;
David Blaikie6943dea2013-08-20 01:28:15 +00002038 QualType Ty = CGM.getContext().getRecordType(RD);
Eric Christophere7b87e52014-10-26 23:40:33 +00002039 void *TyPtr = Ty.getAsOpaquePtr();
David Blaikieef8a9512014-05-05 23:23:53 +00002040 auto I = TypeCache.find(TyPtr);
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002041 if (I != TypeCache.end() && !cast<llvm::DIType>(I->second)->isForwardDecl())
David Blaikieb2e86eb2013-08-15 20:49:17 +00002042 return;
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002043 llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<RecordType>());
Duncan P. N. Exon Smith4caa7f22015-04-16 01:00:56 +00002044 assert(!Res->isForwardDecl());
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002045 TypeCache[TyPtr].reset(Res);
David Blaikieb2e86eb2013-08-15 20:49:17 +00002046}
2047
David Blaikie0e716b42014-03-03 23:48:23 +00002048static bool hasExplicitMemberDefinition(CXXRecordDecl::method_iterator I,
2049 CXXRecordDecl::method_iterator End) {
David Majnemer58ed0f32016-07-17 00:39:12 +00002050 for (CXXMethodDecl *MD : llvm::make_range(I, End))
2051 if (FunctionDecl *Tmpl = MD->getInstantiatedFromMemberFunction())
David Blaikief7f21852014-03-04 03:08:14 +00002052 if (!Tmpl->isImplicit() && Tmpl->isThisDeclarationADefinition() &&
David Majnemer58ed0f32016-07-17 00:39:12 +00002053 !MD->getMemberSpecializationInfo()->isExplicitSpecialization())
David Blaikie0e716b42014-03-03 23:48:23 +00002054 return true;
2055 return false;
2056}
2057
Benjamin Kramer8c305922016-02-02 11:06:51 +00002058static bool shouldOmitDefinition(codegenoptions::DebugInfoKind DebugKind,
2059 bool DebugTypeExtRefs, const RecordDecl *RD,
David Blaikie0e716b42014-03-03 23:48:23 +00002060 const LangOptions &LangOpts) {
Adrian Prantl88d79172016-04-26 21:58:18 +00002061 if (DebugTypeExtRefs && isDefinedInClangModule(RD->getDefinition()))
Adrian Prantl43e00812016-01-19 23:42:53 +00002062 return true;
Adrian Prantl5c8bd882015-09-11 17:23:08 +00002063
David Blaikie1ac9c982017-04-11 21:13:37 +00002064 if (auto *ES = RD->getASTContext().getExternalSource())
2065 if (ES->hasExternalDefinitions(RD) == ExternalASTSource::EK_Always)
2066 return true;
2067
Benjamin Kramer8c305922016-02-02 11:06:51 +00002068 if (DebugKind > codegenoptions::LimitedDebugInfo)
David Blaikie0e716b42014-03-03 23:48:23 +00002069 return false;
2070
2071 if (!LangOpts.CPlusPlus)
2072 return false;
2073
2074 if (!RD->isCompleteDefinitionRequired())
2075 return true;
2076
David Majnemer58ed0f32016-07-17 00:39:12 +00002077 const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
David Blaikie0e716b42014-03-03 23:48:23 +00002078
2079 if (!CXXDecl)
2080 return false;
2081
Adrian McCarthy99242982016-08-16 22:11:18 +00002082 // Only emit complete debug info for a dynamic class when its vtable is
2083 // emitted. However, Microsoft debuggers don't resolve type information
Reid Klecknerc9404e12016-09-09 16:27:04 +00002084 // across DLL boundaries, so skip this optimization if the class or any of its
2085 // methods are marked dllimport. This isn't a complete solution, since objects
2086 // without any dllimport methods can be used in one DLL and constructed in
2087 // another, but it is the current behavior of LimitedDebugInfo.
Adrian McCarthy99242982016-08-16 22:11:18 +00002088 if (CXXDecl->hasDefinition() && CXXDecl->isDynamicClass() &&
Reid Klecknerc9404e12016-09-09 16:27:04 +00002089 !isClassOrMethodDLLImport(CXXDecl))
David Blaikie0e716b42014-03-03 23:48:23 +00002090 return true;
2091
2092 TemplateSpecializationKind Spec = TSK_Undeclared;
David Majnemer58ed0f32016-07-17 00:39:12 +00002093 if (const auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD))
David Blaikie0e716b42014-03-03 23:48:23 +00002094 Spec = SD->getSpecializationKind();
2095
2096 if (Spec == TSK_ExplicitInstantiationDeclaration &&
2097 hasExplicitMemberDefinition(CXXDecl->method_begin(),
2098 CXXDecl->method_end()))
2099 return true;
2100
2101 return false;
2102}
2103
Reid Kleckner6c7b1c62016-09-13 00:01:23 +00002104void CGDebugInfo::completeRequiredType(const RecordDecl *RD) {
2105 if (shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD, CGM.getLangOpts()))
2106 return;
2107
2108 QualType Ty = CGM.getContext().getRecordType(RD);
2109 llvm::DIType *T = getTypeOrNull(Ty);
2110 if (T && T->isForwardDecl())
2111 completeClassData(RD);
2112}
2113
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002114llvm::DIType *CGDebugInfo::CreateType(const RecordType *Ty) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002115 RecordDecl *RD = Ty->getDecl();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002116 llvm::DIType *T = cast_or_null<llvm::DIType>(getTypeOrNull(QualType(Ty, 0)));
Adrian Prantl5c8bd882015-09-11 17:23:08 +00002117 if (T || shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD,
2118 CGM.getLangOpts())) {
David Blaikie3b1cc9b2013-09-06 06:45:04 +00002119 if (!T)
Adrian Prantl6ec370a2015-09-10 18:39:45 +00002120 T = getOrCreateRecordFwdDecl(Ty, getDeclContextDescriptor(RD));
David Blaikie3b1cc9b2013-09-06 06:45:04 +00002121 return T;
David Blaikiee36464c2013-06-05 05:32:23 +00002122 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002123
David Blaikieb2e86eb2013-08-15 20:49:17 +00002124 return CreateTypeDefinition(Ty);
2125}
2126
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002127llvm::DIType *CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) {
David Blaikieb2e86eb2013-08-15 20:49:17 +00002128 RecordDecl *RD = Ty->getDecl();
2129
Guy Benyei11169dd2012-12-18 14:30:41 +00002130 // Get overall information about the record type for the debug info.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002131 llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00002132
2133 // Records and classes and unions can all be recursive. To handle them, we
2134 // first generate a debug descriptor for the struct as a forward declaration.
2135 // Then (if it is a definition) we go through and get debug info for all of
2136 // its members. Finally, we create a descriptor for the complete type (which
2137 // may refer to the forward decl if the struct is recursive) and replace all
2138 // uses of the forward declaration with the final definition.
Duncan P. N. Exon Smithbd210e62015-07-24 20:34:41 +00002139 llvm::DICompositeType *FwdDecl = getOrCreateLimitedType(Ty, DefUnit);
Guy Benyei11169dd2012-12-18 14:30:41 +00002140
Adrian Prantl5f66bae2015-02-11 17:45:15 +00002141 const RecordDecl *D = RD->getDefinition();
2142 if (!D || !D->isCompleteDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00002143 return FwdDecl;
2144
David Majnemer58ed0f32016-07-17 00:39:12 +00002145 if (const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
David Blaikieadfbf992013-08-18 16:55:33 +00002146 CollectContainingType(CXXDecl, FwdDecl);
2147
Guy Benyei11169dd2012-12-18 14:30:41 +00002148 // Push the struct on region stack.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002149 LexicalBlockStack.emplace_back(&*FwdDecl);
2150 RegionMap[Ty->getDecl()].reset(FwdDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00002151
Guy Benyei11169dd2012-12-18 14:30:41 +00002152 // Convert all the elements.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002153 SmallVector<llvm::Metadata *, 16> EltTys;
David Blaikie6943dea2013-08-20 01:28:15 +00002154 // what about nested types?
Guy Benyei11169dd2012-12-18 14:30:41 +00002155
2156 // Note: The split of CXXDecl information here is intentional, the
2157 // gdb tests will depend on a certain ordering at printout. The debug
2158 // information offsets are still correct if we merge them all together
2159 // though.
David Majnemer58ed0f32016-07-17 00:39:12 +00002160 const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
Guy Benyei11169dd2012-12-18 14:30:41 +00002161 if (CXXDecl) {
2162 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
Reid Klecknerdc124992016-08-31 16:11:43 +00002163 CollectVTableInfo(CXXDecl, DefUnit, EltTys, FwdDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00002164 }
2165
Eric Christopher91a31902013-01-16 01:22:32 +00002166 // Collect data fields (including static variables and any initializers).
Guy Benyei11169dd2012-12-18 14:30:41 +00002167 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
Eric Christopher2df080e2013-10-11 18:16:51 +00002168 if (CXXDecl)
Guy Benyei11169dd2012-12-18 14:30:41 +00002169 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00002170
2171 LexicalBlockStack.pop_back();
2172 RegionMap.erase(Ty->getDecl());
2173
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002174 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
Duncan P. N. Exon Smithc8ee63e2014-12-18 00:48:56 +00002175 DBuilder.replaceArrays(FwdDecl, Elements);
Guy Benyei11169dd2012-12-18 14:30:41 +00002176
Adrian Prantl5f66bae2015-02-11 17:45:15 +00002177 if (FwdDecl->isTemporary())
Duncan P. N. Exon Smith4078ad42015-04-16 16:36:45 +00002178 FwdDecl =
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002179 llvm::MDNode::replaceWithPermanent(llvm::TempDICompositeType(FwdDecl));
Adrian Prantl5f66bae2015-02-11 17:45:15 +00002180
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002181 RegionMap[Ty->getDecl()].reset(FwdDecl);
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00002182 return FwdDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00002183}
2184
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002185llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectType *Ty,
2186 llvm::DIFile *Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002187 // Ignore protocols.
2188 return getOrCreateType(Ty->getBaseType(), Unit);
2189}
2190
Manman Rene6be26c2016-09-13 17:25:08 +00002191llvm::DIType *CGDebugInfo::CreateType(const ObjCTypeParamType *Ty,
2192 llvm::DIFile *Unit) {
2193 // Ignore protocols.
2194 SourceLocation Loc = Ty->getDecl()->getLocation();
2195
2196 // Use Typedefs to represent ObjCTypeParamType.
2197 return DBuilder.createTypedef(
2198 getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit),
2199 Ty->getDecl()->getName(), getOrCreateFile(Loc), getLineNumber(Loc),
2200 getDeclContextDescriptor(Ty->getDecl()));
2201}
2202
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00002203/// \return true if Getter has the default name for the property PD.
2204static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,
2205 const ObjCMethodDecl *Getter) {
2206 assert(PD);
2207 if (!Getter)
2208 return true;
2209
2210 assert(Getter->getDeclName().isObjCZeroArgSelector());
2211 return PD->getName() ==
Eric Christophere7b87e52014-10-26 23:40:33 +00002212 Getter->getDeclName().getObjCSelector().getNameForSlot(0);
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00002213}
2214
2215/// \return true if Setter has the default name for the property PD.
2216static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,
2217 const ObjCMethodDecl *Setter) {
2218 assert(PD);
2219 if (!Setter)
2220 return true;
2221
2222 assert(Setter->getDeclName().isObjCOneArgSelector());
Adrian Prantla4ce9062013-06-07 22:29:12 +00002223 return SelectorTable::constructSetterName(PD->getName()) ==
Eric Christophere7b87e52014-10-26 23:40:33 +00002224 Setter->getDeclName().getObjCSelector().getNameForSlot(0);
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00002225}
2226
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002227llvm::DIType *CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
2228 llvm::DIFile *Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002229 ObjCInterfaceDecl *ID = Ty->getDecl();
2230 if (!ID)
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00002231 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00002232
Adrian Prantl50fd1a82016-04-20 23:59:32 +00002233 // Return a forward declaration if this type was imported from a clang module,
2234 // and this is not the compile unit with the implementation of the type (which
2235 // may contain hidden ivars).
2236 if (DebugTypeExtRefs && ID->isFromASTFile() && ID->getDefinition() &&
2237 !ID->getImplementation())
Adrian Prantl5c8bd882015-09-11 17:23:08 +00002238 return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
2239 ID->getName(),
2240 getDeclContextDescriptor(ID), Unit, 0);
2241
Guy Benyei11169dd2012-12-18 14:30:41 +00002242 // Get overall information about the record type for the debug info.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002243 llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00002244 unsigned Line = getLineNumber(ID->getLocation());
Duncan P. N. Exon Smith798d5652015-04-15 23:19:15 +00002245 auto RuntimeLang =
2246 static_cast<llvm::dwarf::SourceLanguage>(TheCU->getSourceLanguage());
Guy Benyei11169dd2012-12-18 14:30:41 +00002247
2248 // If this is just a forward declaration return a special forward-declaration
2249 // debug type since we won't be able to lay out the entire type.
2250 ObjCInterfaceDecl *Def = ID->getDefinition();
David Blaikieef8a9512014-05-05 23:23:53 +00002251 if (!Def || !Def->getImplementation()) {
Adrian Prantl42ce2d32015-10-01 16:57:02 +00002252 llvm::DIScope *Mod = getParentModuleOrNull(ID);
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002253 llvm::DIType *FwdDecl = DBuilder.createReplaceableCompositeType(
Adrian Prantl42ce2d32015-10-01 16:57:02 +00002254 llvm::dwarf::DW_TAG_structure_type, ID->getName(), Mod ? Mod : TheCU,
2255 DefUnit, Line, RuntimeLang);
David Blaikieef8a9512014-05-05 23:23:53 +00002256 ObjCInterfaceCache.push_back(ObjCInterfaceCacheEntry(Ty, FwdDecl, Unit));
Guy Benyei11169dd2012-12-18 14:30:41 +00002257 return FwdDecl;
2258 }
2259
David Blaikieef8a9512014-05-05 23:23:53 +00002260 return CreateTypeDefinition(Ty, Unit);
2261}
2262
Adrian Prantlc4bb47e2015-06-30 17:39:51 +00002263llvm::DIModule *
Adrian Prantl66689202015-09-18 23:01:45 +00002264CGDebugInfo::getOrCreateModuleRef(ExternalASTSource::ASTSourceDescriptor Mod,
2265 bool CreateSkeletonCU) {
Adrian Prantleb66a262015-09-24 16:10:04 +00002266 // Use the Module pointer as the key into the cache. This is a
2267 // nullptr if the "Module" is a PCH, which is safe because we don't
2268 // support chained PCH debug info, so there can only be a single PCH.
2269 const Module *M = Mod.getModuleOrNull();
Adrian Prantl9e8ea352015-09-29 20:44:46 +00002270 auto ModRef = ModuleCache.find(M);
2271 if (ModRef != ModuleCache.end())
2272 return cast<llvm::DIModule>(ModRef->second);
Adrian Prantl2388ead2015-06-30 18:01:05 +00002273
2274 // Macro definitions that were defined with "-D" on the command line.
2275 SmallString<128> ConfigMacros;
2276 {
2277 llvm::raw_svector_ostream OS(ConfigMacros);
2278 const auto &PPOpts = CGM.getPreprocessorOpts();
2279 unsigned I = 0;
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002280 // Translate the macro definitions back into a command line.
Adrian Prantl2388ead2015-06-30 18:01:05 +00002281 for (auto &M : PPOpts.Macros) {
2282 if (++I > 1)
2283 OS << " ";
2284 const std::string &Macro = M.first;
2285 bool Undef = M.second;
2286 OS << "\"-" << (Undef ? 'U' : 'D');
2287 for (char c : Macro)
2288 switch (c) {
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00002289 case '\\':
2290 OS << "\\\\";
2291 break;
2292 case '"':
2293 OS << "\\\"";
2294 break;
2295 default:
2296 OS << c;
Adrian Prantl2388ead2015-06-30 18:01:05 +00002297 }
2298 OS << '\"';
Adrian Prantlc4bb47e2015-06-30 17:39:51 +00002299 }
Adrian Prantlc4bb47e2015-06-30 17:39:51 +00002300 }
Adrian Prantl66689202015-09-18 23:01:45 +00002301
Adrian Prantl835e6632015-09-24 16:10:10 +00002302 bool IsRootModule = M ? !M->Parent : true;
2303 if (CreateSkeletonCU && IsRootModule) {
Adrian Prantlc96da8f2016-01-22 17:43:43 +00002304 // PCH files don't have a signature field in the control block,
2305 // but LLVM detects skeleton CUs by looking for a non-zero DWO id.
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002306 // We use the lower 64 bits for debug info.
2307 uint64_t Signature =
2308 Mod.getSignature()
2309 ? (uint64_t)Mod.getSignature()[1] << 32 | Mod.getSignature()[0]
2310 : ~1ULL;
Adrian Prantl66689202015-09-18 23:01:45 +00002311 llvm::DIBuilder DIB(CGM.getModule());
Amjad Aboudfa9a17e2016-12-14 20:24:40 +00002312 DIB.createCompileUnit(TheCU->getSourceLanguage(),
Scott Lindera2fbcef2018-02-26 17:32:31 +00002313 // TODO: Support "Source" from external AST providers?
Amjad Aboudfa9a17e2016-12-14 20:24:40 +00002314 DIB.createFile(Mod.getModuleName(), Mod.getPath()),
2315 TheCU->getProducer(), true, StringRef(), 0,
2316 Mod.getASTFile(), llvm::DICompileUnit::FullDebug,
2317 Signature);
Adrian Prantl66689202015-09-18 23:01:45 +00002318 DIB.finalize();
Adrian Prantl2f957ac2015-09-19 00:59:22 +00002319 }
Adrian Prantl835e6632015-09-24 16:10:10 +00002320 llvm::DIModule *Parent =
2321 IsRootModule ? nullptr
2322 : getOrCreateModuleRef(
2323 ExternalASTSource::ASTSourceDescriptor(*M->Parent),
2324 CreateSkeletonCU);
Adrian Prantleb66a262015-09-24 16:10:04 +00002325 llvm::DIModule *DIMod =
Adrian Prantl835e6632015-09-24 16:10:10 +00002326 DBuilder.createModule(Parent, Mod.getModuleName(), ConfigMacros,
2327 Mod.getPath(), CGM.getHeaderSearchOpts().Sysroot);
Adrian Prantl9e8ea352015-09-29 20:44:46 +00002328 ModuleCache[M].reset(DIMod);
Adrian Prantleb66a262015-09-24 16:10:04 +00002329 return DIMod;
Adrian Prantlc4bb47e2015-06-30 17:39:51 +00002330}
2331
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002332llvm::DIType *CGDebugInfo::CreateTypeDefinition(const ObjCInterfaceType *Ty,
2333 llvm::DIFile *Unit) {
David Blaikieef8a9512014-05-05 23:23:53 +00002334 ObjCInterfaceDecl *ID = Ty->getDecl();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002335 llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
David Blaikieef8a9512014-05-05 23:23:53 +00002336 unsigned Line = getLineNumber(ID->getLocation());
Duncan P. N. Exon Smith798d5652015-04-15 23:19:15 +00002337 unsigned RuntimeLang = TheCU->getSourceLanguage();
Guy Benyei11169dd2012-12-18 14:30:41 +00002338
2339 // Bit size, align and offset of the type.
2340 uint64_t Size = CGM.getContext().getTypeSize(Ty);
Victor Leschuka7ece032016-10-20 00:13:19 +00002341 auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00002342
Leny Kholodov80c047d2016-09-06 10:48:04 +00002343 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
Guy Benyei11169dd2012-12-18 14:30:41 +00002344 if (ID->getImplementation())
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002345 Flags |= llvm::DINode::FlagObjcClassComplete;
Guy Benyei11169dd2012-12-18 14:30:41 +00002346
Adrian Prantlfd696112015-10-01 00:48:51 +00002347 llvm::DIScope *Mod = getParentModuleOrNull(ID);
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002348 llvm::DICompositeType *RealDecl = DBuilder.createStructType(
Adrian Prantlfd696112015-10-01 00:48:51 +00002349 Mod ? Mod : Unit, ID->getName(), DefUnit, Line, Size, Align, Flags,
2350 nullptr, llvm::DINodeArray(), RuntimeLang);
Guy Benyei11169dd2012-12-18 14:30:41 +00002351
David Blaikieef8a9512014-05-05 23:23:53 +00002352 QualType QTy(Ty, 0);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002353 TypeCache[QTy.getAsOpaquePtr()].reset(RealDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00002354
Eric Christopher35f1f9f2013-07-14 21:00:07 +00002355 // Push the struct on region stack.
Duncan P. N. Exon Smith4078ad42015-04-16 16:36:45 +00002356 LexicalBlockStack.emplace_back(RealDecl);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002357 RegionMap[Ty->getDecl()].reset(RealDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00002358
2359 // Convert all the elements.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002360 SmallVector<llvm::Metadata *, 16> EltTys;
Guy Benyei11169dd2012-12-18 14:30:41 +00002361
2362 ObjCInterfaceDecl *SClass = ID->getSuperClass();
2363 if (SClass) {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002364 llvm::DIType *SClassTy =
Eric Christophere7b87e52014-10-26 23:40:33 +00002365 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
Duncan P. N. Exon Smithb7470232015-04-15 23:48:50 +00002366 if (!SClassTy)
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00002367 return nullptr;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002368
Brock Wyma3db2b102018-05-14 21:21:22 +00002369 llvm::DIType *InhTag = DBuilder.createInheritance(RealDecl, SClassTy, 0, 0,
Leny Kholodovdf050fd2016-09-06 17:06:14 +00002370 llvm::DINode::FlagZero);
Guy Benyei11169dd2012-12-18 14:30:41 +00002371 EltTys.push_back(InhTag);
2372 }
2373
Eric Christopher35f1f9f2013-07-14 21:00:07 +00002374 // Create entries for all of the properties.
Nico Weber7123bca2015-12-04 19:14:14 +00002375 auto AddProperty = [&](const ObjCPropertyDecl *PD) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002376 SourceLocation Loc = PD->getLocation();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002377 llvm::DIFile *PUnit = getOrCreateFile(Loc);
Guy Benyei11169dd2012-12-18 14:30:41 +00002378 unsigned PLine = getLineNumber(Loc);
2379 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
2380 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
Eric Christophere7b87e52014-10-26 23:40:33 +00002381 llvm::MDNode *PropertyNode = DBuilder.createObjCProperty(
2382 PD->getName(), PUnit, PLine,
2383 hasDefaultGetterName(PD, Getter) ? ""
2384 : getSelectorName(PD->getGetterName()),
2385 hasDefaultSetterName(PD, Setter) ? ""
2386 : getSelectorName(PD->getSetterName()),
2387 PD->getPropertyAttributes(), getOrCreateType(PD->getType(), PUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00002388 EltTys.push_back(PropertyNode);
Nico Weber7123bca2015-12-04 19:14:14 +00002389 };
2390 {
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00002391 llvm::SmallPtrSet<const IdentifierInfo *, 16> PropertySet;
Nico Weberde059e12015-12-04 19:35:45 +00002392 for (const ObjCCategoryDecl *ClassExt : ID->known_extensions())
Manman Renefe1bac2016-01-27 20:00:32 +00002393 for (auto *PD : ClassExt->properties()) {
Nico Weberde059e12015-12-04 19:35:45 +00002394 PropertySet.insert(PD->getIdentifier());
2395 AddProperty(PD);
2396 }
Manman Renefe1bac2016-01-27 20:00:32 +00002397 for (const auto *PD : ID->properties()) {
Nico Weber7123bca2015-12-04 19:14:14 +00002398 // Don't emit duplicate metadata for properties that were already in a
2399 // class extension.
2400 if (!PropertySet.insert(PD->getIdentifier()).second)
2401 continue;
2402 AddProperty(PD);
2403 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002404 }
2405
2406 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
2407 unsigned FieldNo = 0;
2408 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
2409 Field = Field->getNextIvar(), ++FieldNo) {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002410 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
Duncan P. N. Exon Smithb7470232015-04-15 23:48:50 +00002411 if (!FieldTy)
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00002412 return nullptr;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002413
Guy Benyei11169dd2012-12-18 14:30:41 +00002414 StringRef FieldName = Field->getName();
2415
2416 // Ignore unnamed fields.
2417 if (FieldName.empty())
2418 continue;
2419
2420 // Get the location for the field.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002421 llvm::DIFile *FieldDefUnit = getOrCreateFile(Field->getLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00002422 unsigned FieldLine = getLineNumber(Field->getLocation());
2423 QualType FType = Field->getType();
2424 uint64_t FieldSize = 0;
Victor Leschuk802e4a52016-10-19 22:11:07 +00002425 uint32_t FieldAlign = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00002426
2427 if (!FType->isIncompleteArrayType()) {
2428
2429 // Bit size, align and offset of the type.
2430 FieldSize = Field->isBitField()
Eric Christopher35f1f9f2013-07-14 21:00:07 +00002431 ? Field->getBitWidthValue(CGM.getContext())
2432 : CGM.getContext().getTypeSize(FType);
Victor Leschuka7ece032016-10-20 00:13:19 +00002433 FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00002434 }
2435
2436 uint64_t FieldOffset;
2437 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
2438 // We don't know the runtime offset of an ivar if we're using the
2439 // non-fragile ABI. For bitfields, use the bit offset into the first
2440 // byte of storage of the bitfield. For other fields, use zero.
2441 if (Field->isBitField()) {
Eric Christophere7b87e52014-10-26 23:40:33 +00002442 FieldOffset =
2443 CGM.getObjCRuntime().ComputeBitfieldBitOffset(CGM, ID, Field);
Guy Benyei11169dd2012-12-18 14:30:41 +00002444 FieldOffset %= CGM.getContext().getCharWidth();
2445 } else {
2446 FieldOffset = 0;
2447 }
2448 } else {
2449 FieldOffset = RL.getFieldOffset(FieldNo);
2450 }
2451
Leny Kholodov80c047d2016-09-06 10:48:04 +00002452 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
Guy Benyei11169dd2012-12-18 14:30:41 +00002453 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002454 Flags = llvm::DINode::FlagProtected;
Guy Benyei11169dd2012-12-18 14:30:41 +00002455 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002456 Flags = llvm::DINode::FlagPrivate;
Adrian Prantl21361fb2014-08-29 22:44:27 +00002457 else if (Field->getAccessControl() == ObjCIvarDecl::Public)
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002458 Flags = llvm::DINode::FlagPublic;
Guy Benyei11169dd2012-12-18 14:30:41 +00002459
Craig Topper8a13c412014-05-21 05:09:00 +00002460 llvm::MDNode *PropertyNode = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00002461 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00002462 if (ObjCPropertyImplDecl *PImpD =
Eric Christophere7b87e52014-10-26 23:40:33 +00002463 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002464 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
Eric Christopherc0c5d462013-02-21 22:35:08 +00002465 SourceLocation Loc = PD->getLocation();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002466 llvm::DIFile *PUnit = getOrCreateFile(Loc);
Eric Christopherc0c5d462013-02-21 22:35:08 +00002467 unsigned PLine = getLineNumber(Loc);
Guy Benyei11169dd2012-12-18 14:30:41 +00002468 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
2469 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
Eric Christophere7b87e52014-10-26 23:40:33 +00002470 PropertyNode = DBuilder.createObjCProperty(
2471 PD->getName(), PUnit, PLine,
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00002472 hasDefaultGetterName(PD, Getter)
2473 ? ""
2474 : getSelectorName(PD->getGetterName()),
2475 hasDefaultSetterName(PD, Setter)
2476 ? ""
2477 : getSelectorName(PD->getSetterName()),
Eric Christophere7b87e52014-10-26 23:40:33 +00002478 PD->getPropertyAttributes(),
2479 getOrCreateType(PD->getType(), PUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00002480 }
2481 }
2482 }
Eric Christophere7b87e52014-10-26 23:40:33 +00002483 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit, FieldLine,
2484 FieldSize, FieldAlign, FieldOffset, Flags,
2485 FieldTy, PropertyNode);
Guy Benyei11169dd2012-12-18 14:30:41 +00002486 EltTys.push_back(FieldTy);
2487 }
2488
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002489 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
Duncan P. N. Exon Smithc8ee63e2014-12-18 00:48:56 +00002490 DBuilder.replaceArrays(RealDecl, Elements);
Adrian Prantla03a85a2013-03-06 22:03:30 +00002491
Guy Benyei11169dd2012-12-18 14:30:41 +00002492 LexicalBlockStack.pop_back();
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00002493 return RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00002494}
2495
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002496llvm::DIType *CGDebugInfo::CreateType(const VectorType *Ty,
2497 llvm::DIFile *Unit) {
2498 llvm::DIType *ElementTy = getOrCreateType(Ty->getElementType(), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00002499 int64_t Count = Ty->getNumElements();
Guy Benyei11169dd2012-12-18 14:30:41 +00002500
Sander de Smalen891af03a2018-02-03 13:55:59 +00002501 llvm::Metadata *Subscript;
2502 QualType QTy(Ty, 0);
2503 auto SizeExpr = SizeExprCache.find(QTy);
2504 if (SizeExpr != SizeExprCache.end())
2505 Subscript = DBuilder.getOrCreateSubrange(0, SizeExpr->getSecond());
2506 else
2507 Subscript = DBuilder.getOrCreateSubrange(0, Count ? Count : -1);
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002508 llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
Guy Benyei11169dd2012-12-18 14:30:41 +00002509
2510 uint64_t Size = CGM.getContext().getTypeSize(Ty);
Victor Leschuka7ece032016-10-20 00:13:19 +00002511 auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00002512
2513 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
2514}
2515
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002516llvm::DIType *CGDebugInfo::CreateType(const ArrayType *Ty, llvm::DIFile *Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002517 uint64_t Size;
Victor Leschuk802e4a52016-10-19 22:11:07 +00002518 uint32_t Align;
Guy Benyei11169dd2012-12-18 14:30:41 +00002519
2520 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
David Majnemer58ed0f32016-07-17 00:39:12 +00002521 if (const auto *VAT = dyn_cast<VariableArrayType>(Ty)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002522 Size = 0;
Victor Leschuka7ece032016-10-20 00:13:19 +00002523 Align = getTypeAlignIfRequired(CGM.getContext().getBaseElementType(VAT),
2524 CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00002525 } else if (Ty->isIncompleteArrayType()) {
2526 Size = 0;
2527 if (Ty->getElementType()->isIncompleteType())
2528 Align = 0;
2529 else
Victor Leschuka7ece032016-10-20 00:13:19 +00002530 Align = getTypeAlignIfRequired(Ty->getElementType(), CGM.getContext());
David Blaikief03b2e82013-05-09 20:48:12 +00002531 } else if (Ty->isIncompleteType()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002532 Size = 0;
2533 Align = 0;
2534 } else {
2535 // Size and align of the whole array, not the element type.
2536 Size = CGM.getContext().getTypeSize(Ty);
Victor Leschuka7ece032016-10-20 00:13:19 +00002537 Align = getTypeAlignIfRequired(Ty, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00002538 }
2539
2540 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
2541 // interior arrays, do we care? Why aren't nested arrays represented the
2542 // obvious/recursive way?
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002543 SmallVector<llvm::Metadata *, 8> Subscripts;
Guy Benyei11169dd2012-12-18 14:30:41 +00002544 QualType EltTy(Ty, 0);
2545 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
2546 // If the number of elements is known, then count is that number. Otherwise,
2547 // it's -1. This allows us to represent a subrange with an array of 0
2548 // elements, like this:
2549 //
2550 // struct foo {
2551 // int x[0];
2552 // };
Eric Christophere7b87e52014-10-26 23:40:33 +00002553 int64_t Count = -1; // Count == -1 is an unbounded array.
David Majnemer58ed0f32016-07-17 00:39:12 +00002554 if (const auto *CAT = dyn_cast<ConstantArrayType>(Ty))
Guy Benyei11169dd2012-12-18 14:30:41 +00002555 Count = CAT->getSize().getZExtValue();
David Blaikie87173f12016-08-22 17:49:56 +00002556 else if (const auto *VAT = dyn_cast<VariableArrayType>(Ty)) {
Eli Friedman01d6b962016-10-19 22:16:32 +00002557 if (Expr *Size = VAT->getSizeExpr()) {
Fangrui Song407659a2018-11-30 23:41:18 +00002558 Expr::EvalResult Result;
2559 if (Size->EvaluateAsInt(Result, CGM.getContext()))
2560 Count = Result.Val.getInt().getExtValue();
Eli Friedman01d6b962016-10-19 22:16:32 +00002561 }
David Blaikie87173f12016-08-22 17:49:56 +00002562 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00002563
Sander de Smalen891af03a2018-02-03 13:55:59 +00002564 auto SizeNode = SizeExprCache.find(EltTy);
2565 if (SizeNode != SizeExprCache.end())
2566 Subscripts.push_back(
2567 DBuilder.getOrCreateSubrange(0, SizeNode->getSecond()));
2568 else
2569 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
Guy Benyei11169dd2012-12-18 14:30:41 +00002570 EltTy = Ty->getElementType();
2571 }
2572
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002573 llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
Guy Benyei11169dd2012-12-18 14:30:41 +00002574
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00002575 return DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
2576 SubscriptArray);
Guy Benyei11169dd2012-12-18 14:30:41 +00002577}
2578
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002579llvm::DIType *CGDebugInfo::CreateType(const LValueReferenceType *Ty,
2580 llvm::DIFile *Unit) {
Eric Christophere7b87e52014-10-26 23:40:33 +00002581 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type, Ty,
2582 Ty->getPointeeType(), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00002583}
2584
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002585llvm::DIType *CGDebugInfo::CreateType(const RValueReferenceType *Ty,
2586 llvm::DIFile *Unit) {
Eric Christophere7b87e52014-10-26 23:40:33 +00002587 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type, Ty,
2588 Ty->getPointeeType(), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00002589}
2590
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002591llvm::DIType *CGDebugInfo::CreateType(const MemberPointerType *Ty,
2592 llvm::DIFile *U) {
Leny Kholodov80c047d2016-09-06 10:48:04 +00002593 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
Reid Klecknerfb727182016-06-17 22:27:59 +00002594 uint64_t Size = 0;
2595
2596 if (!Ty->isIncompleteType()) {
2597 Size = CGM.getContext().getTypeSize(Ty);
2598
2599 // Set the MS inheritance model. There is no flag for the unspecified model.
2600 if (CGM.getTarget().getCXXABI().isMicrosoft()) {
2601 switch (Ty->getMostRecentCXXRecordDecl()->getMSInheritanceModel()) {
2602 case MSInheritanceAttr::Keyword_single_inheritance:
2603 Flags |= llvm::DINode::FlagSingleInheritance;
2604 break;
2605 case MSInheritanceAttr::Keyword_multiple_inheritance:
2606 Flags |= llvm::DINode::FlagMultipleInheritance;
2607 break;
2608 case MSInheritanceAttr::Keyword_virtual_inheritance:
2609 Flags |= llvm::DINode::FlagVirtualInheritance;
2610 break;
2611 case MSInheritanceAttr::Keyword_unspecified_inheritance:
2612 break;
2613 }
2614 }
2615 }
2616
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002617 llvm::DIType *ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
David Majnemer5fd33e02015-04-24 01:25:08 +00002618 if (Ty->isMemberDataPointerType())
David Blaikie2c705ca2013-01-19 19:20:56 +00002619 return DBuilder.createMemberPointerType(
Reid Klecknerfb727182016-06-17 22:27:59 +00002620 getOrCreateType(Ty->getPointeeType(), U), ClassType, Size, /*Align=*/0,
2621 Flags);
Adrian Prantl0866acd2013-12-19 01:38:47 +00002622
2623 const FunctionProtoType *FPT =
Eric Christophere7b87e52014-10-26 23:40:33 +00002624 Ty->getPointeeType()->getAs<FunctionProtoType>();
2625 return DBuilder.createMemberPointerType(
2626 getOrCreateInstanceMethodType(CGM.getContext().getPointerType(QualType(
2627 Ty->getClass(), FPT->getTypeQuals())),
2628 FPT, U),
Reid Klecknerfb727182016-06-17 22:27:59 +00002629 ClassType, Size, /*Align=*/0, Flags);
Guy Benyei11169dd2012-12-18 14:30:41 +00002630}
2631
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002632llvm::DIType *CGDebugInfo::CreateType(const AtomicType *Ty, llvm::DIFile *U) {
Victor Leschuk0df190372016-10-31 19:09:47 +00002633 auto *FromTy = getOrCreateType(Ty->getValueType(), U);
2634 return DBuilder.createQualifiedType(llvm::dwarf::DW_TAG_atomic_type, FromTy);
Guy Benyei11169dd2012-12-18 14:30:41 +00002635}
2636
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00002637llvm::DIType *CGDebugInfo::CreateType(const PipeType *Ty, llvm::DIFile *U) {
Xiuli Pan9c14e282016-01-09 12:53:17 +00002638 return getOrCreateType(Ty->getElementType(), U);
2639}
2640
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002641llvm::DIType *CGDebugInfo::CreateEnumType(const EnumType *Ty) {
Manman Ren1b457022013-08-28 21:20:28 +00002642 const EnumDecl *ED = Ty->getDecl();
Adrian Prantl5c8bd882015-09-11 17:23:08 +00002643
Guy Benyei11169dd2012-12-18 14:30:41 +00002644 uint64_t Size = 0;
Victor Leschuk802e4a52016-10-19 22:11:07 +00002645 uint32_t Align = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00002646 if (!ED->getTypeForDecl()->isIncompleteType()) {
2647 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
Victor Leschuka7ece032016-10-20 00:13:19 +00002648 Align = getDeclAlignIfRequired(ED, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00002649 }
2650
Brock Wyma8557ec52018-05-22 12:41:19 +00002651 SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
Manman Rene0064d82013-08-29 23:19:58 +00002652
Adrian Prantl5c8bd882015-09-11 17:23:08 +00002653 bool isImportedFromModule =
2654 DebugTypeExtRefs && ED->isFromASTFile() && ED->getDefinition();
2655
Guy Benyei11169dd2012-12-18 14:30:41 +00002656 // If this is just a forward declaration, construct an appropriately
2657 // marked node and just return it.
Adrian Prantl5c8bd882015-09-11 17:23:08 +00002658 if (isImportedFromModule || !ED->getDefinition()) {
Adrian Prantl45946062016-02-23 19:30:08 +00002659 // Note that it is possible for enums to be created as part of
2660 // their own declcontext. In this case a FwdDecl will be created
2661 // twice. This doesn't cause a problem because both FwdDecls are
2662 // entered into the ReplaceMap: finalize() will replace the first
2663 // FwdDecl with the second and then replace the second with
2664 // complete type.
Amjad Abouddc4531e2016-04-30 01:44:38 +00002665 llvm::DIScope *EDContext = getDeclContextDescriptor(ED);
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002666 llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
Adrian Prantlff9d83c2016-02-08 17:03:28 +00002667 llvm::TempDIScope TmpContext(DBuilder.createReplaceableCompositeType(
2668 llvm::dwarf::DW_TAG_enumeration_type, "", TheCU, DefUnit, 0));
Adrian Prantla40030f2016-02-06 01:59:09 +00002669
Guy Benyei11169dd2012-12-18 14:30:41 +00002670 unsigned Line = getLineNumber(ED->getLocation());
2671 StringRef EDName = ED->getName();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002672 llvm::DIType *RetTy = DBuilder.createReplaceableCompositeType(
Adrian Prantl45946062016-02-23 19:30:08 +00002673 llvm::dwarf::DW_TAG_enumeration_type, EDName, EDContext, DefUnit, Line,
Brock Wyma8557ec52018-05-22 12:41:19 +00002674 0, Size, Align, llvm::DINode::FlagFwdDecl, Identifier);
Adrian Prantla40030f2016-02-06 01:59:09 +00002675
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002676 ReplaceMap.emplace_back(
2677 std::piecewise_construct, std::make_tuple(Ty),
2678 std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
David Blaikief427b002014-05-06 03:42:01 +00002679 return RetTy;
Guy Benyei11169dd2012-12-18 14:30:41 +00002680 }
2681
David Blaikie483a9da2014-05-06 18:35:21 +00002682 return CreateTypeDefinition(Ty);
2683}
2684
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002685llvm::DIType *CGDebugInfo::CreateTypeDefinition(const EnumType *Ty) {
David Blaikie483a9da2014-05-06 18:35:21 +00002686 const EnumDecl *ED = Ty->getDecl();
2687 uint64_t Size = 0;
Victor Leschuk802e4a52016-10-19 22:11:07 +00002688 uint32_t Align = 0;
David Blaikie483a9da2014-05-06 18:35:21 +00002689 if (!ED->getTypeForDecl()->isIncompleteType()) {
2690 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
Victor Leschuka7ece032016-10-20 00:13:19 +00002691 Align = getDeclAlignIfRequired(ED, CGM.getContext());
David Blaikie483a9da2014-05-06 18:35:21 +00002692 }
2693
Brock Wyma8557ec52018-05-22 12:41:19 +00002694 SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
David Blaikie483a9da2014-05-06 18:35:21 +00002695
Duncan P. N. Exon Smithdadc2b62015-04-21 18:43:54 +00002696 // Create elements for each enumerator.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002697 SmallVector<llvm::Metadata *, 16> Enumerators;
Guy Benyei11169dd2012-12-18 14:30:41 +00002698 ED = ED->getDefinition();
Momchil Velikov25f6be52018-02-12 16:12:52 +00002699 bool IsSigned = ED->getIntegerType()->isSignedIntegerType();
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00002700 for (const auto *Enum : ED->enumerators()) {
Momchil Velikov25f6be52018-02-12 16:12:52 +00002701 const auto &InitVal = Enum->getInitVal();
2702 auto Value = IsSigned ? InitVal.getSExtValue() : InitVal.getZExtValue();
2703 Enumerators.push_back(
2704 DBuilder.createEnumerator(Enum->getName(), Value, !IsSigned));
Guy Benyei11169dd2012-12-18 14:30:41 +00002705 }
2706
2707 // Return a CompositeType for the enum itself.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002708 llvm::DINodeArray EltArray = DBuilder.getOrCreateArray(Enumerators);
Guy Benyei11169dd2012-12-18 14:30:41 +00002709
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002710 llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00002711 unsigned Line = getLineNumber(ED->getLocation());
Amjad Abouddc4531e2016-04-30 01:44:38 +00002712 llvm::DIScope *EnumContext = getDeclContextDescriptor(ED);
Momchil Velikov25f6be52018-02-12 16:12:52 +00002713 llvm::DIType *ClassTy = getOrCreateType(ED->getIntegerType(), DefUnit);
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00002714 return DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit,
2715 Line, Size, Align, EltArray, ClassTy,
Brock Wyma8557ec52018-05-22 12:41:19 +00002716 Identifier, ED->isFixed());
Guy Benyei11169dd2012-12-18 14:30:41 +00002717}
2718
Amjad Aboud546bc112017-02-09 22:07:24 +00002719llvm::DIMacro *CGDebugInfo::CreateMacro(llvm::DIMacroFile *Parent,
2720 unsigned MType, SourceLocation LineLoc,
2721 StringRef Name, StringRef Value) {
2722 unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(LineLoc);
2723 return DBuilder.createMacro(Parent, Line, MType, Name, Value);
2724}
2725
2726llvm::DIMacroFile *CGDebugInfo::CreateTempMacroFile(llvm::DIMacroFile *Parent,
2727 SourceLocation LineLoc,
2728 SourceLocation FileLoc) {
2729 llvm::DIFile *FName = getOrCreateFile(FileLoc);
2730 unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(LineLoc);
2731 return DBuilder.createTempMacroFile(Parent, Line, FName);
2732}
2733
David Blaikie05491062013-01-21 04:37:12 +00002734static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
2735 Qualifiers Quals;
Guy Benyei11169dd2012-12-18 14:30:41 +00002736 do {
Adrian Prantl179af902013-09-26 21:35:50 +00002737 Qualifiers InnerQuals = T.getLocalQualifiers();
2738 // Qualifiers::operator+() doesn't like it if you add a Qualifier
2739 // that is already there.
2740 Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals);
2741 Quals += InnerQuals;
Guy Benyei11169dd2012-12-18 14:30:41 +00002742 QualType LastT = T;
2743 switch (T->getTypeClass()) {
2744 default:
David Blaikie05491062013-01-21 04:37:12 +00002745 return C.getQualifiedType(T.getTypePtr(), Quals);
David Blaikief1b382e2014-04-06 17:14:06 +00002746 case Type::TemplateSpecialization: {
2747 const auto *Spec = cast<TemplateSpecializationType>(T);
2748 if (Spec->isTypeAlias())
2749 return C.getQualifiedType(T.getTypePtr(), Quals);
2750 T = Spec->desugar();
Eric Christophere7b87e52014-10-26 23:40:33 +00002751 break;
2752 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002753 case Type::TypeOfExpr:
2754 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
2755 break;
2756 case Type::TypeOf:
2757 T = cast<TypeOfType>(T)->getUnderlyingType();
2758 break;
2759 case Type::Decltype:
2760 T = cast<DecltypeType>(T)->getUnderlyingType();
2761 break;
2762 case Type::UnaryTransform:
2763 T = cast<UnaryTransformType>(T)->getUnderlyingType();
2764 break;
2765 case Type::Attributed:
2766 T = cast<AttributedType>(T)->getEquivalentType();
2767 break;
2768 case Type::Elaborated:
2769 T = cast<ElaboratedType>(T)->getNamedType();
2770 break;
2771 case Type::Paren:
2772 T = cast<ParenType>(T)->getInnerType();
2773 break;
David Blaikie05491062013-01-21 04:37:12 +00002774 case Type::SubstTemplateTypeParm:
Guy Benyei11169dd2012-12-18 14:30:41 +00002775 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
Guy Benyei11169dd2012-12-18 14:30:41 +00002776 break;
Richard Smitha0abc422017-02-22 00:13:14 +00002777 case Type::Auto:
2778 case Type::DeducedTemplateSpecialization: {
2779 QualType DT = cast<DeducedType>(T)->getDeducedType();
David Blaikie42edade2014-11-11 20:44:45 +00002780 assert(!DT.isNull() && "Undeduced types shouldn't reach here.");
David Blaikie22c460a02013-05-24 21:24:35 +00002781 T = DT;
Guy Benyei11169dd2012-12-18 14:30:41 +00002782 break;
2783 }
Jordan Rose303e2f12016-11-10 23:28:17 +00002784 case Type::Adjusted:
2785 case Type::Decayed:
2786 // Decayed and adjusted types use the adjusted type in LLVM and DWARF.
2787 T = cast<AdjustedType>(T)->getAdjustedType();
2788 break;
2789 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00002790
Guy Benyei11169dd2012-12-18 14:30:41 +00002791 assert(T != LastT && "Type unwrapping failed to unwrap!");
NAKAMURA Takumi3e0a3632013-01-21 10:51:28 +00002792 (void)LastT;
Guy Benyei11169dd2012-12-18 14:30:41 +00002793 } while (true);
2794}
2795
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002796llvm::DIType *CGDebugInfo::getTypeOrNull(QualType Ty) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002797
2798 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00002799 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Eric Christopherb2a008c2013-05-16 00:45:12 +00002800
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00002801 auto It = TypeCache.find(Ty.getAsOpaquePtr());
2802 if (It != TypeCache.end()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002803 // Verify that the debug info still exists.
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00002804 if (llvm::Metadata *V = It->second)
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002805 return cast<llvm::DIType>(V);
Guy Benyei11169dd2012-12-18 14:30:41 +00002806 }
2807
Duncan P. N. Exon Smithc7551282015-04-06 23:21:33 +00002808 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00002809}
2810
David Blaikie0e716b42014-03-03 23:48:23 +00002811void CGDebugInfo::completeTemplateDefinition(
2812 const ClassTemplateSpecializationDecl &SD) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00002813 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
David Blaikie0856f662014-03-04 22:01:08 +00002814 return;
David Blaikie1ac9c982017-04-11 21:13:37 +00002815 completeUnusedClass(SD);
2816}
David Blaikie0856f662014-03-04 22:01:08 +00002817
David Blaikie1ac9c982017-04-11 21:13:37 +00002818void CGDebugInfo::completeUnusedClass(const CXXRecordDecl &D) {
2819 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
2820 return;
2821
2822 completeClassData(&D);
David Blaikie0e716b42014-03-03 23:48:23 +00002823 // In case this type has no member function definitions being emitted, ensure
2824 // it is retained
David Blaikie1ac9c982017-04-11 21:13:37 +00002825 RetainedTypes.push_back(CGM.getContext().getRecordType(&D).getAsOpaquePtr());
David Blaikie0e716b42014-03-03 23:48:23 +00002826}
2827
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002828llvm::DIType *CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile *Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002829 if (Ty.isNull())
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00002830 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00002831
2832 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00002833 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00002834
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00002835 if (auto *T = getTypeOrNull(Ty))
Guy Benyei11169dd2012-12-18 14:30:41 +00002836 return T;
2837
Adrian Prantlca844182015-09-11 17:23:03 +00002838 llvm::DIType *Res = CreateTypeNode(Ty, Unit);
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00002839 void *TyPtr = Ty.getAsOpaquePtr();
Adrian Prantl73409ce2013-03-11 18:33:46 +00002840
2841 // And update the type cache.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002842 TypeCache[TyPtr].reset(Res);
Guy Benyei11169dd2012-12-18 14:30:41 +00002843
Guy Benyei11169dd2012-12-18 14:30:41 +00002844 return Res;
2845}
2846
Adrian Prantl5c8bd882015-09-11 17:23:08 +00002847llvm::DIModule *CGDebugInfo::getParentModuleOrNull(const Decl *D) {
Adrian Prantl335f5c72015-10-02 17:36:14 +00002848 // A forward declaration inside a module header does not belong to the module.
2849 if (isa<RecordDecl>(D) && !cast<RecordDecl>(D)->getDefinition())
2850 return nullptr;
Adrian Prantl85d938a2015-09-21 17:48:37 +00002851 if (DebugTypeExtRefs && D->isFromASTFile()) {
2852 // Record a reference to an imported clang module or precompiled header.
2853 auto *Reader = CGM.getContext().getExternalSource();
2854 auto Idx = D->getOwningModuleID();
2855 auto Info = Reader->getSourceDescriptor(Idx);
2856 if (Info)
2857 return getOrCreateModuleRef(*Info, /*SkeletonCU=*/true);
2858 } else if (ClangModuleMap) {
Adrian Prantl9402cef2015-09-20 16:51:35 +00002859 // We are building a clang module or a precompiled header.
2860 //
2861 // TODO: When D is a CXXRecordDecl or a C++ Enum, the ODR applies
2862 // and it wouldn't be necessary to specify the parent scope
2863 // because the type is already unique by definition (it would look
2864 // like the output of -fno-standalone-debug). On the other hand,
2865 // the parent scope helps a consumer to quickly locate the object
2866 // file where the type's definition is located, so it might be
2867 // best to make this behavior a command line or debugger tuning
2868 // option.
Richard Smith54f04402017-05-18 02:29:20 +00002869 if (Module *M = D->getOwningModule()) {
Adrian Prantlaa5d08d2016-01-22 21:14:41 +00002870 // This is a (sub-)module.
Adrian Prantl9402cef2015-09-20 16:51:35 +00002871 auto Info = ExternalASTSource::ASTSourceDescriptor(*M);
2872 return getOrCreateModuleRef(Info, /*SkeletonCU=*/false);
Adrian Prantlaa5d08d2016-01-22 21:14:41 +00002873 } else {
2874 // This the precompiled header being built.
2875 return getOrCreateModuleRef(PCHDescriptor, /*SkeletonCU=*/false);
Adrian Prantl9402cef2015-09-20 16:51:35 +00002876 }
2877 }
Adrian Prantl5c8bd882015-09-11 17:23:08 +00002878
Adrian Prantl9402cef2015-09-20 16:51:35 +00002879 return nullptr;
Adrian Prantl5c8bd882015-09-11 17:23:08 +00002880}
2881
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002882llvm::DIType *CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile *Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002883 // Handle qualifiers, which recursively handles what they refer to.
2884 if (Ty.hasLocalQualifiers())
David Blaikie99dab3b2013-09-04 22:03:57 +00002885 return CreateQualifiedType(Ty, Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00002886
Guy Benyei11169dd2012-12-18 14:30:41 +00002887 // Work out details of type.
2888 switch (Ty->getTypeClass()) {
2889#define TYPE(Class, Base)
2890#define ABSTRACT_TYPE(Class, Base)
2891#define NON_CANONICAL_TYPE(Class, Base)
2892#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2893#include "clang/AST/TypeNodes.def"
2894 llvm_unreachable("Dependent types cannot show up in debug information");
2895
2896 case Type::ExtVector:
2897 case Type::Vector:
2898 return CreateType(cast<VectorType>(Ty), Unit);
2899 case Type::ObjCObjectPointer:
2900 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
2901 case Type::ObjCObject:
2902 return CreateType(cast<ObjCObjectType>(Ty), Unit);
Manman Rene6be26c2016-09-13 17:25:08 +00002903 case Type::ObjCTypeParam:
2904 return CreateType(cast<ObjCTypeParamType>(Ty), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00002905 case Type::ObjCInterface:
2906 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
2907 case Type::Builtin:
2908 return CreateType(cast<BuiltinType>(Ty));
2909 case Type::Complex:
2910 return CreateType(cast<ComplexType>(Ty));
2911 case Type::Pointer:
2912 return CreateType(cast<PointerType>(Ty), Unit);
2913 case Type::BlockPointer:
2914 return CreateType(cast<BlockPointerType>(Ty), Unit);
2915 case Type::Typedef:
David Blaikie99dab3b2013-09-04 22:03:57 +00002916 return CreateType(cast<TypedefType>(Ty), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00002917 case Type::Record:
David Blaikie99dab3b2013-09-04 22:03:57 +00002918 return CreateType(cast<RecordType>(Ty));
Guy Benyei11169dd2012-12-18 14:30:41 +00002919 case Type::Enum:
Manman Ren1b457022013-08-28 21:20:28 +00002920 return CreateEnumType(cast<EnumType>(Ty));
Guy Benyei11169dd2012-12-18 14:30:41 +00002921 case Type::FunctionProto:
2922 case Type::FunctionNoProto:
2923 return CreateType(cast<FunctionType>(Ty), Unit);
2924 case Type::ConstantArray:
2925 case Type::VariableArray:
2926 case Type::IncompleteArray:
2927 return CreateType(cast<ArrayType>(Ty), Unit);
2928
2929 case Type::LValueReference:
2930 return CreateType(cast<LValueReferenceType>(Ty), Unit);
2931 case Type::RValueReference:
2932 return CreateType(cast<RValueReferenceType>(Ty), Unit);
2933
2934 case Type::MemberPointer:
2935 return CreateType(cast<MemberPointerType>(Ty), Unit);
2936
2937 case Type::Atomic:
2938 return CreateType(cast<AtomicType>(Ty), Unit);
2939
Xiuli Pan9c14e282016-01-09 12:53:17 +00002940 case Type::Pipe:
2941 return CreateType(cast<PipeType>(Ty), Unit);
2942
Guy Benyei11169dd2012-12-18 14:30:41 +00002943 case Type::TemplateSpecialization:
David Blaikief1b382e2014-04-06 17:14:06 +00002944 return CreateType(cast<TemplateSpecializationType>(Ty), Unit);
2945
David Blaikie42edade2014-11-11 20:44:45 +00002946 case Type::Auto:
David Blaikief1b382e2014-04-06 17:14:06 +00002947 case Type::Attributed:
Jordan Rose303e2f12016-11-10 23:28:17 +00002948 case Type::Adjusted:
2949 case Type::Decayed:
Richard Smith600b5262017-01-26 20:40:47 +00002950 case Type::DeducedTemplateSpecialization:
Guy Benyei11169dd2012-12-18 14:30:41 +00002951 case Type::Elaborated:
2952 case Type::Paren:
2953 case Type::SubstTemplateTypeParm:
2954 case Type::TypeOfExpr:
2955 case Type::TypeOf:
2956 case Type::Decltype:
2957 case Type::UnaryTransform:
David Blaikie66ed89d2013-07-13 21:08:08 +00002958 case Type::PackExpansion:
David Blaikie22c460a02013-05-24 21:24:35 +00002959 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002960 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00002961
David Blaikie42edade2014-11-11 20:44:45 +00002962 llvm_unreachable("type should have been unwrapped!");
Guy Benyei11169dd2012-12-18 14:30:41 +00002963}
2964
Duncan P. N. Exon Smithbd210e62015-07-24 20:34:41 +00002965llvm::DICompositeType *CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty,
2966 llvm::DIFile *Unit) {
David Blaikie4a2b5ef2013-08-12 22:24:20 +00002967 QualType QTy(Ty, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00002968
Duncan P. N. Exon Smithbd210e62015-07-24 20:34:41 +00002969 auto *T = cast_or_null<llvm::DICompositeType>(getTypeOrNull(QTy));
Guy Benyei11169dd2012-12-18 14:30:41 +00002970
2971 // We may have cached a forward decl when we could have created
2972 // a non-forward decl. Go ahead and create a non-forward decl
2973 // now.
Duncan P. N. Exon Smith4caa7f22015-04-16 01:00:56 +00002974 if (T && !T->isForwardDecl())
Eric Christophere7b87e52014-10-26 23:40:33 +00002975 return T;
Guy Benyei11169dd2012-12-18 14:30:41 +00002976
2977 // Otherwise create the type.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002978 llvm::DICompositeType *Res = CreateLimitedType(Ty);
David Blaikie8d5e1282013-08-20 21:03:29 +00002979
2980 // Propagate members from the declaration to the definition
2981 // CreateType(const RecordType*) will overwrite this with the members in the
2982 // correct order if the full type is needed.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002983 DBuilder.replaceArrays(Res, T ? T->getElements() : llvm::DINodeArray());
Guy Benyei11169dd2012-12-18 14:30:41 +00002984
Guy Benyei11169dd2012-12-18 14:30:41 +00002985 // And update the type cache.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002986 TypeCache[QTy.getAsOpaquePtr()].reset(Res);
Guy Benyei11169dd2012-12-18 14:30:41 +00002987 return Res;
2988}
2989
2990// TODO: Currently used for context chains when limiting debug info.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002991llvm::DICompositeType *CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002992 RecordDecl *RD = Ty->getDecl();
Eric Christopherb2a008c2013-05-16 00:45:12 +00002993
Guy Benyei11169dd2012-12-18 14:30:41 +00002994 // Get overall information about the record type for the debug info.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002995 llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00002996 unsigned Line = getLineNumber(RD->getLocation());
2997 StringRef RDName = getClassName(RD);
2998
Amjad Abouddc4531e2016-04-30 01:44:38 +00002999 llvm::DIScope *RDContext = getDeclContextDescriptor(RD);
Guy Benyei11169dd2012-12-18 14:30:41 +00003000
David Blaikied2785892013-08-18 17:36:19 +00003001 // If we ended up creating the type during the context chain construction,
3002 // just return that.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003003 auto *T = cast_or_null<llvm::DICompositeType>(
Duncan P. N. Exon Smithc7551282015-04-06 23:21:33 +00003004 getTypeOrNull(CGM.getContext().getRecordType(RD)));
Duncan P. N. Exon Smith4caa7f22015-04-16 01:00:56 +00003005 if (T && (!T->isForwardDecl() || !RD->getDefinition()))
Eric Christophere7b87e52014-10-26 23:40:33 +00003006 return T;
David Blaikied2785892013-08-18 17:36:19 +00003007
Adrian Prantl381e7552014-02-04 21:29:50 +00003008 // If this is just a forward or incomplete declaration, construct an
3009 // appropriately marked node and just return it.
3010 const RecordDecl *D = RD->getDefinition();
3011 if (!D || !D->isCompleteDefinition())
Manman Ren1b457022013-08-28 21:20:28 +00003012 return getOrCreateRecordFwdDecl(Ty, RDContext);
Guy Benyei11169dd2012-12-18 14:30:41 +00003013
3014 uint64_t Size = CGM.getContext().getTypeSize(Ty);
Victor Leschuka7ece032016-10-20 00:13:19 +00003015 auto Align = getDeclAlignIfRequired(D, CGM.getContext());
Eric Christopherb2a008c2013-05-16 00:45:12 +00003016
Brock Wyma8557ec52018-05-22 12:41:19 +00003017 SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
Manman Rene0064d82013-08-29 23:19:58 +00003018
Adrian Prantl6c5f03a2018-01-05 01:13:52 +00003019 // Explicitly record the calling convention for C++ records.
3020 auto Flags = llvm::DINode::FlagZero;
3021 if (auto CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3022 if (CGM.getCXXABI().getRecordArgABI(CXXRD) == CGCXXABI::RAA_Indirect)
3023 Flags |= llvm::DINode::FlagTypePassByReference;
3024 else
3025 Flags |= llvm::DINode::FlagTypePassByValue;
Aaron Smith044326c2018-07-23 20:49:07 +00003026
3027 // Record if a C++ record is trivial type.
3028 if (CXXRD->isTrivial())
3029 Flags |= llvm::DINode::FlagTrivial;
Adrian Prantl6c5f03a2018-01-05 01:13:52 +00003030 }
3031
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003032 llvm::DICompositeType *RealDecl = DBuilder.createReplaceableCompositeType(
Leny Kholodov80c047d2016-09-06 10:48:04 +00003033 getTagForRecord(RD), RDName, RDContext, DefUnit, Line, 0, Size, Align,
Brock Wyma8557ec52018-05-22 12:41:19 +00003034 Flags, Identifier);
Guy Benyei11169dd2012-12-18 14:30:41 +00003035
Duncan P. N. Exon Smithf9521b02016-04-17 07:45:08 +00003036 // Elements of composite types usually have back to the type, creating
3037 // uniquing cycles. Distinct nodes are more efficient.
3038 switch (RealDecl->getTag()) {
3039 default:
3040 llvm_unreachable("invalid composite type tag");
3041
3042 case llvm::dwarf::DW_TAG_array_type:
3043 case llvm::dwarf::DW_TAG_enumeration_type:
3044 // Array elements and most enumeration elements don't have back references,
3045 // so they don't tend to be involved in uniquing cycles and there is some
3046 // chance of merging them when linking together two modules. Only make
3047 // them distinct if they are ODR-uniqued.
Brock Wyma8557ec52018-05-22 12:41:19 +00003048 if (Identifier.empty())
Duncan P. N. Exon Smithf9521b02016-04-17 07:45:08 +00003049 break;
Galina Kistanova0872d6c2017-06-03 06:30:46 +00003050 LLVM_FALLTHROUGH;
Duncan P. N. Exon Smithf9521b02016-04-17 07:45:08 +00003051
3052 case llvm::dwarf::DW_TAG_structure_type:
3053 case llvm::dwarf::DW_TAG_union_type:
3054 case llvm::dwarf::DW_TAG_class_type:
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00003055 // Immediately resolve to a distinct node.
Duncan P. N. Exon Smithf9521b02016-04-17 07:45:08 +00003056 RealDecl =
3057 llvm::MDNode::replaceWithDistinct(llvm::TempDICompositeType(RealDecl));
3058 break;
3059 }
3060
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003061 RegionMap[Ty->getDecl()].reset(RealDecl);
3062 TypeCache[QualType(Ty, 0).getAsOpaquePtr()].reset(RealDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00003063
David Majnemer58ed0f32016-07-17 00:39:12 +00003064 if (const auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD))
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003065 DBuilder.replaceArrays(RealDecl, llvm::DINodeArray(),
Duncan P. N. Exon Smithc8ee63e2014-12-18 00:48:56 +00003066 CollectCXXTemplateParams(TSpecial, DefUnit));
David Blaikie952dac32013-08-15 22:42:12 +00003067 return RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00003068}
3069
David Blaikieadfbf992013-08-18 16:55:33 +00003070void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD,
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003071 llvm::DICompositeType *RealDecl) {
David Blaikieadfbf992013-08-18 16:55:33 +00003072 // A class's primary base or the class itself contains the vtable.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003073 llvm::DICompositeType *ContainingType = nullptr;
David Blaikieadfbf992013-08-18 16:55:33 +00003074 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
3075 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
Alp Tokerd4733632013-12-05 04:47:09 +00003076 // Seek non-virtual primary base root.
David Blaikieadfbf992013-08-18 16:55:33 +00003077 while (1) {
3078 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
3079 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
3080 if (PBT && !BRL.isPrimaryBaseVirtual())
3081 PBase = PBT;
3082 else
3083 break;
3084 }
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003085 ContainingType = cast<llvm::DICompositeType>(
David Blaikieadfbf992013-08-18 16:55:33 +00003086 getOrCreateType(QualType(PBase->getTypeForDecl(), 0),
3087 getOrCreateFile(RD->getLocation())));
3088 } else if (RD->isDynamicClass())
3089 ContainingType = RealDecl;
3090
Duncan P. N. Exon Smithc8ee63e2014-12-18 00:48:56 +00003091 DBuilder.replaceVTableHolder(RealDecl, ContainingType);
David Blaikieadfbf992013-08-18 16:55:33 +00003092}
3093
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003094llvm::DIType *CGDebugInfo::CreateMemberType(llvm::DIFile *Unit, QualType FType,
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00003095 StringRef Name, uint64_t *Offset) {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003096 llvm::DIType *FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00003097 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
Victor Leschuka7ece032016-10-20 00:13:19 +00003098 auto FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext());
Leny Kholodovdf050fd2016-09-06 17:06:14 +00003099 llvm::DIType *Ty =
3100 DBuilder.createMemberType(Unit, Name, Unit, 0, FieldSize, FieldAlign,
3101 *Offset, llvm::DINode::FlagZero, FieldTy);
Guy Benyei11169dd2012-12-18 14:30:41 +00003102 *Offset += FieldSize;
3103 return Ty;
3104}
3105
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003106void CGDebugInfo::collectFunctionDeclProps(GlobalDecl GD, llvm::DIFile *Unit,
Duncan P. N. Exon Smith8e47da42015-04-21 20:07:29 +00003107 StringRef &Name,
3108 StringRef &LinkageName,
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003109 llvm::DIScope *&FDContext,
3110 llvm::DINodeArray &TParamsArray,
Leny Kholodov80c047d2016-09-06 10:48:04 +00003111 llvm::DINode::DIFlags &Flags) {
David Majnemer58ed0f32016-07-17 00:39:12 +00003112 const auto *FD = cast<FunctionDecl>(GD.getDecl());
Frederic Riss9db79f12014-11-18 03:40:46 +00003113 Name = getFunctionName(FD);
3114 // Use mangled name as linkage name for C/C++ functions.
3115 if (FD->hasPrototype()) {
3116 LinkageName = CGM.getMangledName(GD);
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003117 Flags |= llvm::DINode::FlagPrototyped;
Frederic Riss9db79f12014-11-18 03:40:46 +00003118 }
3119 // No need to replicate the linkage name if it isn't different from the
3120 // subprogram name, no need to have it at all unless coverage is enabled or
Dehao Chenb3a70de2017-01-19 00:44:21 +00003121 // debug is set to more than just line tables or extra debug info is needed.
Benjamin Kramer8c305922016-02-02 11:06:51 +00003122 if (LinkageName == Name || (!CGM.getCodeGenOpts().EmitGcovArcs &&
3123 !CGM.getCodeGenOpts().EmitGcovNotes &&
Dehao Chenb3a70de2017-01-19 00:44:21 +00003124 !CGM.getCodeGenOpts().DebugInfoForProfiling &&
Benjamin Kramer8c305922016-02-02 11:06:51 +00003125 DebugKind <= codegenoptions::DebugLineTablesOnly))
Frederic Riss9db79f12014-11-18 03:40:46 +00003126 LinkageName = StringRef();
3127
Benjamin Kramer8c305922016-02-02 11:06:51 +00003128 if (DebugKind >= codegenoptions::LimitedDebugInfo) {
Frederic Riss9db79f12014-11-18 03:40:46 +00003129 if (const NamespaceDecl *NSDecl =
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00003130 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
Adrian Prantlddb8e062017-05-12 16:23:53 +00003131 FDContext = getOrCreateNamespace(NSDecl);
Frederic Riss9db79f12014-11-18 03:40:46 +00003132 else if (const RecordDecl *RDecl =
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00003133 dyn_cast_or_null<RecordDecl>(FD->getDeclContext())) {
Adrian Prantl5c8bd882015-09-11 17:23:08 +00003134 llvm::DIScope *Mod = getParentModuleOrNull(RDecl);
3135 FDContext = getContextDescriptor(RDecl, Mod ? Mod : TheCU);
3136 }
Adrian Prantlfd5ac8a2016-08-17 16:20:32 +00003137 // Check if it is a noreturn-marked function
3138 if (FD->isNoReturn())
3139 Flags |= llvm::DINode::FlagNoReturn;
Frederic Riss9db79f12014-11-18 03:40:46 +00003140 // Collect template parameters.
3141 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
3142 }
3143}
3144
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003145void CGDebugInfo::collectVarDeclProps(const VarDecl *VD, llvm::DIFile *&Unit,
Frederic Riss9db79f12014-11-18 03:40:46 +00003146 unsigned &LineNo, QualType &T,
3147 StringRef &Name, StringRef &LinkageName,
Matthew Voss20165362018-10-03 18:45:04 +00003148 llvm::MDTuple *&TemplateParameters,
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003149 llvm::DIScope *&VDContext) {
Frederic Riss9db79f12014-11-18 03:40:46 +00003150 Unit = getOrCreateFile(VD->getLocation());
3151 LineNo = getLineNumber(VD->getLocation());
3152
3153 setLocation(VD->getLocation());
3154
3155 T = VD->getType();
3156 if (T->isIncompleteArrayType()) {
3157 // CodeGen turns int[] into int[1] so we'll do the same here.
3158 llvm::APInt ConstVal(32, 1);
3159 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3160
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00003161 T = CGM.getContext().getConstantArrayType(ET, ConstVal, ArrayType::Normal,
3162 0);
Frederic Riss9db79f12014-11-18 03:40:46 +00003163 }
3164
3165 Name = VD->getName();
3166 if (VD->getDeclContext() && !isa<FunctionDecl>(VD->getDeclContext()) &&
3167 !isa<ObjCMethodDecl>(VD->getDeclContext()))
3168 LinkageName = CGM.getMangledName(VD);
3169 if (LinkageName == Name)
3170 LinkageName = StringRef();
3171
Matthew Voss20165362018-10-03 18:45:04 +00003172 if (isa<VarTemplateSpecializationDecl>(VD)) {
3173 llvm::DINodeArray parameterNodes = CollectVarTemplateParams(VD, &*Unit);
3174 TemplateParameters = parameterNodes.get();
3175 } else {
3176 TemplateParameters = nullptr;
3177 }
3178
Frederic Riss9db79f12014-11-18 03:40:46 +00003179 // Since we emit declarations (DW_AT_members) for static members, place the
3180 // definition of those static members in the namespace they were declared in
3181 // in the source code (the lexical decl context).
3182 // FIXME: Generalize this for even non-member global variables where the
3183 // declaration and definition may have different lexical decl contexts, once
3184 // we have support for emitting declarations of (non-member) global variables.
Saleem Abdulrasoolcd187f02015-02-28 00:13:13 +00003185 const DeclContext *DC = VD->isStaticDataMember() ? VD->getLexicalDeclContext()
3186 : VD->getDeclContext();
3187 // When a record type contains an in-line initialization of a static data
3188 // member, and the record type is marked as __declspec(dllexport), an implicit
3189 // definition of the member will be created in the record context. DWARF
3190 // doesn't seem to have a nice way to describe this in a form that consumers
3191 // are likely to understand, so fake the "normal" situation of a definition
3192 // outside the class by putting it in the global scope.
3193 if (DC->isRecord())
3194 DC = CGM.getContext().getTranslationUnitDecl();
Adrian Prantl5c8bd882015-09-11 17:23:08 +00003195
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00003196 llvm::DIScope *Mod = getParentModuleOrNull(VD);
3197 VDContext = getContextDescriptor(cast<Decl>(DC), Mod ? Mod : TheCU);
Frederic Riss9db79f12014-11-18 03:40:46 +00003198}
3199
Adrian Prantlb7acfc02017-02-27 21:30:05 +00003200llvm::DISubprogram *CGDebugInfo::getFunctionFwdDeclOrStub(GlobalDecl GD,
3201 bool Stub) {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003202 llvm::DINodeArray TParamsArray;
Frederic Rissd253ed62014-11-18 03:40:51 +00003203 StringRef Name, LinkageName;
Leny Kholodov80c047d2016-09-06 10:48:04 +00003204 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
Paul Robinsoncda54212018-11-19 18:29:28 +00003205 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
Adrian Prantlb7acfc02017-02-27 21:30:05 +00003206 SourceLocation Loc = GD.getDecl()->getLocation();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003207 llvm::DIFile *Unit = getOrCreateFile(Loc);
3208 llvm::DIScope *DContext = Unit;
Frederic Rissd253ed62014-11-18 03:40:51 +00003209 unsigned Line = getLineNumber(Loc);
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00003210 collectFunctionDeclProps(GD, Unit, Name, LinkageName, DContext, TParamsArray,
3211 Flags);
Adrian Prantlb7acfc02017-02-27 21:30:05 +00003212 auto *FD = dyn_cast<FunctionDecl>(GD.getDecl());
3213
Frederic Rissd253ed62014-11-18 03:40:51 +00003214 // Build function type.
3215 SmallVector<QualType, 16> ArgTypes;
Adrian Prantlb7acfc02017-02-27 21:30:05 +00003216 if (FD)
3217 for (const ParmVarDecl *Parm : FD->parameters())
3218 ArgTypes.push_back(Parm->getType());
Reid Klecknerf00f8032016-06-08 20:41:54 +00003219 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
3220 QualType FnType = CGM.getContext().getFunctionType(
3221 FD->getReturnType(), ArgTypes, FunctionProtoType::ExtProtoInfo(CC));
Paul Robinsoncda54212018-11-19 18:29:28 +00003222 if (!FD->isExternallyVisible())
3223 SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;
3224 if (CGM.getLangOpts().Optimize)
3225 SPFlags |= llvm::DISubprogram::SPFlagOptimized;
3226
Adrian Prantlb7acfc02017-02-27 21:30:05 +00003227 if (Stub) {
Vedant Kumar5931b4e2018-10-05 20:37:17 +00003228 Flags |= getCallSiteRelatedAttrs();
Paul Robinsoncda54212018-11-19 18:29:28 +00003229 SPFlags |= llvm::DISubprogram::SPFlagDefinition;
Adrian Prantlb7acfc02017-02-27 21:30:05 +00003230 return DBuilder.createFunction(
3231 DContext, Name, LinkageName, Unit, Line,
Paul Robinsoncda54212018-11-19 18:29:28 +00003232 getOrCreateFunctionType(GD.getDecl(), FnType, Unit), 0, Flags, SPFlags,
Adrian Prantlb7acfc02017-02-27 21:30:05 +00003233 TParamsArray.get(), getFunctionDeclaration(FD));
3234 }
3235
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003236 llvm::DISubprogram *SP = DBuilder.createTempFunctionFwdDecl(
Duncan P. N. Exon Smithebad0aa2015-04-07 16:50:49 +00003237 DContext, Name, LinkageName, Unit, Line,
Paul Robinsoncda54212018-11-19 18:29:28 +00003238 getOrCreateFunctionType(GD.getDecl(), FnType, Unit), 0, Flags, SPFlags,
Duncan P. N. Exon Smithebad0aa2015-04-07 16:50:49 +00003239 TParamsArray.get(), getFunctionDeclaration(FD));
George Burgess IV00f70bd2018-03-01 05:43:23 +00003240 const FunctionDecl *CanonDecl = FD->getCanonicalDecl();
Duncan P. N. Exon Smith4078ad42015-04-16 16:36:45 +00003241 FwdDeclReplaceMap.emplace_back(std::piecewise_construct,
3242 std::make_tuple(CanonDecl),
3243 std::make_tuple(SP));
Frederic Rissd253ed62014-11-18 03:40:51 +00003244 return SP;
3245}
3246
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00003247llvm::DISubprogram *CGDebugInfo::getFunctionForwardDeclaration(GlobalDecl GD) {
Adrian Prantlb7acfc02017-02-27 21:30:05 +00003248 return getFunctionFwdDeclOrStub(GD, /* Stub = */ false);
3249}
3250
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00003251llvm::DISubprogram *CGDebugInfo::getFunctionStub(GlobalDecl GD) {
Adrian Prantlb7acfc02017-02-27 21:30:05 +00003252 return getFunctionFwdDeclOrStub(GD, /* Stub = */ true);
3253}
3254
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003255llvm::DIGlobalVariable *
Frederic Rissd253ed62014-11-18 03:40:51 +00003256CGDebugInfo::getGlobalVariableForwardDeclaration(const VarDecl *VD) {
3257 QualType T;
3258 StringRef Name, LinkageName;
3259 SourceLocation Loc = VD->getLocation();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003260 llvm::DIFile *Unit = getOrCreateFile(Loc);
3261 llvm::DIScope *DContext = Unit;
Frederic Rissd253ed62014-11-18 03:40:51 +00003262 unsigned Line = getLineNumber(Loc);
Matthew Voss20165362018-10-03 18:45:04 +00003263 llvm::MDTuple *TemplateParameters = nullptr;
Frederic Rissd253ed62014-11-18 03:40:51 +00003264
Matthew Voss20165362018-10-03 18:45:04 +00003265 collectVarDeclProps(VD, Unit, Line, T, Name, LinkageName, TemplateParameters,
3266 DContext);
Victor Leschuka7ece032016-10-20 00:13:19 +00003267 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
Duncan P. N. Exon Smithdadc2b62015-04-21 18:43:54 +00003268 auto *GV = DBuilder.createTempGlobalVariableFwdDecl(
3269 DContext, Name, LinkageName, Unit, Line, getOrCreateType(T, Unit),
Matthew Voss20165362018-10-03 18:45:04 +00003270 !VD->isExternallyVisible(), nullptr, TemplateParameters, Align);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003271 FwdDeclReplaceMap.emplace_back(
3272 std::piecewise_construct,
3273 std::make_tuple(cast<VarDecl>(VD->getCanonicalDecl())),
3274 std::make_tuple(static_cast<llvm::Metadata *>(GV)));
Frederic Rissd253ed62014-11-18 03:40:51 +00003275 return GV;
3276}
3277
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003278llvm::DINode *CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
David Blaikiebd483762013-05-20 04:58:53 +00003279 // We only need a declaration (not a definition) of the type - so use whatever
3280 // we would otherwise do to get a type for a pointee. (forward declarations in
3281 // limited debug info, full definitions (if the type definition is available)
3282 // in unlimited debug info)
David Majnemer58ed0f32016-07-17 00:39:12 +00003283 if (const auto *TD = dyn_cast<TypeDecl>(D))
David Blaikie6b7d060c2013-08-12 23:14:36 +00003284 return getOrCreateType(CGM.getContext().getTypeDeclType(TD),
David Blaikie99dab3b2013-09-04 22:03:57 +00003285 getOrCreateFile(TD->getLocation()));
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003286 auto I = DeclCache.find(D->getCanonicalDecl());
Frederic Rissd253ed62014-11-18 03:40:51 +00003287
Adrian Prantl5f4740d2016-12-20 02:10:02 +00003288 if (I != DeclCache.end()) {
3289 auto N = I->second;
3290 if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(N))
3291 return GVE->getVariable();
3292 return dyn_cast_or_null<llvm::DINode>(N);
3293 }
Frederic Rissd253ed62014-11-18 03:40:51 +00003294
3295 // No definition for now. Emit a forward definition that might be
3296 // merged with a potential upcoming definition.
David Majnemer58ed0f32016-07-17 00:39:12 +00003297 if (const auto *FD = dyn_cast<FunctionDecl>(D))
Frederic Rissd253ed62014-11-18 03:40:51 +00003298 return getFunctionForwardDeclaration(FD);
3299 else if (const auto *VD = dyn_cast<VarDecl>(D))
3300 return getGlobalVariableForwardDeclaration(VD);
3301
Duncan P. N. Exon Smith4078ad42015-04-16 16:36:45 +00003302 return nullptr;
David Blaikiebd483762013-05-20 04:58:53 +00003303}
3304
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003305llvm::DISubprogram *CGDebugInfo::getFunctionDeclaration(const Decl *D) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00003306 if (!D || DebugKind <= codegenoptions::DebugLineTablesOnly)
Duncan P. N. Exon Smitha7fbcbf2015-04-20 22:09:57 +00003307 return nullptr;
David Blaikie18cfbc52013-06-22 00:09:36 +00003308
David Majnemer58ed0f32016-07-17 00:39:12 +00003309 const auto *FD = dyn_cast<FunctionDecl>(D);
Eric Christophere7b87e52014-10-26 23:40:33 +00003310 if (!FD)
Duncan P. N. Exon Smitha7fbcbf2015-04-20 22:09:57 +00003311 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003312
3313 // Setup context.
Adrian Prantl6ec370a2015-09-10 18:39:45 +00003314 auto *S = getDeclContextDescriptor(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00003315
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003316 auto MI = SPCache.find(FD->getCanonicalDecl());
David Blaikiefd07c602013-08-09 17:20:05 +00003317 if (MI == SPCache.end()) {
David Majnemer58ed0f32016-07-17 00:39:12 +00003318 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {
Duncan P. N. Exon Smithc09c5482015-04-20 21:17:26 +00003319 return CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()),
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003320 cast<llvm::DICompositeType>(S));
David Blaikiefd07c602013-08-09 17:20:05 +00003321 }
3322 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003323 if (MI != SPCache.end()) {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003324 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
Duncan P. N. Exon Smith87afdeb2015-04-14 03:24:14 +00003325 if (SP && !SP->isDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00003326 return SP;
3327 }
3328
Aaron Ballman86c93902014-03-06 23:45:36 +00003329 for (auto NextFD : FD->redecls()) {
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003330 auto MI = SPCache.find(NextFD->getCanonicalDecl());
Guy Benyei11169dd2012-12-18 14:30:41 +00003331 if (MI != SPCache.end()) {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003332 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
Duncan P. N. Exon Smith87afdeb2015-04-14 03:24:14 +00003333 if (SP && !SP->isDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00003334 return SP;
3335 }
3336 }
Duncan P. N. Exon Smitha7fbcbf2015-04-20 22:09:57 +00003337 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003338}
3339
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00003340// getOrCreateFunctionType - Construct type. If it is a c++ method, include
Guy Benyei11169dd2012-12-18 14:30:41 +00003341// implicit parameter "this".
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003342llvm::DISubroutineType *CGDebugInfo::getOrCreateFunctionType(const Decl *D,
Duncan P. N. Exon Smith4078ad42015-04-16 16:36:45 +00003343 QualType FnType,
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003344 llvm::DIFile *F) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00003345 if (!D || DebugKind <= codegenoptions::DebugLineTablesOnly)
Duncan P. N. Exon Smitha7fbcbf2015-04-20 22:09:57 +00003346 // Create fake but valid subroutine type. Otherwise -verify would fail, and
3347 // subprogram DIE will miss DW_AT_decl_file and DW_AT_decl_line fields.
Eric Christopher28a6db52015-10-15 06:56:08 +00003348 return DBuilder.createSubroutineType(DBuilder.getOrCreateTypeArray(None));
Guy Benyei11169dd2012-12-18 14:30:41 +00003349
David Majnemer58ed0f32016-07-17 00:39:12 +00003350 if (const auto *Method = dyn_cast<CXXMethodDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00003351 return getOrCreateMethodType(Method, F);
Reid Klecknerf00f8032016-06-08 20:41:54 +00003352
3353 const auto *FTy = FnType->getAs<FunctionType>();
3354 CallingConv CC = FTy ? FTy->getCallConv() : CallingConv::CC_C;
3355
David Majnemer58ed0f32016-07-17 00:39:12 +00003356 if (const auto *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003357 // Add "self" and "_cmd"
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003358 SmallVector<llvm::Metadata *, 16> Elts;
Guy Benyei11169dd2012-12-18 14:30:41 +00003359
3360 // First element is always return type. For 'void' functions it is NULL.
Alp Toker314cc812014-01-25 16:55:45 +00003361 QualType ResultTy = OMethod->getReturnType();
Adrian Prantl5f360102013-05-22 21:37:49 +00003362
3363 // Replace the instancetype keyword with the actual type.
3364 if (ResultTy == CGM.getContext().getObjCInstanceType())
3365 ResultTy = CGM.getContext().getPointerType(
Eric Christophere7b87e52014-10-26 23:40:33 +00003366 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
Adrian Prantl5f360102013-05-22 21:37:49 +00003367
Adrian Prantl7bec9032013-05-10 21:08:31 +00003368 Elts.push_back(getOrCreateType(ResultTy, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00003369 // "self" pointer is always first argument.
Adrian Prantl748a6cd2015-09-08 20:41:52 +00003370 QualType SelfDeclTy;
3371 if (auto *SelfDecl = OMethod->getSelfDecl())
3372 SelfDeclTy = SelfDecl->getType();
3373 else if (auto *FPT = dyn_cast<FunctionProtoType>(FnType))
3374 if (FPT->getNumParams() > 1)
3375 SelfDeclTy = FPT->getParamType(0);
3376 if (!SelfDeclTy.isNull())
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00003377 Elts.push_back(
3378 CreateSelfType(SelfDeclTy, getOrCreateType(SelfDeclTy, F)));
Guy Benyei11169dd2012-12-18 14:30:41 +00003379 // "_cmd" pointer is always second argument.
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00003380 Elts.push_back(DBuilder.createArtificialType(
Adrian Prantl748a6cd2015-09-08 20:41:52 +00003381 getOrCreateType(CGM.getContext().getObjCSelType(), F)));
Guy Benyei11169dd2012-12-18 14:30:41 +00003382 // Get rest of the arguments.
David Majnemer59f77922016-06-24 04:05:48 +00003383 for (const auto *PI : OMethod->parameters())
Aaron Ballman43b68be2014-03-07 17:50:17 +00003384 Elts.push_back(getOrCreateType(PI->getType(), F));
Frederic Riss787d9d62014-08-12 04:42:23 +00003385 // Variadic methods need a special marker at the end of the type list.
3386 if (OMethod->isVariadic())
3387 Elts.push_back(DBuilder.createUnspecifiedParameter());
Guy Benyei11169dd2012-12-18 14:30:41 +00003388
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003389 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
Leny Kholodov80c047d2016-09-06 10:48:04 +00003390 return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
3391 getDwarfCC(CC));
Guy Benyei11169dd2012-12-18 14:30:41 +00003392 }
Adrian Prantld45ba252014-02-25 19:38:11 +00003393
Adrian Prantl800faef2014-02-25 23:42:18 +00003394 // Handle variadic function types; they need an additional
3395 // unspecified parameter.
David Majnemer58ed0f32016-07-17 00:39:12 +00003396 if (const auto *FD = dyn_cast<FunctionDecl>(D))
Adrian Prantld45ba252014-02-25 19:38:11 +00003397 if (FD->isVariadic()) {
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003398 SmallVector<llvm::Metadata *, 16> EltTys;
Adrian Prantld45ba252014-02-25 19:38:11 +00003399 EltTys.push_back(getOrCreateType(FD->getReturnType(), F));
David Majnemer58ed0f32016-07-17 00:39:12 +00003400 if (const auto *FPT = dyn_cast<FunctionProtoType>(FnType))
3401 for (QualType ParamType : FPT->param_types())
3402 EltTys.push_back(getOrCreateType(ParamType, F));
Adrian Prantld45ba252014-02-25 19:38:11 +00003403 EltTys.push_back(DBuilder.createUnspecifiedParameter());
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003404 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
Leny Kholodov80c047d2016-09-06 10:48:04 +00003405 return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
3406 getDwarfCC(CC));
Adrian Prantld45ba252014-02-25 19:38:11 +00003407 }
3408
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003409 return cast<llvm::DISubroutineType>(getOrCreateType(FnType, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00003410}
3411
Eric Christophere7b87e52014-10-26 23:40:33 +00003412void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, SourceLocation Loc,
3413 SourceLocation ScopeLoc, QualType FnType,
Brock Wyma94ece8f2018-04-16 16:53:57 +00003414 llvm::Function *Fn, bool CurFuncIsThunk,
3415 CGBuilderTy &Builder) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003416
3417 StringRef Name;
3418 StringRef LinkageName;
3419
3420 FnBeginRegionCount.push_back(LexicalBlockStack.size());
3421
3422 const Decl *D = GD.getDecl();
Craig Topper8a13c412014-05-21 05:09:00 +00003423 bool HasDecl = (D != nullptr);
Eric Christopher885c41b2014-04-01 22:25:28 +00003424
Leny Kholodov80c047d2016-09-06 10:48:04 +00003425 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
Paul Robinsoncda54212018-11-19 18:29:28 +00003426 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003427 llvm::DIFile *Unit = getOrCreateFile(Loc);
3428 llvm::DIScope *FDContext = Unit;
3429 llvm::DINodeArray TParamsArray;
Guy Benyei11169dd2012-12-18 14:30:41 +00003430 if (!HasDecl) {
3431 // Use llvm function name.
David Blaikieebe87e12013-08-27 23:57:18 +00003432 LinkageName = Fn->getName();
David Majnemer58ed0f32016-07-17 00:39:12 +00003433 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Duncan P. N. Exon Smitha7fbcbf2015-04-20 22:09:57 +00003434 // If there is a subprogram for this function available then use it.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003435 auto FI = SPCache.find(FD->getCanonicalDecl());
Guy Benyei11169dd2012-12-18 14:30:41 +00003436 if (FI != SPCache.end()) {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003437 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
Duncan P. N. Exon Smith87afdeb2015-04-14 03:24:14 +00003438 if (SP && SP->isDefinition()) {
Duncan P. N. Exon Smithd899f6e2015-04-18 00:07:30 +00003439 LexicalBlockStack.emplace_back(SP);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003440 RegionMap[D].reset(SP);
Guy Benyei11169dd2012-12-18 14:30:41 +00003441 return;
3442 }
3443 }
Frederic Riss9db79f12014-11-18 03:40:46 +00003444 collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
3445 TParamsArray, Flags);
David Majnemer58ed0f32016-07-17 00:39:12 +00003446 } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003447 Name = getObjCMethodName(OMD);
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003448 Flags |= llvm::DINode::FlagPrototyped;
Guy Benyei11169dd2012-12-18 14:30:41 +00003449 } else {
3450 // Use llvm function name.
3451 Name = Fn->getName();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003452 Flags |= llvm::DINode::FlagPrototyped;
Guy Benyei11169dd2012-12-18 14:30:41 +00003453 }
David Majnemer58ed0f32016-07-17 00:39:12 +00003454 if (Name.startswith("\01"))
Guy Benyei11169dd2012-12-18 14:30:41 +00003455 Name = Name.substr(1);
3456
Erich Keane293a0552018-02-14 00:14:07 +00003457 if (!HasDecl || D->isImplicit() || D->hasAttr<ArtificialAttr>()) {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003458 Flags |= llvm::DINode::FlagArtificial;
Adrian Prantldb763572016-11-09 21:43:51 +00003459 // Artificial functions should not silently reuse CurLoc.
3460 CurLoc = SourceLocation();
Adrian Prantl42d71b92014-04-10 23:21:53 +00003461 }
Brock Wyma94ece8f2018-04-16 16:53:57 +00003462
3463 if (CurFuncIsThunk)
3464 Flags |= llvm::DINode::FlagThunk;
3465
Paul Robinsoncda54212018-11-19 18:29:28 +00003466 if (Fn->hasLocalLinkage())
3467 SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;
3468 if (CGM.getLangOpts().Optimize)
3469 SPFlags |= llvm::DISubprogram::SPFlagOptimized;
3470
Vedant Kumar5931b4e2018-10-05 20:37:17 +00003471 llvm::DINode::DIFlags FlagsForDef = Flags | getCallSiteRelatedAttrs();
Paul Robinsoncda54212018-11-19 18:29:28 +00003472 llvm::DISubprogram::DISPFlags SPFlagsForDef =
3473 SPFlags | llvm::DISubprogram::SPFlagDefinition;
Vedant Kumar5931b4e2018-10-05 20:37:17 +00003474
Adrian Prantl42d71b92014-04-10 23:21:53 +00003475 unsigned LineNo = getLineNumber(Loc);
3476 unsigned ScopeLine = getLineNumber(ScopeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00003477
Eric Christopher8018e412014-03-27 18:50:35 +00003478 // FIXME: The function declaration we're constructing here is mostly reusing
3479 // declarations from CXXMethodDecl and not constructing new ones for arbitrary
3480 // FunctionDecls. When/if we fix this we can have FDContext be TheCU/null for
3481 // all subprograms instead of the actual context since subprogram definitions
3482 // are emitted as CU level entities by the backend.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003483 llvm::DISubprogram *SP = DBuilder.createFunction(
Eric Christophere7b87e52014-10-26 23:40:33 +00003484 FDContext, Name, LinkageName, Unit, LineNo,
Paul Robinsoncda54212018-11-19 18:29:28 +00003485 getOrCreateFunctionType(D, FnType, Unit), ScopeLine, FlagsForDef,
3486 SPFlagsForDef, TParamsArray.get(), getFunctionDeclaration(D));
Peter Collingbourne0900fe02015-11-05 22:04:14 +00003487 Fn->setSubprogram(SP);
Frederic Rissb1ab28c2014-11-05 19:19:04 +00003488 // We might get here with a VarDecl in the case we're generating
3489 // code for the initialization of globals. Do not record these decls
3490 // as they will overwrite the actual VarDecl Decl in the cache.
3491 if (HasDecl && isa<FunctionDecl>(D))
David Majnemer58ed0f32016-07-17 00:39:12 +00003492 DeclCache[D->getCanonicalDecl()].reset(SP);
Guy Benyei11169dd2012-12-18 14:30:41 +00003493
Jonas Devlieghered8ba8ae2018-06-27 17:31:59 +00003494 if (CGM.getCodeGenOpts().DwarfVersion >= 5) {
3495 // Starting with DWARF V5 method declarations are emitted as children of
3496 // the interface type.
3497 if (const auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(D)) {
3498 const ObjCInterfaceDecl *ID = OMD->getClassInterface();
3499 QualType QTy(ID->getTypeForDecl(), 0);
3500 auto It = TypeCache.find(QTy.getAsOpaquePtr());
3501 if (It != TypeCache.end()) {
3502 llvm::DICompositeType *InterfaceDecl =
3503 cast<llvm::DICompositeType>(It->second);
3504 llvm::DISubprogram *FD = DBuilder.createFunction(
3505 InterfaceDecl, Name, LinkageName, Unit, LineNo,
Paul Robinsoncda54212018-11-19 18:29:28 +00003506 getOrCreateFunctionType(D, FnType, Unit), ScopeLine, Flags, SPFlags,
Jonas Devlieghered8ba8ae2018-06-27 17:31:59 +00003507 TParamsArray.get());
3508 DBuilder.finalizeSubprogram(FD);
3509 ObjCMethodCache[ID].push_back(FD);
3510 }
3511 }
3512 }
3513
Adrian Prantlbebb8932014-03-21 21:01:58 +00003514 // Push the function onto the lexical block stack.
Duncan P. N. Exon Smithd899f6e2015-04-18 00:07:30 +00003515 LexicalBlockStack.emplace_back(SP);
Adrian Prantlbebb8932014-03-21 21:01:58 +00003516
Guy Benyei11169dd2012-12-18 14:30:41 +00003517 if (HasDecl)
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003518 RegionMap[D].reset(SP);
Guy Benyei11169dd2012-12-18 14:30:41 +00003519}
3520
Adrian Prantl748a6cd2015-09-08 20:41:52 +00003521void CGDebugInfo::EmitFunctionDecl(GlobalDecl GD, SourceLocation Loc,
3522 QualType FnType) {
3523 StringRef Name;
3524 StringRef LinkageName;
3525
3526 const Decl *D = GD.getDecl();
3527 if (!D)
3528 return;
3529
Leny Kholodov80c047d2016-09-06 10:48:04 +00003530 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
Adrian Prantl748a6cd2015-09-08 20:41:52 +00003531 llvm::DIFile *Unit = getOrCreateFile(Loc);
Adrian Prantlf0cd6772015-10-04 23:23:04 +00003532 llvm::DIScope *FDContext = getDeclContextDescriptor(D);
Adrian Prantl748a6cd2015-09-08 20:41:52 +00003533 llvm::DINodeArray TParamsArray;
3534 if (isa<FunctionDecl>(D)) {
3535 // If there is a DISubprogram for this function available then use it.
3536 collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
3537 TParamsArray, Flags);
David Majnemer58ed0f32016-07-17 00:39:12 +00003538 } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) {
Adrian Prantl748a6cd2015-09-08 20:41:52 +00003539 Name = getObjCMethodName(OMD);
3540 Flags |= llvm::DINode::FlagPrototyped;
3541 } else {
3542 llvm_unreachable("not a function or ObjC method");
3543 }
3544 if (!Name.empty() && Name[0] == '\01')
3545 Name = Name.substr(1);
3546
3547 if (D->isImplicit()) {
3548 Flags |= llvm::DINode::FlagArtificial;
3549 // Artificial functions without a location should not silently reuse CurLoc.
3550 if (Loc.isInvalid())
3551 CurLoc = SourceLocation();
3552 }
3553 unsigned LineNo = getLineNumber(Loc);
3554 unsigned ScopeLine = 0;
Paul Robinsoncda54212018-11-19 18:29:28 +00003555 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
3556 if (CGM.getLangOpts().Optimize)
3557 SPFlags |= llvm::DISubprogram::SPFlagOptimized;
Adrian Prantl748a6cd2015-09-08 20:41:52 +00003558
Adrian Prantle76bda52016-04-15 15:55:45 +00003559 DBuilder.retainType(DBuilder.createFunction(
3560 FDContext, Name, LinkageName, Unit, LineNo,
Paul Robinsoncda54212018-11-19 18:29:28 +00003561 getOrCreateFunctionType(D, FnType, Unit), ScopeLine, Flags, SPFlags,
Adrian Prantle76bda52016-04-15 15:55:45 +00003562 TParamsArray.get(), getFunctionDeclaration(D)));
Adrian Prantl748a6cd2015-09-08 20:41:52 +00003563}
3564
Adrian Prantlb7acfc02017-02-27 21:30:05 +00003565void CGDebugInfo::EmitInlineFunctionStart(CGBuilderTy &Builder, GlobalDecl GD) {
3566 const auto *FD = cast<FunctionDecl>(GD.getDecl());
3567 // If there is a subprogram for this function available then use it.
3568 auto FI = SPCache.find(FD->getCanonicalDecl());
3569 llvm::DISubprogram *SP = nullptr;
3570 if (FI != SPCache.end())
3571 SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
Adrian Prantl8040a212017-08-23 21:24:12 +00003572 if (!SP || !SP->isDefinition())
Adrian Prantlb7acfc02017-02-27 21:30:05 +00003573 SP = getFunctionStub(GD);
3574 FnBeginRegionCount.push_back(LexicalBlockStack.size());
3575 LexicalBlockStack.emplace_back(SP);
3576 setInlinedAt(Builder.getCurrentDebugLocation());
3577 EmitLocation(Builder, FD->getLocation());
3578}
3579
3580void CGDebugInfo::EmitInlineFunctionEnd(CGBuilderTy &Builder) {
3581 assert(CurInlinedAt && "unbalanced inline scope stack");
Keno Fischer41d4b4e2017-06-01 21:14:03 +00003582 EmitFunctionEnd(Builder, nullptr);
Adrian Prantlb7acfc02017-02-27 21:30:05 +00003583 setInlinedAt(llvm::DebugLoc(CurInlinedAt).getInlinedAt());
3584}
3585
Calixte Denizetfcd661d2018-09-24 18:24:18 +00003586void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003587 // Update our current location
3588 setLocation(Loc);
3589
Adrian Prantl42ab39f2018-11-09 21:17:38 +00003590 if (CurLoc.isInvalid() || CurLoc.isMacroID() || LexicalBlockStack.empty())
Eric Christophere7b87e52014-10-26 23:40:33 +00003591 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00003592
Adrian Prantle83b1302014-01-07 22:05:52 +00003593 llvm::MDNode *Scope = LexicalBlockStack.back();
Calixte Denizetfcd661d2018-09-24 18:24:18 +00003594 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(
3595 getLineNumber(CurLoc), getColumnNumber(CurLoc), Scope, CurInlinedAt));
Guy Benyei11169dd2012-12-18 14:30:41 +00003596}
3597
Guy Benyei11169dd2012-12-18 14:30:41 +00003598void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
Duncan P. N. Exon Smitha66e3052014-12-09 19:22:40 +00003599 llvm::MDNode *Back = nullptr;
3600 if (!LexicalBlockStack.empty())
3601 Back = LexicalBlockStack.back().get();
Duncan P. N. Exon Smithd899f6e2015-04-18 00:07:30 +00003602 LexicalBlockStack.emplace_back(DBuilder.createLexicalBlock(
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003603 cast<llvm::DIScope>(Back), getOrCreateFile(CurLoc), getLineNumber(CurLoc),
Duncan P. N. Exon Smithd899f6e2015-04-18 00:07:30 +00003604 getColumnNumber(CurLoc)));
Guy Benyei11169dd2012-12-18 14:30:41 +00003605}
3606
Konstantin Zhuravlyov2b4917f2017-03-09 18:06:23 +00003607void CGDebugInfo::AppendAddressSpaceXDeref(
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00003608 unsigned AddressSpace, SmallVectorImpl<int64_t> &Expr) const {
Konstantin Zhuravlyov2b4917f2017-03-09 18:06:23 +00003609 Optional<unsigned> DWARFAddressSpace =
3610 CGM.getTarget().getDWARFAddressSpace(AddressSpace);
3611 if (!DWARFAddressSpace)
3612 return;
3613
3614 Expr.push_back(llvm::dwarf::DW_OP_constu);
3615 Expr.push_back(DWARFAddressSpace.getValue());
3616 Expr.push_back(llvm::dwarf::DW_OP_swap);
3617 Expr.push_back(llvm::dwarf::DW_OP_xderef);
3618}
3619
Eric Christopher0fdcb312013-05-16 00:52:20 +00003620void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
3621 SourceLocation Loc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003622 // Set our current location.
3623 setLocation(Loc);
3624
Guy Benyei11169dd2012-12-18 14:30:41 +00003625 // Emit a line table change for the current location inside the new scope.
Adrian Prantlb7acfc02017-02-27 21:30:05 +00003626 Builder.SetCurrentDebugLocation(
3627 llvm::DebugLoc::get(getLineNumber(Loc), getColumnNumber(Loc),
3628 LexicalBlockStack.back(), CurInlinedAt));
David Blaikie60a877b2014-10-22 19:34:33 +00003629
Benjamin Kramer8c305922016-02-02 11:06:51 +00003630 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
David Blaikie60a877b2014-10-22 19:34:33 +00003631 return;
3632
3633 // Create a new lexical block and push it on the stack.
3634 CreateLexicalBlock(Loc);
Guy Benyei11169dd2012-12-18 14:30:41 +00003635}
3636
Eric Christopher0fdcb312013-05-16 00:52:20 +00003637void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
3638 SourceLocation Loc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003639 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
3640
3641 // Provide an entry in the line table for the end of the block.
Calixte Denizetfcd661d2018-09-24 18:24:18 +00003642 EmitLocation(Builder, Loc);
Guy Benyei11169dd2012-12-18 14:30:41 +00003643
Benjamin Kramer8c305922016-02-02 11:06:51 +00003644 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
David Blaikie60a877b2014-10-22 19:34:33 +00003645 return;
3646
Guy Benyei11169dd2012-12-18 14:30:41 +00003647 LexicalBlockStack.pop_back();
3648}
3649
Keno Fischer41d4b4e2017-06-01 21:14:03 +00003650void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder, llvm::Function *Fn) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003651 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
3652 unsigned RCount = FnBeginRegionCount.back();
3653 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
3654
3655 // Pop all regions for this function.
David Blaikie60a877b2014-10-22 19:34:33 +00003656 while (LexicalBlockStack.size() != RCount) {
3657 // Provide an entry in the line table for the end of the block.
Calixte Denizetfcd661d2018-09-24 18:24:18 +00003658 EmitLocation(Builder, CurLoc);
David Blaikie60a877b2014-10-22 19:34:33 +00003659 LexicalBlockStack.pop_back();
3660 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003661 FnBeginRegionCount.pop_back();
Keno Fischer41d4b4e2017-06-01 21:14:03 +00003662
3663 if (Fn && Fn->getSubprogram())
3664 DBuilder.finalizeSubprogram(Fn->getSubprogram());
Guy Benyei11169dd2012-12-18 14:30:41 +00003665}
3666
Adrian Prantl05a623e2018-09-10 16:14:28 +00003667CGDebugInfo::BlockByRefType
3668CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
3669 uint64_t *XOffset) {
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003670 SmallVector<llvm::Metadata *, 5> EltTys;
Guy Benyei11169dd2012-12-18 14:30:41 +00003671 QualType FType;
3672 uint64_t FieldSize, FieldOffset;
Victor Leschuk802e4a52016-10-19 22:11:07 +00003673 uint32_t FieldAlign;
Eric Christopherb2a008c2013-05-16 00:45:12 +00003674
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003675 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
Eric Christopherb2a008c2013-05-16 00:45:12 +00003676 QualType Type = VD->getType();
Guy Benyei11169dd2012-12-18 14:30:41 +00003677
3678 FieldOffset = 0;
3679 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
3680 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
3681 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
3682 FType = CGM.getContext().IntTy;
3683 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
3684 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
3685
3686 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
3687 if (HasCopyAndDispose) {
3688 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
Eric Christophere7b87e52014-10-26 23:40:33 +00003689 EltTys.push_back(
3690 CreateMemberType(Unit, FType, "__copy_helper", &FieldOffset));
3691 EltTys.push_back(
3692 CreateMemberType(Unit, FType, "__destroy_helper", &FieldOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00003693 }
3694 bool HasByrefExtendedLayout;
3695 Qualifiers::ObjCLifetime Lifetime;
Eric Christophere7b87e52014-10-26 23:40:33 +00003696 if (CGM.getContext().getByrefLifetime(Type, Lifetime,
3697 HasByrefExtendedLayout) &&
3698 HasByrefExtendedLayout) {
Adrian Prantlead2ba42013-07-23 00:12:14 +00003699 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
Eric Christophere7b87e52014-10-26 23:40:33 +00003700 EltTys.push_back(
3701 CreateMemberType(Unit, FType, "__byref_variable_layout", &FieldOffset));
Adrian Prantlead2ba42013-07-23 00:12:14 +00003702 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00003703
Guy Benyei11169dd2012-12-18 14:30:41 +00003704 CharUnits Align = CGM.getContext().getDeclAlign(VD);
3705 if (Align > CGM.getContext().toCharUnitsFromBits(
Eric Christophere7b87e52014-10-26 23:40:33 +00003706 CGM.getTarget().getPointerAlign(0))) {
3707 CharUnits FieldOffsetInBytes =
3708 CGM.getContext().toCharUnitsFromBits(FieldOffset);
Rui Ueyama83aa9792016-01-14 21:00:27 +00003709 CharUnits AlignedOffsetInBytes = FieldOffsetInBytes.alignTo(Align);
Eric Christophere7b87e52014-10-26 23:40:33 +00003710 CharUnits NumPaddingBytes = AlignedOffsetInBytes - FieldOffsetInBytes;
Eric Christopherb2a008c2013-05-16 00:45:12 +00003711
Guy Benyei11169dd2012-12-18 14:30:41 +00003712 if (NumPaddingBytes.isPositive()) {
3713 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
3714 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
3715 pad, ArrayType::Normal, 0);
3716 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
3717 }
3718 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00003719
Guy Benyei11169dd2012-12-18 14:30:41 +00003720 FType = Type;
Adrian Prantl05a623e2018-09-10 16:14:28 +00003721 llvm::DIType *WrappedTy = getOrCreateType(FType, Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00003722 FieldSize = CGM.getContext().getTypeSize(FType);
3723 FieldAlign = CGM.getContext().toBits(Align);
3724
Eric Christopherb2a008c2013-05-16 00:45:12 +00003725 *XOffset = FieldOffset;
Adrian Prantl05a623e2018-09-10 16:14:28 +00003726 llvm::DIType *FieldTy = DBuilder.createMemberType(
3727 Unit, VD->getName(), Unit, 0, FieldSize, FieldAlign, FieldOffset,
3728 llvm::DINode::FlagZero, WrappedTy);
Guy Benyei11169dd2012-12-18 14:30:41 +00003729 EltTys.push_back(FieldTy);
3730 FieldOffset += FieldSize;
Eric Christopherb2a008c2013-05-16 00:45:12 +00003731
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003732 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
Adrian Prantl05a623e2018-09-10 16:14:28 +00003733 return {DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0,
3734 llvm::DINode::FlagZero, nullptr, Elements),
3735 WrappedTy};
Guy Benyei11169dd2012-12-18 14:30:41 +00003736}
3737
Sander de Smalen891af03a2018-02-03 13:55:59 +00003738llvm::DILocalVariable *CGDebugInfo::EmitDeclare(const VarDecl *VD,
3739 llvm::Value *Storage,
3740 llvm::Optional<unsigned> ArgNo,
3741 CGBuilderTy &Builder) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00003742 assert(DebugKind >= codegenoptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00003743 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
Paul Robinsonafd2dde2016-06-16 00:42:36 +00003744 if (VD->hasAttr<NoDebugAttr>())
Sander de Smalen891af03a2018-02-03 13:55:59 +00003745 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003746
David Blaikie7fceebf2013-08-19 03:37:48 +00003747 bool Unwritten =
3748 VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) &&
3749 cast<Decl>(VD->getDeclContext())->isImplicit());
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003750 llvm::DIFile *Unit = nullptr;
David Blaikie7fceebf2013-08-19 03:37:48 +00003751 if (!Unwritten)
3752 Unit = getOrCreateFile(VD->getLocation());
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003753 llvm::DIType *Ty;
Guy Benyei11169dd2012-12-18 14:30:41 +00003754 uint64_t XOffset = 0;
3755 if (VD->hasAttr<BlocksAttr>())
Adrian Prantl05a623e2018-09-10 16:14:28 +00003756 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset).WrappedType;
Eric Christopherb2a008c2013-05-16 00:45:12 +00003757 else
Guy Benyei11169dd2012-12-18 14:30:41 +00003758 Ty = getOrCreateType(VD->getType(), Unit);
3759
3760 // If there is no debug info for this type then do not emit debug info
3761 // for this variable.
3762 if (!Ty)
Sander de Smalen891af03a2018-02-03 13:55:59 +00003763 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003764
Guy Benyei11169dd2012-12-18 14:30:41 +00003765 // Get location information.
David Blaikie7fceebf2013-08-19 03:37:48 +00003766 unsigned Line = 0;
3767 unsigned Column = 0;
3768 if (!Unwritten) {
3769 Line = getLineNumber(VD->getLocation());
3770 Column = getColumnNumber(VD->getLocation());
3771 }
Konstantin Zhuravlyov2b4917f2017-03-09 18:06:23 +00003772 SmallVector<int64_t, 13> Expr;
Leny Kholodov80c047d2016-09-06 10:48:04 +00003773 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
Guy Benyei11169dd2012-12-18 14:30:41 +00003774 if (VD->isImplicit())
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003775 Flags |= llvm::DINode::FlagArtificial;
Victor Leschuka7ece032016-10-20 00:13:19 +00003776
3777 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
3778
Konstantin Zhuravlyov2b4917f2017-03-09 18:06:23 +00003779 unsigned AddressSpace = CGM.getContext().getTargetAddressSpace(VD->getType());
3780 AppendAddressSpaceXDeref(AddressSpace, Expr);
3781
Alexey Bataev24f710182017-06-09 13:55:08 +00003782 // If this is implicit parameter of CXXThis or ObjCSelf kind, then give it an
3783 // object pointer flag.
Alexey Bataev56223232017-06-09 13:40:18 +00003784 if (const auto *IPD = dyn_cast<ImplicitParamDecl>(VD)) {
3785 if (IPD->getParameterKind() == ImplicitParamDecl::CXXThis ||
3786 IPD->getParameterKind() == ImplicitParamDecl::ObjCSelf)
3787 Flags |= llvm::DINode::FlagObjectPointer;
3788 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003789
Adrian Prantlc3782a12017-04-18 01:22:01 +00003790 // Note: Older versions of clang used to emit byval references with an extra
3791 // DW_OP_deref, because they referenced the IR arg directly instead of
3792 // referencing an alloca. Newer versions of LLVM don't treat allocas
3793 // differently from other function arguments when used in a dbg.declare.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003794 auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
Guy Benyei11169dd2012-12-18 14:30:41 +00003795 StringRef Name = VD->getName();
3796 if (!Name.empty()) {
3797 if (VD->hasAttr<BlocksAttr>()) {
Adrian Prantlc3782a12017-04-18 01:22:01 +00003798 // Here, we need an offset *into* the alloca.
Guy Benyei11169dd2012-12-18 14:30:41 +00003799 CharUnits offset = CharUnits::fromQuantity(32);
Florian Hahn3dbcced2017-06-13 18:06:15 +00003800 Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
Guy Benyei11169dd2012-12-18 14:30:41 +00003801 // offset of __forwarding field
3802 offset = CGM.getContext().toCharUnitsFromBits(
Eric Christophere7b87e52014-10-26 23:40:33 +00003803 CGM.getTarget().getPointerWidth(0));
Adrian Prantl7c6f9442015-01-19 17:51:58 +00003804 Expr.push_back(offset.getQuantity());
3805 Expr.push_back(llvm::dwarf::DW_OP_deref);
Florian Hahn3dbcced2017-06-13 18:06:15 +00003806 Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
Guy Benyei11169dd2012-12-18 14:30:41 +00003807 // offset of x field
3808 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
Adrian Prantl7c6f9442015-01-19 17:51:58 +00003809 Expr.push_back(offset.getQuantity());
Adrian Prantlc3782a12017-04-18 01:22:01 +00003810 }
David Majnemer58ed0f32016-07-17 00:39:12 +00003811 } else if (const auto *RT = dyn_cast<RecordType>(VD->getType())) {
Adrian Prantl0d820892015-04-29 15:05:50 +00003812 // If VD is an anonymous union then Storage represents value for
3813 // all union fields.
George Burgess IV00f70bd2018-03-01 05:43:23 +00003814 const RecordDecl *RD = RT->getDecl();
Adrian Prantl0d820892015-04-29 15:05:50 +00003815 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
Adrian Prantl00820ab2015-04-29 16:52:31 +00003816 // GDB has trouble finding local variables in anonymous unions, so we emit
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00003817 // artificial local variables for each of the members.
Adrian Prantl00820ab2015-04-29 16:52:31 +00003818 //
3819 // FIXME: Remove this code as soon as GDB supports this.
3820 // The debug info verifier in LLVM operates based on the assumption that a
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00003821 // variable has the same size as its storage and we had to disable the
3822 // check for artificial variables.
Adrian Prantl0d820892015-04-29 15:05:50 +00003823 for (const auto *Field : RD->fields()) {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003824 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
Adrian Prantl0d820892015-04-29 15:05:50 +00003825 StringRef FieldName = Field->getName();
3826
3827 // Ignore unnamed fields. Do not ignore unnamed records.
3828 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
3829 continue;
3830
3831 // Use VarDecl's Tag, Scope and Line number.
Victor Leschuka7ece032016-10-20 00:13:19 +00003832 auto FieldAlign = getDeclAlignIfRequired(Field, CGM.getContext());
Duncan P. N. Exon Smithe4306542015-07-31 17:56:14 +00003833 auto *D = DBuilder.createAutoVariable(
3834 Scope, FieldName, Unit, Line, FieldTy, CGM.getLangOpts().Optimize,
Victor Leschuka7ece032016-10-20 00:13:19 +00003835 Flags | llvm::DINode::FlagArtificial, FieldAlign);
Adrian Prantl0d820892015-04-29 15:05:50 +00003836
3837 // Insert an llvm.dbg.declare into the current block.
Adrian Prantlb7acfc02017-02-27 21:30:05 +00003838 DBuilder.insertDeclare(
3839 Storage, D, DBuilder.createExpression(Expr),
3840 llvm::DebugLoc::get(Line, Column, Scope, CurInlinedAt),
3841 Builder.GetInsertBlock());
Adrian Prantl0d820892015-04-29 15:05:50 +00003842 }
Adrian Prantl0d820892015-04-29 15:05:50 +00003843 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003844 }
David Blaikiea76a7c92013-01-05 05:58:35 +00003845
3846 // Create the descriptor for the variable.
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00003847 auto *D = ArgNo ? DBuilder.createParameterVariable(
3848 Scope, Name, *ArgNo, Unit, Line, Ty,
3849 CGM.getLangOpts().Optimize, Flags)
3850 : DBuilder.createAutoVariable(Scope, Name, Unit, Line, Ty,
3851 CGM.getLangOpts().Optimize,
3852 Flags, Align);
David Blaikiea76a7c92013-01-05 05:58:35 +00003853
3854 // Insert an llvm.dbg.declare into the current block.
Duncan P. N. Exon Smithfe88b482015-04-15 21:18:30 +00003855 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
Adrian Prantlb7acfc02017-02-27 21:30:05 +00003856 llvm::DebugLoc::get(Line, Column, Scope, CurInlinedAt),
Duncan P. N. Exon Smithfe88b482015-04-15 21:18:30 +00003857 Builder.GetInsertBlock());
Sander de Smalen891af03a2018-02-03 13:55:59 +00003858
3859 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00003860}
3861
Sander de Smalen891af03a2018-02-03 13:55:59 +00003862llvm::DILocalVariable *
3863CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD, llvm::Value *Storage,
3864 CGBuilderTy &Builder) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00003865 assert(DebugKind >= codegenoptions::LimitedDebugInfo);
Sander de Smalen891af03a2018-02-03 13:55:59 +00003866 return EmitDeclare(VD, Storage, llvm::None, Builder);
Guy Benyei11169dd2012-12-18 14:30:41 +00003867}
3868
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003869llvm::DIType *CGDebugInfo::CreateSelfType(const QualType &QualTy,
3870 llvm::DIType *Ty) {
3871 llvm::DIType *CachedTy = getTypeOrNull(QualTy);
Eric Christophere7b87e52014-10-26 23:40:33 +00003872 if (CachedTy)
3873 Ty = CachedTy;
Adrian Prantlde17db32013-03-29 19:20:29 +00003874 return DBuilder.createObjectPointerType(Ty);
3875}
3876
Eric Christophere7b87e52014-10-26 23:40:33 +00003877void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(
3878 const VarDecl *VD, llvm::Value *Storage, CGBuilderTy &Builder,
Adrian Prantl88eec392014-11-21 00:35:25 +00003879 const CGBlockInfo &blockInfo, llvm::Instruction *InsertPoint) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00003880 assert(DebugKind >= codegenoptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00003881 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
Eric Christopherb2a008c2013-05-16 00:45:12 +00003882
Craig Topper8a13c412014-05-21 05:09:00 +00003883 if (Builder.GetInsertBlock() == nullptr)
Guy Benyei11169dd2012-12-18 14:30:41 +00003884 return;
Paul Robinsonafd2dde2016-06-16 00:42:36 +00003885 if (VD->hasAttr<NoDebugAttr>())
3886 return;
Eric Christopherb2a008c2013-05-16 00:45:12 +00003887
Guy Benyei11169dd2012-12-18 14:30:41 +00003888 bool isByRef = VD->hasAttr<BlocksAttr>();
Eric Christopherb2a008c2013-05-16 00:45:12 +00003889
Guy Benyei11169dd2012-12-18 14:30:41 +00003890 uint64_t XOffset = 0;
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003891 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
3892 llvm::DIType *Ty;
Guy Benyei11169dd2012-12-18 14:30:41 +00003893 if (isByRef)
Adrian Prantl05a623e2018-09-10 16:14:28 +00003894 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset).WrappedType;
Eric Christopherb2a008c2013-05-16 00:45:12 +00003895 else
Guy Benyei11169dd2012-12-18 14:30:41 +00003896 Ty = getOrCreateType(VD->getType(), Unit);
3897
3898 // Self is passed along as an implicit non-arg variable in a
3899 // block. Mark it as the object pointer.
Alexey Bataev56223232017-06-09 13:40:18 +00003900 if (const auto *IPD = dyn_cast<ImplicitParamDecl>(VD))
3901 if (IPD->getParameterKind() == ImplicitParamDecl::ObjCSelf)
3902 Ty = CreateSelfType(VD->getType(), Ty);
Guy Benyei11169dd2012-12-18 14:30:41 +00003903
3904 // Get location information.
3905 unsigned Line = getLineNumber(VD->getLocation());
3906 unsigned Column = getColumnNumber(VD->getLocation());
3907
3908 const llvm::DataLayout &target = CGM.getDataLayout();
3909
3910 CharUnits offset = CharUnits::fromQuantity(
Eric Christophere7b87e52014-10-26 23:40:33 +00003911 target.getStructLayout(blockInfo.StructureType)
Guy Benyei11169dd2012-12-18 14:30:41 +00003912 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
3913
Duncan P. N. Exon Smithf3dc4292014-10-01 20:26:18 +00003914 SmallVector<int64_t, 9> addr;
Adrian Prantlc3782a12017-04-18 01:22:01 +00003915 addr.push_back(llvm::dwarf::DW_OP_deref);
Florian Hahn3dbcced2017-06-13 18:06:15 +00003916 addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
Duncan P. N. Exon Smithf3dc4292014-10-01 20:26:18 +00003917 addr.push_back(offset.getQuantity());
Guy Benyei11169dd2012-12-18 14:30:41 +00003918 if (isByRef) {
Duncan P. N. Exon Smithf3dc4292014-10-01 20:26:18 +00003919 addr.push_back(llvm::dwarf::DW_OP_deref);
Florian Hahn3dbcced2017-06-13 18:06:15 +00003920 addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
Guy Benyei11169dd2012-12-18 14:30:41 +00003921 // offset of __forwarding field
Eric Christophere7b87e52014-10-26 23:40:33 +00003922 offset =
3923 CGM.getContext().toCharUnitsFromBits(target.getPointerSizeInBits(0));
Duncan P. N. Exon Smithf3dc4292014-10-01 20:26:18 +00003924 addr.push_back(offset.getQuantity());
3925 addr.push_back(llvm::dwarf::DW_OP_deref);
Florian Hahn3dbcced2017-06-13 18:06:15 +00003926 addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
Guy Benyei11169dd2012-12-18 14:30:41 +00003927 // offset of x field
3928 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
Duncan P. N. Exon Smithf3dc4292014-10-01 20:26:18 +00003929 addr.push_back(offset.getQuantity());
Guy Benyei11169dd2012-12-18 14:30:41 +00003930 }
3931
3932 // Create the descriptor for the variable.
Victor Leschuka7ece032016-10-20 00:13:19 +00003933 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
Duncan P. N. Exon Smithe4306542015-07-31 17:56:14 +00003934 auto *D = DBuilder.createAutoVariable(
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003935 cast<llvm::DILocalScope>(LexicalBlockStack.back()), VD->getName(), Unit,
Victor Leschuka7ece032016-10-20 00:13:19 +00003936 Line, Ty, false, llvm::DINode::FlagZero, Align);
Adrian Prantl0f6df002013-03-29 19:20:35 +00003937
Guy Benyei11169dd2012-12-18 14:30:41 +00003938 // Insert an llvm.dbg.declare into the current block.
Adrian Prantlb7acfc02017-02-27 21:30:05 +00003939 auto DL =
3940 llvm::DebugLoc::get(Line, Column, LexicalBlockStack.back(), CurInlinedAt);
Adrian Prantlc3782a12017-04-18 01:22:01 +00003941 auto *Expr = DBuilder.createExpression(addr);
Duncan P. N. Exon Smithfe88b482015-04-15 21:18:30 +00003942 if (InsertPoint)
Adrian Prantlc3782a12017-04-18 01:22:01 +00003943 DBuilder.insertDeclare(Storage, D, Expr, DL, InsertPoint);
Duncan P. N. Exon Smithfe88b482015-04-15 21:18:30 +00003944 else
Adrian Prantlc3782a12017-04-18 01:22:01 +00003945 DBuilder.insertDeclare(Storage, D, Expr, DL, Builder.GetInsertBlock());
Guy Benyei11169dd2012-12-18 14:30:41 +00003946}
3947
Guy Benyei11169dd2012-12-18 14:30:41 +00003948void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
3949 unsigned ArgNo,
3950 CGBuilderTy &Builder) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00003951 assert(DebugKind >= codegenoptions::LimitedDebugInfo);
Duncan P. N. Exon Smithe4306542015-07-31 17:56:14 +00003952 EmitDeclare(VD, AI, ArgNo, Builder);
Guy Benyei11169dd2012-12-18 14:30:41 +00003953}
3954
3955namespace {
Eric Christophere7b87e52014-10-26 23:40:33 +00003956struct BlockLayoutChunk {
3957 uint64_t OffsetInBits;
3958 const BlockDecl::Capture *Capture;
3959};
3960bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
3961 return l.OffsetInBits < r.OffsetInBits;
3962}
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00003963} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00003964
Scott Linder58df0e42018-08-08 15:56:12 +00003965void CGDebugInfo::collectDefaultFieldsForBlockLiteralDeclare(
3966 const CGBlockInfo &Block, const ASTContext &Context, SourceLocation Loc,
3967 const llvm::StructLayout &BlockLayout, llvm::DIFile *Unit,
3968 SmallVectorImpl<llvm::Metadata *> &Fields) {
3969 // Blocks in OpenCL have unique constraints which make the standard fields
3970 // redundant while requiring size and align fields for enqueue_kernel. See
3971 // initializeForBlockHeader in CGBlocks.cpp
3972 if (CGM.getLangOpts().OpenCL) {
3973 Fields.push_back(createFieldType("__size", Context.IntTy, Loc, AS_public,
3974 BlockLayout.getElementOffsetInBits(0),
3975 Unit, Unit));
3976 Fields.push_back(createFieldType("__align", Context.IntTy, Loc, AS_public,
3977 BlockLayout.getElementOffsetInBits(1),
3978 Unit, Unit));
3979 } else {
3980 Fields.push_back(createFieldType("__isa", Context.VoidPtrTy, Loc, AS_public,
3981 BlockLayout.getElementOffsetInBits(0),
3982 Unit, Unit));
3983 Fields.push_back(createFieldType("__flags", Context.IntTy, Loc, AS_public,
3984 BlockLayout.getElementOffsetInBits(1),
3985 Unit, Unit));
3986 Fields.push_back(
3987 createFieldType("__reserved", Context.IntTy, Loc, AS_public,
3988 BlockLayout.getElementOffsetInBits(2), Unit, Unit));
3989 auto *FnTy = Block.getBlockExpr()->getFunctionType();
3990 auto FnPtrType = CGM.getContext().getPointerType(FnTy->desugar());
3991 Fields.push_back(createFieldType("__FuncPtr", FnPtrType, Loc, AS_public,
3992 BlockLayout.getElementOffsetInBits(3),
3993 Unit, Unit));
3994 Fields.push_back(createFieldType(
3995 "__descriptor",
3996 Context.getPointerType(Block.NeedsCopyDispose
3997 ? Context.getBlockDescriptorExtendedType()
3998 : Context.getBlockDescriptorType()),
3999 Loc, AS_public, BlockLayout.getElementOffsetInBits(4), Unit, Unit));
4000 }
4001}
4002
Guy Benyei11169dd2012-12-18 14:30:41 +00004003void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
Adrian Prantl356347b2017-10-26 20:08:52 +00004004 StringRef Name,
David Blaikie77bbb5f2014-08-08 17:10:14 +00004005 unsigned ArgNo,
Adrian Prantl356347b2017-10-26 20:08:52 +00004006 llvm::AllocaInst *Alloca,
Guy Benyei11169dd2012-12-18 14:30:41 +00004007 CGBuilderTy &Builder) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00004008 assert(DebugKind >= codegenoptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00004009 ASTContext &C = CGM.getContext();
4010 const BlockDecl *blockDecl = block.getBlockDecl();
4011
4012 // Collect some general information about the block's location.
4013 SourceLocation loc = blockDecl->getCaretLocation();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004014 llvm::DIFile *tunit = getOrCreateFile(loc);
Guy Benyei11169dd2012-12-18 14:30:41 +00004015 unsigned line = getLineNumber(loc);
4016 unsigned column = getColumnNumber(loc);
Eric Christopherb2a008c2013-05-16 00:45:12 +00004017
Guy Benyei11169dd2012-12-18 14:30:41 +00004018 // Build the debug-info type for the block literal.
Adrian Prantl6ec370a2015-09-10 18:39:45 +00004019 getDeclContextDescriptor(blockDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00004020
4021 const llvm::StructLayout *blockLayout =
Eric Christophere7b87e52014-10-26 23:40:33 +00004022 CGM.getDataLayout().getStructLayout(block.StructureType);
Guy Benyei11169dd2012-12-18 14:30:41 +00004023
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00004024 SmallVector<llvm::Metadata *, 16> fields;
Scott Linder58df0e42018-08-08 15:56:12 +00004025 collectDefaultFieldsForBlockLiteralDeclare(block, C, loc, *blockLayout, tunit,
4026 fields);
Guy Benyei11169dd2012-12-18 14:30:41 +00004027
4028 // We want to sort the captures by offset, not because DWARF
4029 // requires this, but because we're paranoid about debuggers.
4030 SmallVector<BlockLayoutChunk, 8> chunks;
4031
4032 // 'this' capture.
4033 if (blockDecl->capturesCXXThis()) {
4034 BlockLayoutChunk chunk;
4035 chunk.OffsetInBits =
Eric Christophere7b87e52014-10-26 23:40:33 +00004036 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
Craig Topper8a13c412014-05-21 05:09:00 +00004037 chunk.Capture = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004038 chunks.push_back(chunk);
4039 }
4040
4041 // Variable captures.
Aaron Ballman9371dd22014-03-14 18:34:04 +00004042 for (const auto &capture : blockDecl->captures()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004043 const VarDecl *variable = capture.getVariable();
4044 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
4045
4046 // Ignore constant captures.
4047 if (captureInfo.isConstant())
4048 continue;
4049
4050 BlockLayoutChunk chunk;
4051 chunk.OffsetInBits =
Eric Christophere7b87e52014-10-26 23:40:33 +00004052 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
Guy Benyei11169dd2012-12-18 14:30:41 +00004053 chunk.Capture = &capture;
4054 chunks.push_back(chunk);
4055 }
4056
4057 // Sort by offset.
4058 llvm::array_pod_sort(chunks.begin(), chunks.end());
4059
David Majnemer58ed0f32016-07-17 00:39:12 +00004060 for (const BlockLayoutChunk &Chunk : chunks) {
4061 uint64_t offsetInBits = Chunk.OffsetInBits;
4062 const BlockDecl::Capture *capture = Chunk.Capture;
Guy Benyei11169dd2012-12-18 14:30:41 +00004063
4064 // If we have a null capture, this must be the C++ 'this' capture.
4065 if (!capture) {
Adrian Prantl2526fca2016-04-18 23:48:16 +00004066 QualType type;
4067 if (auto *Method =
4068 cast_or_null<CXXMethodDecl>(blockDecl->getNonClosureContext()))
4069 type = Method->getThisType(C);
4070 else if (auto *RDecl = dyn_cast<CXXRecordDecl>(blockDecl->getParent()))
4071 type = QualType(RDecl->getTypeForDecl(), 0);
4072 else
4073 llvm_unreachable("unexpected block declcontext");
Guy Benyei11169dd2012-12-18 14:30:41 +00004074
David Majnemerb4b671e2016-06-30 03:01:59 +00004075 fields.push_back(createFieldType("this", type, loc, AS_public,
Guy Benyei11169dd2012-12-18 14:30:41 +00004076 offsetInBits, tunit, tunit));
4077 continue;
4078 }
4079
4080 const VarDecl *variable = capture->getVariable();
4081 StringRef name = variable->getName();
4082
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004083 llvm::DIType *fieldType;
Guy Benyei11169dd2012-12-18 14:30:41 +00004084 if (capture->isByRef()) {
David Majnemer34b57492014-07-30 01:30:47 +00004085 TypeInfo PtrInfo = C.getTypeInfo(C.VoidPtrTy);
Victor Leschuka7ece032016-10-20 00:13:19 +00004086 auto Align = PtrInfo.AlignIsRequired ? PtrInfo.Align : 0;
Adrian Prantl05a623e2018-09-10 16:14:28 +00004087 // FIXME: This recomputes the layout of the BlockByRefWrapper.
Guy Benyei11169dd2012-12-18 14:30:41 +00004088 uint64_t xoffset;
Adrian Prantl05a623e2018-09-10 16:14:28 +00004089 fieldType =
4090 EmitTypeForVarWithBlocksAttr(variable, &xoffset).BlockByRefWrapper;
David Majnemer34b57492014-07-30 01:30:47 +00004091 fieldType = DBuilder.createPointerType(fieldType, PtrInfo.Width);
Victor Leschuka7ece032016-10-20 00:13:19 +00004092 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
4093 PtrInfo.Width, Align, offsetInBits,
4094 llvm::DINode::FlagZero, fieldType);
Guy Benyei11169dd2012-12-18 14:30:41 +00004095 } else {
Victor Leschuka7ece032016-10-20 00:13:19 +00004096 auto Align = getDeclAlignIfRequired(variable, CGM.getContext());
David Majnemerb4b671e2016-06-30 03:01:59 +00004097 fieldType = createFieldType(name, variable->getType(), loc, AS_public,
Victor Leschuka7ece032016-10-20 00:13:19 +00004098 offsetInBits, Align, tunit, tunit);
Guy Benyei11169dd2012-12-18 14:30:41 +00004099 }
4100 fields.push_back(fieldType);
4101 }
4102
4103 SmallString<36> typeName;
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004104 llvm::raw_svector_ostream(typeName)
4105 << "__block_literal_" << CGM.getUniqueBlockCount();
Guy Benyei11169dd2012-12-18 14:30:41 +00004106
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004107 llvm::DINodeArray fieldsArray = DBuilder.getOrCreateArray(fields);
Guy Benyei11169dd2012-12-18 14:30:41 +00004108
Leny Kholodovdf050fd2016-09-06 17:06:14 +00004109 llvm::DIType *type =
4110 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
Victor Leschuka7ece032016-10-20 00:13:19 +00004111 CGM.getContext().toBits(block.BlockSize), 0,
Leny Kholodovdf050fd2016-09-06 17:06:14 +00004112 llvm::DINode::FlagZero, nullptr, fieldsArray);
Guy Benyei11169dd2012-12-18 14:30:41 +00004113 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
4114
4115 // Get overall information about the block.
Leny Kholodov80c047d2016-09-06 10:48:04 +00004116 llvm::DINode::DIFlags flags = llvm::DINode::FlagArtificial;
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004117 auto *scope = cast<llvm::DILocalScope>(LexicalBlockStack.back());
Guy Benyei11169dd2012-12-18 14:30:41 +00004118
4119 // Create the descriptor for the parameter.
Duncan P. N. Exon Smithe4306542015-07-31 17:56:14 +00004120 auto *debugVar = DBuilder.createParameterVariable(
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004121 scope, Name, ArgNo, tunit, line, type, CGM.getLangOpts().Optimize, flags);
Adrian Prantl51936dd2013-03-14 17:53:33 +00004122
Adrian Prantl616bef42013-03-14 21:52:59 +00004123 // Insert an llvm.dbg.declare into the current block.
Adrian Prantl356347b2017-10-26 20:08:52 +00004124 DBuilder.insertDeclare(Alloca, debugVar, DBuilder.createExpression(),
Adrian Prantlb7acfc02017-02-27 21:30:05 +00004125 llvm::DebugLoc::get(line, column, scope, CurInlinedAt),
Duncan P. N. Exon Smithfe88b482015-04-15 21:18:30 +00004126 Builder.GetInsertBlock());
Guy Benyei11169dd2012-12-18 14:30:41 +00004127}
4128
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004129llvm::DIDerivedType *
David Blaikie6943dea2013-08-20 01:28:15 +00004130CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) {
4131 if (!D->isStaticDataMember())
Duncan P. N. Exon Smithc09c5482015-04-20 21:17:26 +00004132 return nullptr;
Saleem Abdulrasoolcd187f02015-02-28 00:13:13 +00004133
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00004134 auto MI = StaticDataMemberCache.find(D->getCanonicalDecl());
David Blaikie6943dea2013-08-20 01:28:15 +00004135 if (MI != StaticDataMemberCache.end()) {
4136 assert(MI->second && "Static data member declaration should still exist");
Duncan P. N. Exon Smithac346ba2015-07-24 18:05:58 +00004137 return MI->second;
Evgeniy Stepanov37b3f732013-08-16 10:35:31 +00004138 }
David Blaikiece763042013-08-20 21:49:21 +00004139
4140 // If the member wasn't found in the cache, lazily construct and add it to the
4141 // type (used when a limited form of the type is emitted).
Adrian Prantl21361fb2014-08-29 22:44:27 +00004142 auto DC = D->getDeclContext();
Adrian Prantl6ec370a2015-09-10 18:39:45 +00004143 auto *Ctxt = cast<llvm::DICompositeType>(getDeclContextDescriptor(D));
Adrian Prantl21361fb2014-08-29 22:44:27 +00004144 return CreateRecordStaticField(D, Ctxt, cast<RecordDecl>(DC));
David Blaikie6943dea2013-08-20 01:28:15 +00004145}
4146
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004147llvm::DIGlobalVariableExpression *CGDebugInfo::CollectAnonRecordDecls(
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004148 const RecordDecl *RD, llvm::DIFile *Unit, unsigned LineNo,
4149 StringRef LinkageName, llvm::GlobalVariable *Var, llvm::DIScope *DContext) {
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004150 llvm::DIGlobalVariableExpression *GVE = nullptr;
Eric Christophercab9fae2014-04-10 05:20:00 +00004151
4152 for (const auto *Field : RD->fields()) {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004153 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
Eric Christophercab9fae2014-04-10 05:20:00 +00004154 StringRef FieldName = Field->getName();
4155
4156 // Ignore unnamed fields, but recurse into anonymous records.
4157 if (FieldName.empty()) {
David Majnemer58ed0f32016-07-17 00:39:12 +00004158 if (const auto *RT = dyn_cast<RecordType>(Field->getType()))
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004159 GVE = CollectAnonRecordDecls(RT->getDecl(), Unit, LineNo, LinkageName,
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004160 Var, DContext);
Eric Christophercab9fae2014-04-10 05:20:00 +00004161 continue;
4162 }
4163 // Use VarDecl's Tag, Scope and Line number.
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004164 GVE = DBuilder.createGlobalVariableExpression(
4165 DContext, FieldName, LinkageName, Unit, LineNo, FieldTy,
4166 Var->hasLocalLinkage());
4167 Var->addDebugInfo(GVE);
Eric Christophercab9fae2014-04-10 05:20:00 +00004168 }
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004169 return GVE;
Eric Christophercab9fae2014-04-10 05:20:00 +00004170}
4171
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00004172void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
Guy Benyei11169dd2012-12-18 14:30:41 +00004173 const VarDecl *D) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00004174 assert(DebugKind >= codegenoptions::LimitedDebugInfo);
Paul Robinsonb17327d2016-04-27 17:37:12 +00004175 if (D->hasAttr<NoDebugAttr>())
4176 return;
Adrian Prantl338ef7a2016-11-09 00:42:03 +00004177
4178 // If we already created a DIGlobalVariable for this declaration, just attach
4179 // it to the llvm::GlobalVariable.
4180 auto Cached = DeclCache.find(D->getCanonicalDecl());
4181 if (Cached != DeclCache.end())
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004182 return Var->addDebugInfo(
4183 cast<llvm::DIGlobalVariableExpression>(Cached->second));
Adrian Prantl338ef7a2016-11-09 00:42:03 +00004184
Guy Benyei11169dd2012-12-18 14:30:41 +00004185 // Create global variable debug descriptor.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004186 llvm::DIFile *Unit = nullptr;
4187 llvm::DIScope *DContext = nullptr;
Frederic Riss9db79f12014-11-18 03:40:46 +00004188 unsigned LineNo;
4189 StringRef DeclName, LinkageName;
4190 QualType T;
Matthew Voss20165362018-10-03 18:45:04 +00004191 llvm::MDTuple *TemplateParameters = nullptr;
4192 collectVarDeclProps(D, Unit, LineNo, T, DeclName, LinkageName,
4193 TemplateParameters, DContext);
Eric Christophercab9fae2014-04-10 05:20:00 +00004194
4195 // Attempt to store one global variable for the declaration - even if we
4196 // emit a lot of fields.
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004197 llvm::DIGlobalVariableExpression *GVE = nullptr;
Eric Christophercab9fae2014-04-10 05:20:00 +00004198
4199 // If this is an anonymous union then we'll want to emit a global
4200 // variable for each member of the anonymous union so that it's possible
4201 // to find the name of any field in the union.
4202 if (T->isUnionType() && DeclName.empty()) {
Reid Kleckner43ecd7c2015-11-20 17:41:12 +00004203 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
Eric Christophere7b87e52014-10-26 23:40:33 +00004204 assert(RD->isAnonymousStructOrUnion() &&
4205 "unnamed non-anonymous struct or union?");
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004206 GVE = CollectAnonRecordDecls(RD, Unit, LineNo, LinkageName, Var, DContext);
Eric Christophercab9fae2014-04-10 05:20:00 +00004207 } else {
Victor Leschuka7ece032016-10-20 00:13:19 +00004208 auto Align = getDeclAlignIfRequired(D, CGM.getContext());
Konstantin Zhuravlyov2b4917f2017-03-09 18:06:23 +00004209
4210 SmallVector<int64_t, 4> Expr;
4211 unsigned AddressSpace =
4212 CGM.getContext().getTargetAddressSpace(D->getType());
4213 AppendAddressSpaceXDeref(AddressSpace, Expr);
4214
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004215 GVE = DBuilder.createGlobalVariableExpression(
Eric Christophercab9fae2014-04-10 05:20:00 +00004216 DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),
Konstantin Zhuravlyov2b4917f2017-03-09 18:06:23 +00004217 Var->hasLocalLinkage(),
4218 Expr.empty() ? nullptr : DBuilder.createExpression(Expr),
Matthew Voss20165362018-10-03 18:45:04 +00004219 getOrCreateStaticDataMemberDeclarationOrNull(D), TemplateParameters,
4220 Align);
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004221 Var->addDebugInfo(GVE);
Eric Christophercab9fae2014-04-10 05:20:00 +00004222 }
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004223 DeclCache[D->getCanonicalDecl()].reset(GVE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004224}
4225
Peter Collingbourneeeb56ab2016-09-13 01:13:19 +00004226void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD, const APValue &Init) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00004227 assert(DebugKind >= codegenoptions::LimitedDebugInfo);
Paul Robinsonb17327d2016-04-27 17:37:12 +00004228 if (VD->hasAttr<NoDebugAttr>())
4229 return;
Victor Leschuka7ece032016-10-20 00:13:19 +00004230 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00004231 // Create the descriptor for the variable.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004232 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00004233 StringRef Name = VD->getName();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004234 llvm::DIType *Ty = getOrCreateType(VD->getType(), Unit);
David Majnemer58ed0f32016-07-17 00:39:12 +00004235 if (const auto *ECD = dyn_cast<EnumConstantDecl>(VD)) {
4236 const auto *ED = cast<EnumDecl>(ECD->getDeclContext());
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00004237 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
4238 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
4239 }
Duncan P. N. Exon Smithdadc2b62015-04-21 18:43:54 +00004240 // Do not use global variables for enums.
4241 //
4242 // FIXME: why not?
Duncan P. N. Exon Smith4caa7f22015-04-16 01:00:56 +00004243 if (Ty->getTag() == llvm::dwarf::DW_TAG_enumeration_type)
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00004244 return;
David Blaikiea15565562014-04-04 20:56:17 +00004245 // Do not emit separate definitions for function local const/statics.
4246 if (isa<FunctionDecl>(VD->getDeclContext()))
4247 return;
David Blaikiebb113912014-04-05 07:23:17 +00004248 VD = cast<ValueDecl>(VD->getCanonicalDecl());
David Blaikie423eb5a2014-11-19 19:42:40 +00004249 auto *VarD = cast<VarDecl>(VD);
David Blaikieaf080852014-11-21 00:20:58 +00004250 if (VarD->isStaticDataMember()) {
4251 auto *RD = cast<RecordDecl>(VarD->getDeclContext());
Adrian Prantl6ec370a2015-09-10 18:39:45 +00004252 getDeclContextDescriptor(VarD);
David Blaikie423eb5a2014-11-19 19:42:40 +00004253 // Ensure that the type is retained even though it's otherwise unreferenced.
Duncan P. N. Exon Smith383f8412016-04-23 21:08:27 +00004254 //
4255 // FIXME: This is probably unnecessary, since Ty should reference RD
4256 // through its scope.
David Blaikie423eb5a2014-11-19 19:42:40 +00004257 RetainedTypes.push_back(
David Blaikieaf080852014-11-21 00:20:58 +00004258 CGM.getContext().getRecordType(RD).getAsOpaquePtr());
David Blaikie423eb5a2014-11-19 19:42:40 +00004259 return;
4260 }
4261
Adrian Prantl6ec370a2015-09-10 18:39:45 +00004262 llvm::DIScope *DContext = getDeclContextDescriptor(VD);
David Blaikieaf080852014-11-21 00:20:58 +00004263
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00004264 auto &GV = DeclCache[VD];
4265 if (GV)
David Blaikiebb113912014-04-05 07:23:17 +00004266 return;
Peter Collingbourneeeb56ab2016-09-13 01:13:19 +00004267 llvm::DIExpression *InitExpr = nullptr;
Peter Collingbourneb7013632016-12-16 22:10:52 +00004268 if (CGM.getContext().getTypeSize(VD->getType()) <= 64) {
4269 // FIXME: Add a representation for integer constants wider than 64 bits.
4270 if (Init.isInt())
4271 InitExpr =
4272 DBuilder.createConstantValueExpression(Init.getInt().getExtValue());
4273 else if (Init.isFloat())
4274 InitExpr = DBuilder.createConstantValueExpression(
4275 Init.getFloat().bitcastToAPInt().getZExtValue());
4276 }
Matthew Voss20165362018-10-03 18:45:04 +00004277
4278 llvm::MDTuple *TemplateParameters = nullptr;
4279
4280 if (isa<VarTemplateSpecializationDecl>(VD))
4281 if (VarD) {
4282 llvm::DINodeArray parameterNodes = CollectVarTemplateParams(VarD, &*Unit);
4283 TemplateParameters = parameterNodes.get();
4284 }
4285
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004286 GV.reset(DBuilder.createGlobalVariableExpression(
David Blaikie506a7452014-04-05 07:46:57 +00004287 DContext, Name, StringRef(), Unit, getLineNumber(VD->getLocation()), Ty,
Victor Leschuka7ece032016-10-20 00:13:19 +00004288 true, InitExpr, getOrCreateStaticDataMemberDeclarationOrNull(VarD),
Matthew Voss20165362018-10-03 18:45:04 +00004289 TemplateParameters, Align));
David Blaikiebd483762013-05-20 04:58:53 +00004290}
4291
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004292llvm::DIScope *CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
David Blaikiebd483762013-05-20 04:58:53 +00004293 if (!LexicalBlockStack.empty())
Duncan P. N. Exon Smithfc8d9d92015-04-20 18:32:15 +00004294 return LexicalBlockStack.back();
Adrian Prantl5c8bd882015-09-11 17:23:08 +00004295 llvm::DIScope *Mod = getParentModuleOrNull(D);
4296 return getContextDescriptor(D, Mod ? Mod : TheCU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004297}
4298
David Blaikie9f88fe82013-04-22 06:13:21 +00004299void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00004300 if (CGM.getCodeGenOpts().getDebugInfo() < codegenoptions::LimitedDebugInfo)
David Blaikiebd483762013-05-20 04:58:53 +00004301 return;
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +00004302 const NamespaceDecl *NSDecl = UD.getNominatedNamespace();
Adrian McCarthyab1e7862016-07-21 18:43:20 +00004303 if (!NSDecl->isAnonymousNamespace() ||
4304 CGM.getCodeGenOpts().DebugExplicitImport) {
Adrian Prantl5649b0e2017-07-19 00:09:58 +00004305 auto Loc = UD.getLocation();
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +00004306 DBuilder.createImportedModule(
4307 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
Adrian Prantl5649b0e2017-07-19 00:09:58 +00004308 getOrCreateNamespace(NSDecl), getOrCreateFile(Loc), getLineNumber(Loc));
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +00004309 }
David Blaikie9f88fe82013-04-22 06:13:21 +00004310}
4311
David Blaikiebd483762013-05-20 04:58:53 +00004312void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00004313 if (CGM.getCodeGenOpts().getDebugInfo() < codegenoptions::LimitedDebugInfo)
David Blaikiebd483762013-05-20 04:58:53 +00004314 return;
4315 assert(UD.shadow_size() &&
4316 "We shouldn't be codegening an invalid UsingDecl containing no decls");
4317 // Emitting one decl is sufficient - debuggers can detect that this is an
4318 // overloaded name & provide lookup for all the overloads.
4319 const UsingShadowDecl &USD = **UD.shadow_begin();
David Blaikie2a58a182016-08-05 19:03:01 +00004320
4321 // FIXME: Skip functions with undeduced auto return type for now since we
4322 // don't currently have the plumbing for separate declarations & definitions
4323 // of free functions and mismatched types (auto in the declaration, concrete
4324 // return type in the definition)
4325 if (const auto *FD = dyn_cast<FunctionDecl>(USD.getUnderlyingDecl()))
4326 if (const auto *AT =
4327 FD->getType()->getAs<FunctionProtoType>()->getContainedAutoType())
4328 if (AT->getDeducedType().isNull())
4329 return;
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004330 if (llvm::DINode *Target =
Adrian Prantl5649b0e2017-07-19 00:09:58 +00004331 getDeclarationOrDefinition(USD.getUnderlyingDecl())) {
4332 auto Loc = USD.getLocation();
David Blaikiebd483762013-05-20 04:58:53 +00004333 DBuilder.createImportedDeclaration(
4334 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
Adrian Prantl5649b0e2017-07-19 00:09:58 +00004335 getOrCreateFile(Loc), getLineNumber(Loc));
4336 }
David Blaikiebd483762013-05-20 04:58:53 +00004337}
4338
Adrian Prantlc4bb47e2015-06-30 17:39:51 +00004339void CGDebugInfo::EmitImportDecl(const ImportDecl &ID) {
David Blaikieaf09f4a2016-05-03 23:06:40 +00004340 if (CGM.getCodeGenOpts().getDebuggerTuning() != llvm::DebuggerKind::LLDB)
4341 return;
Adrian Prantl8a634c12015-12-18 19:44:31 +00004342 if (Module *M = ID.getImportedModule()) {
Chad Rosiere5dafd12015-12-18 20:08:40 +00004343 auto Info = ExternalASTSource::ASTSourceDescriptor(*M);
Adrian Prantl5649b0e2017-07-19 00:09:58 +00004344 auto Loc = ID.getLocation();
Adrian Prantl8a634c12015-12-18 19:44:31 +00004345 DBuilder.createImportedDeclaration(
4346 getCurrentContextDescriptor(cast<Decl>(ID.getDeclContext())),
Adrian Prantl5649b0e2017-07-19 00:09:58 +00004347 getOrCreateModuleRef(Info, DebugTypeExtRefs), getOrCreateFile(Loc),
4348 getLineNumber(Loc));
Adrian Prantl8a634c12015-12-18 19:44:31 +00004349 }
Adrian Prantlc4bb47e2015-06-30 17:39:51 +00004350}
4351
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004352llvm::DIImportedEntity *
David Blaikief121b932013-05-20 22:50:41 +00004353CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00004354 if (CGM.getCodeGenOpts().getDebugInfo() < codegenoptions::LimitedDebugInfo)
Duncan P. N. Exon Smithdadc2b62015-04-21 18:43:54 +00004355 return nullptr;
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00004356 auto &VH = NamespaceAliasCache[&NA];
David Blaikief121b932013-05-20 22:50:41 +00004357 if (VH)
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004358 return cast<llvm::DIImportedEntity>(VH);
4359 llvm::DIImportedEntity *R;
Adrian Prantl5649b0e2017-07-19 00:09:58 +00004360 auto Loc = NA.getLocation();
David Majnemer58ed0f32016-07-17 00:39:12 +00004361 if (const auto *Underlying =
David Blaikief121b932013-05-20 22:50:41 +00004362 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
4363 // This could cache & dedup here rather than relying on metadata deduping.
David Blaikie551fb0a2014-04-06 06:30:03 +00004364 R = DBuilder.createImportedDeclaration(
David Blaikief121b932013-05-20 22:50:41 +00004365 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
Adrian Prantl5649b0e2017-07-19 00:09:58 +00004366 EmitNamespaceAlias(*Underlying), getOrCreateFile(Loc),
4367 getLineNumber(Loc), NA.getName());
David Blaikief121b932013-05-20 22:50:41 +00004368 else
David Blaikie551fb0a2014-04-06 06:30:03 +00004369 R = DBuilder.createImportedDeclaration(
David Blaikief121b932013-05-20 22:50:41 +00004370 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
Adrian Prantlddb8e062017-05-12 16:23:53 +00004371 getOrCreateNamespace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
Adrian Prantl5649b0e2017-07-19 00:09:58 +00004372 getOrCreateFile(Loc), getLineNumber(Loc), NA.getName());
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00004373 VH.reset(R);
David Blaikief121b932013-05-20 22:50:41 +00004374 return R;
4375}
4376
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004377llvm::DINamespace *
Adrian Prantlddb8e062017-05-12 16:23:53 +00004378CGDebugInfo::getOrCreateNamespace(const NamespaceDecl *NSDecl) {
4379 // Don't canonicalize the NamespaceDecl here: The DINamespace will be uniqued
4380 // if necessary, and this way multiple declarations of the same namespace in
4381 // different parent modules stay distinct.
4382 auto I = NamespaceCache.find(NSDecl);
Adrian Prantld8870552017-05-11 22:59:19 +00004383 if (I != NamespaceCache.end())
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004384 return cast<llvm::DINamespace>(I->second);
Eric Christopherb2a008c2013-05-16 00:45:12 +00004385
Adrian Prantl6ec370a2015-09-10 18:39:45 +00004386 llvm::DIScope *Context = getDeclContextDescriptor(NSDecl);
Adrian Prantld8870552017-05-11 22:59:19 +00004387 // Don't trust the context if it is a DIModule (see comment above).
Adrian Prantlddb8e062017-05-12 16:23:53 +00004388 llvm::DINamespace *NS =
4389 DBuilder.createNameSpace(Context, NSDecl->getName(), NSDecl->isInline());
4390 NamespaceCache[NSDecl].reset(NS);
Guy Benyei11169dd2012-12-18 14:30:41 +00004391 return NS;
4392}
4393
Adrian Prantla5206ce2015-09-22 23:26:43 +00004394void CGDebugInfo::setDwoId(uint64_t Signature) {
4395 assert(TheCU && "no main compile unit");
4396 TheCU->setDWOId(Signature);
4397}
4398
Guy Benyei11169dd2012-12-18 14:30:41 +00004399void CGDebugInfo::finalize() {
David Blaikie87dab872014-05-07 16:56:58 +00004400 // Creating types might create further types - invalidating the current
4401 // element and the size(), so don't cache/reference them.
4402 for (size_t i = 0; i != ObjCInterfaceCache.size(); ++i) {
4403 ObjCInterfaceCacheEntry E = ObjCInterfaceCache[i];
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004404 llvm::DIType *Ty = E.Type->getDecl()->getDefinition()
Duncan P. N. Exon Smith497d4d462015-04-11 19:05:04 +00004405 ? CreateTypeDefinition(E.Type, E.Unit)
4406 : E.Decl;
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004407 DBuilder.replaceTemporary(llvm::TempDIType(E.Decl), Ty);
David Blaikie87dab872014-05-07 16:56:58 +00004408 }
4409
Jonas Devlieghered8ba8ae2018-06-27 17:31:59 +00004410 if (CGM.getCodeGenOpts().DwarfVersion >= 5) {
4411 // Add methods to interface.
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004412 for (const auto &P : ObjCMethodCache) {
Jonas Devlieghered8ba8ae2018-06-27 17:31:59 +00004413 if (P.second.empty())
4414 continue;
4415
4416 QualType QTy(P.first->getTypeForDecl(), 0);
4417 auto It = TypeCache.find(QTy.getAsOpaquePtr());
4418 assert(It != TypeCache.end());
4419
4420 llvm::DICompositeType *InterfaceDecl =
4421 cast<llvm::DICompositeType>(It->second);
4422
4423 SmallVector<llvm::Metadata *, 16> EltTys;
4424 auto CurrenetElts = InterfaceDecl->getElements();
4425 EltTys.append(CurrenetElts.begin(), CurrenetElts.end());
4426 for (auto &MD : P.second)
4427 EltTys.push_back(MD);
4428 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
4429 DBuilder.replaceArrays(InterfaceDecl, Elements);
4430 }
4431 }
4432
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004433 for (const auto &P : ReplaceMap) {
4434 assert(P.second);
4435 auto *Ty = cast<llvm::DIType>(P.second);
Duncan P. N. Exon Smith4caa7f22015-04-16 01:00:56 +00004436 assert(Ty->isForwardDecl());
Eric Christopherb2a008c2013-05-16 00:45:12 +00004437
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004438 auto It = TypeCache.find(P.first);
4439 assert(It != TypeCache.end());
4440 assert(It->second);
Adrian Prantl73409ce2013-03-11 18:33:46 +00004441
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004442 DBuilder.replaceTemporary(llvm::TempDIType(Ty),
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004443 cast<llvm::DIType>(It->second));
Guy Benyei11169dd2012-12-18 14:30:41 +00004444 }
Adrian Prantl73409ce2013-03-11 18:33:46 +00004445
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004446 for (const auto &P : FwdDeclReplaceMap) {
4447 assert(P.second);
4448 llvm::TempMDNode FwdDecl(cast<llvm::MDNode>(P.second));
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00004449 llvm::Metadata *Repl;
Frederic Rissd253ed62014-11-18 03:40:51 +00004450
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004451 auto It = DeclCache.find(P.first);
Adrian Prantl97f76852014-12-19 01:02:11 +00004452 // If there has been no definition for the declaration, call RAUW
Frederic Rissd253ed62014-11-18 03:40:51 +00004453 // with ourselves, that will destroy the temporary MDNode and
4454 // replace it with a standard one, avoiding leaking memory.
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004455 if (It == DeclCache.end())
4456 Repl = P.second;
Frederic Rissd253ed62014-11-18 03:40:51 +00004457 else
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004458 Repl = It->second;
Frederic Rissdce60a72014-11-19 18:53:46 +00004459
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004460 if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(Repl))
4461 Repl = GVE->getVariable();
Duncan P. N. Exon Smithd899f6e2015-04-18 00:07:30 +00004462 DBuilder.replaceTemporary(std::move(FwdDecl), cast<llvm::MDNode>(Repl));
Frederic Rissd253ed62014-11-18 03:40:51 +00004463 }
4464
Adrian Prantl73409ce2013-03-11 18:33:46 +00004465 // We keep our own list of retained types, because we need to look
4466 // up the final type in the type cache.
Adrian Prantl3a884fa2015-08-27 22:56:46 +00004467 for (auto &RT : RetainedTypes)
Adrian Prantlad9a195e2015-08-27 21:21:19 +00004468 if (auto MD = TypeCache[RT])
4469 DBuilder.retainType(cast<llvm::DIType>(MD));
Adrian Prantl73409ce2013-03-11 18:33:46 +00004470
Guy Benyei11169dd2012-12-18 14:30:41 +00004471 DBuilder.finalize();
4472}
David Blaikie66088d52014-09-24 17:01:27 +00004473
4474void CGDebugInfo::EmitExplicitCastType(QualType Ty) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00004475 if (CGM.getCodeGenOpts().getDebugInfo() < codegenoptions::LimitedDebugInfo)
David Blaikie66088d52014-09-24 17:01:27 +00004476 return;
Duncan P. N. Exon Smith5043f912015-03-27 22:58:05 +00004477
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00004478 if (auto *DieTy = getOrCreateType(Ty, getOrCreateMainFile()))
Duncan P. N. Exon Smith5043f912015-03-27 22:58:05 +00004479 // Don't ignore in case of explicit cast where it is referenced indirectly.
4480 DBuilder.retainType(DieTy);
David Blaikie66088d52014-09-24 17:01:27 +00004481}
Amara Emerson652795d2016-11-10 14:44:30 +00004482
4483llvm::DebugLoc CGDebugInfo::SourceLocToDebugLoc(SourceLocation Loc) {
4484 if (LexicalBlockStack.empty())
4485 return llvm::DebugLoc();
4486
4487 llvm::MDNode *Scope = LexicalBlockStack.back();
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004488 return llvm::DebugLoc::get(getLineNumber(Loc), getColumnNumber(Loc), Scope);
Amara Emerson652795d2016-11-10 14:44:30 +00004489}
Vedant Kumar5931b4e2018-10-05 20:37:17 +00004490
4491llvm::DINode::DIFlags CGDebugInfo::getCallSiteRelatedAttrs() const {
4492 // Call site-related attributes are only useful in optimized programs, and
4493 // when there's a possibility of debugging backtraces.
4494 if (!CGM.getLangOpts().Optimize || DebugKind == codegenoptions::NoDebugInfo ||
4495 DebugKind == codegenoptions::LocTrackingOnly)
4496 return llvm::DINode::FlagZero;
4497
4498 // Call site-related attributes are available in DWARF v5. Some debuggers,
4499 // while not fully DWARF v5-compliant, may accept these attributes as if they
4500 // were part of DWARF v4.
4501 bool SupportsDWARFv4Ext =
4502 CGM.getCodeGenOpts().DwarfVersion == 4 &&
4503 CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB;
4504 if (!SupportsDWARFv4Ext && CGM.getCodeGenOpts().DwarfVersion < 5)
4505 return llvm::DINode::FlagZero;
4506
4507 return llvm::DINode::FlagAllCallsDescribed;
4508}