Bug Summary

File:clang/lib/Sema/SemaTemplateInstantiate.cpp
Warning:line 903, column 15
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaTemplateInstantiate.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-10/lib/clang/10.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/include -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-10/lib/clang/10.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2019-12-09-002921-48462-1 -x c++ /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp

/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp

1//===------- SemaTemplateInstantiate.cpp - C++ Template Instantiation ------===/
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//===----------------------------------------------------------------------===/
7//
8// This file implements C++ template instantiation.
9//
10//===----------------------------------------------------------------------===/
11
12#include "clang/Sema/SemaInternal.h"
13#include "TreeTransform.h"
14#include "clang/AST/ASTConsumer.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/ASTLambda.h"
17#include "clang/AST/ASTMutationListener.h"
18#include "clang/AST/DeclTemplate.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/PrettyDeclStackTrace.h"
21#include "clang/Basic/LangOptions.h"
22#include "clang/Basic/Stack.h"
23#include "clang/Sema/DeclSpec.h"
24#include "clang/Sema/Initialization.h"
25#include "clang/Sema/Lookup.h"
26#include "clang/Sema/Template.h"
27#include "clang/Sema/TemplateDeduction.h"
28#include "clang/Sema/TemplateInstCallback.h"
29#include "llvm/Support/TimeProfiler.h"
30
31using namespace clang;
32using namespace sema;
33
34//===----------------------------------------------------------------------===/
35// Template Instantiation Support
36//===----------------------------------------------------------------------===/
37
38/// Retrieve the template argument list(s) that should be used to
39/// instantiate the definition of the given declaration.
40///
41/// \param D the declaration for which we are computing template instantiation
42/// arguments.
43///
44/// \param Innermost if non-NULL, the innermost template argument list.
45///
46/// \param RelativeToPrimary true if we should get the template
47/// arguments relative to the primary template, even when we're
48/// dealing with a specialization. This is only relevant for function
49/// template specializations.
50///
51/// \param Pattern If non-NULL, indicates the pattern from which we will be
52/// instantiating the definition of the given declaration, \p D. This is
53/// used to determine the proper set of template instantiation arguments for
54/// friend function template specializations.
55MultiLevelTemplateArgumentList
56Sema::getTemplateInstantiationArgs(NamedDecl *D,
57 const TemplateArgumentList *Innermost,
58 bool RelativeToPrimary,
59 const FunctionDecl *Pattern) {
60 // Accumulate the set of template argument lists in this structure.
61 MultiLevelTemplateArgumentList Result;
62
63 if (Innermost)
64 Result.addOuterTemplateArguments(Innermost);
65
66 DeclContext *Ctx = dyn_cast<DeclContext>(D);
67 if (!Ctx) {
68 Ctx = D->getDeclContext();
69
70 // Add template arguments from a variable template instantiation. For a
71 // class-scope explicit specialization, there are no template arguments
72 // at this level, but there may be enclosing template arguments.
73 VarTemplateSpecializationDecl *Spec =
74 dyn_cast<VarTemplateSpecializationDecl>(D);
75 if (Spec && !Spec->isClassScopeExplicitSpecialization()) {
76 // We're done when we hit an explicit specialization.
77 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
78 !isa<VarTemplatePartialSpecializationDecl>(Spec))
79 return Result;
80
81 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
82
83 // If this variable template specialization was instantiated from a
84 // specialized member that is a variable template, we're done.
85 assert(Spec->getSpecializedTemplate() && "No variable template?")((Spec->getSpecializedTemplate() && "No variable template?"
) ? static_cast<void> (0) : __assert_fail ("Spec->getSpecializedTemplate() && \"No variable template?\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 85, __PRETTY_FUNCTION__))
;
86 llvm::PointerUnion<VarTemplateDecl*,
87 VarTemplatePartialSpecializationDecl*> Specialized
88 = Spec->getSpecializedTemplateOrPartial();
89 if (VarTemplatePartialSpecializationDecl *Partial =
90 Specialized.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
91 if (Partial->isMemberSpecialization())
92 return Result;
93 } else {
94 VarTemplateDecl *Tmpl = Specialized.get<VarTemplateDecl *>();
95 if (Tmpl->isMemberSpecialization())
96 return Result;
97 }
98 }
99
100 // If we have a template template parameter with translation unit context,
101 // then we're performing substitution into a default template argument of
102 // this template template parameter before we've constructed the template
103 // that will own this template template parameter. In this case, we
104 // use empty template parameter lists for all of the outer templates
105 // to avoid performing any substitutions.
106 if (Ctx->isTranslationUnit()) {
107 if (TemplateTemplateParmDecl *TTP
108 = dyn_cast<TemplateTemplateParmDecl>(D)) {
109 for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
110 Result.addOuterTemplateArguments(None);
111 return Result;
112 }
113 }
114 }
115
116 while (!Ctx->isFileContext()) {
117 // Add template arguments from a class template instantiation.
118 ClassTemplateSpecializationDecl *Spec
119 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx);
120 if (Spec && !Spec->isClassScopeExplicitSpecialization()) {
121 // We're done when we hit an explicit specialization.
122 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
123 !isa<ClassTemplatePartialSpecializationDecl>(Spec))
124 break;
125
126 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
127
128 // If this class template specialization was instantiated from a
129 // specialized member that is a class template, we're done.
130 assert(Spec->getSpecializedTemplate() && "No class template?")((Spec->getSpecializedTemplate() && "No class template?"
) ? static_cast<void> (0) : __assert_fail ("Spec->getSpecializedTemplate() && \"No class template?\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 130, __PRETTY_FUNCTION__))
;
131 if (Spec->getSpecializedTemplate()->isMemberSpecialization())
132 break;
133 }
134 // Add template arguments from a function template specialization.
135 else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) {
136 if (!RelativeToPrimary &&
137 Function->getTemplateSpecializationKindForInstantiation() ==
138 TSK_ExplicitSpecialization)
139 break;
140
141 if (const TemplateArgumentList *TemplateArgs
142 = Function->getTemplateSpecializationArgs()) {
143 // Add the template arguments for this specialization.
144 Result.addOuterTemplateArguments(TemplateArgs);
145
146 // If this function was instantiated from a specialized member that is
147 // a function template, we're done.
148 assert(Function->getPrimaryTemplate() && "No function template?")((Function->getPrimaryTemplate() && "No function template?"
) ? static_cast<void> (0) : __assert_fail ("Function->getPrimaryTemplate() && \"No function template?\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 148, __PRETTY_FUNCTION__))
;
149 if (Function->getPrimaryTemplate()->isMemberSpecialization())
150 break;
151
152 // If this function is a generic lambda specialization, we are done.
153 if (isGenericLambdaCallOperatorSpecialization(Function))
154 break;
155
156 } else if (FunctionTemplateDecl *FunTmpl
157 = Function->getDescribedFunctionTemplate()) {
158 // Add the "injected" template arguments.
159 Result.addOuterTemplateArguments(FunTmpl->getInjectedTemplateArgs());
160 }
161
162 // If this is a friend declaration and it declares an entity at
163 // namespace scope, take arguments from its lexical parent
164 // instead of its semantic parent, unless of course the pattern we're
165 // instantiating actually comes from the file's context!
166 if (Function->getFriendObjectKind() &&
167 Function->getDeclContext()->isFileContext() &&
168 (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
169 Ctx = Function->getLexicalDeclContext();
170 RelativeToPrimary = false;
171 continue;
172 }
173 } else if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Ctx)) {
174 if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
175 QualType T = ClassTemplate->getInjectedClassNameSpecialization();
176 const TemplateSpecializationType *TST =
177 cast<TemplateSpecializationType>(Context.getCanonicalType(T));
178 Result.addOuterTemplateArguments(
179 llvm::makeArrayRef(TST->getArgs(), TST->getNumArgs()));
180 if (ClassTemplate->isMemberSpecialization())
181 break;
182 }
183 }
184
185 Ctx = Ctx->getParent();
186 RelativeToPrimary = false;
187 }
188
189 return Result;
190}
191
192bool Sema::CodeSynthesisContext::isInstantiationRecord() const {
193 switch (Kind) {
194 case TemplateInstantiation:
195 case ExceptionSpecInstantiation:
196 case DefaultTemplateArgumentInstantiation:
197 case DefaultFunctionArgumentInstantiation:
198 case ExplicitTemplateArgumentSubstitution:
199 case DeducedTemplateArgumentSubstitution:
200 case PriorTemplateArgumentSubstitution:
201 case ConstraintsCheck:
202 return true;
203
204 case DefaultTemplateArgumentChecking:
205 case DeclaringSpecialMember:
206 case DefiningSynthesizedFunction:
207 case ExceptionSpecEvaluation:
208 case ConstraintSubstitution:
209 case RewritingOperatorAsSpaceship:
210 return false;
211
212 // This function should never be called when Kind's value is Memoization.
213 case Memoization:
214 break;
215 }
216
217 llvm_unreachable("Invalid SynthesisKind!")::llvm::llvm_unreachable_internal("Invalid SynthesisKind!", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 217)
;
218}
219
220Sema::InstantiatingTemplate::InstantiatingTemplate(
221 Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
222 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
223 Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
224 sema::TemplateDeductionInfo *DeductionInfo)
225 : SemaRef(SemaRef) {
226 // Don't allow further instantiation if a fatal error and an uncompilable
227 // error have occurred. Any diagnostics we might have raised will not be
228 // visible, and we do not need to construct a correct AST.
229 if (SemaRef.Diags.hasFatalErrorOccurred() &&
230 SemaRef.Diags.hasUncompilableErrorOccurred()) {
231 Invalid = true;
232 return;
233 }
234 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
235 if (!Invalid) {
236 CodeSynthesisContext Inst;
237 Inst.Kind = Kind;
238 Inst.PointOfInstantiation = PointOfInstantiation;
239 Inst.Entity = Entity;
240 Inst.Template = Template;
241 Inst.TemplateArgs = TemplateArgs.data();
242 Inst.NumTemplateArgs = TemplateArgs.size();
243 Inst.DeductionInfo = DeductionInfo;
244 Inst.InstantiationRange = InstantiationRange;
245 SemaRef.pushCodeSynthesisContext(Inst);
246
247 AlreadyInstantiating =
248 !SemaRef.InstantiatingSpecializations
249 .insert(std::make_pair(Inst.Entity->getCanonicalDecl(), Inst.Kind))
250 .second;
251 atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, Inst);
252 }
253}
254
255Sema::InstantiatingTemplate::InstantiatingTemplate(
256 Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity,
257 SourceRange InstantiationRange)
258 : InstantiatingTemplate(SemaRef,
259 CodeSynthesisContext::TemplateInstantiation,
260 PointOfInstantiation, InstantiationRange, Entity) {}
261
262Sema::InstantiatingTemplate::InstantiatingTemplate(
263 Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity,
264 ExceptionSpecification, SourceRange InstantiationRange)
265 : InstantiatingTemplate(
266 SemaRef, CodeSynthesisContext::ExceptionSpecInstantiation,
267 PointOfInstantiation, InstantiationRange, Entity) {}
268
269Sema::InstantiatingTemplate::InstantiatingTemplate(
270 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param,
271 TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
272 SourceRange InstantiationRange)
273 : InstantiatingTemplate(
274 SemaRef,
275 CodeSynthesisContext::DefaultTemplateArgumentInstantiation,
276 PointOfInstantiation, InstantiationRange, getAsNamedDecl(Param),
277 Template, TemplateArgs) {}
278
279Sema::InstantiatingTemplate::InstantiatingTemplate(
280 Sema &SemaRef, SourceLocation PointOfInstantiation,
281 FunctionTemplateDecl *FunctionTemplate,
282 ArrayRef<TemplateArgument> TemplateArgs,
283 CodeSynthesisContext::SynthesisKind Kind,
284 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
285 : InstantiatingTemplate(SemaRef, Kind, PointOfInstantiation,
286 InstantiationRange, FunctionTemplate, nullptr,
287 TemplateArgs, &DeductionInfo) {
288 assert(((Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution
|| Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution
) ? static_cast<void> (0) : __assert_fail ("Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution || Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 290, __PRETTY_FUNCTION__))
289 Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution ||((Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution
|| Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution
) ? static_cast<void> (0) : __assert_fail ("Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution || Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 290, __PRETTY_FUNCTION__))
290 Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution)((Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution
|| Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution
) ? static_cast<void> (0) : __assert_fail ("Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution || Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 290, __PRETTY_FUNCTION__))
;
291}
292
293Sema::InstantiatingTemplate::InstantiatingTemplate(
294 Sema &SemaRef, SourceLocation PointOfInstantiation,
295 TemplateDecl *Template,
296 ArrayRef<TemplateArgument> TemplateArgs,
297 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
298 : InstantiatingTemplate(
299 SemaRef,
300 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
301 PointOfInstantiation, InstantiationRange, Template, nullptr,
302 TemplateArgs, &DeductionInfo) {}
303
304Sema::InstantiatingTemplate::InstantiatingTemplate(
305 Sema &SemaRef, SourceLocation PointOfInstantiation,
306 ClassTemplatePartialSpecializationDecl *PartialSpec,
307 ArrayRef<TemplateArgument> TemplateArgs,
308 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
309 : InstantiatingTemplate(
310 SemaRef,
311 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
312 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
313 TemplateArgs, &DeductionInfo) {}
314
315Sema::InstantiatingTemplate::InstantiatingTemplate(
316 Sema &SemaRef, SourceLocation PointOfInstantiation,
317 VarTemplatePartialSpecializationDecl *PartialSpec,
318 ArrayRef<TemplateArgument> TemplateArgs,
319 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
320 : InstantiatingTemplate(
321 SemaRef,
322 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
323 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
324 TemplateArgs, &DeductionInfo) {}
325
326Sema::InstantiatingTemplate::InstantiatingTemplate(
327 Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param,
328 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
329 : InstantiatingTemplate(
330 SemaRef,
331 CodeSynthesisContext::DefaultFunctionArgumentInstantiation,
332 PointOfInstantiation, InstantiationRange, Param, nullptr,
333 TemplateArgs) {}
334
335Sema::InstantiatingTemplate::InstantiatingTemplate(
336 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
337 NonTypeTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
338 SourceRange InstantiationRange)
339 : InstantiatingTemplate(
340 SemaRef,
341 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
342 PointOfInstantiation, InstantiationRange, Param, Template,
343 TemplateArgs) {}
344
345Sema::InstantiatingTemplate::InstantiatingTemplate(
346 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
347 TemplateTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
348 SourceRange InstantiationRange)
349 : InstantiatingTemplate(
350 SemaRef,
351 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
352 PointOfInstantiation, InstantiationRange, Param, Template,
353 TemplateArgs) {}
354
355Sema::InstantiatingTemplate::InstantiatingTemplate(
356 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template,
357 NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
358 SourceRange InstantiationRange)
359 : InstantiatingTemplate(
360 SemaRef, CodeSynthesisContext::DefaultTemplateArgumentChecking,
361 PointOfInstantiation, InstantiationRange, Param, Template,
362 TemplateArgs) {}
363
364Sema::InstantiatingTemplate::InstantiatingTemplate(
365 Sema &SemaRef, SourceLocation PointOfInstantiation,
366 ConstraintsCheck, TemplateDecl *Template,
367 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
368 : InstantiatingTemplate(
369 SemaRef, CodeSynthesisContext::ConstraintsCheck,
370 PointOfInstantiation, InstantiationRange, Template, nullptr,
371 TemplateArgs) {}
372
373Sema::InstantiatingTemplate::InstantiatingTemplate(
374 Sema &SemaRef, SourceLocation PointOfInstantiation,
375 ConstraintSubstitution, TemplateDecl *Template,
376 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
377 : InstantiatingTemplate(
378 SemaRef, CodeSynthesisContext::ConstraintSubstitution,
379 PointOfInstantiation, InstantiationRange, Template, nullptr,
380 {}, &DeductionInfo) {}
381
382void Sema::pushCodeSynthesisContext(CodeSynthesisContext Ctx) {
383 Ctx.SavedInNonInstantiationSFINAEContext = InNonInstantiationSFINAEContext;
384 InNonInstantiationSFINAEContext = false;
385
386 CodeSynthesisContexts.push_back(Ctx);
387
388 if (!Ctx.isInstantiationRecord())
389 ++NonInstantiationEntries;
390
391 // Check to see if we're low on stack space. We can't do anything about this
392 // from here, but we can at least warn the user.
393 if (isStackNearlyExhausted())
394 warnStackExhausted(Ctx.PointOfInstantiation);
395}
396
397void Sema::popCodeSynthesisContext() {
398 auto &Active = CodeSynthesisContexts.back();
399 if (!Active.isInstantiationRecord()) {
400 assert(NonInstantiationEntries > 0)((NonInstantiationEntries > 0) ? static_cast<void> (
0) : __assert_fail ("NonInstantiationEntries > 0", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 400, __PRETTY_FUNCTION__))
;
401 --NonInstantiationEntries;
402 }
403
404 InNonInstantiationSFINAEContext = Active.SavedInNonInstantiationSFINAEContext;
405
406 // Name lookup no longer looks in this template's defining module.
407 assert(CodeSynthesisContexts.size() >=((CodeSynthesisContexts.size() >= CodeSynthesisContextLookupModules
.size() && "forgot to remove a lookup module for a template instantiation"
) ? static_cast<void> (0) : __assert_fail ("CodeSynthesisContexts.size() >= CodeSynthesisContextLookupModules.size() && \"forgot to remove a lookup module for a template instantiation\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 409, __PRETTY_FUNCTION__))
408 CodeSynthesisContextLookupModules.size() &&((CodeSynthesisContexts.size() >= CodeSynthesisContextLookupModules
.size() && "forgot to remove a lookup module for a template instantiation"
) ? static_cast<void> (0) : __assert_fail ("CodeSynthesisContexts.size() >= CodeSynthesisContextLookupModules.size() && \"forgot to remove a lookup module for a template instantiation\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 409, __PRETTY_FUNCTION__))
409 "forgot to remove a lookup module for a template instantiation")((CodeSynthesisContexts.size() >= CodeSynthesisContextLookupModules
.size() && "forgot to remove a lookup module for a template instantiation"
) ? static_cast<void> (0) : __assert_fail ("CodeSynthesisContexts.size() >= CodeSynthesisContextLookupModules.size() && \"forgot to remove a lookup module for a template instantiation\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 409, __PRETTY_FUNCTION__))
;
410 if (CodeSynthesisContexts.size() ==
411 CodeSynthesisContextLookupModules.size()) {
412 if (Module *M = CodeSynthesisContextLookupModules.back())
413 LookupModulesCache.erase(M);
414 CodeSynthesisContextLookupModules.pop_back();
415 }
416
417 // If we've left the code synthesis context for the current context stack,
418 // stop remembering that we've emitted that stack.
419 if (CodeSynthesisContexts.size() ==
420 LastEmittedCodeSynthesisContextDepth)
421 LastEmittedCodeSynthesisContextDepth = 0;
422
423 CodeSynthesisContexts.pop_back();
424}
425
426void Sema::InstantiatingTemplate::Clear() {
427 if (!Invalid) {
428 if (!AlreadyInstantiating) {
429 auto &Active = SemaRef.CodeSynthesisContexts.back();
430 SemaRef.InstantiatingSpecializations.erase(
431 std::make_pair(Active.Entity, Active.Kind));
432 }
433
434 atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef,
435 SemaRef.CodeSynthesisContexts.back());
436
437 SemaRef.popCodeSynthesisContext();
438 Invalid = true;
439 }
440}
441
442bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
443 SourceLocation PointOfInstantiation,
444 SourceRange InstantiationRange) {
445 assert(SemaRef.NonInstantiationEntries <=((SemaRef.NonInstantiationEntries <= SemaRef.CodeSynthesisContexts
.size()) ? static_cast<void> (0) : __assert_fail ("SemaRef.NonInstantiationEntries <= SemaRef.CodeSynthesisContexts.size()"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 446, __PRETTY_FUNCTION__))
446 SemaRef.CodeSynthesisContexts.size())((SemaRef.NonInstantiationEntries <= SemaRef.CodeSynthesisContexts
.size()) ? static_cast<void> (0) : __assert_fail ("SemaRef.NonInstantiationEntries <= SemaRef.CodeSynthesisContexts.size()"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 446, __PRETTY_FUNCTION__))
;
447 if ((SemaRef.CodeSynthesisContexts.size() -
448 SemaRef.NonInstantiationEntries)
449 <= SemaRef.getLangOpts().InstantiationDepth)
450 return false;
451
452 SemaRef.Diag(PointOfInstantiation,
453 diag::err_template_recursion_depth_exceeded)
454 << SemaRef.getLangOpts().InstantiationDepth
455 << InstantiationRange;
456 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
457 << SemaRef.getLangOpts().InstantiationDepth;
458 return true;
459}
460
461/// Prints the current instantiation stack through a series of
462/// notes.
463void Sema::PrintInstantiationStack() {
464 // Determine which template instantiations to skip, if any.
465 unsigned SkipStart = CodeSynthesisContexts.size(), SkipEnd = SkipStart;
466 unsigned Limit = Diags.getTemplateBacktraceLimit();
467 if (Limit && Limit < CodeSynthesisContexts.size()) {
468 SkipStart = Limit / 2 + Limit % 2;
469 SkipEnd = CodeSynthesisContexts.size() - Limit / 2;
470 }
471
472 // FIXME: In all of these cases, we need to show the template arguments
473 unsigned InstantiationIdx = 0;
474 for (SmallVectorImpl<CodeSynthesisContext>::reverse_iterator
475 Active = CodeSynthesisContexts.rbegin(),
476 ActiveEnd = CodeSynthesisContexts.rend();
477 Active != ActiveEnd;
478 ++Active, ++InstantiationIdx) {
479 // Skip this instantiation?
480 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
481 if (InstantiationIdx == SkipStart) {
482 // Note that we're skipping instantiations.
483 Diags.Report(Active->PointOfInstantiation,
484 diag::note_instantiation_contexts_suppressed)
485 << unsigned(CodeSynthesisContexts.size() - Limit);
486 }
487 continue;
488 }
489
490 switch (Active->Kind) {
491 case CodeSynthesisContext::TemplateInstantiation: {
492 Decl *D = Active->Entity;
493 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
494 unsigned DiagID = diag::note_template_member_class_here;
495 if (isa<ClassTemplateSpecializationDecl>(Record))
496 DiagID = diag::note_template_class_instantiation_here;
497 Diags.Report(Active->PointOfInstantiation, DiagID)
498 << Record << Active->InstantiationRange;
499 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
500 unsigned DiagID;
501 if (Function->getPrimaryTemplate())
502 DiagID = diag::note_function_template_spec_here;
503 else
504 DiagID = diag::note_template_member_function_here;
505 Diags.Report(Active->PointOfInstantiation, DiagID)
506 << Function
507 << Active->InstantiationRange;
508 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
509 Diags.Report(Active->PointOfInstantiation,
510 VD->isStaticDataMember()?
511 diag::note_template_static_data_member_def_here
512 : diag::note_template_variable_def_here)
513 << VD
514 << Active->InstantiationRange;
515 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
516 Diags.Report(Active->PointOfInstantiation,
517 diag::note_template_enum_def_here)
518 << ED
519 << Active->InstantiationRange;
520 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
521 Diags.Report(Active->PointOfInstantiation,
522 diag::note_template_nsdmi_here)
523 << FD << Active->InstantiationRange;
524 } else {
525 Diags.Report(Active->PointOfInstantiation,
526 diag::note_template_type_alias_instantiation_here)
527 << cast<TypeAliasTemplateDecl>(D)
528 << Active->InstantiationRange;
529 }
530 break;
531 }
532
533 case CodeSynthesisContext::DefaultTemplateArgumentInstantiation: {
534 TemplateDecl *Template = cast<TemplateDecl>(Active->Template);
535 SmallVector<char, 128> TemplateArgsStr;
536 llvm::raw_svector_ostream OS(TemplateArgsStr);
537 Template->printName(OS);
538 printTemplateArgumentList(OS, Active->template_arguments(),
539 getPrintingPolicy());
540 Diags.Report(Active->PointOfInstantiation,
541 diag::note_default_arg_instantiation_here)
542 << OS.str()
543 << Active->InstantiationRange;
544 break;
545 }
546
547 case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution: {
548 FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
549 Diags.Report(Active->PointOfInstantiation,
550 diag::note_explicit_template_arg_substitution_here)
551 << FnTmpl
552 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
553 Active->TemplateArgs,
554 Active->NumTemplateArgs)
555 << Active->InstantiationRange;
556 break;
557 }
558
559 case CodeSynthesisContext::DeducedTemplateArgumentSubstitution: {
560 if (FunctionTemplateDecl *FnTmpl =
561 dyn_cast<FunctionTemplateDecl>(Active->Entity)) {
562 Diags.Report(Active->PointOfInstantiation,
563 diag::note_function_template_deduction_instantiation_here)
564 << FnTmpl
565 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
566 Active->TemplateArgs,
567 Active->NumTemplateArgs)
568 << Active->InstantiationRange;
569 } else {
570 bool IsVar = isa<VarTemplateDecl>(Active->Entity) ||
571 isa<VarTemplateSpecializationDecl>(Active->Entity);
572 bool IsTemplate = false;
573 TemplateParameterList *Params;
574 if (auto *D = dyn_cast<TemplateDecl>(Active->Entity)) {
575 IsTemplate = true;
576 Params = D->getTemplateParameters();
577 } else if (auto *D = dyn_cast<ClassTemplatePartialSpecializationDecl>(
578 Active->Entity)) {
579 Params = D->getTemplateParameters();
580 } else if (auto *D = dyn_cast<VarTemplatePartialSpecializationDecl>(
581 Active->Entity)) {
582 Params = D->getTemplateParameters();
583 } else {
584 llvm_unreachable("unexpected template kind")::llvm::llvm_unreachable_internal("unexpected template kind",
"/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 584)
;
585 }
586
587 Diags.Report(Active->PointOfInstantiation,
588 diag::note_deduced_template_arg_substitution_here)
589 << IsVar << IsTemplate << cast<NamedDecl>(Active->Entity)
590 << getTemplateArgumentBindingsText(Params, Active->TemplateArgs,
591 Active->NumTemplateArgs)
592 << Active->InstantiationRange;
593 }
594 break;
595 }
596
597 case CodeSynthesisContext::DefaultFunctionArgumentInstantiation: {
598 ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
599 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
600
601 SmallVector<char, 128> TemplateArgsStr;
602 llvm::raw_svector_ostream OS(TemplateArgsStr);
603 FD->printName(OS);
604 printTemplateArgumentList(OS, Active->template_arguments(),
605 getPrintingPolicy());
606 Diags.Report(Active->PointOfInstantiation,
607 diag::note_default_function_arg_instantiation_here)
608 << OS.str()
609 << Active->InstantiationRange;
610 break;
611 }
612
613 case CodeSynthesisContext::PriorTemplateArgumentSubstitution: {
614 NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
615 std::string Name;
616 if (!Parm->getName().empty())
617 Name = std::string(" '") + Parm->getName().str() + "'";
618
619 TemplateParameterList *TemplateParams = nullptr;
620 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
621 TemplateParams = Template->getTemplateParameters();
622 else
623 TemplateParams =
624 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
625 ->getTemplateParameters();
626 Diags.Report(Active->PointOfInstantiation,
627 diag::note_prior_template_arg_substitution)
628 << isa<TemplateTemplateParmDecl>(Parm)
629 << Name
630 << getTemplateArgumentBindingsText(TemplateParams,
631 Active->TemplateArgs,
632 Active->NumTemplateArgs)
633 << Active->InstantiationRange;
634 break;
635 }
636
637 case CodeSynthesisContext::DefaultTemplateArgumentChecking: {
638 TemplateParameterList *TemplateParams = nullptr;
639 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
640 TemplateParams = Template->getTemplateParameters();
641 else
642 TemplateParams =
643 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
644 ->getTemplateParameters();
645
646 Diags.Report(Active->PointOfInstantiation,
647 diag::note_template_default_arg_checking)
648 << getTemplateArgumentBindingsText(TemplateParams,
649 Active->TemplateArgs,
650 Active->NumTemplateArgs)
651 << Active->InstantiationRange;
652 break;
653 }
654
655 case CodeSynthesisContext::ExceptionSpecEvaluation:
656 Diags.Report(Active->PointOfInstantiation,
657 diag::note_evaluating_exception_spec_here)
658 << cast<FunctionDecl>(Active->Entity);
659 break;
660
661 case CodeSynthesisContext::ExceptionSpecInstantiation:
662 Diags.Report(Active->PointOfInstantiation,
663 diag::note_template_exception_spec_instantiation_here)
664 << cast<FunctionDecl>(Active->Entity)
665 << Active->InstantiationRange;
666 break;
667
668 case CodeSynthesisContext::DeclaringSpecialMember:
669 Diags.Report(Active->PointOfInstantiation,
670 diag::note_in_declaration_of_implicit_special_member)
671 << cast<CXXRecordDecl>(Active->Entity) << Active->SpecialMember;
672 break;
673
674 case CodeSynthesisContext::DefiningSynthesizedFunction: {
675 // FIXME: For synthesized members other than special members, produce a note.
676 auto *MD = dyn_cast<CXXMethodDecl>(Active->Entity);
677 auto CSM = MD ? getSpecialMember(MD) : CXXInvalid;
678 if (CSM != CXXInvalid) {
679 Diags.Report(Active->PointOfInstantiation,
680 diag::note_member_synthesized_at)
681 << CSM << Context.getTagDeclType(MD->getParent());
682 }
683 break;
684 }
685
686 case CodeSynthesisContext::RewritingOperatorAsSpaceship:
687 Diags.Report(Active->Entity->getLocation(),
688 diag::note_rewriting_operator_as_spaceship);
689 break;
690
691 case CodeSynthesisContext::Memoization:
692 break;
693
694 case CodeSynthesisContext::ConstraintsCheck:
695 if (auto *CD = dyn_cast<ConceptDecl>(Active->Entity)) {
696 SmallVector<char, 128> TemplateArgsStr;
697 llvm::raw_svector_ostream OS(TemplateArgsStr);
698 CD->printName(OS);
699 printTemplateArgumentList(OS, Active->template_arguments(),
700 getPrintingPolicy());
701 Diags.Report(Active->PointOfInstantiation,
702 diag::note_concept_specialization_here)
703 << OS.str()
704 << Active->InstantiationRange;
705 break;
706 }
707 // TODO: Concepts - implement this for constrained templates and partial
708 // specializations.
709 llvm_unreachable("only concept constraints are supported right now")::llvm::llvm_unreachable_internal("only concept constraints are supported right now"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 709)
;
710 break;
711
712 case CodeSynthesisContext::ConstraintSubstitution:
713 Diags.Report(Active->PointOfInstantiation,
714 diag::note_constraint_substitution_here)
715 << Active->InstantiationRange;
716 break;
717 }
718 }
719}
720
721Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
722 if (InNonInstantiationSFINAEContext)
723 return Optional<TemplateDeductionInfo *>(nullptr);
724
725 for (SmallVectorImpl<CodeSynthesisContext>::const_reverse_iterator
726 Active = CodeSynthesisContexts.rbegin(),
727 ActiveEnd = CodeSynthesisContexts.rend();
728 Active != ActiveEnd;
729 ++Active)
730 {
731 switch (Active->Kind) {
732 case CodeSynthesisContext::TemplateInstantiation:
733 // An instantiation of an alias template may or may not be a SFINAE
734 // context, depending on what else is on the stack.
735 if (isa<TypeAliasTemplateDecl>(Active->Entity))
736 break;
737 LLVM_FALLTHROUGH[[gnu::fallthrough]];
738 case CodeSynthesisContext::DefaultFunctionArgumentInstantiation:
739 case CodeSynthesisContext::ExceptionSpecInstantiation:
740 case CodeSynthesisContext::ConstraintsCheck:
741 // This is a template instantiation, so there is no SFINAE.
742 return None;
743
744 case CodeSynthesisContext::DefaultTemplateArgumentInstantiation:
745 case CodeSynthesisContext::PriorTemplateArgumentSubstitution:
746 case CodeSynthesisContext::DefaultTemplateArgumentChecking:
747 // A default template argument instantiation and substitution into
748 // template parameters with arguments for prior parameters may or may
749 // not be a SFINAE context; look further up the stack.
750 break;
751
752 case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution:
753 case CodeSynthesisContext::DeducedTemplateArgumentSubstitution:
754 case CodeSynthesisContext::ConstraintSubstitution:
755 // We're either substituting explicitly-specified template arguments
756 // or deduced template arguments or a constraint expression, so SFINAE
757 // applies.
758 assert(Active->DeductionInfo && "Missing deduction info pointer")((Active->DeductionInfo && "Missing deduction info pointer"
) ? static_cast<void> (0) : __assert_fail ("Active->DeductionInfo && \"Missing deduction info pointer\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 758, __PRETTY_FUNCTION__))
;
759 return Active->DeductionInfo;
760
761 case CodeSynthesisContext::DeclaringSpecialMember:
762 case CodeSynthesisContext::DefiningSynthesizedFunction:
763 case CodeSynthesisContext::RewritingOperatorAsSpaceship:
764 // This happens in a context unrelated to template instantiation, so
765 // there is no SFINAE.
766 return None;
767
768 case CodeSynthesisContext::ExceptionSpecEvaluation:
769 // FIXME: This should not be treated as a SFINAE context, because
770 // we will cache an incorrect exception specification. However, clang
771 // bootstrap relies this! See PR31692.
772 break;
773
774 case CodeSynthesisContext::Memoization:
775 break;
776 }
777
778 // The inner context was transparent for SFINAE. If it occurred within a
779 // non-instantiation SFINAE context, then SFINAE applies.
780 if (Active->SavedInNonInstantiationSFINAEContext)
781 return Optional<TemplateDeductionInfo *>(nullptr);
782 }
783
784 return None;
785}
786
787//===----------------------------------------------------------------------===/
788// Template Instantiation for Types
789//===----------------------------------------------------------------------===/
790namespace {
791 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
792 const MultiLevelTemplateArgumentList &TemplateArgs;
793 SourceLocation Loc;
794 DeclarationName Entity;
795
796 public:
797 typedef TreeTransform<TemplateInstantiator> inherited;
798
799 TemplateInstantiator(Sema &SemaRef,
800 const MultiLevelTemplateArgumentList &TemplateArgs,
801 SourceLocation Loc,
802 DeclarationName Entity)
803 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
804 Entity(Entity) { }
805
806 /// Determine whether the given type \p T has already been
807 /// transformed.
808 ///
809 /// For the purposes of template instantiation, a type has already been
810 /// transformed if it is NULL or if it is not dependent.
811 bool AlreadyTransformed(QualType T);
812
813 /// Returns the location of the entity being instantiated, if known.
814 SourceLocation getBaseLocation() { return Loc; }
815
816 /// Returns the name of the entity being instantiated, if any.
817 DeclarationName getBaseEntity() { return Entity; }
818
819 /// Sets the "base" location and entity when that
820 /// information is known based on another transformation.
821 void setBase(SourceLocation Loc, DeclarationName Entity) {
822 this->Loc = Loc;
823 this->Entity = Entity;
824 }
825
826 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
827 SourceRange PatternRange,
828 ArrayRef<UnexpandedParameterPack> Unexpanded,
829 bool &ShouldExpand, bool &RetainExpansion,
830 Optional<unsigned> &NumExpansions) {
831 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
832 PatternRange, Unexpanded,
833 TemplateArgs,
834 ShouldExpand,
835 RetainExpansion,
836 NumExpansions);
837 }
838
839 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
840 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
841 }
842
843 TemplateArgument ForgetPartiallySubstitutedPack() {
844 TemplateArgument Result;
845 if (NamedDecl *PartialPack
846 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
847 MultiLevelTemplateArgumentList &TemplateArgs
848 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
849 unsigned Depth, Index;
850 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
851 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
852 Result = TemplateArgs(Depth, Index);
853 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
854 }
855 }
856
857 return Result;
858 }
859
860 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
861 if (Arg.isNull())
862 return;
863
864 if (NamedDecl *PartialPack
865 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
866 MultiLevelTemplateArgumentList &TemplateArgs
867 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
868 unsigned Depth, Index;
869 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
870 TemplateArgs.setArgument(Depth, Index, Arg);
871 }
872 }
873
874 /// Transform the given declaration by instantiating a reference to
875 /// this declaration.
876 Decl *TransformDecl(SourceLocation Loc, Decl *D);
877
878 void transformAttrs(Decl *Old, Decl *New) {
879 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
880 }
881
882 void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> NewDecls) {
883 if (Old->isParameterPack()) {
1
Assuming the condition is false
2
Taking false branch
884 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Old);
885 for (auto *New : NewDecls)
886 SemaRef.CurrentInstantiationScope->InstantiatedLocalPackArg(
887 Old, cast<VarDecl>(New));
888 return;
889 }
890
891 assert(NewDecls.size() == 1 &&((NewDecls.size() == 1 && "should only have multiple expansions for a pack"
) ? static_cast<void> (0) : __assert_fail ("NewDecls.size() == 1 && \"should only have multiple expansions for a pack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 892, __PRETTY_FUNCTION__))
3
Assuming the condition is true
4
'?' condition is true
892 "should only have multiple expansions for a pack")((NewDecls.size() == 1 && "should only have multiple expansions for a pack"
) ? static_cast<void> (0) : __assert_fail ("NewDecls.size() == 1 && \"should only have multiple expansions for a pack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 892, __PRETTY_FUNCTION__))
;
893 Decl *New = NewDecls.front();
894
895 // If we've instantiated the call operator of a lambda or the call
896 // operator template of a generic lambda, update the "instantiation of"
897 // information.
898 auto *NewMD = dyn_cast<CXXMethodDecl>(New);
5
Assuming 'New' is a 'CXXMethodDecl'
899 if (NewMD
5.1
'NewMD' is non-null
5.1
'NewMD' is non-null
5.1
'NewMD' is non-null
&& isLambdaCallOperator(NewMD)) {
6
Calling 'isLambdaCallOperator'
15
Returning from 'isLambdaCallOperator'
16
Taking true branch
900 auto *OldMD = dyn_cast<CXXMethodDecl>(Old);
17
Assuming 'Old' is not a 'CXXMethodDecl'
18
'OldMD' initialized to a null pointer value
901 if (auto *NewTD = NewMD->getDescribedFunctionTemplate())
19
Assuming 'NewTD' is non-null
20
Taking true branch
902 NewTD->setInstantiatedFromMemberTemplate(
903 OldMD->getDescribedFunctionTemplate());
21
Called C++ object pointer is null
904 else
905 NewMD->setInstantiationOfMemberFunction(OldMD,
906 TSK_ImplicitInstantiation);
907 }
908
909 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);
910
911 // We recreated a local declaration, but not by instantiating it. There
912 // may be pending dependent diagnostics to produce.
913 if (auto *DC = dyn_cast<DeclContext>(Old))
914 SemaRef.PerformDependentDiagnostics(DC, TemplateArgs);
915 }
916
917 /// Transform the definition of the given declaration by
918 /// instantiating it.
919 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
920
921 /// Transform the first qualifier within a scope by instantiating the
922 /// declaration.
923 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
924
925 /// Rebuild the exception declaration and register the declaration
926 /// as an instantiated local.
927 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
928 TypeSourceInfo *Declarator,
929 SourceLocation StartLoc,
930 SourceLocation NameLoc,
931 IdentifierInfo *Name);
932
933 /// Rebuild the Objective-C exception declaration and register the
934 /// declaration as an instantiated local.
935 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
936 TypeSourceInfo *TSInfo, QualType T);
937
938 /// Check for tag mismatches when instantiating an
939 /// elaborated type.
940 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
941 ElaboratedTypeKeyword Keyword,
942 NestedNameSpecifierLoc QualifierLoc,
943 QualType T);
944
945 TemplateName
946 TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
947 SourceLocation NameLoc,
948 QualType ObjectType = QualType(),
949 NamedDecl *FirstQualifierInScope = nullptr,
950 bool AllowInjectedClassName = false);
951
952 const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
953
954 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
955 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
956 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
957
958 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
959 NonTypeTemplateParmDecl *D);
960 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
961 SubstNonTypeTemplateParmPackExpr *E);
962
963 /// Rebuild a DeclRefExpr for a VarDecl reference.
964 ExprResult RebuildVarDeclRefExpr(VarDecl *PD, SourceLocation Loc);
965
966 /// Transform a reference to a function or init-capture parameter pack.
967 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E, VarDecl *PD);
968
969 /// Transform a FunctionParmPackExpr which was built when we couldn't
970 /// expand a function parameter pack reference which refers to an expanded
971 /// pack.
972 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
973
974 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
975 FunctionProtoTypeLoc TL) {
976 // Call the base version; it will forward to our overridden version below.
977 return inherited::TransformFunctionProtoType(TLB, TL);
978 }
979
980 template<typename Fn>
981 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
982 FunctionProtoTypeLoc TL,
983 CXXRecordDecl *ThisContext,
984 Qualifiers ThisTypeQuals,
985 Fn TransformExceptionSpec);
986
987 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
988 int indexAdjustment,
989 Optional<unsigned> NumExpansions,
990 bool ExpectParameterPack);
991
992 /// Transforms a template type parameter type by performing
993 /// substitution of the corresponding template type argument.
994 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
995 TemplateTypeParmTypeLoc TL);
996
997 /// Transforms an already-substituted template type parameter pack
998 /// into either itself (if we aren't substituting into its pack expansion)
999 /// or the appropriate substituted argument.
1000 QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
1001 SubstTemplateTypeParmPackTypeLoc TL);
1002
1003 ExprResult TransformLambdaExpr(LambdaExpr *E) {
1004 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1005 return TreeTransform<TemplateInstantiator>::TransformLambdaExpr(E);
1006 }
1007
1008 TemplateParameterList *TransformTemplateParameterList(
1009 TemplateParameterList *OrigTPL) {
1010 if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
1011
1012 DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
1013 TemplateDeclInstantiator DeclInstantiator(getSema(),
1014 /* DeclContext *Owner */ Owner, TemplateArgs);
1015 return DeclInstantiator.SubstTemplateParams(OrigTPL);
1016 }
1017 private:
1018 ExprResult transformNonTypeTemplateParmRef(NonTypeTemplateParmDecl *parm,
1019 SourceLocation loc,
1020 TemplateArgument arg);
1021 };
1022}
1023
1024bool TemplateInstantiator::AlreadyTransformed(QualType T) {
1025 if (T.isNull())
1026 return true;
1027
1028 if (T->isInstantiationDependentType() || T->isVariablyModifiedType())
1029 return false;
1030
1031 getSema().MarkDeclarationsReferencedInType(Loc, T);
1032 return true;
1033}
1034
1035static TemplateArgument
1036getPackSubstitutedTemplateArgument(Sema &S, TemplateArgument Arg) {
1037 assert(S.ArgumentPackSubstitutionIndex >= 0)((S.ArgumentPackSubstitutionIndex >= 0) ? static_cast<void
> (0) : __assert_fail ("S.ArgumentPackSubstitutionIndex >= 0"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1037, __PRETTY_FUNCTION__))
;
1038 assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size())((S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size()) ?
static_cast<void> (0) : __assert_fail ("S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size()"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1038, __PRETTY_FUNCTION__))
;
1039 Arg = Arg.pack_begin()[S.ArgumentPackSubstitutionIndex];
1040 if (Arg.isPackExpansion())
1041 Arg = Arg.getPackExpansionPattern();
1042 return Arg;
1043}
1044
1045Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
1046 if (!D)
1047 return nullptr;
1048
1049 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
1050 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1051 // If the corresponding template argument is NULL or non-existent, it's
1052 // because we are performing instantiation from explicitly-specified
1053 // template arguments in a function template, but there were some
1054 // arguments left unspecified.
1055 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1056 TTP->getPosition()))
1057 return D;
1058
1059 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1060
1061 if (TTP->isParameterPack()) {
1062 assert(Arg.getKind() == TemplateArgument::Pack &&((Arg.getKind() == TemplateArgument::Pack && "Missing argument pack"
) ? static_cast<void> (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1063, __PRETTY_FUNCTION__))
1063 "Missing argument pack")((Arg.getKind() == TemplateArgument::Pack && "Missing argument pack"
) ? static_cast<void> (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1063, __PRETTY_FUNCTION__))
;
1064 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1065 }
1066
1067 TemplateName Template = Arg.getAsTemplate().getNameToSubstitute();
1068 assert(!Template.isNull() && Template.getAsTemplateDecl() &&((!Template.isNull() && Template.getAsTemplateDecl() &&
"Wrong kind of template template argument") ? static_cast<
void> (0) : __assert_fail ("!Template.isNull() && Template.getAsTemplateDecl() && \"Wrong kind of template template argument\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1069, __PRETTY_FUNCTION__))
1069 "Wrong kind of template template argument")((!Template.isNull() && Template.getAsTemplateDecl() &&
"Wrong kind of template template argument") ? static_cast<
void> (0) : __assert_fail ("!Template.isNull() && Template.getAsTemplateDecl() && \"Wrong kind of template template argument\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1069, __PRETTY_FUNCTION__))
;
1070 return Template.getAsTemplateDecl();
1071 }
1072
1073 // Fall through to find the instantiated declaration for this template
1074 // template parameter.
1075 }
1076
1077 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
1078}
1079
1080Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
1081 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
1082 if (!Inst)
1083 return nullptr;
1084
1085 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1086 return Inst;
1087}
1088
1089NamedDecl *
1090TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
1091 SourceLocation Loc) {
1092 // If the first part of the nested-name-specifier was a template type
1093 // parameter, instantiate that type parameter down to a tag type.
1094 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
1095 const TemplateTypeParmType *TTP
1096 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
1097
1098 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1099 // FIXME: This needs testing w/ member access expressions.
1100 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
1101
1102 if (TTP->isParameterPack()) {
1103 assert(Arg.getKind() == TemplateArgument::Pack &&((Arg.getKind() == TemplateArgument::Pack && "Missing argument pack"
) ? static_cast<void> (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1104, __PRETTY_FUNCTION__))
1104 "Missing argument pack")((Arg.getKind() == TemplateArgument::Pack && "Missing argument pack"
) ? static_cast<void> (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1104, __PRETTY_FUNCTION__))
;
1105
1106 if (getSema().ArgumentPackSubstitutionIndex == -1)
1107 return nullptr;
1108
1109 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1110 }
1111
1112 QualType T = Arg.getAsType();
1113 if (T.isNull())
1114 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1115
1116 if (const TagType *Tag = T->getAs<TagType>())
1117 return Tag->getDecl();
1118
1119 // The resulting type is not a tag; complain.
1120 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
1121 return nullptr;
1122 }
1123 }
1124
1125 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1126}
1127
1128VarDecl *
1129TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
1130 TypeSourceInfo *Declarator,
1131 SourceLocation StartLoc,
1132 SourceLocation NameLoc,
1133 IdentifierInfo *Name) {
1134 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
1135 StartLoc, NameLoc, Name);
1136 if (Var)
1137 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1138 return Var;
1139}
1140
1141VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1142 TypeSourceInfo *TSInfo,
1143 QualType T) {
1144 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
1145 if (Var)
1146 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1147 return Var;
1148}
1149
1150QualType
1151TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
1152 ElaboratedTypeKeyword Keyword,
1153 NestedNameSpecifierLoc QualifierLoc,
1154 QualType T) {
1155 if (const TagType *TT = T->getAs<TagType>()) {
1156 TagDecl* TD = TT->getDecl();
1157
1158 SourceLocation TagLocation = KeywordLoc;
1159
1160 IdentifierInfo *Id = TD->getIdentifier();
1161
1162 // TODO: should we even warn on struct/class mismatches for this? Seems
1163 // like it's likely to produce a lot of spurious errors.
1164 if (Id && Keyword != ETK_None && Keyword != ETK_Typename) {
1165 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
1166 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
1167 TagLocation, Id)) {
1168 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
1169 << Id
1170 << FixItHint::CreateReplacement(SourceRange(TagLocation),
1171 TD->getKindName());
1172 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
1173 }
1174 }
1175 }
1176
1177 return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(KeywordLoc,
1178 Keyword,
1179 QualifierLoc,
1180 T);
1181}
1182
1183TemplateName TemplateInstantiator::TransformTemplateName(
1184 CXXScopeSpec &SS, TemplateName Name, SourceLocation NameLoc,
1185 QualType ObjectType, NamedDecl *FirstQualifierInScope,
1186 bool AllowInjectedClassName) {
1187 if (TemplateTemplateParmDecl *TTP
1188 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
1189 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1190 // If the corresponding template argument is NULL or non-existent, it's
1191 // because we are performing instantiation from explicitly-specified
1192 // template arguments in a function template, but there were some
1193 // arguments left unspecified.
1194 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1195 TTP->getPosition()))
1196 return Name;
1197
1198 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1199
1200 if (TTP->isParameterPack()) {
1201 assert(Arg.getKind() == TemplateArgument::Pack &&((Arg.getKind() == TemplateArgument::Pack && "Missing argument pack"
) ? static_cast<void> (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1202, __PRETTY_FUNCTION__))
1202 "Missing argument pack")((Arg.getKind() == TemplateArgument::Pack && "Missing argument pack"
) ? static_cast<void> (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1202, __PRETTY_FUNCTION__))
;
1203
1204 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1205 // We have the template argument pack to substitute, but we're not
1206 // actually expanding the enclosing pack expansion yet. So, just
1207 // keep the entire argument pack.
1208 return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg);
1209 }
1210
1211 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1212 }
1213
1214 TemplateName Template = Arg.getAsTemplate().getNameToSubstitute();
1215 assert(!Template.isNull() && "Null template template argument")((!Template.isNull() && "Null template template argument"
) ? static_cast<void> (0) : __assert_fail ("!Template.isNull() && \"Null template template argument\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1215, __PRETTY_FUNCTION__))
;
1216 assert(!Template.getAsQualifiedTemplateName() &&((!Template.getAsQualifiedTemplateName() && "template decl to substitute is qualified?"
) ? static_cast<void> (0) : __assert_fail ("!Template.getAsQualifiedTemplateName() && \"template decl to substitute is qualified?\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1217, __PRETTY_FUNCTION__))
1217 "template decl to substitute is qualified?")((!Template.getAsQualifiedTemplateName() && "template decl to substitute is qualified?"
) ? static_cast<void> (0) : __assert_fail ("!Template.getAsQualifiedTemplateName() && \"template decl to substitute is qualified?\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1217, __PRETTY_FUNCTION__))
;
1218
1219 Template = getSema().Context.getSubstTemplateTemplateParm(TTP, Template);
1220 return Template;
1221 }
1222 }
1223
1224 if (SubstTemplateTemplateParmPackStorage *SubstPack
1225 = Name.getAsSubstTemplateTemplateParmPack()) {
1226 if (getSema().ArgumentPackSubstitutionIndex == -1)
1227 return Name;
1228
1229 TemplateArgument Arg = SubstPack->getArgumentPack();
1230 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1231 return Arg.getAsTemplate().getNameToSubstitute();
1232 }
1233
1234 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
1235 FirstQualifierInScope,
1236 AllowInjectedClassName);
1237}
1238
1239ExprResult
1240TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
1241 if (!E->isTypeDependent())
1242 return E;
1243
1244 return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentKind());
1245}
1246
1247ExprResult
1248TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
1249 NonTypeTemplateParmDecl *NTTP) {
1250 // If the corresponding template argument is NULL or non-existent, it's
1251 // because we are performing instantiation from explicitly-specified
1252 // template arguments in a function template, but there were some
1253 // arguments left unspecified.
1254 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
1255 NTTP->getPosition()))
1256 return E;
1257
1258 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
1259
1260 if (TemplateArgs.getNumLevels() != TemplateArgs.getNumSubstitutedLevels()) {
1261 // We're performing a partial substitution, so the substituted argument
1262 // could be dependent. As a result we can't create a SubstNonType*Expr
1263 // node now, since that represents a fully-substituted argument.
1264 // FIXME: We should have some AST representation for this.
1265 if (Arg.getKind() == TemplateArgument::Pack) {
1266 // FIXME: This won't work for alias templates.
1267 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&((Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion
() && "unexpected pack arguments in partial substitution"
) ? static_cast<void> (0) : __assert_fail ("Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() && \"unexpected pack arguments in partial substitution\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1268, __PRETTY_FUNCTION__))
1268 "unexpected pack arguments in partial substitution")((Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion
() && "unexpected pack arguments in partial substitution"
) ? static_cast<void> (0) : __assert_fail ("Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() && \"unexpected pack arguments in partial substitution\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1268, __PRETTY_FUNCTION__))
;
1269 Arg = Arg.pack_begin()->getPackExpansionPattern();
1270 }
1271 assert(Arg.getKind() == TemplateArgument::Expression &&((Arg.getKind() == TemplateArgument::Expression && "unexpected nontype template argument kind in partial substitution"
) ? static_cast<void> (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Expression && \"unexpected nontype template argument kind in partial substitution\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1272, __PRETTY_FUNCTION__))
1272 "unexpected nontype template argument kind in partial substitution")((Arg.getKind() == TemplateArgument::Expression && "unexpected nontype template argument kind in partial substitution"
) ? static_cast<void> (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Expression && \"unexpected nontype template argument kind in partial substitution\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1272, __PRETTY_FUNCTION__))
;
1273 return Arg.getAsExpr();
1274 }
1275
1276 if (NTTP->isParameterPack()) {
1277 assert(Arg.getKind() == TemplateArgument::Pack &&((Arg.getKind() == TemplateArgument::Pack && "Missing argument pack"
) ? static_cast<void> (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1278, __PRETTY_FUNCTION__))
1278 "Missing argument pack")((Arg.getKind() == TemplateArgument::Pack && "Missing argument pack"
) ? static_cast<void> (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1278, __PRETTY_FUNCTION__))
;
1279
1280 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1281 // We have an argument pack, but we can't select a particular argument
1282 // out of it yet. Therefore, we'll build an expression to hold on to that
1283 // argument pack.
1284 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1285 E->getLocation(),
1286 NTTP->getDeclName());
1287 if (TargetType.isNull())
1288 return ExprError();
1289
1290 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(
1291 TargetType.getNonLValueExprType(SemaRef.Context),
1292 TargetType->isReferenceType() ? VK_LValue : VK_RValue, NTTP,
1293 E->getLocation(), Arg);
1294 }
1295
1296 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1297 }
1298
1299 return transformNonTypeTemplateParmRef(NTTP, E->getLocation(), Arg);
1300}
1301
1302const LoopHintAttr *
1303TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
1304 Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get();
1305
1306 if (TransformedExpr == LH->getValue())
1307 return LH;
1308
1309 // Generate error if there is a problem with the value.
1310 if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation()))
1311 return LH;
1312
1313 // Create new LoopHintValueAttr with integral expression in place of the
1314 // non-type template parameter.
1315 return LoopHintAttr::CreateImplicit(getSema().Context, LH->getOption(),
1316 LH->getState(), TransformedExpr, *LH);
1317}
1318
1319ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
1320 NonTypeTemplateParmDecl *parm,
1321 SourceLocation loc,
1322 TemplateArgument arg) {
1323 ExprResult result;
1324 QualType type;
1325
1326 // The template argument itself might be an expression, in which
1327 // case we just return that expression.
1328 if (arg.getKind() == TemplateArgument::Expression) {
1329 Expr *argExpr = arg.getAsExpr();
1330 result = argExpr;
1331 type = argExpr->getType();
1332
1333 } else if (arg.getKind() == TemplateArgument::Declaration ||
1334 arg.getKind() == TemplateArgument::NullPtr) {
1335 ValueDecl *VD;
1336 if (arg.getKind() == TemplateArgument::Declaration) {
1337 VD = arg.getAsDecl();
1338
1339 // Find the instantiation of the template argument. This is
1340 // required for nested templates.
1341 VD = cast_or_null<ValueDecl>(
1342 getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
1343 if (!VD)
1344 return ExprError();
1345 } else {
1346 // Propagate NULL template argument.
1347 VD = nullptr;
1348 }
1349
1350 // Derive the type we want the substituted decl to have. This had
1351 // better be non-dependent, or these checks will have serious problems.
1352 if (parm->isExpandedParameterPack()) {
1353 type = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex);
1354 } else if (parm->isParameterPack() &&
1355 isa<PackExpansionType>(parm->getType())) {
1356 type = SemaRef.SubstType(
1357 cast<PackExpansionType>(parm->getType())->getPattern(),
1358 TemplateArgs, loc, parm->getDeclName());
1359 } else {
1360 type = SemaRef.SubstType(VD ? arg.getParamTypeForDecl() : arg.getNullPtrType(),
1361 TemplateArgs, loc, parm->getDeclName());
1362 }
1363 assert(!type.isNull() && "type substitution failed for param type")((!type.isNull() && "type substitution failed for param type"
) ? static_cast<void> (0) : __assert_fail ("!type.isNull() && \"type substitution failed for param type\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1363, __PRETTY_FUNCTION__))
;
1364 assert(!type->isDependentType() && "param type still dependent")((!type->isDependentType() && "param type still dependent"
) ? static_cast<void> (0) : __assert_fail ("!type->isDependentType() && \"param type still dependent\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1364, __PRETTY_FUNCTION__))
;
1365 result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, type, loc);
1366
1367 if (!result.isInvalid()) type = result.get()->getType();
1368 } else {
1369 result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc);
1370
1371 // Note that this type can be different from the type of 'result',
1372 // e.g. if it's an enum type.
1373 type = arg.getIntegralType();
1374 }
1375 if (result.isInvalid()) return ExprError();
1376
1377 Expr *resultExpr = result.get();
1378 return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
1379 type, resultExpr->getValueKind(), loc, parm, resultExpr);
1380}
1381
1382ExprResult
1383TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
1384 SubstNonTypeTemplateParmPackExpr *E) {
1385 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1386 // We aren't expanding the parameter pack, so just return ourselves.
1387 return E;
1388 }
1389
1390 TemplateArgument Arg = E->getArgumentPack();
1391 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1392 return transformNonTypeTemplateParmRef(E->getParameterPack(),
1393 E->getParameterPackLocation(),
1394 Arg);
1395}
1396
1397ExprResult TemplateInstantiator::RebuildVarDeclRefExpr(VarDecl *PD,
1398 SourceLocation Loc) {
1399 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
1400 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
1401}
1402
1403ExprResult
1404TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
1405 if (getSema().ArgumentPackSubstitutionIndex != -1) {
1406 // We can expand this parameter pack now.
1407 VarDecl *D = E->getExpansion(getSema().ArgumentPackSubstitutionIndex);
1408 VarDecl *VD = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), D));
1409 if (!VD)
1410 return ExprError();
1411 return RebuildVarDeclRefExpr(VD, E->getExprLoc());
1412 }
1413
1414 QualType T = TransformType(E->getType());
1415 if (T.isNull())
1416 return ExprError();
1417
1418 // Transform each of the parameter expansions into the corresponding
1419 // parameters in the instantiation of the function decl.
1420 SmallVector<VarDecl *, 8> Vars;
1421 Vars.reserve(E->getNumExpansions());
1422 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
1423 I != End; ++I) {
1424 VarDecl *D = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), *I));
1425 if (!D)
1426 return ExprError();
1427 Vars.push_back(D);
1428 }
1429
1430 auto *PackExpr =
1431 FunctionParmPackExpr::Create(getSema().Context, T, E->getParameterPack(),
1432 E->getParameterPackLocation(), Vars);
1433 getSema().MarkFunctionParmPackReferenced(PackExpr);
1434 return PackExpr;
1435}
1436
1437ExprResult
1438TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
1439 VarDecl *PD) {
1440 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
1441 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
1442 = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
1443 assert(Found && "no instantiation for parameter pack")((Found && "no instantiation for parameter pack") ? static_cast
<void> (0) : __assert_fail ("Found && \"no instantiation for parameter pack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1443, __PRETTY_FUNCTION__))
;
1444
1445 Decl *TransformedDecl;
1446 if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
1447 // If this is a reference to a function parameter pack which we can
1448 // substitute but can't yet expand, build a FunctionParmPackExpr for it.
1449 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1450 QualType T = TransformType(E->getType());
1451 if (T.isNull())
1452 return ExprError();
1453 auto *PackExpr = FunctionParmPackExpr::Create(getSema().Context, T, PD,
1454 E->getExprLoc(), *Pack);
1455 getSema().MarkFunctionParmPackReferenced(PackExpr);
1456 return PackExpr;
1457 }
1458
1459 TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
1460 } else {
1461 TransformedDecl = Found->get<Decl*>();
1462 }
1463
1464 // We have either an unexpanded pack or a specific expansion.
1465 return RebuildVarDeclRefExpr(cast<VarDecl>(TransformedDecl), E->getExprLoc());
1466}
1467
1468ExprResult
1469TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
1470 NamedDecl *D = E->getDecl();
1471
1472 // Handle references to non-type template parameters and non-type template
1473 // parameter packs.
1474 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
1475 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
1476 return TransformTemplateParmRefExpr(E, NTTP);
1477
1478 // We have a non-type template parameter that isn't fully substituted;
1479 // FindInstantiatedDecl will find it in the local instantiation scope.
1480 }
1481
1482 // Handle references to function parameter packs.
1483 if (VarDecl *PD = dyn_cast<VarDecl>(D))
1484 if (PD->isParameterPack())
1485 return TransformFunctionParmPackRefExpr(E, PD);
1486
1487 return TreeTransform<TemplateInstantiator>::TransformDeclRefExpr(E);
1488}
1489
1490ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
1491 CXXDefaultArgExpr *E) {
1492 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->((!cast<FunctionDecl>(E->getParam()->getDeclContext
())-> getDescribedFunctionTemplate() && "Default arg expressions are never formed in dependent cases."
) ? static_cast<void> (0) : __assert_fail ("!cast<FunctionDecl>(E->getParam()->getDeclContext())-> getDescribedFunctionTemplate() && \"Default arg expressions are never formed in dependent cases.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1494, __PRETTY_FUNCTION__))
1493 getDescribedFunctionTemplate() &&((!cast<FunctionDecl>(E->getParam()->getDeclContext
())-> getDescribedFunctionTemplate() && "Default arg expressions are never formed in dependent cases."
) ? static_cast<void> (0) : __assert_fail ("!cast<FunctionDecl>(E->getParam()->getDeclContext())-> getDescribedFunctionTemplate() && \"Default arg expressions are never formed in dependent cases.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1494, __PRETTY_FUNCTION__))
1494 "Default arg expressions are never formed in dependent cases.")((!cast<FunctionDecl>(E->getParam()->getDeclContext
())-> getDescribedFunctionTemplate() && "Default arg expressions are never formed in dependent cases."
) ? static_cast<void> (0) : __assert_fail ("!cast<FunctionDecl>(E->getParam()->getDeclContext())-> getDescribedFunctionTemplate() && \"Default arg expressions are never formed in dependent cases.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1494, __PRETTY_FUNCTION__))
;
1495 return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
1496 cast<FunctionDecl>(E->getParam()->getDeclContext()),
1497 E->getParam());
1498}
1499
1500template<typename Fn>
1501QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
1502 FunctionProtoTypeLoc TL,
1503 CXXRecordDecl *ThisContext,
1504 Qualifiers ThisTypeQuals,
1505 Fn TransformExceptionSpec) {
1506 // We need a local instantiation scope for this function prototype.
1507 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1508 return inherited::TransformFunctionProtoType(
1509 TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
1510}
1511
1512ParmVarDecl *
1513TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
1514 int indexAdjustment,
1515 Optional<unsigned> NumExpansions,
1516 bool ExpectParameterPack) {
1517 return SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment,
1518 NumExpansions, ExpectParameterPack);
1519}
1520
1521QualType
1522TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1523 TemplateTypeParmTypeLoc TL) {
1524 const TemplateTypeParmType *T = TL.getTypePtr();
1525 if (T->getDepth() < TemplateArgs.getNumLevels()) {
1526 // Replace the template type parameter with its corresponding
1527 // template argument.
1528
1529 // If the corresponding template argument is NULL or doesn't exist, it's
1530 // because we are performing instantiation from explicitly-specified
1531 // template arguments in a function template class, but there were some
1532 // arguments left unspecified.
1533 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
1534 TemplateTypeParmTypeLoc NewTL
1535 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
1536 NewTL.setNameLoc(TL.getNameLoc());
1537 return TL.getType();
1538 }
1539
1540 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
1541
1542 if (T->isParameterPack()) {
1543 assert(Arg.getKind() == TemplateArgument::Pack &&((Arg.getKind() == TemplateArgument::Pack && "Missing argument pack"
) ? static_cast<void> (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1544, __PRETTY_FUNCTION__))
1544 "Missing argument pack")((Arg.getKind() == TemplateArgument::Pack && "Missing argument pack"
) ? static_cast<void> (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1544, __PRETTY_FUNCTION__))
;
1545
1546 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1547 // We have the template argument pack, but we're not expanding the
1548 // enclosing pack expansion yet. Just save the template argument
1549 // pack for later substitution.
1550 QualType Result
1551 = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg);
1552 SubstTemplateTypeParmPackTypeLoc NewTL
1553 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
1554 NewTL.setNameLoc(TL.getNameLoc());
1555 return Result;
1556 }
1557
1558 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1559 }
1560
1561 assert(Arg.getKind() == TemplateArgument::Type &&((Arg.getKind() == TemplateArgument::Type && "Template argument kind mismatch"
) ? static_cast<void> (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Type && \"Template argument kind mismatch\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1562, __PRETTY_FUNCTION__))
1562 "Template argument kind mismatch")((Arg.getKind() == TemplateArgument::Type && "Template argument kind mismatch"
) ? static_cast<void> (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Type && \"Template argument kind mismatch\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1562, __PRETTY_FUNCTION__))
;
1563
1564 QualType Replacement = Arg.getAsType();
1565
1566 // TODO: only do this uniquing once, at the start of instantiation.
1567 QualType Result
1568 = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
1569 SubstTemplateTypeParmTypeLoc NewTL
1570 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1571 NewTL.setNameLoc(TL.getNameLoc());
1572 return Result;
1573 }
1574
1575 // The template type parameter comes from an inner template (e.g.,
1576 // the template parameter list of a member template inside the
1577 // template we are instantiating). Create a new template type
1578 // parameter with the template "level" reduced by one.
1579 TemplateTypeParmDecl *NewTTPDecl = nullptr;
1580 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
1581 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
1582 TransformDecl(TL.getNameLoc(), OldTTPDecl));
1583
1584 QualType Result = getSema().Context.getTemplateTypeParmType(
1585 T->getDepth() - TemplateArgs.getNumSubstitutedLevels(), T->getIndex(),
1586 T->isParameterPack(), NewTTPDecl);
1587 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
1588 NewTL.setNameLoc(TL.getNameLoc());
1589 return Result;
1590}
1591
1592QualType
1593TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
1594 TypeLocBuilder &TLB,
1595 SubstTemplateTypeParmPackTypeLoc TL) {
1596 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1597 // We aren't expanding the parameter pack, so just return ourselves.
1598 SubstTemplateTypeParmPackTypeLoc NewTL
1599 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(TL.getType());
1600 NewTL.setNameLoc(TL.getNameLoc());
1601 return TL.getType();
1602 }
1603
1604 TemplateArgument Arg = TL.getTypePtr()->getArgumentPack();
1605 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1606 QualType Result = Arg.getAsType();
1607
1608 Result = getSema().Context.getSubstTemplateTypeParmType(
1609 TL.getTypePtr()->getReplacedParameter(),
1610 Result);
1611 SubstTemplateTypeParmTypeLoc NewTL
1612 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1613 NewTL.setNameLoc(TL.getNameLoc());
1614 return Result;
1615}
1616
1617/// Perform substitution on the type T with a given set of template
1618/// arguments.
1619///
1620/// This routine substitutes the given template arguments into the
1621/// type T and produces the instantiated type.
1622///
1623/// \param T the type into which the template arguments will be
1624/// substituted. If this type is not dependent, it will be returned
1625/// immediately.
1626///
1627/// \param Args the template arguments that will be
1628/// substituted for the top-level template parameters within T.
1629///
1630/// \param Loc the location in the source code where this substitution
1631/// is being performed. It will typically be the location of the
1632/// declarator (if we're instantiating the type of some declaration)
1633/// or the location of the type in the source code (if, e.g., we're
1634/// instantiating the type of a cast expression).
1635///
1636/// \param Entity the name of the entity associated with a declaration
1637/// being instantiated (if any). May be empty to indicate that there
1638/// is no such entity (if, e.g., this is a type that occurs as part of
1639/// a cast expression) or that the entity has no name (e.g., an
1640/// unnamed function parameter).
1641///
1642/// \param AllowDeducedTST Whether a DeducedTemplateSpecializationType is
1643/// acceptable as the top level type of the result.
1644///
1645/// \returns If the instantiation succeeds, the instantiated
1646/// type. Otherwise, produces diagnostics and returns a NULL type.
1647TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
1648 const MultiLevelTemplateArgumentList &Args,
1649 SourceLocation Loc,
1650 DeclarationName Entity,
1651 bool AllowDeducedTST) {
1652 assert(!CodeSynthesisContexts.empty() &&((!CodeSynthesisContexts.empty() && "Cannot perform an instantiation without some context on the "
"instantiation stack") ? static_cast<void> (0) : __assert_fail
("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1654, __PRETTY_FUNCTION__))
1653 "Cannot perform an instantiation without some context on the "((!CodeSynthesisContexts.empty() && "Cannot perform an instantiation without some context on the "
"instantiation stack") ? static_cast<void> (0) : __assert_fail
("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1654, __PRETTY_FUNCTION__))
1654 "instantiation stack")((!CodeSynthesisContexts.empty() && "Cannot perform an instantiation without some context on the "
"instantiation stack") ? static_cast<void> (0) : __assert_fail
("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1654, __PRETTY_FUNCTION__))
;
1655
1656 if (!T->getType()->isInstantiationDependentType() &&
1657 !T->getType()->isVariablyModifiedType())
1658 return T;
1659
1660 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1661 return AllowDeducedTST ? Instantiator.TransformTypeWithDeducedTST(T)
1662 : Instantiator.TransformType(T);
1663}
1664
1665TypeSourceInfo *Sema::SubstType(TypeLoc TL,
1666 const MultiLevelTemplateArgumentList &Args,
1667 SourceLocation Loc,
1668 DeclarationName Entity) {
1669 assert(!CodeSynthesisContexts.empty() &&((!CodeSynthesisContexts.empty() && "Cannot perform an instantiation without some context on the "
"instantiation stack") ? static_cast<void> (0) : __assert_fail
("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1671, __PRETTY_FUNCTION__))
1670 "Cannot perform an instantiation without some context on the "((!CodeSynthesisContexts.empty() && "Cannot perform an instantiation without some context on the "
"instantiation stack") ? static_cast<void> (0) : __assert_fail
("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1671, __PRETTY_FUNCTION__))
1671 "instantiation stack")((!CodeSynthesisContexts.empty() && "Cannot perform an instantiation without some context on the "
"instantiation stack") ? static_cast<void> (0) : __assert_fail
("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1671, __PRETTY_FUNCTION__))
;
1672
1673 if (TL.getType().isNull())
1674 return nullptr;
1675
1676 if (!TL.getType()->isInstantiationDependentType() &&
1677 !TL.getType()->isVariablyModifiedType()) {
1678 // FIXME: Make a copy of the TypeLoc data here, so that we can
1679 // return a new TypeSourceInfo. Inefficient!
1680 TypeLocBuilder TLB;
1681 TLB.pushFullCopy(TL);
1682 return TLB.getTypeSourceInfo(Context, TL.getType());
1683 }
1684
1685 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1686 TypeLocBuilder TLB;
1687 TLB.reserve(TL.getFullDataSize());
1688 QualType Result = Instantiator.TransformType(TLB, TL);
1689 if (Result.isNull())
1690 return nullptr;
1691
1692 return TLB.getTypeSourceInfo(Context, Result);
1693}
1694
1695/// Deprecated form of the above.
1696QualType Sema::SubstType(QualType T,
1697 const MultiLevelTemplateArgumentList &TemplateArgs,
1698 SourceLocation Loc, DeclarationName Entity) {
1699 assert(!CodeSynthesisContexts.empty() &&((!CodeSynthesisContexts.empty() && "Cannot perform an instantiation without some context on the "
"instantiation stack") ? static_cast<void> (0) : __assert_fail
("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1701, __PRETTY_FUNCTION__))
1700 "Cannot perform an instantiation without some context on the "((!CodeSynthesisContexts.empty() && "Cannot perform an instantiation without some context on the "
"instantiation stack") ? static_cast<void> (0) : __assert_fail
("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1701, __PRETTY_FUNCTION__))
1701 "instantiation stack")((!CodeSynthesisContexts.empty() && "Cannot perform an instantiation without some context on the "
"instantiation stack") ? static_cast<void> (0) : __assert_fail
("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1701, __PRETTY_FUNCTION__))
;
1702
1703 // If T is not a dependent type or a variably-modified type, there
1704 // is nothing to do.
1705 if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
1706 return T;
1707
1708 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
1709 return Instantiator.TransformType(T);
1710}
1711
1712static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
1713 if (T->getType()->isInstantiationDependentType() ||
1714 T->getType()->isVariablyModifiedType())
1715 return true;
1716
1717 TypeLoc TL = T->getTypeLoc().IgnoreParens();
1718 if (!TL.getAs<FunctionProtoTypeLoc>())
1719 return false;
1720
1721 FunctionProtoTypeLoc FP = TL.castAs<FunctionProtoTypeLoc>();
1722 for (ParmVarDecl *P : FP.getParams()) {
1723 // This must be synthesized from a typedef.
1724 if (!P) continue;
1725
1726 // If there are any parameters, a new TypeSourceInfo that refers to the
1727 // instantiated parameters must be built.
1728 return true;
1729 }
1730
1731 return false;
1732}
1733
1734/// A form of SubstType intended specifically for instantiating the
1735/// type of a FunctionDecl. Its purpose is solely to force the
1736/// instantiation of default-argument expressions and to avoid
1737/// instantiating an exception-specification.
1738TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
1739 const MultiLevelTemplateArgumentList &Args,
1740 SourceLocation Loc,
1741 DeclarationName Entity,
1742 CXXRecordDecl *ThisContext,
1743 Qualifiers ThisTypeQuals) {
1744 assert(!CodeSynthesisContexts.empty() &&((!CodeSynthesisContexts.empty() && "Cannot perform an instantiation without some context on the "
"instantiation stack") ? static_cast<void> (0) : __assert_fail
("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1746, __PRETTY_FUNCTION__))
1745 "Cannot perform an instantiation without some context on the "((!CodeSynthesisContexts.empty() && "Cannot perform an instantiation without some context on the "
"instantiation stack") ? static_cast<void> (0) : __assert_fail
("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1746, __PRETTY_FUNCTION__))
1746 "instantiation stack")((!CodeSynthesisContexts.empty() && "Cannot perform an instantiation without some context on the "
"instantiation stack") ? static_cast<void> (0) : __assert_fail
("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1746, __PRETTY_FUNCTION__))
;
1747
1748 if (!NeedsInstantiationAsFunctionType(T))
1749 return T;
1750
1751 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1752
1753 TypeLocBuilder TLB;
1754
1755 TypeLoc TL = T->getTypeLoc();
1756 TLB.reserve(TL.getFullDataSize());
1757
1758 QualType Result;
1759
1760 if (FunctionProtoTypeLoc Proto =
1761 TL.IgnoreParens().getAs<FunctionProtoTypeLoc>()) {
1762 // Instantiate the type, other than its exception specification. The
1763 // exception specification is instantiated in InitFunctionInstantiation
1764 // once we've built the FunctionDecl.
1765 // FIXME: Set the exception specification to EST_Uninstantiated here,
1766 // instead of rebuilding the function type again later.
1767 Result = Instantiator.TransformFunctionProtoType(
1768 TLB, Proto, ThisContext, ThisTypeQuals,
1769 [](FunctionProtoType::ExceptionSpecInfo &ESI,
1770 bool &Changed) { return false; });
1771 } else {
1772 Result = Instantiator.TransformType(TLB, TL);
1773 }
1774 if (Result.isNull())
1775 return nullptr;
1776
1777 return TLB.getTypeSourceInfo(Context, Result);
1778}
1779
1780bool Sema::SubstExceptionSpec(SourceLocation Loc,
1781 FunctionProtoType::ExceptionSpecInfo &ESI,
1782 SmallVectorImpl<QualType> &ExceptionStorage,
1783 const MultiLevelTemplateArgumentList &Args) {
1784 assert(ESI.Type != EST_Uninstantiated)((ESI.Type != EST_Uninstantiated) ? static_cast<void> (
0) : __assert_fail ("ESI.Type != EST_Uninstantiated", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1784, __PRETTY_FUNCTION__))
;
1785
1786 bool Changed = false;
1787 TemplateInstantiator Instantiator(*this, Args, Loc, DeclarationName());
1788 return Instantiator.TransformExceptionSpec(Loc, ESI, ExceptionStorage,
1789 Changed);
1790}
1791
1792void Sema::SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
1793 const MultiLevelTemplateArgumentList &Args) {
1794 FunctionProtoType::ExceptionSpecInfo ESI =
1795 Proto->getExtProtoInfo().ExceptionSpec;
1796
1797 SmallVector<QualType, 4> ExceptionStorage;
1798 if (SubstExceptionSpec(New->getTypeSourceInfo()->getTypeLoc().getEndLoc(),
1799 ESI, ExceptionStorage, Args))
1800 // On error, recover by dropping the exception specification.
1801 ESI.Type = EST_None;
1802
1803 UpdateExceptionSpec(New, ESI);
1804}
1805
1806ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm,
1807 const MultiLevelTemplateArgumentList &TemplateArgs,
1808 int indexAdjustment,
1809 Optional<unsigned> NumExpansions,
1810 bool ExpectParameterPack) {
1811 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
1812 TypeSourceInfo *NewDI = nullptr;
1813
1814 TypeLoc OldTL = OldDI->getTypeLoc();
1815 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
1816
1817 // We have a function parameter pack. Substitute into the pattern of the
1818 // expansion.
1819 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
1820 OldParm->getLocation(), OldParm->getDeclName());
1821 if (!NewDI)
1822 return nullptr;
1823
1824 if (NewDI->getType()->containsUnexpandedParameterPack()) {
1825 // We still have unexpanded parameter packs, which means that
1826 // our function parameter is still a function parameter pack.
1827 // Therefore, make its type a pack expansion type.
1828 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
1829 NumExpansions);
1830 } else if (ExpectParameterPack) {
1831 // We expected to get a parameter pack but didn't (because the type
1832 // itself is not a pack expansion type), so complain. This can occur when
1833 // the substitution goes through an alias template that "loses" the
1834 // pack expansion.
1835 Diag(OldParm->getLocation(),
1836 diag::err_function_parameter_pack_without_parameter_packs)
1837 << NewDI->getType();
1838 return nullptr;
1839 }
1840 } else {
1841 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
1842 OldParm->getDeclName());
1843 }
1844
1845 if (!NewDI)
1846 return nullptr;
1847
1848 if (NewDI->getType()->isVoidType()) {
1849 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
1850 return nullptr;
1851 }
1852
1853 ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
1854 OldParm->getInnerLocStart(),
1855 OldParm->getLocation(),
1856 OldParm->getIdentifier(),
1857 NewDI->getType(), NewDI,
1858 OldParm->getStorageClass());
1859 if (!NewParm)
1860 return nullptr;
1861
1862 // Mark the (new) default argument as uninstantiated (if any).
1863 if (OldParm->hasUninstantiatedDefaultArg()) {
1864 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
1865 NewParm->setUninstantiatedDefaultArg(Arg);
1866 } else if (OldParm->hasUnparsedDefaultArg()) {
1867 NewParm->setUnparsedDefaultArg();
1868 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
1869 } else if (Expr *Arg = OldParm->getDefaultArg()) {
1870 FunctionDecl *OwningFunc = cast<FunctionDecl>(OldParm->getDeclContext());
1871 if (OwningFunc->isLexicallyWithinFunctionOrMethod()) {
1872 // Instantiate default arguments for methods of local classes (DR1484)
1873 // and non-defining declarations.
1874 Sema::ContextRAII SavedContext(*this, OwningFunc);
1875 LocalInstantiationScope Local(*this, true);
1876 ExprResult NewArg = SubstExpr(Arg, TemplateArgs);
1877 if (NewArg.isUsable()) {
1878 // It would be nice if we still had this.
1879 SourceLocation EqualLoc = NewArg.get()->getBeginLoc();
1880 SetParamDefaultArgument(NewParm, NewArg.get(), EqualLoc);
1881 }
1882 } else {
1883 // FIXME: if we non-lazily instantiated non-dependent default args for
1884 // non-dependent parameter types we could remove a bunch of duplicate
1885 // conversion warnings for such arguments.
1886 NewParm->setUninstantiatedDefaultArg(Arg);
1887 }
1888 }
1889
1890 NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
1891
1892 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
1893 // Add the new parameter to the instantiated parameter pack.
1894 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
1895 } else {
1896 // Introduce an Old -> New mapping
1897 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
1898 }
1899
1900 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
1901 // can be anything, is this right ?
1902 NewParm->setDeclContext(CurContext);
1903
1904 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
1905 OldParm->getFunctionScopeIndex() + indexAdjustment);
1906
1907 InstantiateAttrs(TemplateArgs, OldParm, NewParm);
1908
1909 return NewParm;
1910}
1911
1912/// Substitute the given template arguments into the given set of
1913/// parameters, producing the set of parameter types that would be generated
1914/// from such a substitution.
1915bool Sema::SubstParmTypes(
1916 SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
1917 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
1918 const MultiLevelTemplateArgumentList &TemplateArgs,
1919 SmallVectorImpl<QualType> &ParamTypes,
1920 SmallVectorImpl<ParmVarDecl *> *OutParams,
1921 ExtParameterInfoBuilder &ParamInfos) {
1922 assert(!CodeSynthesisContexts.empty() &&((!CodeSynthesisContexts.empty() && "Cannot perform an instantiation without some context on the "
"instantiation stack") ? static_cast<void> (0) : __assert_fail
("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1924, __PRETTY_FUNCTION__))
1923 "Cannot perform an instantiation without some context on the "((!CodeSynthesisContexts.empty() && "Cannot perform an instantiation without some context on the "
"instantiation stack") ? static_cast<void> (0) : __assert_fail
("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1924, __PRETTY_FUNCTION__))
1924 "instantiation stack")((!CodeSynthesisContexts.empty() && "Cannot perform an instantiation without some context on the "
"instantiation stack") ? static_cast<void> (0) : __assert_fail
("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1924, __PRETTY_FUNCTION__))
;
1925
1926 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
1927 DeclarationName());
1928 return Instantiator.TransformFunctionTypeParams(
1929 Loc, Params, nullptr, ExtParamInfos, ParamTypes, OutParams, ParamInfos);
1930}
1931
1932/// Perform substitution on the base class specifiers of the
1933/// given class template specialization.
1934///
1935/// Produces a diagnostic and returns true on error, returns false and
1936/// attaches the instantiated base classes to the class template
1937/// specialization if successful.
1938bool
1939Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
1940 CXXRecordDecl *Pattern,
1941 const MultiLevelTemplateArgumentList &TemplateArgs) {
1942 bool Invalid = false;
1943 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
1944 for (const auto &Base : Pattern->bases()) {
1945 if (!Base.getType()->isDependentType()) {
1946 if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
1947 if (RD->isInvalidDecl())
1948 Instantiation->setInvalidDecl();
1949 }
1950 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
1951 continue;
1952 }
1953
1954 SourceLocation EllipsisLoc;
1955 TypeSourceInfo *BaseTypeLoc;
1956 if (Base.isPackExpansion()) {
1957 // This is a pack expansion. See whether we should expand it now, or
1958 // wait until later.
1959 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1960 collectUnexpandedParameterPacks(Base.getTypeSourceInfo()->getTypeLoc(),
1961 Unexpanded);
1962 bool ShouldExpand = false;
1963 bool RetainExpansion = false;
1964 Optional<unsigned> NumExpansions;
1965 if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(),
1966 Base.getSourceRange(),
1967 Unexpanded,
1968 TemplateArgs, ShouldExpand,
1969 RetainExpansion,
1970 NumExpansions)) {
1971 Invalid = true;
1972 continue;
1973 }
1974
1975 // If we should expand this pack expansion now, do so.
1976 if (ShouldExpand) {
1977 for (unsigned I = 0; I != *NumExpansions; ++I) {
1978 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
1979
1980 TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
1981 TemplateArgs,
1982 Base.getSourceRange().getBegin(),
1983 DeclarationName());
1984 if (!BaseTypeLoc) {
1985 Invalid = true;
1986 continue;
1987 }
1988
1989 if (CXXBaseSpecifier *InstantiatedBase
1990 = CheckBaseSpecifier(Instantiation,
1991 Base.getSourceRange(),
1992 Base.isVirtual(),
1993 Base.getAccessSpecifierAsWritten(),
1994 BaseTypeLoc,
1995 SourceLocation()))
1996 InstantiatedBases.push_back(InstantiatedBase);
1997 else
1998 Invalid = true;
1999 }
2000
2001 continue;
2002 }
2003
2004 // The resulting base specifier will (still) be a pack expansion.
2005 EllipsisLoc = Base.getEllipsisLoc();
2006 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
2007 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
2008 TemplateArgs,
2009 Base.getSourceRange().getBegin(),
2010 DeclarationName());
2011 } else {
2012 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
2013 TemplateArgs,
2014 Base.getSourceRange().getBegin(),
2015 DeclarationName());
2016 }
2017
2018 if (!BaseTypeLoc) {
2019 Invalid = true;
2020 continue;
2021 }
2022
2023 if (CXXBaseSpecifier *InstantiatedBase
2024 = CheckBaseSpecifier(Instantiation,
2025 Base.getSourceRange(),
2026 Base.isVirtual(),
2027 Base.getAccessSpecifierAsWritten(),
2028 BaseTypeLoc,
2029 EllipsisLoc))
2030 InstantiatedBases.push_back(InstantiatedBase);
2031 else
2032 Invalid = true;
2033 }
2034
2035 if (!Invalid && AttachBaseSpecifiers(Instantiation, InstantiatedBases))
2036 Invalid = true;
2037
2038 return Invalid;
2039}
2040
2041// Defined via #include from SemaTemplateInstantiateDecl.cpp
2042namespace clang {
2043 namespace sema {
2044 Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S,
2045 const MultiLevelTemplateArgumentList &TemplateArgs);
2046 Attr *instantiateTemplateAttributeForDecl(
2047 const Attr *At, ASTContext &C, Sema &S,
2048 const MultiLevelTemplateArgumentList &TemplateArgs);
2049 }
2050}
2051
2052/// Instantiate the definition of a class from a given pattern.
2053///
2054/// \param PointOfInstantiation The point of instantiation within the
2055/// source code.
2056///
2057/// \param Instantiation is the declaration whose definition is being
2058/// instantiated. This will be either a class template specialization
2059/// or a member class of a class template specialization.
2060///
2061/// \param Pattern is the pattern from which the instantiation
2062/// occurs. This will be either the declaration of a class template or
2063/// the declaration of a member class of a class template.
2064///
2065/// \param TemplateArgs The template arguments to be substituted into
2066/// the pattern.
2067///
2068/// \param TSK the kind of implicit or explicit instantiation to perform.
2069///
2070/// \param Complain whether to complain if the class cannot be instantiated due
2071/// to the lack of a definition.
2072///
2073/// \returns true if an error occurred, false otherwise.
2074bool
2075Sema::InstantiateClass(SourceLocation PointOfInstantiation,
2076 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
2077 const MultiLevelTemplateArgumentList &TemplateArgs,
2078 TemplateSpecializationKind TSK,
2079 bool Complain) {
2080 CXXRecordDecl *PatternDef
2081 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
2082 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
2083 Instantiation->getInstantiatedFromMemberClass(),
2084 Pattern, PatternDef, TSK, Complain))
2085 return true;
2086
2087 llvm::TimeTraceScope TimeScope("InstantiateClass", [&]() {
2088 std::string Name;
2089 llvm::raw_string_ostream OS(Name);
2090 Instantiation->getNameForDiagnostic(OS, getPrintingPolicy(),
2091 /*Qualified=*/true);
2092 return Name;
2093 });
2094
2095 Pattern = PatternDef;
2096
2097 // Record the point of instantiation.
2098 if (MemberSpecializationInfo *MSInfo
2099 = Instantiation->getMemberSpecializationInfo()) {
2100 MSInfo->setTemplateSpecializationKind(TSK);
2101 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2102 } else if (ClassTemplateSpecializationDecl *Spec
2103 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
2104 Spec->setTemplateSpecializationKind(TSK);
2105 Spec->setPointOfInstantiation(PointOfInstantiation);
2106 }
2107
2108 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2109 if (Inst.isInvalid())
2110 return true;
2111 assert(!Inst.isAlreadyInstantiating() && "should have been caught by caller")((!Inst.isAlreadyInstantiating() && "should have been caught by caller"
) ? static_cast<void> (0) : __assert_fail ("!Inst.isAlreadyInstantiating() && \"should have been caught by caller\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2111, __PRETTY_FUNCTION__))
;
2112 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
2113 "instantiating class definition");
2114
2115 // Enter the scope of this instantiation. We don't use
2116 // PushDeclContext because we don't have a scope.
2117 ContextRAII SavedContext(*this, Instantiation);
2118 EnterExpressionEvaluationContext EvalContext(
2119 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
2120
2121 // If this is an instantiation of a local class, merge this local
2122 // instantiation scope with the enclosing scope. Otherwise, every
2123 // instantiation of a class has its own local instantiation scope.
2124 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
2125 LocalInstantiationScope Scope(*this, MergeWithParentScope);
2126
2127 // Some class state isn't processed immediately but delayed till class
2128 // instantiation completes. We may not be ready to handle any delayed state
2129 // already on the stack as it might correspond to a different class, so save
2130 // it now and put it back later.
2131 SavePendingParsedClassStateRAII SavedPendingParsedClassState(*this);
2132
2133 // Pull attributes from the pattern onto the instantiation.
2134 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2135
2136 // Start the definition of this instantiation.
2137 Instantiation->startDefinition();
2138
2139 // The instantiation is visible here, even if it was first declared in an
2140 // unimported module.
2141 Instantiation->setVisibleDespiteOwningModule();
2142
2143 // FIXME: This loses the as-written tag kind for an explicit instantiation.
2144 Instantiation->setTagKind(Pattern->getTagKind());
2145
2146 // Do substitution on the base class specifiers.
2147 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
2148 Instantiation->setInvalidDecl();
2149
2150 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2151 SmallVector<Decl*, 4> Fields;
2152 // Delay instantiation of late parsed attributes.
2153 LateInstantiatedAttrVec LateAttrs;
2154 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
2155
2156 bool MightHaveConstexprVirtualFunctions = false;
2157 for (auto *Member : Pattern->decls()) {
2158 // Don't instantiate members not belonging in this semantic context.
2159 // e.g. for:
2160 // @code
2161 // template <int i> class A {
2162 // class B *g;
2163 // };
2164 // @endcode
2165 // 'class B' has the template as lexical context but semantically it is
2166 // introduced in namespace scope.
2167 if (Member->getDeclContext() != Pattern)
2168 continue;
2169
2170 // BlockDecls can appear in a default-member-initializer. They must be the
2171 // child of a BlockExpr, so we only know how to instantiate them from there.
2172 if (isa<BlockDecl>(Member))
2173 continue;
2174
2175 if (Member->isInvalidDecl()) {
2176 Instantiation->setInvalidDecl();
2177 continue;
2178 }
2179
2180 Decl *NewMember = Instantiator.Visit(Member);
2181 if (NewMember) {
2182 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
2183 Fields.push_back(Field);
2184 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
2185 // C++11 [temp.inst]p1: The implicit instantiation of a class template
2186 // specialization causes the implicit instantiation of the definitions
2187 // of unscoped member enumerations.
2188 // Record a point of instantiation for this implicit instantiation.
2189 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
2190 Enum->isCompleteDefinition()) {
2191 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
2192 assert(MSInfo && "no spec info for member enum specialization")((MSInfo && "no spec info for member enum specialization"
) ? static_cast<void> (0) : __assert_fail ("MSInfo && \"no spec info for member enum specialization\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2192, __PRETTY_FUNCTION__))
;
2193 MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation);
2194 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2195 }
2196 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
2197 if (SA->isFailed()) {
2198 // A static_assert failed. Bail out; instantiating this
2199 // class is probably not meaningful.
2200 Instantiation->setInvalidDecl();
2201 break;
2202 }
2203 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewMember)) {
2204 if (MD->isConstexpr() && !MD->getFriendObjectKind() &&
2205 (MD->isVirtualAsWritten() || Instantiation->getNumBases()))
2206 MightHaveConstexprVirtualFunctions = true;
2207 }
2208
2209 if (NewMember->isInvalidDecl())
2210 Instantiation->setInvalidDecl();
2211 } else {
2212 // FIXME: Eventually, a NULL return will mean that one of the
2213 // instantiations was a semantic disaster, and we'll want to mark the
2214 // declaration invalid.
2215 // For now, we expect to skip some members that we can't yet handle.
2216 }
2217 }
2218
2219 // Finish checking fields.
2220 ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
2221 SourceLocation(), SourceLocation(), ParsedAttributesView());
2222 CheckCompletedCXXClass(Instantiation);
2223
2224 // Default arguments are parsed, if not instantiated. We can go instantiate
2225 // default arg exprs for default constructors if necessary now.
2226 ActOnFinishCXXNonNestedClass(Instantiation);
2227
2228 // Instantiate late parsed attributes, and attach them to their decls.
2229 // See Sema::InstantiateAttrs
2230 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
2231 E = LateAttrs.end(); I != E; ++I) {
2232 assert(CurrentInstantiationScope == Instantiator.getStartingScope())((CurrentInstantiationScope == Instantiator.getStartingScope(
)) ? static_cast<void> (0) : __assert_fail ("CurrentInstantiationScope == Instantiator.getStartingScope()"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2232, __PRETTY_FUNCTION__))
;
2233 CurrentInstantiationScope = I->Scope;
2234
2235 // Allow 'this' within late-parsed attributes.
2236 NamedDecl *ND = dyn_cast<NamedDecl>(I->NewDecl);
2237 CXXRecordDecl *ThisContext =
2238 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
2239 CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
2240 ND && ND->isCXXInstanceMember());
2241
2242 Attr *NewAttr =
2243 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
2244 I->NewDecl->addAttr(NewAttr);
2245 LocalInstantiationScope::deleteScopes(I->Scope,
2246 Instantiator.getStartingScope());
2247 }
2248 Instantiator.disableLateAttributeInstantiation();
2249 LateAttrs.clear();
2250
2251 ActOnFinishDelayedMemberInitializers(Instantiation);
2252
2253 // FIXME: We should do something similar for explicit instantiations so they
2254 // end up in the right module.
2255 if (TSK == TSK_ImplicitInstantiation) {
2256 Instantiation->setLocation(Pattern->getLocation());
2257 Instantiation->setLocStart(Pattern->getInnerLocStart());
2258 Instantiation->setBraceRange(Pattern->getBraceRange());
2259 }
2260
2261 if (!Instantiation->isInvalidDecl()) {
2262 // Perform any dependent diagnostics from the pattern.
2263 PerformDependentDiagnostics(Pattern, TemplateArgs);
2264
2265 // Instantiate any out-of-line class template partial
2266 // specializations now.
2267 for (TemplateDeclInstantiator::delayed_partial_spec_iterator
2268 P = Instantiator.delayed_partial_spec_begin(),
2269 PEnd = Instantiator.delayed_partial_spec_end();
2270 P != PEnd; ++P) {
2271 if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
2272 P->first, P->second)) {
2273 Instantiation->setInvalidDecl();
2274 break;
2275 }
2276 }
2277
2278 // Instantiate any out-of-line variable template partial
2279 // specializations now.
2280 for (TemplateDeclInstantiator::delayed_var_partial_spec_iterator
2281 P = Instantiator.delayed_var_partial_spec_begin(),
2282 PEnd = Instantiator.delayed_var_partial_spec_end();
2283 P != PEnd; ++P) {
2284 if (!Instantiator.InstantiateVarTemplatePartialSpecialization(
2285 P->first, P->second)) {
2286 Instantiation->setInvalidDecl();
2287 break;
2288 }
2289 }
2290 }
2291
2292 // Exit the scope of this instantiation.
2293 SavedContext.pop();
2294
2295 if (!Instantiation->isInvalidDecl()) {
2296 Consumer.HandleTagDeclDefinition(Instantiation);
2297
2298 // Always emit the vtable for an explicit instantiation definition
2299 // of a polymorphic class template specialization. Otherwise, eagerly
2300 // instantiate only constexpr virtual functions in preparation for their use
2301 // in constant evaluation.
2302 if (TSK == TSK_ExplicitInstantiationDefinition)
2303 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
2304 else if (MightHaveConstexprVirtualFunctions)
2305 MarkVirtualMembersReferenced(PointOfInstantiation, Instantiation,
2306 /*ConstexprOnly*/ true);
2307 }
2308
2309 return Instantiation->isInvalidDecl();
2310}
2311
2312/// Instantiate the definition of an enum from a given pattern.
2313///
2314/// \param PointOfInstantiation The point of instantiation within the
2315/// source code.
2316/// \param Instantiation is the declaration whose definition is being
2317/// instantiated. This will be a member enumeration of a class
2318/// temploid specialization, or a local enumeration within a
2319/// function temploid specialization.
2320/// \param Pattern The templated declaration from which the instantiation
2321/// occurs.
2322/// \param TemplateArgs The template arguments to be substituted into
2323/// the pattern.
2324/// \param TSK The kind of implicit or explicit instantiation to perform.
2325///
2326/// \return \c true if an error occurred, \c false otherwise.
2327bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
2328 EnumDecl *Instantiation, EnumDecl *Pattern,
2329 const MultiLevelTemplateArgumentList &TemplateArgs,
2330 TemplateSpecializationKind TSK) {
2331 EnumDecl *PatternDef = Pattern->getDefinition();
2332 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
2333 Instantiation->getInstantiatedFromMemberEnum(),
2334 Pattern, PatternDef, TSK,/*Complain*/true))
2335 return true;
2336 Pattern = PatternDef;
2337
2338 // Record the point of instantiation.
2339 if (MemberSpecializationInfo *MSInfo
2340 = Instantiation->getMemberSpecializationInfo()) {
2341 MSInfo->setTemplateSpecializationKind(TSK);
2342 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2343 }
2344
2345 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2346 if (Inst.isInvalid())
2347 return true;
2348 if (Inst.isAlreadyInstantiating())
2349 return false;
2350 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
2351 "instantiating enum definition");
2352
2353 // The instantiation is visible here, even if it was first declared in an
2354 // unimported module.
2355 Instantiation->setVisibleDespiteOwningModule();
2356
2357 // Enter the scope of this instantiation. We don't use
2358 // PushDeclContext because we don't have a scope.
2359 ContextRAII SavedContext(*this, Instantiation);
2360 EnterExpressionEvaluationContext EvalContext(
2361 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
2362
2363 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
2364
2365 // Pull attributes from the pattern onto the instantiation.
2366 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2367
2368 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2369 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
2370
2371 // Exit the scope of this instantiation.
2372 SavedContext.pop();
2373
2374 return Instantiation->isInvalidDecl();
2375}
2376
2377
2378/// Instantiate the definition of a field from the given pattern.
2379///
2380/// \param PointOfInstantiation The point of instantiation within the
2381/// source code.
2382/// \param Instantiation is the declaration whose definition is being
2383/// instantiated. This will be a class of a class temploid
2384/// specialization, or a local enumeration within a function temploid
2385/// specialization.
2386/// \param Pattern The templated declaration from which the instantiation
2387/// occurs.
2388/// \param TemplateArgs The template arguments to be substituted into
2389/// the pattern.
2390///
2391/// \return \c true if an error occurred, \c false otherwise.
2392bool Sema::InstantiateInClassInitializer(
2393 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
2394 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
2395 // If there is no initializer, we don't need to do anything.
2396 if (!Pattern->hasInClassInitializer())
2397 return false;
2398
2399 assert(Instantiation->getInClassInitStyle() ==((Instantiation->getInClassInitStyle() == Pattern->getInClassInitStyle
() && "pattern and instantiation disagree about init style"
) ? static_cast<void> (0) : __assert_fail ("Instantiation->getInClassInitStyle() == Pattern->getInClassInitStyle() && \"pattern and instantiation disagree about init style\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2401, __PRETTY_FUNCTION__))
2400 Pattern->getInClassInitStyle() &&((Instantiation->getInClassInitStyle() == Pattern->getInClassInitStyle
() && "pattern and instantiation disagree about init style"
) ? static_cast<void> (0) : __assert_fail ("Instantiation->getInClassInitStyle() == Pattern->getInClassInitStyle() && \"pattern and instantiation disagree about init style\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2401, __PRETTY_FUNCTION__))
2401 "pattern and instantiation disagree about init style")((Instantiation->getInClassInitStyle() == Pattern->getInClassInitStyle
() && "pattern and instantiation disagree about init style"
) ? static_cast<void> (0) : __assert_fail ("Instantiation->getInClassInitStyle() == Pattern->getInClassInitStyle() && \"pattern and instantiation disagree about init style\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2401, __PRETTY_FUNCTION__))
;
2402
2403 // Error out if we haven't parsed the initializer of the pattern yet because
2404 // we are waiting for the closing brace of the outer class.
2405 Expr *OldInit = Pattern->getInClassInitializer();
2406 if (!OldInit) {
2407 RecordDecl *PatternRD = Pattern->getParent();
2408 RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext();
2409 Diag(PointOfInstantiation,
2410 diag::err_in_class_initializer_not_yet_parsed)
2411 << OutermostClass << Pattern;
2412 Diag(Pattern->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed);
2413 Instantiation->setInvalidDecl();
2414 return true;
2415 }
2416
2417 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2418 if (Inst.isInvalid())
2419 return true;
2420 if (Inst.isAlreadyInstantiating()) {
2421 // Error out if we hit an instantiation cycle for this initializer.
2422 Diag(PointOfInstantiation, diag::err_in_class_initializer_cycle)
2423 << Instantiation;
2424 return true;
2425 }
2426 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
2427 "instantiating default member init");
2428
2429 // Enter the scope of this instantiation. We don't use PushDeclContext because
2430 // we don't have a scope.
2431 ContextRAII SavedContext(*this, Instantiation->getParent());
2432 EnterExpressionEvaluationContext EvalContext(
2433 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
2434
2435 LocalInstantiationScope Scope(*this, true);
2436
2437 // Instantiate the initializer.
2438 ActOnStartCXXInClassMemberInitializer();
2439 CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), Qualifiers());
2440
2441 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
2442 /*CXXDirectInit=*/false);
2443 Expr *Init = NewInit.get();
2444 assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class")(((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class"
) ? static_cast<void> (0) : __assert_fail ("(!Init || !isa<ParenListExpr>(Init)) && \"call-style init in class\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2444, __PRETTY_FUNCTION__))
;
2445 ActOnFinishCXXInClassMemberInitializer(
2446 Instantiation, Init ? Init->getBeginLoc() : SourceLocation(), Init);
2447
2448 if (auto *L = getASTMutationListener())
2449 L->DefaultMemberInitializerInstantiated(Instantiation);
2450
2451 // Return true if the in-class initializer is still missing.
2452 return !Instantiation->getInClassInitializer();
2453}
2454
2455namespace {
2456 /// A partial specialization whose template arguments have matched
2457 /// a given template-id.
2458 struct PartialSpecMatchResult {
2459 ClassTemplatePartialSpecializationDecl *Partial;
2460 TemplateArgumentList *Args;
2461 };
2462}
2463
2464bool Sema::usesPartialOrExplicitSpecialization(
2465 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec) {
2466 if (ClassTemplateSpec->getTemplateSpecializationKind() ==
2467 TSK_ExplicitSpecialization)
2468 return true;
2469
2470 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2471 ClassTemplateSpec->getSpecializedTemplate()
2472 ->getPartialSpecializations(PartialSpecs);
2473 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2474 TemplateDeductionInfo Info(Loc);
2475 if (!DeduceTemplateArguments(PartialSpecs[I],
2476 ClassTemplateSpec->getTemplateArgs(), Info))
2477 return true;
2478 }
2479
2480 return false;
2481}
2482
2483/// Get the instantiation pattern to use to instantiate the definition of a
2484/// given ClassTemplateSpecializationDecl (either the pattern of the primary
2485/// template or of a partial specialization).
2486static CXXRecordDecl *
2487getPatternForClassTemplateSpecialization(
2488 Sema &S, SourceLocation PointOfInstantiation,
2489 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2490 TemplateSpecializationKind TSK, bool Complain) {
2491 Sema::InstantiatingTemplate Inst(S, PointOfInstantiation, ClassTemplateSpec);
2492 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
2493 return nullptr;
2494
2495 llvm::PointerUnion<ClassTemplateDecl *,
2496 ClassTemplatePartialSpecializationDecl *>
2497 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
2498 if (!Specialized.is<ClassTemplatePartialSpecializationDecl *>()) {
2499 // Find best matching specialization.
2500 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
2501
2502 // C++ [temp.class.spec.match]p1:
2503 // When a class template is used in a context that requires an
2504 // instantiation of the class, it is necessary to determine
2505 // whether the instantiation is to be generated using the primary
2506 // template or one of the partial specializations. This is done by
2507 // matching the template arguments of the class template
2508 // specialization with the template argument lists of the partial
2509 // specializations.
2510 typedef PartialSpecMatchResult MatchResult;
2511 SmallVector<MatchResult, 4> Matched;
2512 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2513 Template->getPartialSpecializations(PartialSpecs);
2514 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
2515 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2516 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
2517 TemplateDeductionInfo Info(FailedCandidates.getLocation());
2518 if (Sema::TemplateDeductionResult Result = S.DeduceTemplateArguments(
2519 Partial, ClassTemplateSpec->getTemplateArgs(), Info)) {
2520 // Store the failed-deduction information for use in diagnostics, later.
2521 // TODO: Actually use the failed-deduction info?
2522 FailedCandidates.addCandidate().set(
2523 DeclAccessPair::make(Template, AS_public), Partial,
2524 MakeDeductionFailureInfo(S.Context, Result, Info));
2525 (void)Result;
2526 } else {
2527 Matched.push_back(PartialSpecMatchResult());
2528 Matched.back().Partial = Partial;
2529 Matched.back().Args = Info.take();
2530 }
2531 }
2532
2533 // If we're dealing with a member template where the template parameters
2534 // have been instantiated, this provides the original template parameters
2535 // from which the member template's parameters were instantiated.
2536
2537 if (Matched.size() >= 1) {
2538 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
2539 if (Matched.size() == 1) {
2540 // -- If exactly one matching specialization is found, the
2541 // instantiation is generated from that specialization.
2542 // We don't need to do anything for this.
2543 } else {
2544 // -- If more than one matching specialization is found, the
2545 // partial order rules (14.5.4.2) are used to determine
2546 // whether one of the specializations is more specialized
2547 // than the others. If none of the specializations is more
2548 // specialized than all of the other matching
2549 // specializations, then the use of the class template is
2550 // ambiguous and the program is ill-formed.
2551 for (SmallVectorImpl<MatchResult>::iterator P = Best + 1,
2552 PEnd = Matched.end();
2553 P != PEnd; ++P) {
2554 if (S.getMoreSpecializedPartialSpecialization(
2555 P->Partial, Best->Partial, PointOfInstantiation) ==
2556 P->Partial)
2557 Best = P;
2558 }
2559
2560 // Determine if the best partial specialization is more specialized than
2561 // the others.
2562 bool Ambiguous = false;
2563 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2564 PEnd = Matched.end();
2565 P != PEnd; ++P) {
2566 if (P != Best && S.getMoreSpecializedPartialSpecialization(
2567 P->Partial, Best->Partial,
2568 PointOfInstantiation) != Best->Partial) {
2569 Ambiguous = true;
2570 break;
2571 }
2572 }
2573
2574 if (Ambiguous) {
2575 // Partial ordering did not produce a clear winner. Complain.
2576 Inst.Clear();
2577 ClassTemplateSpec->setInvalidDecl();
2578 S.Diag(PointOfInstantiation,
2579 diag::err_partial_spec_ordering_ambiguous)
2580 << ClassTemplateSpec;
2581
2582 // Print the matching partial specializations.
2583 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2584 PEnd = Matched.end();
2585 P != PEnd; ++P)
2586 S.Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2587 << S.getTemplateArgumentBindingsText(
2588 P->Partial->getTemplateParameters(), *P->Args);
2589
2590 return nullptr;
2591 }
2592 }
2593
2594 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
2595 } else {
2596 // -- If no matches are found, the instantiation is generated
2597 // from the primary template.
2598 }
2599 }
2600
2601 CXXRecordDecl *Pattern = nullptr;
2602 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
2603 if (auto *PartialSpec =
2604 Specialized.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
2605 // Instantiate using the best class template partial specialization.
2606 while (PartialSpec->getInstantiatedFromMember()) {
2607 // If we've found an explicit specialization of this class template,
2608 // stop here and use that as the pattern.
2609 if (PartialSpec->isMemberSpecialization())
2610 break;
2611
2612 PartialSpec = PartialSpec->getInstantiatedFromMember();
2613 }
2614 Pattern = PartialSpec;
2615 } else {
2616 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
2617 while (Template->getInstantiatedFromMemberTemplate()) {
2618 // If we've found an explicit specialization of this class template,
2619 // stop here and use that as the pattern.
2620 if (Template->isMemberSpecialization())
2621 break;
2622
2623 Template = Template->getInstantiatedFromMemberTemplate();
2624 }
2625 Pattern = Template->getTemplatedDecl();
2626 }
2627
2628 return Pattern;
2629}
2630
2631bool Sema::InstantiateClassTemplateSpecialization(
2632 SourceLocation PointOfInstantiation,
2633 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2634 TemplateSpecializationKind TSK, bool Complain) {
2635 // Perform the actual instantiation on the canonical declaration.
2636 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
2637 ClassTemplateSpec->getCanonicalDecl());
2638 if (ClassTemplateSpec->isInvalidDecl())
2639 return true;
2640
2641 CXXRecordDecl *Pattern = getPatternForClassTemplateSpecialization(
2642 *this, PointOfInstantiation, ClassTemplateSpec, TSK, Complain);
2643 if (!Pattern)
2644 return true;
2645
2646 return InstantiateClass(PointOfInstantiation, ClassTemplateSpec, Pattern,
2647 getTemplateInstantiationArgs(ClassTemplateSpec), TSK,
2648 Complain);
2649}
2650
2651/// Instantiates the definitions of all of the member
2652/// of the given class, which is an instantiation of a class template
2653/// or a member class of a template.
2654void
2655Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
2656 CXXRecordDecl *Instantiation,
2657 const MultiLevelTemplateArgumentList &TemplateArgs,
2658 TemplateSpecializationKind TSK) {
2659 // FIXME: We need to notify the ASTMutationListener that we did all of these
2660 // things, in case we have an explicit instantiation definition in a PCM, a
2661 // module, or preamble, and the declaration is in an imported AST.
2662 assert((((TSK == TSK_ExplicitInstantiationDefinition || TSK == TSK_ExplicitInstantiationDeclaration
|| (TSK == TSK_ImplicitInstantiation && Instantiation
->isLocalClass())) && "Unexpected template specialization kind!"
) ? static_cast<void> (0) : __assert_fail ("(TSK == TSK_ExplicitInstantiationDefinition || TSK == TSK_ExplicitInstantiationDeclaration || (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) && \"Unexpected template specialization kind!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2666, __PRETTY_FUNCTION__))
2663 (TSK == TSK_ExplicitInstantiationDefinition ||(((TSK == TSK_ExplicitInstantiationDefinition || TSK == TSK_ExplicitInstantiationDeclaration
|| (TSK == TSK_ImplicitInstantiation && Instantiation
->isLocalClass())) && "Unexpected template specialization kind!"
) ? static_cast<void> (0) : __assert_fail ("(TSK == TSK_ExplicitInstantiationDefinition || TSK == TSK_ExplicitInstantiationDeclaration || (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) && \"Unexpected template specialization kind!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2666, __PRETTY_FUNCTION__))
2664 TSK == TSK_ExplicitInstantiationDeclaration ||(((TSK == TSK_ExplicitInstantiationDefinition || TSK == TSK_ExplicitInstantiationDeclaration
|| (TSK == TSK_ImplicitInstantiation && Instantiation
->isLocalClass())) && "Unexpected template specialization kind!"
) ? static_cast<void> (0) : __assert_fail ("(TSK == TSK_ExplicitInstantiationDefinition || TSK == TSK_ExplicitInstantiationDeclaration || (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) && \"Unexpected template specialization kind!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2666, __PRETTY_FUNCTION__))
2665 (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&(((TSK == TSK_ExplicitInstantiationDefinition || TSK == TSK_ExplicitInstantiationDeclaration
|| (TSK == TSK_ImplicitInstantiation && Instantiation
->isLocalClass())) && "Unexpected template specialization kind!"
) ? static_cast<void> (0) : __assert_fail ("(TSK == TSK_ExplicitInstantiationDefinition || TSK == TSK_ExplicitInstantiationDeclaration || (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) && \"Unexpected template specialization kind!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2666, __PRETTY_FUNCTION__))
2666 "Unexpected template specialization kind!")(((TSK == TSK_ExplicitInstantiationDefinition || TSK == TSK_ExplicitInstantiationDeclaration
|| (TSK == TSK_ImplicitInstantiation && Instantiation
->isLocalClass())) && "Unexpected template specialization kind!"
) ? static_cast<void> (0) : __assert_fail ("(TSK == TSK_ExplicitInstantiationDefinition || TSK == TSK_ExplicitInstantiationDeclaration || (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) && \"Unexpected template specialization kind!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2666, __PRETTY_FUNCTION__))
;
2667 for (auto *D : Instantiation->decls()) {
2668 bool SuppressNew = false;
2669 if (auto *Function = dyn_cast<FunctionDecl>(D)) {
2670 if (FunctionDecl *Pattern =
2671 Function->getInstantiatedFromMemberFunction()) {
2672
2673 if (Function->hasAttr<ExcludeFromExplicitInstantiationAttr>())
2674 continue;
2675
2676 MemberSpecializationInfo *MSInfo =
2677 Function->getMemberSpecializationInfo();
2678 assert(MSInfo && "No member specialization information?")((MSInfo && "No member specialization information?") ?
static_cast<void> (0) : __assert_fail ("MSInfo && \"No member specialization information?\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2678, __PRETTY_FUNCTION__))
;
2679 if (MSInfo->getTemplateSpecializationKind()
2680 == TSK_ExplicitSpecialization)
2681 continue;
2682
2683 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2684 Function,
2685 MSInfo->getTemplateSpecializationKind(),
2686 MSInfo->getPointOfInstantiation(),
2687 SuppressNew) ||
2688 SuppressNew)
2689 continue;
2690
2691 // C++11 [temp.explicit]p8:
2692 // An explicit instantiation definition that names a class template
2693 // specialization explicitly instantiates the class template
2694 // specialization and is only an explicit instantiation definition
2695 // of members whose definition is visible at the point of
2696 // instantiation.
2697 if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())
2698 continue;
2699
2700 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2701
2702 if (Function->isDefined()) {
2703 // Let the ASTConsumer know that this function has been explicitly
2704 // instantiated now, and its linkage might have changed.
2705 Consumer.HandleTopLevelDecl(DeclGroupRef(Function));
2706 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
2707 InstantiateFunctionDefinition(PointOfInstantiation, Function);
2708 } else if (TSK == TSK_ImplicitInstantiation) {
2709 PendingLocalImplicitInstantiations.push_back(
2710 std::make_pair(Function, PointOfInstantiation));
2711 }
2712 }
2713 } else if (auto *Var = dyn_cast<VarDecl>(D)) {
2714 if (isa<VarTemplateSpecializationDecl>(Var))
2715 continue;
2716
2717 if (Var->isStaticDataMember()) {
2718 if (Var->hasAttr<ExcludeFromExplicitInstantiationAttr>())
2719 continue;
2720
2721 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
2722 assert(MSInfo && "No member specialization information?")((MSInfo && "No member specialization information?") ?
static_cast<void> (0) : __assert_fail ("MSInfo && \"No member specialization information?\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2722, __PRETTY_FUNCTION__))
;
2723 if (MSInfo->getTemplateSpecializationKind()
2724 == TSK_ExplicitSpecialization)
2725 continue;
2726
2727 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2728 Var,
2729 MSInfo->getTemplateSpecializationKind(),
2730 MSInfo->getPointOfInstantiation(),
2731 SuppressNew) ||
2732 SuppressNew)
2733 continue;
2734
2735 if (TSK == TSK_ExplicitInstantiationDefinition) {
2736 // C++0x [temp.explicit]p8:
2737 // An explicit instantiation definition that names a class template
2738 // specialization explicitly instantiates the class template
2739 // specialization and is only an explicit instantiation definition
2740 // of members whose definition is visible at the point of
2741 // instantiation.
2742 if (!Var->getInstantiatedFromStaticDataMember()->getDefinition())
2743 continue;
2744
2745 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2746 InstantiateVariableDefinition(PointOfInstantiation, Var);
2747 } else {
2748 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2749 }
2750 }
2751 } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
2752 if (Record->hasAttr<ExcludeFromExplicitInstantiationAttr>())
2753 continue;
2754
2755 // Always skip the injected-class-name, along with any
2756 // redeclarations of nested classes, since both would cause us
2757 // to try to instantiate the members of a class twice.
2758 // Skip closure types; they'll get instantiated when we instantiate
2759 // the corresponding lambda-expression.
2760 if (Record->isInjectedClassName() || Record->getPreviousDecl() ||
2761 Record->isLambda())
2762 continue;
2763
2764 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
2765 assert(MSInfo && "No member specialization information?")((MSInfo && "No member specialization information?") ?
static_cast<void> (0) : __assert_fail ("MSInfo && \"No member specialization information?\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2765, __PRETTY_FUNCTION__))
;
2766
2767 if (MSInfo->getTemplateSpecializationKind()
2768 == TSK_ExplicitSpecialization)
2769 continue;
2770
2771 if (Context.getTargetInfo().getTriple().isOSWindows() &&
2772 TSK == TSK_ExplicitInstantiationDeclaration) {
2773 // On Windows, explicit instantiation decl of the outer class doesn't
2774 // affect the inner class. Typically extern template declarations are
2775 // used in combination with dll import/export annotations, but those
2776 // are not propagated from the outer class templates to inner classes.
2777 // Therefore, do not instantiate inner classes on this platform, so
2778 // that users don't end up with undefined symbols during linking.
2779 continue;
2780 }
2781
2782 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2783 Record,
2784 MSInfo->getTemplateSpecializationKind(),
2785 MSInfo->getPointOfInstantiation(),
2786 SuppressNew) ||
2787 SuppressNew)
2788 continue;
2789
2790 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2791 assert(Pattern && "Missing instantiated-from-template information")((Pattern && "Missing instantiated-from-template information"
) ? static_cast<void> (0) : __assert_fail ("Pattern && \"Missing instantiated-from-template information\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2791, __PRETTY_FUNCTION__))
;
2792
2793 if (!Record->getDefinition()) {
2794 if (!Pattern->getDefinition()) {
2795 // C++0x [temp.explicit]p8:
2796 // An explicit instantiation definition that names a class template
2797 // specialization explicitly instantiates the class template
2798 // specialization and is only an explicit instantiation definition
2799 // of members whose definition is visible at the point of
2800 // instantiation.
2801 if (TSK == TSK_ExplicitInstantiationDeclaration) {
2802 MSInfo->setTemplateSpecializationKind(TSK);
2803 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2804 }
2805
2806 continue;
2807 }
2808
2809 InstantiateClass(PointOfInstantiation, Record, Pattern,
2810 TemplateArgs,
2811 TSK);
2812 } else {
2813 if (TSK == TSK_ExplicitInstantiationDefinition &&
2814 Record->getTemplateSpecializationKind() ==
2815 TSK_ExplicitInstantiationDeclaration) {
2816 Record->setTemplateSpecializationKind(TSK);
2817 MarkVTableUsed(PointOfInstantiation, Record, true);
2818 }
2819 }
2820
2821 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
2822 if (Pattern)
2823 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
2824 TSK);
2825 } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
2826 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
2827 assert(MSInfo && "No member specialization information?")((MSInfo && "No member specialization information?") ?
static_cast<void> (0) : __assert_fail ("MSInfo && \"No member specialization information?\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2827, __PRETTY_FUNCTION__))
;
2828
2829 if (MSInfo->getTemplateSpecializationKind()
2830 == TSK_ExplicitSpecialization)
2831 continue;
2832
2833 if (CheckSpecializationInstantiationRedecl(
2834 PointOfInstantiation, TSK, Enum,
2835 MSInfo->getTemplateSpecializationKind(),
2836 MSInfo->getPointOfInstantiation(), SuppressNew) ||
2837 SuppressNew)
2838 continue;
2839
2840 if (Enum->getDefinition())
2841 continue;
2842
2843 EnumDecl *Pattern = Enum->getTemplateInstantiationPattern();
2844 assert(Pattern && "Missing instantiated-from-template information")((Pattern && "Missing instantiated-from-template information"
) ? static_cast<void> (0) : __assert_fail ("Pattern && \"Missing instantiated-from-template information\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2844, __PRETTY_FUNCTION__))
;
2845
2846 if (TSK == TSK_ExplicitInstantiationDefinition) {
2847 if (!Pattern->getDefinition())
2848 continue;
2849
2850 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
2851 } else {
2852 MSInfo->setTemplateSpecializationKind(TSK);
2853 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2854 }
2855 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
2856 // No need to instantiate in-class initializers during explicit
2857 // instantiation.
2858 if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) {
2859 CXXRecordDecl *ClassPattern =
2860 Instantiation->getTemplateInstantiationPattern();
2861 DeclContext::lookup_result Lookup =
2862 ClassPattern->lookup(Field->getDeclName());
2863 FieldDecl *Pattern = cast<FieldDecl>(Lookup.front());
2864 InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern,
2865 TemplateArgs);
2866 }
2867 }
2868 }
2869}
2870
2871/// Instantiate the definitions of all of the members of the
2872/// given class template specialization, which was named as part of an
2873/// explicit instantiation.
2874void
2875Sema::InstantiateClassTemplateSpecializationMembers(
2876 SourceLocation PointOfInstantiation,
2877 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2878 TemplateSpecializationKind TSK) {
2879 // C++0x [temp.explicit]p7:
2880 // An explicit instantiation that names a class template
2881 // specialization is an explicit instantion of the same kind
2882 // (declaration or definition) of each of its members (not
2883 // including members inherited from base classes) that has not
2884 // been previously explicitly specialized in the translation unit
2885 // containing the explicit instantiation, except as described
2886 // below.
2887 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
2888 getTemplateInstantiationArgs(ClassTemplateSpec),
2889 TSK);
2890}
2891
2892StmtResult
2893Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
2894 if (!S)
2895 return S;
2896
2897 TemplateInstantiator Instantiator(*this, TemplateArgs,
2898 SourceLocation(),
2899 DeclarationName());
2900 return Instantiator.TransformStmt(S);
2901}
2902
2903ExprResult
2904Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
2905 if (!E)
2906 return E;
2907
2908 TemplateInstantiator Instantiator(*this, TemplateArgs,
2909 SourceLocation(),
2910 DeclarationName());
2911 return Instantiator.TransformExpr(E);
2912}
2913
2914ExprResult Sema::SubstInitializer(Expr *Init,
2915 const MultiLevelTemplateArgumentList &TemplateArgs,
2916 bool CXXDirectInit) {
2917 TemplateInstantiator Instantiator(*this, TemplateArgs,
2918 SourceLocation(),
2919 DeclarationName());
2920 return Instantiator.TransformInitializer(Init, CXXDirectInit);
2921}
2922
2923bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
2924 const MultiLevelTemplateArgumentList &TemplateArgs,
2925 SmallVectorImpl<Expr *> &Outputs) {
2926 if (Exprs.empty())
2927 return false;
2928
2929 TemplateInstantiator Instantiator(*this, TemplateArgs,
2930 SourceLocation(),
2931 DeclarationName());
2932 return Instantiator.TransformExprs(Exprs.data(), Exprs.size(),
2933 IsCall, Outputs);
2934}
2935
2936NestedNameSpecifierLoc
2937Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
2938 const MultiLevelTemplateArgumentList &TemplateArgs) {
2939 if (!NNS)
2940 return NestedNameSpecifierLoc();
2941
2942 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
2943 DeclarationName());
2944 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
2945}
2946
2947/// Do template substitution on declaration name info.
2948DeclarationNameInfo
2949Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
2950 const MultiLevelTemplateArgumentList &TemplateArgs) {
2951 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
2952 NameInfo.getName());
2953 return Instantiator.TransformDeclarationNameInfo(NameInfo);
2954}
2955
2956TemplateName
2957Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,
2958 TemplateName Name, SourceLocation Loc,
2959 const MultiLevelTemplateArgumentList &TemplateArgs) {
2960 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
2961 DeclarationName());
2962 CXXScopeSpec SS;
2963 SS.Adopt(QualifierLoc);
2964 return Instantiator.TransformTemplateName(SS, Name, Loc);
2965}
2966
2967bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
2968 TemplateArgumentListInfo &Result,
2969 const MultiLevelTemplateArgumentList &TemplateArgs) {
2970 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
2971 DeclarationName());
2972
2973 return Instantiator.TransformTemplateArguments(Args, NumArgs, Result);
2974}
2975
2976static const Decl *getCanonicalParmVarDecl(const Decl *D) {
2977 // When storing ParmVarDecls in the local instantiation scope, we always
2978 // want to use the ParmVarDecl from the canonical function declaration,
2979 // since the map is then valid for any redeclaration or definition of that
2980 // function.
2981 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
2982 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
2983 unsigned i = PV->getFunctionScopeIndex();
2984 // This parameter might be from a freestanding function type within the
2985 // function and isn't necessarily referring to one of FD's parameters.
2986 if (i < FD->getNumParams() && FD->getParamDecl(i) == PV)
2987 return FD->getCanonicalDecl()->getParamDecl(i);
2988 }
2989 }
2990 return D;
2991}
2992
2993
2994llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
2995LocalInstantiationScope::findInstantiationOf(const Decl *D) {
2996 D = getCanonicalParmVarDecl(D);
2997 for (LocalInstantiationScope *Current = this; Current;
2998 Current = Current->Outer) {
2999
3000 // Check if we found something within this scope.
3001 const Decl *CheckD = D;
3002 do {
3003 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
3004 if (Found != Current->LocalDecls.end())
3005 return &Found->second;
3006
3007 // If this is a tag declaration, it's possible that we need to look for
3008 // a previous declaration.
3009 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
3010 CheckD = Tag->getPreviousDecl();
3011 else
3012 CheckD = nullptr;
3013 } while (CheckD);
3014
3015 // If we aren't combined with our outer scope, we're done.
3016 if (!Current->CombineWithOuterScope)
3017 break;
3018 }
3019
3020 // If we're performing a partial substitution during template argument
3021 // deduction, we may not have values for template parameters yet.
3022 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
3023 isa<TemplateTemplateParmDecl>(D))
3024 return nullptr;
3025
3026 // Local types referenced prior to definition may require instantiation.
3027 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
3028 if (RD->isLocalClass())
3029 return nullptr;
3030
3031 // Enumeration types referenced prior to definition may appear as a result of
3032 // error recovery.
3033 if (isa<EnumDecl>(D))
3034 return nullptr;
3035
3036 // If we didn't find the decl, then we either have a sema bug, or we have a
3037 // forward reference to a label declaration. Return null to indicate that
3038 // we have an uninstantiated label.
3039 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope")((isa<LabelDecl>(D) && "declaration not instantiated in this scope"
) ? static_cast<void> (0) : __assert_fail ("isa<LabelDecl>(D) && \"declaration not instantiated in this scope\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 3039, __PRETTY_FUNCTION__))
;
3040 return nullptr;
3041}
3042
3043void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
3044 D = getCanonicalParmVarDecl(D);
3045 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
3046 if (Stored.isNull()) {
3047#ifndef NDEBUG
3048 // It should not be present in any surrounding scope either.
3049 LocalInstantiationScope *Current = this;
3050 while (Current->CombineWithOuterScope && Current->Outer) {
3051 Current = Current->Outer;
3052 assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&((Current->LocalDecls.find(D) == Current->LocalDecls.end
() && "Instantiated local in inner and outer scopes")
? static_cast<void> (0) : __assert_fail ("Current->LocalDecls.find(D) == Current->LocalDecls.end() && \"Instantiated local in inner and outer scopes\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 3053, __PRETTY_FUNCTION__))
3053 "Instantiated local in inner and outer scopes")((Current->LocalDecls.find(D) == Current->LocalDecls.end
() && "Instantiated local in inner and outer scopes")
? static_cast<void> (0) : __assert_fail ("Current->LocalDecls.find(D) == Current->LocalDecls.end() && \"Instantiated local in inner and outer scopes\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 3053, __PRETTY_FUNCTION__))
;
3054 }
3055#endif
3056 Stored = Inst;
3057 } else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>()) {
3058 Pack->push_back(cast<VarDecl>(Inst));
3059 } else {
3060 assert(Stored.get<Decl *>() == Inst && "Already instantiated this local")((Stored.get<Decl *>() == Inst && "Already instantiated this local"
) ? static_cast<void> (0) : __assert_fail ("Stored.get<Decl *>() == Inst && \"Already instantiated this local\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 3060, __PRETTY_FUNCTION__))
;
3061 }
3062}
3063
3064void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
3065 VarDecl *Inst) {
3066 D = getCanonicalParmVarDecl(D);
3067 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
3068 Pack->push_back(Inst);
3069}
3070
3071void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
3072#ifndef NDEBUG
3073 // This should be the first time we've been told about this decl.
3074 for (LocalInstantiationScope *Current = this;
3075 Current && Current->CombineWithOuterScope; Current = Current->Outer)
3076 assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&((Current->LocalDecls.find(D) == Current->LocalDecls.end
() && "Creating local pack after instantiation of local"
) ? static_cast<void> (0) : __assert_fail ("Current->LocalDecls.find(D) == Current->LocalDecls.end() && \"Creating local pack after instantiation of local\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 3077, __PRETTY_FUNCTION__))
3077 "Creating local pack after instantiation of local")((Current->LocalDecls.find(D) == Current->LocalDecls.end
() && "Creating local pack after instantiation of local"
) ? static_cast<void> (0) : __assert_fail ("Current->LocalDecls.find(D) == Current->LocalDecls.end() && \"Creating local pack after instantiation of local\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 3077, __PRETTY_FUNCTION__))
;
3078#endif
3079
3080 D = getCanonicalParmVarDecl(D);
3081 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
3082 DeclArgumentPack *Pack = new DeclArgumentPack;
3083 Stored = Pack;
3084 ArgumentPacks.push_back(Pack);
3085}
3086
3087void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
3088 const TemplateArgument *ExplicitArgs,
3089 unsigned NumExplicitArgs) {
3090 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&(((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack
) && "Already have a partially-substituted pack") ? static_cast
<void> (0) : __assert_fail ("(!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) && \"Already have a partially-substituted pack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 3091, __PRETTY_FUNCTION__))
3091 "Already have a partially-substituted pack")(((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack
) && "Already have a partially-substituted pack") ? static_cast
<void> (0) : __assert_fail ("(!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) && \"Already have a partially-substituted pack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 3091, __PRETTY_FUNCTION__))
;
3092 assert((!PartiallySubstitutedPack(((!PartiallySubstitutedPack || NumArgsInPartiallySubstitutedPack
== NumExplicitArgs) && "Wrong number of arguments in partially-substituted pack"
) ? static_cast<void> (0) : __assert_fail ("(!PartiallySubstitutedPack || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) && \"Wrong number of arguments in partially-substituted pack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 3094, __PRETTY_FUNCTION__))
3093 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&(((!PartiallySubstitutedPack || NumArgsInPartiallySubstitutedPack
== NumExplicitArgs) && "Wrong number of arguments in partially-substituted pack"
) ? static_cast<void> (0) : __assert_fail ("(!PartiallySubstitutedPack || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) && \"Wrong number of arguments in partially-substituted pack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 3094, __PRETTY_FUNCTION__))
3094 "Wrong number of arguments in partially-substituted pack")(((!PartiallySubstitutedPack || NumArgsInPartiallySubstitutedPack
== NumExplicitArgs) && "Wrong number of arguments in partially-substituted pack"
) ? static_cast<void> (0) : __assert_fail ("(!PartiallySubstitutedPack || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) && \"Wrong number of arguments in partially-substituted pack\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 3094, __PRETTY_FUNCTION__))
;
3095 PartiallySubstitutedPack = Pack;
3096 ArgsInPartiallySubstitutedPack = ExplicitArgs;
3097 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
3098}
3099
3100NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
3101 const TemplateArgument **ExplicitArgs,
3102 unsigned *NumExplicitArgs) const {
3103 if (ExplicitArgs)
3104 *ExplicitArgs = nullptr;
3105 if (NumExplicitArgs)
3106 *NumExplicitArgs = 0;
3107
3108 for (const LocalInstantiationScope *Current = this; Current;
3109 Current = Current->Outer) {
3110 if (Current->PartiallySubstitutedPack) {
3111 if (ExplicitArgs)
3112 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
3113 if (NumExplicitArgs)
3114 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
3115
3116 return Current->PartiallySubstitutedPack;
3117 }
3118
3119 if (!Current->CombineWithOuterScope)
3120 break;
3121 }
3122
3123 return nullptr;
3124}

/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/ASTLambda.h

1//===--- ASTLambda.h - Lambda Helper Functions --------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file
10/// This file provides some common utility functions for processing
11/// Lambda related AST Constructs.
12///
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_CLANG_AST_ASTLAMBDA_H
16#define LLVM_CLANG_AST_ASTLAMBDA_H
17
18#include "clang/AST/DeclCXX.h"
19#include "clang/AST/DeclTemplate.h"
20
21namespace clang {
22inline StringRef getLambdaStaticInvokerName() {
23 return "__invoke";
24}
25// This function returns true if M is a specialization, a template,
26// or a non-generic lambda call operator.
27inline bool isLambdaCallOperator(const CXXMethodDecl *MD) {
28 const CXXRecordDecl *LambdaClass = MD->getParent();
29 if (!LambdaClass
6.1
'LambdaClass' is non-null, which participates in a condition later
6.1
'LambdaClass' is non-null, which participates in a condition later
6.1
'LambdaClass' is non-null, which participates in a condition later
|| !LambdaClass->isLambda()) return false;
7
Calling 'CXXRecordDecl::isLambda'
10
Returning from 'CXXRecordDecl::isLambda'
11
Assuming the condition is false
12
Taking false branch
30 return MD->getOverloadedOperator() == OO_Call;
13
Assuming the condition is true
14
Returning the value 1, which participates in a condition later
31}
32
33inline bool isLambdaCallOperator(const DeclContext *DC) {
34 if (!DC || !isa<CXXMethodDecl>(DC)) return false;
35 return isLambdaCallOperator(cast<CXXMethodDecl>(DC));
36}
37
38inline bool isGenericLambdaCallOperatorSpecialization(const CXXMethodDecl *MD) {
39 if (!MD) return false;
40 const CXXRecordDecl *LambdaClass = MD->getParent();
41 if (LambdaClass && LambdaClass->isGenericLambda())
42 return isLambdaCallOperator(MD) &&
43 MD->isFunctionTemplateSpecialization();
44 return false;
45}
46
47inline bool isLambdaConversionOperator(CXXConversionDecl *C) {
48 return C ? C->getParent()->isLambda() : false;
49}
50
51inline bool isLambdaConversionOperator(Decl *D) {
52 if (!D) return false;
53 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D))
54 return isLambdaConversionOperator(Conv);
55 if (FunctionTemplateDecl *F = dyn_cast<FunctionTemplateDecl>(D))
56 if (CXXConversionDecl *Conv =
57 dyn_cast_or_null<CXXConversionDecl>(F->getTemplatedDecl()))
58 return isLambdaConversionOperator(Conv);
59 return false;
60}
61
62inline bool isGenericLambdaCallOperatorSpecialization(DeclContext *DC) {
63 return isGenericLambdaCallOperatorSpecialization(
64 dyn_cast<CXXMethodDecl>(DC));
65}
66
67
68// This returns the parent DeclContext ensuring that the correct
69// parent DeclContext is returned for Lambdas
70inline DeclContext *getLambdaAwareParentOfDeclContext(DeclContext *DC) {
71 if (isLambdaCallOperator(DC))
72 return DC->getParent()->getParent();
73 else
74 return DC->getParent();
75}
76
77} // clang
78
79#endif

/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclCXX.h

1//===- DeclCXX.h - Classes for representing C++ declarations --*- C++ -*-=====//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9/// \file
10/// Defines the C++ Decl subclasses, other than those for templates
11/// (found in DeclTemplate.h) and friends (in DeclFriend.h).
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_CLANG_AST_DECLCXX_H
16#define LLVM_CLANG_AST_DECLCXX_H
17
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/ASTUnresolvedSet.h"
20#include "clang/AST/Attr.h"
21#include "clang/AST/Decl.h"
22#include "clang/AST/DeclBase.h"
23#include "clang/AST/DeclarationName.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExternalASTSource.h"
26#include "clang/AST/LambdaCapture.h"
27#include "clang/AST/NestedNameSpecifier.h"
28#include "clang/AST/Redeclarable.h"
29#include "clang/AST/Stmt.h"
30#include "clang/AST/Type.h"
31#include "clang/AST/TypeLoc.h"
32#include "clang/AST/UnresolvedSet.h"
33#include "clang/Basic/LLVM.h"
34#include "clang/Basic/Lambda.h"
35#include "clang/Basic/LangOptions.h"
36#include "clang/Basic/OperatorKinds.h"
37#include "clang/Basic/SourceLocation.h"
38#include "clang/Basic/Specifiers.h"
39#include "llvm/ADT/ArrayRef.h"
40#include "llvm/ADT/DenseMap.h"
41#include "llvm/ADT/PointerIntPair.h"
42#include "llvm/ADT/PointerUnion.h"
43#include "llvm/ADT/STLExtras.h"
44#include "llvm/ADT/iterator_range.h"
45#include "llvm/BinaryFormat/Dwarf.h"
46#include "llvm/Support/Casting.h"
47#include "llvm/Support/Compiler.h"
48#include "llvm/Support/PointerLikeTypeTraits.h"
49#include "llvm/Support/TrailingObjects.h"
50#include <cassert>
51#include <cstddef>
52#include <iterator>
53#include <memory>
54#include <vector>
55
56namespace clang {
57
58class ClassTemplateDecl;
59class ConstructorUsingShadowDecl;
60class CXXBasePath;
61class CXXBasePaths;
62class CXXConstructorDecl;
63class CXXDestructorDecl;
64class CXXFinalOverriderMap;
65class CXXIndirectPrimaryBaseSet;
66class CXXMethodDecl;
67class DecompositionDecl;
68class DiagnosticBuilder;
69class FriendDecl;
70class FunctionTemplateDecl;
71class IdentifierInfo;
72class MemberSpecializationInfo;
73class TemplateDecl;
74class TemplateParameterList;
75class UsingDecl;
76
77/// Represents an access specifier followed by colon ':'.
78///
79/// An objects of this class represents sugar for the syntactic occurrence
80/// of an access specifier followed by a colon in the list of member
81/// specifiers of a C++ class definition.
82///
83/// Note that they do not represent other uses of access specifiers,
84/// such as those occurring in a list of base specifiers.
85/// Also note that this class has nothing to do with so-called
86/// "access declarations" (C++98 11.3 [class.access.dcl]).
87class AccessSpecDecl : public Decl {
88 /// The location of the ':'.
89 SourceLocation ColonLoc;
90
91 AccessSpecDecl(AccessSpecifier AS, DeclContext *DC,
92 SourceLocation ASLoc, SourceLocation ColonLoc)
93 : Decl(AccessSpec, DC, ASLoc), ColonLoc(ColonLoc) {
94 setAccess(AS);
95 }
96
97 AccessSpecDecl(EmptyShell Empty) : Decl(AccessSpec, Empty) {}
98
99 virtual void anchor();
100
101public:
102 /// The location of the access specifier.
103 SourceLocation getAccessSpecifierLoc() const { return getLocation(); }
104
105 /// Sets the location of the access specifier.
106 void setAccessSpecifierLoc(SourceLocation ASLoc) { setLocation(ASLoc); }
107
108 /// The location of the colon following the access specifier.
109 SourceLocation getColonLoc() const { return ColonLoc; }
110
111 /// Sets the location of the colon.
112 void setColonLoc(SourceLocation CLoc) { ColonLoc = CLoc; }
113
114 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
115 return SourceRange(getAccessSpecifierLoc(), getColonLoc());
116 }
117
118 static AccessSpecDecl *Create(ASTContext &C, AccessSpecifier AS,
119 DeclContext *DC, SourceLocation ASLoc,
120 SourceLocation ColonLoc) {
121 return new (C, DC) AccessSpecDecl(AS, DC, ASLoc, ColonLoc);
122 }
123
124 static AccessSpecDecl *CreateDeserialized(ASTContext &C, unsigned ID);
125
126 // Implement isa/cast/dyncast/etc.
127 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
128 static bool classofKind(Kind K) { return K == AccessSpec; }
129};
130
131/// Represents a base class of a C++ class.
132///
133/// Each CXXBaseSpecifier represents a single, direct base class (or
134/// struct) of a C++ class (or struct). It specifies the type of that
135/// base class, whether it is a virtual or non-virtual base, and what
136/// level of access (public, protected, private) is used for the
137/// derivation. For example:
138///
139/// \code
140/// class A { };
141/// class B { };
142/// class C : public virtual A, protected B { };
143/// \endcode
144///
145/// In this code, C will have two CXXBaseSpecifiers, one for "public
146/// virtual A" and the other for "protected B".
147class CXXBaseSpecifier {
148 /// The source code range that covers the full base
149 /// specifier, including the "virtual" (if present) and access
150 /// specifier (if present).
151 SourceRange Range;
152
153 /// The source location of the ellipsis, if this is a pack
154 /// expansion.
155 SourceLocation EllipsisLoc;
156
157 /// Whether this is a virtual base class or not.
158 unsigned Virtual : 1;
159
160 /// Whether this is the base of a class (true) or of a struct (false).
161 ///
162 /// This determines the mapping from the access specifier as written in the
163 /// source code to the access specifier used for semantic analysis.
164 unsigned BaseOfClass : 1;
165
166 /// Access specifier as written in the source code (may be AS_none).
167 ///
168 /// The actual type of data stored here is an AccessSpecifier, but we use
169 /// "unsigned" here to work around a VC++ bug.
170 unsigned Access : 2;
171
172 /// Whether the class contains a using declaration
173 /// to inherit the named class's constructors.
174 unsigned InheritConstructors : 1;
175
176 /// The type of the base class.
177 ///
178 /// This will be a class or struct (or a typedef of such). The source code
179 /// range does not include the \c virtual or the access specifier.
180 TypeSourceInfo *BaseTypeInfo;
181
182public:
183 CXXBaseSpecifier() = default;
184 CXXBaseSpecifier(SourceRange R, bool V, bool BC, AccessSpecifier A,
185 TypeSourceInfo *TInfo, SourceLocation EllipsisLoc)
186 : Range(R), EllipsisLoc(EllipsisLoc), Virtual(V), BaseOfClass(BC),
187 Access(A), InheritConstructors(false), BaseTypeInfo(TInfo) {}
188
189 /// Retrieves the source range that contains the entire base specifier.
190 SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) { return Range; }
191 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Range.getBegin(); }
192 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return Range.getEnd(); }
193
194 /// Get the location at which the base class type was written.
195 SourceLocation getBaseTypeLoc() const LLVM_READONLY__attribute__((__pure__)) {
196 return BaseTypeInfo->getTypeLoc().getBeginLoc();
197 }
198
199 /// Determines whether the base class is a virtual base class (or not).
200 bool isVirtual() const { return Virtual; }
201
202 /// Determine whether this base class is a base of a class declared
203 /// with the 'class' keyword (vs. one declared with the 'struct' keyword).
204 bool isBaseOfClass() const { return BaseOfClass; }
205
206 /// Determine whether this base specifier is a pack expansion.
207 bool isPackExpansion() const { return EllipsisLoc.isValid(); }
208
209 /// Determine whether this base class's constructors get inherited.
210 bool getInheritConstructors() const { return InheritConstructors; }
211
212 /// Set that this base class's constructors should be inherited.
213 void setInheritConstructors(bool Inherit = true) {
214 InheritConstructors = Inherit;
215 }
216
217 /// For a pack expansion, determine the location of the ellipsis.
218 SourceLocation getEllipsisLoc() const {
219 return EllipsisLoc;
220 }
221
222 /// Returns the access specifier for this base specifier.
223 ///
224 /// This is the actual base specifier as used for semantic analysis, so
225 /// the result can never be AS_none. To retrieve the access specifier as
226 /// written in the source code, use getAccessSpecifierAsWritten().
227 AccessSpecifier getAccessSpecifier() const {
228 if ((AccessSpecifier)Access == AS_none)
229 return BaseOfClass? AS_private : AS_public;
230 else
231 return (AccessSpecifier)Access;
232 }
233
234 /// Retrieves the access specifier as written in the source code
235 /// (which may mean that no access specifier was explicitly written).
236 ///
237 /// Use getAccessSpecifier() to retrieve the access specifier for use in
238 /// semantic analysis.
239 AccessSpecifier getAccessSpecifierAsWritten() const {
240 return (AccessSpecifier)Access;
241 }
242
243 /// Retrieves the type of the base class.
244 ///
245 /// This type will always be an unqualified class type.
246 QualType getType() const {
247 return BaseTypeInfo->getType().getUnqualifiedType();
248 }
249
250 /// Retrieves the type and source location of the base class.
251 TypeSourceInfo *getTypeSourceInfo() const { return BaseTypeInfo; }
252};
253
254/// Represents a C++ struct/union/class.
255class CXXRecordDecl : public RecordDecl {
256 friend class ASTDeclReader;
257 friend class ASTDeclWriter;
258 friend class ASTNodeImporter;
259 friend class ASTReader;
260 friend class ASTRecordWriter;
261 friend class ASTWriter;
262 friend class DeclContext;
263 friend class LambdaExpr;
264
265 friend void FunctionDecl::setPure(bool);
266 friend void TagDecl::startDefinition();
267
268 /// Values used in DefinitionData fields to represent special members.
269 enum SpecialMemberFlags {
270 SMF_DefaultConstructor = 0x1,
271 SMF_CopyConstructor = 0x2,
272 SMF_MoveConstructor = 0x4,
273 SMF_CopyAssignment = 0x8,
274 SMF_MoveAssignment = 0x10,
275 SMF_Destructor = 0x20,
276 SMF_All = 0x3f
277 };
278
279 struct DefinitionData {
280 #define FIELD(Name, Width, Merge) \
281 unsigned Name : Width;
282 #include "CXXRecordDeclDefinitionBits.def"
283
284 /// Whether this class describes a C++ lambda.
285 unsigned IsLambda : 1;
286
287 /// Whether we are currently parsing base specifiers.
288 unsigned IsParsingBaseSpecifiers : 1;
289
290 /// True when visible conversion functions are already computed
291 /// and are available.
292 unsigned ComputedVisibleConversions : 1;
293
294 unsigned HasODRHash : 1;
295
296 /// A hash of parts of the class to help in ODR checking.
297 unsigned ODRHash = 0;
298
299 /// The number of base class specifiers in Bases.
300 unsigned NumBases = 0;
301
302 /// The number of virtual base class specifiers in VBases.
303 unsigned NumVBases = 0;
304
305 /// Base classes of this class.
306 ///
307 /// FIXME: This is wasted space for a union.
308 LazyCXXBaseSpecifiersPtr Bases;
309
310 /// direct and indirect virtual base classes of this class.
311 LazyCXXBaseSpecifiersPtr VBases;
312
313 /// The conversion functions of this C++ class (but not its
314 /// inherited conversion functions).
315 ///
316 /// Each of the entries in this overload set is a CXXConversionDecl.
317 LazyASTUnresolvedSet Conversions;
318
319 /// The conversion functions of this C++ class and all those
320 /// inherited conversion functions that are visible in this class.
321 ///
322 /// Each of the entries in this overload set is a CXXConversionDecl or a
323 /// FunctionTemplateDecl.
324 LazyASTUnresolvedSet VisibleConversions;
325
326 /// The declaration which defines this record.
327 CXXRecordDecl *Definition;
328
329 /// The first friend declaration in this class, or null if there
330 /// aren't any.
331 ///
332 /// This is actually currently stored in reverse order.
333 LazyDeclPtr FirstFriend;
334
335 DefinitionData(CXXRecordDecl *D);
336
337 /// Retrieve the set of direct base classes.
338 CXXBaseSpecifier *getBases() const {
339 if (!Bases.isOffset())
340 return Bases.get(nullptr);
341 return getBasesSlowCase();
342 }
343
344 /// Retrieve the set of virtual base classes.
345 CXXBaseSpecifier *getVBases() const {
346 if (!VBases.isOffset())
347 return VBases.get(nullptr);
348 return getVBasesSlowCase();
349 }
350
351 ArrayRef<CXXBaseSpecifier> bases() const {
352 return llvm::makeArrayRef(getBases(), NumBases);
353 }
354
355 ArrayRef<CXXBaseSpecifier> vbases() const {
356 return llvm::makeArrayRef(getVBases(), NumVBases);
357 }
358
359 private:
360 CXXBaseSpecifier *getBasesSlowCase() const;
361 CXXBaseSpecifier *getVBasesSlowCase() const;
362 };
363
364 struct DefinitionData *DefinitionData;
365
366 /// Describes a C++ closure type (generated by a lambda expression).
367 struct LambdaDefinitionData : public DefinitionData {
368 using Capture = LambdaCapture;
369
370 /// Whether this lambda is known to be dependent, even if its
371 /// context isn't dependent.
372 ///
373 /// A lambda with a non-dependent context can be dependent if it occurs
374 /// within the default argument of a function template, because the
375 /// lambda will have been created with the enclosing context as its
376 /// declaration context, rather than function. This is an unfortunate
377 /// artifact of having to parse the default arguments before.
378 unsigned Dependent : 1;
379
380 /// Whether this lambda is a generic lambda.
381 unsigned IsGenericLambda : 1;
382
383 /// The Default Capture.
384 unsigned CaptureDefault : 2;
385
386 /// The number of captures in this lambda is limited 2^NumCaptures.
387 unsigned NumCaptures : 15;
388
389 /// The number of explicit captures in this lambda.
390 unsigned NumExplicitCaptures : 13;
391
392 /// Has known `internal` linkage.
393 unsigned HasKnownInternalLinkage : 1;
394
395 /// The number used to indicate this lambda expression for name
396 /// mangling in the Itanium C++ ABI.
397 unsigned ManglingNumber : 31;
398
399 /// The declaration that provides context for this lambda, if the
400 /// actual DeclContext does not suffice. This is used for lambdas that
401 /// occur within default arguments of function parameters within the class
402 /// or within a data member initializer.
403 LazyDeclPtr ContextDecl;
404
405 /// The list of captures, both explicit and implicit, for this
406 /// lambda.
407 Capture *Captures = nullptr;
408
409 /// The type of the call method.
410 TypeSourceInfo *MethodTyInfo;
411
412 LambdaDefinitionData(CXXRecordDecl *D, TypeSourceInfo *Info, bool Dependent,
413 bool IsGeneric, LambdaCaptureDefault CaptureDefault)
414 : DefinitionData(D), Dependent(Dependent), IsGenericLambda(IsGeneric),
415 CaptureDefault(CaptureDefault), NumCaptures(0),
416 NumExplicitCaptures(0), HasKnownInternalLinkage(0), ManglingNumber(0),
417 MethodTyInfo(Info) {
418 IsLambda = true;
419
420 // C++1z [expr.prim.lambda]p4:
421 // This class type is not an aggregate type.
422 Aggregate = false;
423 PlainOldData = false;
424 }
425 };
426
427 struct DefinitionData *dataPtr() const {
428 // Complete the redecl chain (if necessary).
429 getMostRecentDecl();
430 return DefinitionData;
431 }
432
433 struct DefinitionData &data() const {
434 auto *DD = dataPtr();
435 assert(DD && "queried property of class with no definition")((DD && "queried property of class with no definition"
) ? static_cast<void> (0) : __assert_fail ("DD && \"queried property of class with no definition\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclCXX.h"
, 435, __PRETTY_FUNCTION__))
;
436 return *DD;
437 }
438
439 struct LambdaDefinitionData &getLambdaData() const {
440 // No update required: a merged definition cannot change any lambda
441 // properties.
442 auto *DD = DefinitionData;
443 assert(DD && DD->IsLambda && "queried lambda property of non-lambda class")((DD && DD->IsLambda && "queried lambda property of non-lambda class"
) ? static_cast<void> (0) : __assert_fail ("DD && DD->IsLambda && \"queried lambda property of non-lambda class\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclCXX.h"
, 443, __PRETTY_FUNCTION__))
;
444 return static_cast<LambdaDefinitionData&>(*DD);
445 }
446
447 /// The template or declaration that this declaration
448 /// describes or was instantiated from, respectively.
449 ///
450 /// For non-templates, this value will be null. For record
451 /// declarations that describe a class template, this will be a
452 /// pointer to a ClassTemplateDecl. For member
453 /// classes of class template specializations, this will be the
454 /// MemberSpecializationInfo referring to the member class that was
455 /// instantiated or specialized.
456 llvm::PointerUnion<ClassTemplateDecl *, MemberSpecializationInfo *>
457 TemplateOrInstantiation;
458
459 /// Called from setBases and addedMember to notify the class that a
460 /// direct or virtual base class or a member of class type has been added.
461 void addedClassSubobject(CXXRecordDecl *Base);
462
463 /// Notify the class that member has been added.
464 ///
465 /// This routine helps maintain information about the class based on which
466 /// members have been added. It will be invoked by DeclContext::addDecl()
467 /// whenever a member is added to this record.
468 void addedMember(Decl *D);
469
470 void markedVirtualFunctionPure();
471
472 /// Get the head of our list of friend declarations, possibly
473 /// deserializing the friends from an external AST source.
474 FriendDecl *getFirstFriend() const;
475
476 /// Determine whether this class has an empty base class subobject of type X
477 /// or of one of the types that might be at offset 0 within X (per the C++
478 /// "standard layout" rules).
479 bool hasSubobjectAtOffsetZeroOfEmptyBaseType(ASTContext &Ctx,
480 const CXXRecordDecl *X);
481
482protected:
483 CXXRecordDecl(Kind K, TagKind TK, const ASTContext &C, DeclContext *DC,
484 SourceLocation StartLoc, SourceLocation IdLoc,
485 IdentifierInfo *Id, CXXRecordDecl *PrevDecl);
486
487public:
488 /// Iterator that traverses the base classes of a class.
489 using base_class_iterator = CXXBaseSpecifier *;
490
491 /// Iterator that traverses the base classes of a class.
492 using base_class_const_iterator = const CXXBaseSpecifier *;
493
494 CXXRecordDecl *getCanonicalDecl() override {
495 return cast<CXXRecordDecl>(RecordDecl::getCanonicalDecl());
496 }
497
498 const CXXRecordDecl *getCanonicalDecl() const {
499 return const_cast<CXXRecordDecl*>(this)->getCanonicalDecl();
500 }
501
502 CXXRecordDecl *getPreviousDecl() {
503 return cast_or_null<CXXRecordDecl>(
504 static_cast<RecordDecl *>(this)->getPreviousDecl());
505 }
506
507 const CXXRecordDecl *getPreviousDecl() const {
508 return const_cast<CXXRecordDecl*>(this)->getPreviousDecl();
509 }
510
511 CXXRecordDecl *getMostRecentDecl() {
512 return cast<CXXRecordDecl>(
513 static_cast<RecordDecl *>(this)->getMostRecentDecl());
514 }
515
516 const CXXRecordDecl *getMostRecentDecl() const {
517 return const_cast<CXXRecordDecl*>(this)->getMostRecentDecl();
518 }
519
520 CXXRecordDecl *getMostRecentNonInjectedDecl() {
521 CXXRecordDecl *Recent =
522 static_cast<CXXRecordDecl *>(this)->getMostRecentDecl();
523 while (Recent->isInjectedClassName()) {
524 // FIXME: Does injected class name need to be in the redeclarations chain?
525 assert(Recent->getPreviousDecl())((Recent->getPreviousDecl()) ? static_cast<void> (0)
: __assert_fail ("Recent->getPreviousDecl()", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclCXX.h"
, 525, __PRETTY_FUNCTION__))
;
526 Recent = Recent->getPreviousDecl();
527 }
528 return Recent;
529 }
530
531 const CXXRecordDecl *getMostRecentNonInjectedDecl() const {
532 return const_cast<CXXRecordDecl*>(this)->getMostRecentNonInjectedDecl();
533 }
534
535 CXXRecordDecl *getDefinition() const {
536 // We only need an update if we don't already know which
537 // declaration is the definition.
538 auto *DD = DefinitionData ? DefinitionData : dataPtr();
539 return DD ? DD->Definition : nullptr;
540 }
541
542 bool hasDefinition() const { return DefinitionData || dataPtr(); }
543
544 static CXXRecordDecl *Create(const ASTContext &C, TagKind TK, DeclContext *DC,
545 SourceLocation StartLoc, SourceLocation IdLoc,
546 IdentifierInfo *Id,
547 CXXRecordDecl *PrevDecl = nullptr,
548 bool DelayTypeCreation = false);
549 static CXXRecordDecl *CreateLambda(const ASTContext &C, DeclContext *DC,
550 TypeSourceInfo *Info, SourceLocation Loc,
551 bool DependentLambda, bool IsGeneric,
552 LambdaCaptureDefault CaptureDefault);
553 static CXXRecordDecl *CreateDeserialized(const ASTContext &C, unsigned ID);
554
555 bool isDynamicClass() const {
556 return data().Polymorphic || data().NumVBases != 0;
557 }
558
559 /// @returns true if class is dynamic or might be dynamic because the
560 /// definition is incomplete of dependent.
561 bool mayBeDynamicClass() const {
562 return !hasDefinition() || isDynamicClass() || hasAnyDependentBases();
563 }
564
565 /// @returns true if class is non dynamic or might be non dynamic because the
566 /// definition is incomplete of dependent.
567 bool mayBeNonDynamicClass() const {
568 return !hasDefinition() || !isDynamicClass() || hasAnyDependentBases();
569 }
570
571 void setIsParsingBaseSpecifiers() { data().IsParsingBaseSpecifiers = true; }
572
573 bool isParsingBaseSpecifiers() const {
574 return data().IsParsingBaseSpecifiers;
575 }
576
577 unsigned getODRHash() const;
578
579 /// Sets the base classes of this struct or class.
580 void setBases(CXXBaseSpecifier const * const *Bases, unsigned NumBases);
581
582 /// Retrieves the number of base classes of this class.
583 unsigned getNumBases() const { return data().NumBases; }
584
585 using base_class_range = llvm::iterator_range<base_class_iterator>;
586 using base_class_const_range =
587 llvm::iterator_range<base_class_const_iterator>;
588
589 base_class_range bases() {
590 return base_class_range(bases_begin(), bases_end());
591 }
592 base_class_const_range bases() const {
593 return base_class_const_range(bases_begin(), bases_end());
594 }
595
596 base_class_iterator bases_begin() { return data().getBases(); }
597 base_class_const_iterator bases_begin() const { return data().getBases(); }
598 base_class_iterator bases_end() { return bases_begin() + data().NumBases; }
599 base_class_const_iterator bases_end() const {
600 return bases_begin() + data().NumBases;
601 }
602
603 /// Retrieves the number of virtual base classes of this class.
604 unsigned getNumVBases() const { return data().NumVBases; }
605
606 base_class_range vbases() {
607 return base_class_range(vbases_begin(), vbases_end());
608 }
609 base_class_const_range vbases() const {
610 return base_class_const_range(vbases_begin(), vbases_end());
611 }
612
613 base_class_iterator vbases_begin() { return data().getVBases(); }
614 base_class_const_iterator vbases_begin() const { return data().getVBases(); }
615 base_class_iterator vbases_end() { return vbases_begin() + data().NumVBases; }
616 base_class_const_iterator vbases_end() const {
617 return vbases_begin() + data().NumVBases;
618 }
619
620 /// Determine whether this class has any dependent base classes which
621 /// are not the current instantiation.
622 bool hasAnyDependentBases() const;
623
624 /// Iterator access to method members. The method iterator visits
625 /// all method members of the class, including non-instance methods,
626 /// special methods, etc.
627 using method_iterator = specific_decl_iterator<CXXMethodDecl>;
628 using method_range =
629 llvm::iterator_range<specific_decl_iterator<CXXMethodDecl>>;
630
631 method_range methods() const {
632 return method_range(method_begin(), method_end());
633 }
634
635 /// Method begin iterator. Iterates in the order the methods
636 /// were declared.
637 method_iterator method_begin() const {
638 return method_iterator(decls_begin());
639 }
640
641 /// Method past-the-end iterator.
642 method_iterator method_end() const {
643 return method_iterator(decls_end());
644 }
645
646 /// Iterator access to constructor members.
647 using ctor_iterator = specific_decl_iterator<CXXConstructorDecl>;
648 using ctor_range =
649 llvm::iterator_range<specific_decl_iterator<CXXConstructorDecl>>;
650
651 ctor_range ctors() const { return ctor_range(ctor_begin(), ctor_end()); }
652
653 ctor_iterator ctor_begin() const {
654 return ctor_iterator(decls_begin());
655 }
656
657 ctor_iterator ctor_end() const {
658 return ctor_iterator(decls_end());
659 }
660
661 /// An iterator over friend declarations. All of these are defined
662 /// in DeclFriend.h.
663 class friend_iterator;
664 using friend_range = llvm::iterator_range<friend_iterator>;
665
666 friend_range friends() const;
667 friend_iterator friend_begin() const;
668 friend_iterator friend_end() const;
669 void pushFriendDecl(FriendDecl *FD);
670
671 /// Determines whether this record has any friends.
672 bool hasFriends() const {
673 return data().FirstFriend.isValid();
674 }
675
676 /// \c true if a defaulted copy constructor for this class would be
677 /// deleted.
678 bool defaultedCopyConstructorIsDeleted() const {
679 assert((!needsOverloadResolutionForCopyConstructor() ||(((!needsOverloadResolutionForCopyConstructor() || (data().DeclaredSpecialMembers
& SMF_CopyConstructor)) && "this property has not yet been computed by Sema"
) ? static_cast<void> (0) : __assert_fail ("(!needsOverloadResolutionForCopyConstructor() || (data().DeclaredSpecialMembers & SMF_CopyConstructor)) && \"this property has not yet been computed by Sema\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclCXX.h"
, 681, __PRETTY_FUNCTION__))
680 (data().DeclaredSpecialMembers & SMF_CopyConstructor)) &&(((!needsOverloadResolutionForCopyConstructor() || (data().DeclaredSpecialMembers
& SMF_CopyConstructor)) && "this property has not yet been computed by Sema"
) ? static_cast<void> (0) : __assert_fail ("(!needsOverloadResolutionForCopyConstructor() || (data().DeclaredSpecialMembers & SMF_CopyConstructor)) && \"this property has not yet been computed by Sema\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclCXX.h"
, 681, __PRETTY_FUNCTION__))
681 "this property has not yet been computed by Sema")(((!needsOverloadResolutionForCopyConstructor() || (data().DeclaredSpecialMembers
& SMF_CopyConstructor)) && "this property has not yet been computed by Sema"
) ? static_cast<void> (0) : __assert_fail ("(!needsOverloadResolutionForCopyConstructor() || (data().DeclaredSpecialMembers & SMF_CopyConstructor)) && \"this property has not yet been computed by Sema\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclCXX.h"
, 681, __PRETTY_FUNCTION__))
;
682 return data().DefaultedCopyConstructorIsDeleted;
683 }
684
685 /// \c true if a defaulted move constructor for this class would be
686 /// deleted.
687 bool defaultedMoveConstructorIsDeleted() const {
688 assert((!needsOverloadResolutionForMoveConstructor() ||(((!needsOverloadResolutionForMoveConstructor() || (data().DeclaredSpecialMembers
& SMF_MoveConstructor)) && "this property has not yet been computed by Sema"
) ? static_cast<void> (0) : __assert_fail ("(!needsOverloadResolutionForMoveConstructor() || (data().DeclaredSpecialMembers & SMF_MoveConstructor)) && \"this property has not yet been computed by Sema\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclCXX.h"
, 690, __PRETTY_FUNCTION__))
689 (data().DeclaredSpecialMembers & SMF_MoveConstructor)) &&(((!needsOverloadResolutionForMoveConstructor() || (data().DeclaredSpecialMembers
& SMF_MoveConstructor)) && "this property has not yet been computed by Sema"
) ? static_cast<void> (0) : __assert_fail ("(!needsOverloadResolutionForMoveConstructor() || (data().DeclaredSpecialMembers & SMF_MoveConstructor)) && \"this property has not yet been computed by Sema\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclCXX.h"
, 690, __PRETTY_FUNCTION__))
690 "this property has not yet been computed by Sema")(((!needsOverloadResolutionForMoveConstructor() || (data().DeclaredSpecialMembers
& SMF_MoveConstructor)) && "this property has not yet been computed by Sema"
) ? static_cast<void> (0) : __assert_fail ("(!needsOverloadResolutionForMoveConstructor() || (data().DeclaredSpecialMembers & SMF_MoveConstructor)) && \"this property has not yet been computed by Sema\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclCXX.h"
, 690, __PRETTY_FUNCTION__))
;
691 return data().DefaultedMoveConstructorIsDeleted;
692 }
693
694 /// \c true if a defaulted destructor for this class would be deleted.
695 bool defaultedDestructorIsDeleted() const {
696 assert((!needsOverloadResolutionForDestructor() ||(((!needsOverloadResolutionForDestructor() || (data().DeclaredSpecialMembers
& SMF_Destructor)) && "this property has not yet been computed by Sema"
) ? static_cast<void> (0) : __assert_fail ("(!needsOverloadResolutionForDestructor() || (data().DeclaredSpecialMembers & SMF_Destructor)) && \"this property has not yet been computed by Sema\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclCXX.h"
, 698, __PRETTY_FUNCTION__))
697 (data().DeclaredSpecialMembers & SMF_Destructor)) &&(((!needsOverloadResolutionForDestructor() || (data().DeclaredSpecialMembers
& SMF_Destructor)) && "this property has not yet been computed by Sema"
) ? static_cast<void> (0) : __assert_fail ("(!needsOverloadResolutionForDestructor() || (data().DeclaredSpecialMembers & SMF_Destructor)) && \"this property has not yet been computed by Sema\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclCXX.h"
, 698, __PRETTY_FUNCTION__))
698 "this property has not yet been computed by Sema")(((!needsOverloadResolutionForDestructor() || (data().DeclaredSpecialMembers
& SMF_Destructor)) && "this property has not yet been computed by Sema"
) ? static_cast<void> (0) : __assert_fail ("(!needsOverloadResolutionForDestructor() || (data().DeclaredSpecialMembers & SMF_Destructor)) && \"this property has not yet been computed by Sema\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclCXX.h"
, 698, __PRETTY_FUNCTION__))
;
699 return data().DefaultedDestructorIsDeleted;
700 }
701
702 /// \c true if we know for sure that this class has a single,
703 /// accessible, unambiguous copy constructor that is not deleted.
704 bool hasSimpleCopyConstructor() const {
705 return !hasUserDeclaredCopyConstructor() &&
706 !data().DefaultedCopyConstructorIsDeleted;
707 }
708
709 /// \c true if we know for sure that this class has a single,
710 /// accessible, unambiguous move constructor that is not deleted.
711 bool hasSimpleMoveConstructor() const {
712 return !hasUserDeclaredMoveConstructor() && hasMoveConstructor() &&
713 !data().DefaultedMoveConstructorIsDeleted;
714 }
715
716 /// \c true if we know for sure that this class has a single,
717 /// accessible, unambiguous move assignment operator that is not deleted.
718 bool hasSimpleMoveAssignment() const {
719 return !hasUserDeclaredMoveAssignment() && hasMoveAssignment() &&
720 !data().DefaultedMoveAssignmentIsDeleted;
721 }
722
723 /// \c true if we know for sure that this class has an accessible
724 /// destructor that is not deleted.
725 bool hasSimpleDestructor() const {
726 return !hasUserDeclaredDestructor() &&
727 !data().DefaultedDestructorIsDeleted;
728 }
729
730 /// Determine whether this class has any default constructors.
731 bool hasDefaultConstructor() const {
732 return (data().DeclaredSpecialMembers & SMF_DefaultConstructor) ||
733 needsImplicitDefaultConstructor();
734 }
735
736 /// Determine if we need to declare a default constructor for
737 /// this class.
738 ///
739 /// This value is used for lazy creation of default constructors.
740 bool needsImplicitDefaultConstructor() const {
741 return !data().UserDeclaredConstructor &&
742 !(data().DeclaredSpecialMembers & SMF_DefaultConstructor) &&
743 (!isLambda() || lambdaIsDefaultConstructibleAndAssignable());
744 }
745
746 /// Determine whether this class has any user-declared constructors.
747 ///
748 /// When true, a default constructor will not be implicitly declared.
749 bool hasUserDeclaredConstructor() const {
750 return data().UserDeclaredConstructor;
751 }
752
753 /// Whether this class has a user-provided default constructor
754 /// per C++11.
755 bool hasUserProvidedDefaultConstructor() const {
756 return data().UserProvidedDefaultConstructor;
757 }
758
759 /// Determine whether this class has a user-declared copy constructor.
760 ///
761 /// When false, a copy constructor will be implicitly declared.
762 bool hasUserDeclaredCopyConstructor() const {
763 return data().UserDeclaredSpecialMembers & SMF_CopyConstructor;
764 }
765
766 /// Determine whether this class needs an implicit copy
767 /// constructor to be lazily declared.
768 bool needsImplicitCopyConstructor() const {
769 return !(data().DeclaredSpecialMembers & SMF_CopyConstructor);
770 }
771
772 /// Determine whether we need to eagerly declare a defaulted copy
773 /// constructor for this class.
774 bool needsOverloadResolutionForCopyConstructor() const {
775 // C++17 [class.copy.ctor]p6:
776 // If the class definition declares a move constructor or move assignment
777 // operator, the implicitly declared copy constructor is defined as
778 // deleted.
779 // In MSVC mode, sometimes a declared move assignment does not delete an
780 // implicit copy constructor, so defer this choice to Sema.
781 if (data().UserDeclaredSpecialMembers &
782 (SMF_MoveConstructor | SMF_MoveAssignment))
783 return true;
784 return data().NeedOverloadResolutionForCopyConstructor;
785 }
786
787 /// Determine whether an implicit copy constructor for this type
788 /// would have a parameter with a const-qualified reference type.
789 bool implicitCopyConstructorHasConstParam() const {
790 return data().ImplicitCopyConstructorCanHaveConstParamForNonVBase &&
791 (isAbstract() ||
792 data().ImplicitCopyConstructorCanHaveConstParamForVBase);
793 }
794
795 /// Determine whether this class has a copy constructor with
796 /// a parameter type which is a reference to a const-qualified type.
797 bool hasCopyConstructorWithConstParam() const {
798 return data().HasDeclaredCopyConstructorWithConstParam ||
799 (needsImplicitCopyConstructor() &&
800 implicitCopyConstructorHasConstParam());
801 }
802
803 /// Whether this class has a user-declared move constructor or
804 /// assignment operator.
805 ///
806 /// When false, a move constructor and assignment operator may be
807 /// implicitly declared.
808 bool hasUserDeclaredMoveOperation() const {
809 return data().UserDeclaredSpecialMembers &
810 (SMF_MoveConstructor | SMF_MoveAssignment);
811 }
812
813 /// Determine whether this class has had a move constructor
814 /// declared by the user.
815 bool hasUserDeclaredMoveConstructor() const {
816 return data().UserDeclaredSpecialMembers & SMF_MoveConstructor;
817 }
818
819 /// Determine whether this class has a move constructor.
820 bool hasMoveConstructor() const {
821 return (data().DeclaredSpecialMembers & SMF_MoveConstructor) ||
822 needsImplicitMoveConstructor();
823 }
824
825 /// Set that we attempted to declare an implicit copy
826 /// constructor, but overload resolution failed so we deleted it.
827 void setImplicitCopyConstructorIsDeleted() {
828 assert((data().DefaultedCopyConstructorIsDeleted ||(((data().DefaultedCopyConstructorIsDeleted || needsOverloadResolutionForCopyConstructor
()) && "Copy constructor should not be deleted") ? static_cast
<void> (0) : __assert_fail ("(data().DefaultedCopyConstructorIsDeleted || needsOverloadResolutionForCopyConstructor()) && \"Copy constructor should not be deleted\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclCXX.h"
, 830, __PRETTY_FUNCTION__))
829 needsOverloadResolutionForCopyConstructor()) &&(((data().DefaultedCopyConstructorIsDeleted || needsOverloadResolutionForCopyConstructor
()) && "Copy constructor should not be deleted") ? static_cast
<void> (0) : __assert_fail ("(data().DefaultedCopyConstructorIsDeleted || needsOverloadResolutionForCopyConstructor()) && \"Copy constructor should not be deleted\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclCXX.h"
, 830, __PRETTY_FUNCTION__))
830 "Copy constructor should not be deleted")(((data().DefaultedCopyConstructorIsDeleted || needsOverloadResolutionForCopyConstructor
()) && "Copy constructor should not be deleted") ? static_cast
<void> (0) : __assert_fail ("(data().DefaultedCopyConstructorIsDeleted || needsOverloadResolutionForCopyConstructor()) && \"Copy constructor should not be deleted\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclCXX.h"
, 830, __PRETTY_FUNCTION__))
;
831 data().DefaultedCopyConstructorIsDeleted = true;
832 }
833
834 /// Set that we attempted to declare an implicit move
835 /// constructor, but overload resolution failed so we deleted it.
836 void setImplicitMoveConstructorIsDeleted() {
837 assert((data().DefaultedMoveConstructorIsDeleted ||(((data().DefaultedMoveConstructorIsDeleted || needsOverloadResolutionForMoveConstructor
()) && "move constructor should not be deleted") ? static_cast
<void> (0) : __assert_fail ("(data().DefaultedMoveConstructorIsDeleted || needsOverloadResolutionForMoveConstructor()) && \"move constructor should not be deleted\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclCXX.h"
, 839, __PRETTY_FUNCTION__))
838 needsOverloadResolutionForMoveConstructor()) &&(((data().DefaultedMoveConstructorIsDeleted || needsOverloadResolutionForMoveConstructor
()) && "move constructor should not be deleted") ? static_cast
<void> (0) : __assert_fail ("(data().DefaultedMoveConstructorIsDeleted || needsOverloadResolutionForMoveConstructor()) && \"move constructor should not be deleted\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclCXX.h"
, 839, __PRETTY_FUNCTION__))
839 "move constructor should not be deleted")(((data().DefaultedMoveConstructorIsDeleted || needsOverloadResolutionForMoveConstructor
()) && "move constructor should not be deleted") ? static_cast
<void> (0) : __assert_fail ("(data().DefaultedMoveConstructorIsDeleted || needsOverloadResolutionForMoveConstructor()) && \"move constructor should not be deleted\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclCXX.h"
, 839, __PRETTY_FUNCTION__))
;
840 data().DefaultedMoveConstructorIsDeleted = true;
841 }
842
843 /// Set that we attempted to declare an implicit destructor,
844 /// but overload resolution failed so we deleted it.
845 void setImplicitDestructorIsDeleted() {
846 assert((data().DefaultedDestructorIsDeleted ||(((data().DefaultedDestructorIsDeleted || needsOverloadResolutionForDestructor
()) && "destructor should not be deleted") ? static_cast
<void> (0) : __assert_fail ("(data().DefaultedDestructorIsDeleted || needsOverloadResolutionForDestructor()) && \"destructor should not be deleted\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclCXX.h"
, 848, __PRETTY_FUNCTION__))
847 needsOverloadResolutionForDestructor()) &&(((data().DefaultedDestructorIsDeleted || needsOverloadResolutionForDestructor
()) && "destructor should not be deleted") ? static_cast
<void> (0) : __assert_fail ("(data().DefaultedDestructorIsDeleted || needsOverloadResolutionForDestructor()) && \"destructor should not be deleted\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclCXX.h"
, 848, __PRETTY_FUNCTION__))
848 "destructor should not be deleted")(((data().DefaultedDestructorIsDeleted || needsOverloadResolutionForDestructor
()) && "destructor should not be deleted") ? static_cast
<void> (0) : __assert_fail ("(data().DefaultedDestructorIsDeleted || needsOverloadResolutionForDestructor()) && \"destructor should not be deleted\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclCXX.h"
, 848, __PRETTY_FUNCTION__))
;
849 data().DefaultedDestructorIsDeleted = true;
850 }
851
852 /// Determine whether this class should get an implicit move
853 /// constructor or if any existing special member function inhibits this.
854 bool needsImplicitMoveConstructor() const {
855 return !(data().DeclaredSpecialMembers & SMF_MoveConstructor) &&
856 !hasUserDeclaredCopyConstructor() &&
857 !hasUserDeclaredCopyAssignment() &&
858 !hasUserDeclaredMoveAssignment() &&
859 !hasUserDeclaredDestructor();
860 }
861
862 /// Determine whether we need to eagerly declare a defaulted move
863 /// constructor for this class.
864 bool needsOverloadResolutionForMoveConstructor() const {
865 return data().NeedOverloadResolutionForMoveConstructor;
866 }
867
868 /// Determine whether this class has a user-declared copy assignment
869 /// operator.
870 ///
871 /// When false, a copy assignment operator will be implicitly declared.
872 bool hasUserDeclaredCopyAssignment() const {
873 return data().UserDeclaredSpecialMembers & SMF_CopyAssignment;
874 }
875
876 /// Determine whether this class needs an implicit copy
877 /// assignment operator to be lazily declared.
878 bool needsImplicitCopyAssignment() const {
879 return !(data().DeclaredSpecialMembers & SMF_CopyAssignment);
880 }
881
882 /// Determine whether we need to eagerly declare a defaulted copy
883 /// assignment operator for this class.
884 bool needsOverloadResolutionForCopyAssignment() const {
885 return data().HasMutableFields;
886 }
887
888 /// Determine whether an implicit copy assignment operator for this
889 /// type would have a parameter with a const-qualified reference type.
890 bool implicitCopyAssignmentHasConstParam() const {
891 return data().ImplicitCopyAssignmentHasConstParam;
892 }
893
894 /// Determine whether this class has a copy assignment operator with
895 /// a parameter type which is a reference to a const-qualified type or is not
896 /// a reference.
897 bool hasCopyAssignmentWithConstParam() const {
898 return data().HasDeclaredCopyAssignmentWithConstParam ||
899 (needsImplicitCopyAssignment() &&
900 implicitCopyAssignmentHasConstParam());
901 }
902
903 /// Determine whether this class has had a move assignment
904 /// declared by the user.
905 bool hasUserDeclaredMoveAssignment() const {
906 return data().UserDeclaredSpecialMembers & SMF_MoveAssignment;
907 }
908
909 /// Determine whether this class has a move assignment operator.
910 bool hasMoveAssignment() const {
911 return (data().DeclaredSpecialMembers & SMF_MoveAssignment) ||
912 needsImplicitMoveAssignment();
913 }
914
915 /// Set that we attempted to declare an implicit move assignment
916 /// operator, but overload resolution failed so we deleted it.
917 void setImplicitMoveAssignmentIsDeleted() {
918 assert((data().DefaultedMoveAssignmentIsDeleted ||(((data().DefaultedMoveAssignmentIsDeleted || needsOverloadResolutionForMoveAssignment
()) && "move assignment should not be deleted") ? static_cast
<void> (0) : __assert_fail ("(data().DefaultedMoveAssignmentIsDeleted || needsOverloadResolutionForMoveAssignment()) && \"move assignment should not be deleted\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclCXX.h"
, 920, __PRETTY_FUNCTION__))
919 needsOverloadResolutionForMoveAssignment()) &&(((data().DefaultedMoveAssignmentIsDeleted || needsOverloadResolutionForMoveAssignment
()) && "move assignment should not be deleted") ? static_cast
<void> (0) : __assert_fail ("(data().DefaultedMoveAssignmentIsDeleted || needsOverloadResolutionForMoveAssignment()) && \"move assignment should not be deleted\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclCXX.h"
, 920, __PRETTY_FUNCTION__))
920 "move assignment should not be deleted")(((data().DefaultedMoveAssignmentIsDeleted || needsOverloadResolutionForMoveAssignment
()) && "move assignment should not be deleted") ? static_cast
<void> (0) : __assert_fail ("(data().DefaultedMoveAssignmentIsDeleted || needsOverloadResolutionForMoveAssignment()) && \"move assignment should not be deleted\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclCXX.h"
, 920, __PRETTY_FUNCTION__))
;
921 data().DefaultedMoveAssignmentIsDeleted = true;
922 }
923
924 /// Determine whether this class should get an implicit move
925 /// assignment operator or if any existing special member function inhibits
926 /// this.
927 bool needsImplicitMoveAssignment() const {
928 return !(data().DeclaredSpecialMembers & SMF_MoveAssignment) &&
929 !hasUserDeclaredCopyConstructor() &&
930 !hasUserDeclaredCopyAssignment() &&
931 !hasUserDeclaredMoveConstructor() &&
932 !hasUserDeclaredDestructor() &&
933 (!isLambda() || lambdaIsDefaultConstructibleAndAssignable());
934 }
935
936 /// Determine whether we need to eagerly declare a move assignment
937 /// operator for this class.
938 bool needsOverloadResolutionForMoveAssignment() const {
939 return data().NeedOverloadResolutionForMoveAssignment;
940 }
941
942 /// Determine whether this class has a user-declared destructor.
943 ///
944 /// When false, a destructor will be implicitly declared.
945 bool hasUserDeclaredDestructor() const {
946 return data().UserDeclaredSpecialMembers & SMF_Destructor;
947 }
948
949 /// Determine whether this class needs an implicit destructor to
950 /// be lazily declared.
951 bool needsImplicitDestructor() const {
952 return !(data().DeclaredSpecialMembers & SMF_Destructor);
953 }
954
955 /// Determine whether we need to eagerly declare a destructor for this
956 /// class.
957 bool needsOverloadResolutionForDestructor() const {
958 return data().NeedOverloadResolutionForDestructor;
959 }
960
961 /// Determine whether this class describes a lambda function object.
962 bool isLambda() const {
963 // An update record can't turn a non-lambda into a lambda.
964 auto *DD = DefinitionData;
965 return DD && DD->IsLambda;
8
Assuming 'DD' is non-null
9
Returning value, which participates in a condition later
966 }
967
968 /// Determine whether this class describes a generic
969 /// lambda function object (i.e. function call operator is
970 /// a template).
971 bool isGenericLambda() const;
972
973 /// Determine whether this lambda should have an implicit default constructor
974 /// and copy and move assignment operators.
975 bool lambdaIsDefaultConstructibleAndAssignable() const;
976
977 /// Retrieve the lambda call operator of the closure type
978 /// if this is a closure type.
979 CXXMethodDecl *getLambdaCallOperator() const;
980
981 /// Retrieve the dependent lambda call operator of the closure type
982 /// if this is a templated closure type.
983 FunctionTemplateDecl *getDependentLambdaCallOperator() const;
984
985 /// Retrieve the lambda static invoker, the address of which
986 /// is returned by the conversion operator, and the body of which
987 /// is forwarded to the lambda call operator.
988 CXXMethodDecl *getLambdaStaticInvoker() const;
989
990 /// Retrieve the generic lambda's template parameter list.
991 /// Returns null if the class does not represent a lambda or a generic
992 /// lambda.
993 TemplateParameterList *getGenericLambdaTemplateParameterList() const;
994
995 /// Retrieve the lambda template parameters that were specified explicitly.
996 ArrayRef<NamedDecl *> getLambdaExplicitTemplateParameters() const;
997
998 LambdaCaptureDefault getLambdaCaptureDefault() const {
999 assert(isLambda())((isLambda()) ? static_cast<void> (0) : __assert_fail (
"isLambda()", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclCXX.h"
, 999, __PRETTY_FUNCTION__))
;
1000 return static_cast<LambdaCaptureDefault>(getLambdaData().CaptureDefault);
1001 }
1002
1003 /// For a closure type, retrieve the mapping from captured
1004 /// variables and \c this to the non-static data members that store the
1005 /// values or references of the captures.
1006 ///
1007 /// \param Captures Will be populated with the mapping from captured
1008 /// variables to the corresponding fields.
1009 ///
1010 /// \param ThisCapture Will be set to the field declaration for the
1011 /// \c this capture.
1012 ///
1013 /// \note No entries will be added for init-captures, as they do not capture
1014 /// variables.
1015 void getCaptureFields(llvm::DenseMap<const VarDecl *, FieldDecl *> &Captures,
1016 FieldDecl *&ThisCapture) const;
1017
1018 using capture_const_iterator = const LambdaCapture *;
1019 using capture_const_range = llvm::iterator_range<capture_const_iterator>;
1020
1021 capture_const_range captures() const {
1022 return capture_const_range(captures_begin(), captures_end());
1023 }
1024
1025 capture_const_iterator captures_begin() const {
1026 return isLambda() ? getLambdaData().Captures : nullptr;
1027 }
1028
1029 capture_const_iterator captures_end() const {
1030 return isLambda() ? captures_begin() + getLambdaData().NumCaptures
1031 : nullptr;
1032 }
1033
1034 using conversion_iterator = UnresolvedSetIterator;
1035
1036 conversion_iterator conversion_begin() const {
1037 return data().Conversions.get(getASTContext()).begin();
1038 }
1039
1040 conversion_iterator conversion_end() const {
1041 return data().Conversions.get(getASTContext()).end();
1042 }
1043
1044 /// Removes a conversion function from this class. The conversion
1045 /// function must currently be a member of this class. Furthermore,
1046 /// this class must currently be in the process of being defined.
1047 void removeConversion(const NamedDecl *Old);
1048
1049 /// Get all conversion functions visible in current class,
1050 /// including conversion function templates.
1051 llvm::iterator_range<conversion_iterator> getVisibleConversionFunctions();
1052
1053 /// Determine whether this class is an aggregate (C++ [dcl.init.aggr]),
1054 /// which is a class with no user-declared constructors, no private
1055 /// or protected non-static data members, no base classes, and no virtual
1056 /// functions (C++ [dcl.init.aggr]p1).
1057 bool isAggregate() const { return data().Aggregate; }
1058
1059 /// Whether this class has any in-class initializers
1060 /// for non-static data members (including those in anonymous unions or
1061 /// structs).
1062 bool hasInClassInitializer() const { return data().HasInClassInitializer; }
1063
1064 /// Whether this class or any of its subobjects has any members of
1065 /// reference type which would make value-initialization ill-formed.
1066 ///
1067 /// Per C++03 [dcl.init]p5:
1068 /// - if T is a non-union class type without a user-declared constructor,
1069 /// then every non-static data member and base-class component of T is
1070 /// value-initialized [...] A program that calls for [...]
1071 /// value-initialization of an entity of reference type is ill-formed.
1072 bool hasUninitializedReferenceMember() const {
1073 return !isUnion() && !hasUserDeclaredConstructor() &&
1074 data().HasUninitializedReferenceMember;
1075 }
1076
1077 /// Whether this class is a POD-type (C++ [class]p4)
1078 ///
1079 /// For purposes of this function a class is POD if it is an aggregate
1080 /// that has no non-static non-POD data members, no reference data
1081 /// members, no user-defined copy assignment operator and no
1082 /// user-defined destructor.
1083 ///
1084 /// Note that this is the C++ TR1 definition of POD.
1085 bool isPOD() const { return data().PlainOldData; }
1086
1087 /// True if this class is C-like, without C++-specific features, e.g.
1088 /// it contains only public fields, no bases, tag kind is not 'class', etc.
1089 bool isCLike() const;
1090
1091 /// Determine whether this is an empty class in the sense of
1092 /// (C++11 [meta.unary.prop]).
1093 ///
1094 /// The CXXRecordDecl is a class type, but not a union type,
1095 /// with no non-static data members other than bit-fields of length 0,
1096 /// no virtual member functions, no virtual base classes,
1097 /// and no base class B for which is_empty<B>::value is false.
1098 ///
1099 /// \note This does NOT include a check for union-ness.
1100 bool isEmpty() const { return data().Empty; }
1101
1102 bool hasPrivateFields() const {
1103 return data().HasPrivateFields;
1104 }
1105
1106 bool hasProtectedFields() const {
1107 return data().HasProtectedFields;
1108 }
1109
1110 /// Determine whether this class has direct non-static data members.
1111 bool hasDirectFields() const {
1112 auto &D = data();
1113 return D.HasPublicFields || D.HasProtectedFields || D.HasPrivateFields;
1114 }
1115
1116 /// Whether this class is polymorphic (C++ [class.virtual]),
1117 /// which means that the class contains or inherits a virtual function.
1118 bool isPolymorphic() const { return data().Polymorphic; }
1119
1120 /// Determine whether this class has a pure virtual function.
1121 ///
1122 /// The class is is abstract per (C++ [class.abstract]p2) if it declares
1123 /// a pure virtual function or inherits a pure virtual function that is
1124 /// not overridden.
1125 bool isAbstract() const { return data().Abstract; }
1126
1127 /// Determine whether this class is standard-layout per
1128 /// C++ [class]p7.
1129 bool isStandardLayout() const { return data().IsStandardLayout; }
1130
1131 /// Determine whether this class was standard-layout per
1132 /// C++11 [class]p7, specifically using the C++11 rules without any DRs.
1133 bool isCXX11StandardLayout() const { return data().IsCXX11StandardLayout; }
1134
1135 /// Determine whether this class, or any of its class subobjects,
1136 /// contains a mutable field.
1137 bool hasMutableFields() const { return data().HasMutableFields; }
1138
1139 /// Determine whether this class has any variant members.
1140 bool hasVariantMembers() const { return data().HasVariantMembers; }
1141
1142 /// Determine whether this class has a trivial default constructor
1143 /// (C++11 [class.ctor]p5).
1144 bool hasTrivialDefaultConstructor() const {
1145 return hasDefaultConstructor() &&
1146 (data().HasTrivialSpecialMembers & SMF_DefaultConstructor);
1147 }
1148
1149 /// Determine whether this class has a non-trivial default constructor
1150 /// (C++11 [class.ctor]p5).
1151 bool hasNonTrivialDefaultConstructor() const {
1152 return (data().DeclaredNonTrivialSpecialMembers & SMF_DefaultConstructor) ||
1153 (needsImplicitDefaultConstructor() &&
1154 !(data().HasTrivialSpecialMembers & SMF_DefaultConstructor));
1155 }
1156
1157 /// Determine whether this class has at least one constexpr constructor
1158 /// other than the copy or move constructors.
1159 bool hasConstexprNonCopyMoveConstructor() const {
1160 return data().HasConstexprNonCopyMoveConstructor ||
1161 (needsImplicitDefaultConstructor() &&
1162 defaultedDefaultConstructorIsConstexpr());
1163 }
1164
1165 /// Determine whether a defaulted default constructor for this class
1166 /// would be constexpr.
1167 bool defaultedDefaultConstructorIsConstexpr() const {
1168 return data().DefaultedDefaultConstructorIsConstexpr &&
1169 (!isUnion() || hasInClassInitializer() || !hasVariantMembers() ||
1170 getASTContext().getLangOpts().CPlusPlus2a);
1171 }
1172
1173 /// Determine whether this class has a constexpr default constructor.
1174 bool hasConstexprDefaultConstructor() const {
1175 return data().HasConstexprDefaultConstructor ||
1176 (needsImplicitDefaultConstructor() &&
1177 defaultedDefaultConstructorIsConstexpr());
1178 }
1179
1180 /// Determine whether this class has a trivial copy constructor
1181 /// (C++ [class.copy]p6, C++11 [class.copy]p12)
1182 bool hasTrivialCopyConstructor() const {
1183 return data().HasTrivialSpecialMembers & SMF_CopyConstructor;
1184 }
1185
1186 bool hasTrivialCopyConstructorForCall() const {
1187 return data().HasTrivialSpecialMembersForCall & SMF_CopyConstructor;
1188 }
1189
1190 /// Determine whether this class has a non-trivial copy constructor
1191 /// (C++ [class.copy]p6, C++11 [class.copy]p12)
1192 bool hasNonTrivialCopyConstructor() const {
1193 return data().DeclaredNonTrivialSpecialMembers & SMF_CopyConstructor ||
1194 !hasTrivialCopyConstructor();
1195 }
1196
1197 bool hasNonTrivialCopyConstructorForCall() const {
1198 return (data().DeclaredNonTrivialSpecialMembersForCall &
1199 SMF_CopyConstructor) ||
1200 !hasTrivialCopyConstructorForCall();
1201 }
1202
1203 /// Determine whether this class has a trivial move constructor
1204 /// (C++11 [class.copy]p12)
1205 bool hasTrivialMoveConstructor() const {
1206 return hasMoveConstructor() &&
1207 (data().HasTrivialSpecialMembers & SMF_MoveConstructor);
1208 }
1209
1210 bool hasTrivialMoveConstructorForCall() const {
1211 return hasMoveConstructor() &&
1212 (data().HasTrivialSpecialMembersForCall & SMF_MoveConstructor);
1213 }
1214
1215 /// Determine whether this class has a non-trivial move constructor
1216 /// (C++11 [class.copy]p12)
1217 bool hasNonTrivialMoveConstructor() const {
1218 return (data().DeclaredNonTrivialSpecialMembers & SMF_MoveConstructor) ||
1219 (needsImplicitMoveConstructor() &&
1220 !(data().HasTrivialSpecialMembers & SMF_MoveConstructor));
1221 }
1222
1223 bool hasNonTrivialMoveConstructorForCall() const {
1224 return (data().DeclaredNonTrivialSpecialMembersForCall &
1225 SMF_MoveConstructor) ||
1226 (needsImplicitMoveConstructor() &&
1227 !(data().HasTrivialSpecialMembersForCall & SMF_MoveConstructor));
1228 }
1229
1230 /// Determine whether this class has a trivial copy assignment operator
1231 /// (C++ [class.copy]p11, C++11 [class.copy]p25)
1232 bool hasTrivialCopyAssignment() const {
1233 return data().HasTrivialSpecialMembers & SMF_CopyAssignment;
1234 }
1235
1236 /// Determine whether this class has a non-trivial copy assignment
1237 /// operator (C++ [class.copy]p11, C++11 [class.copy]p25)
1238 bool hasNonTrivialCopyAssignment() const {
1239 return data().DeclaredNonTrivialSpecialMembers & SMF_CopyAssignment ||
1240 !hasTrivialCopyAssignment();
1241 }
1242
1243 /// Determine whether this class has a trivial move assignment operator
1244 /// (C++11 [class.copy]p25)
1245 bool hasTrivialMoveAssignment() const {
1246 return hasMoveAssignment() &&
1247 (data().HasTrivialSpecialMembers & SMF_MoveAssignment);
1248 }
1249
1250 /// Determine whether this class has a non-trivial move assignment
1251 /// operator (C++11 [class.copy]p25)
1252 bool hasNonTrivialMoveAssignment() const {
1253 return (data().DeclaredNonTrivialSpecialMembers & SMF_MoveAssignment) ||
1254 (needsImplicitMoveAssignment() &&
1255 !(data().HasTrivialSpecialMembers & SMF_MoveAssignment));
1256 }
1257
1258 /// Determine whether a defaulted default constructor for this class
1259 /// would be constexpr.
1260 bool defaultedDestructorIsConstexpr() const {
1261 return data().DefaultedDestructorIsConstexpr &&
1262 getASTContext().getLangOpts().CPlusPlus2a;
1263 }
1264
1265 /// Determine whether this class has a constexpr destructor.
1266 bool hasConstexprDestructor() const;
1267
1268 /// Determine whether this class has a trivial destructor
1269 /// (C++ [class.dtor]p3)
1270 bool hasTrivialDestructor() const {
1271 return data().HasTrivialSpecialMembers & SMF_Destructor;
1272 }
1273
1274 bool hasTrivialDestructorForCall() const {
1275 return data().HasTrivialSpecialMembersForCall & SMF_Destructor;
1276 }
1277
1278 /// Determine whether this class has a non-trivial destructor
1279 /// (C++ [class.dtor]p3)
1280 bool hasNonTrivialDestructor() const {
1281 return !(data().HasTrivialSpecialMembers & SMF_Destructor);
1282 }
1283
1284 bool hasNonTrivialDestructorForCall() const {
1285 return !(data().HasTrivialSpecialMembersForCall & SMF_Destructor);
1286 }
1287
1288 void setHasTrivialSpecialMemberForCall() {
1289 data().HasTrivialSpecialMembersForCall =
1290 (SMF_CopyConstructor | SMF_MoveConstructor | SMF_Destructor);
1291 }
1292
1293 /// Determine whether declaring a const variable with this type is ok
1294 /// per core issue 253.
1295 bool allowConstDefaultInit() const {
1296 return !data().HasUninitializedFields ||
1297 !(data().HasDefaultedDefaultConstructor ||
1298 needsImplicitDefaultConstructor());
1299 }
1300
1301 /// Determine whether this class has a destructor which has no
1302 /// semantic effect.
1303 ///
1304 /// Any such destructor will be trivial, public, defaulted and not deleted,
1305 /// and will call only irrelevant destructors.
1306 bool hasIrrelevantDestructor() const {
1307 return data().HasIrrelevantDestructor;
1308 }
1309
1310 /// Determine whether this class has a non-literal or/ volatile type
1311 /// non-static data member or base class.
1312 bool hasNonLiteralTypeFieldsOrBases() const {
1313 return data().HasNonLiteralTypeFieldsOrBases;
1314 }
1315
1316 /// Determine whether this class has a using-declaration that names
1317 /// a user-declared base class constructor.
1318 bool hasInheritedConstructor() const {
1319 return data().HasInheritedConstructor;
1320 }
1321
1322 /// Determine whether this class has a using-declaration that names
1323 /// a base class assignment operator.
1324 bool hasInheritedAssignment() const {
1325 return data().HasInheritedAssignment;
1326 }
1327
1328 /// Determine whether this class is considered trivially copyable per
1329 /// (C++11 [class]p6).
1330 bool isTriviallyCopyable() const;
1331
1332 /// Determine whether this class is considered trivial.
1333 ///
1334 /// C++11 [class]p6:
1335 /// "A trivial class is a class that has a trivial default constructor and
1336 /// is trivially copyable."
1337 bool isTrivial() const {
1338 return isTriviallyCopyable() && hasTrivialDefaultConstructor();
1339 }
1340
1341 /// Determine whether this class is a literal type.
1342 ///
1343 /// C++11 [basic.types]p10:
1344 /// A class type that has all the following properties:
1345 /// - it has a trivial destructor
1346 /// - every constructor call and full-expression in the
1347 /// brace-or-equal-intializers for non-static data members (if any) is
1348 /// a constant expression.
1349 /// - it is an aggregate type or has at least one constexpr constructor
1350 /// or constructor template that is not a copy or move constructor, and
1351 /// - all of its non-static data members and base classes are of literal
1352 /// types
1353 ///
1354 /// We resolve DR1361 by ignoring the second bullet. We resolve DR1452 by
1355 /// treating types with trivial default constructors as literal types.
1356 ///
1357 /// Only in C++17 and beyond, are lambdas literal types.
1358 bool isLiteral() const {
1359 ASTContext &Ctx = getASTContext();
1360 return (Ctx.getLangOpts().CPlusPlus2a ? hasConstexprDestructor()
1361 : hasTrivialDestructor()) &&
1362 (!isLambda() || Ctx.getLangOpts().CPlusPlus17) &&
1363 !hasNonLiteralTypeFieldsOrBases() &&
1364 (isAggregate() || isLambda() ||
1365 hasConstexprNonCopyMoveConstructor() ||
1366 hasTrivialDefaultConstructor());
1367 }
1368
1369 /// If this record is an instantiation of a member class,
1370 /// retrieves the member class from which it was instantiated.
1371 ///
1372 /// This routine will return non-null for (non-templated) member
1373 /// classes of class templates. For example, given:
1374 ///
1375 /// \code
1376 /// template<typename T>
1377 /// struct X {
1378 /// struct A { };
1379 /// };
1380 /// \endcode
1381 ///
1382 /// The declaration for X<int>::A is a (non-templated) CXXRecordDecl
1383 /// whose parent is the class template specialization X<int>. For
1384 /// this declaration, getInstantiatedFromMemberClass() will return
1385 /// the CXXRecordDecl X<T>::A. When a complete definition of
1386 /// X<int>::A is required, it will be instantiated from the
1387 /// declaration returned by getInstantiatedFromMemberClass().
1388 CXXRecordDecl *getInstantiatedFromMemberClass() const;
1389
1390 /// If this class is an instantiation of a member class of a
1391 /// class template specialization, retrieves the member specialization
1392 /// information.
1393 MemberSpecializationInfo *getMemberSpecializationInfo() const;
1394
1395 /// Specify that this record is an instantiation of the
1396 /// member class \p RD.
1397 void setInstantiationOfMemberClass(CXXRecordDecl *RD,
1398 TemplateSpecializationKind TSK);
1399
1400 /// Retrieves the class template that is described by this
1401 /// class declaration.
1402 ///
1403 /// Every class template is represented as a ClassTemplateDecl and a
1404 /// CXXRecordDecl. The former contains template properties (such as
1405 /// the template parameter lists) while the latter contains the
1406 /// actual description of the template's
1407 /// contents. ClassTemplateDecl::getTemplatedDecl() retrieves the
1408 /// CXXRecordDecl that from a ClassTemplateDecl, while
1409 /// getDescribedClassTemplate() retrieves the ClassTemplateDecl from
1410 /// a CXXRecordDecl.
1411 ClassTemplateDecl *getDescribedClassTemplate() const;
1412
1413 void setDescribedClassTemplate(ClassTemplateDecl *Template);
1414
1415 /// Determine whether this particular class is a specialization or
1416 /// instantiation of a class template or member class of a class template,
1417 /// and how it was instantiated or specialized.
1418 TemplateSpecializationKind getTemplateSpecializationKind() const;
1419
1420 /// Set the kind of specialization or template instantiation this is.
1421 void setTemplateSpecializationKind(TemplateSpecializationKind TSK);
1422
1423 /// Retrieve the record declaration from which this record could be
1424 /// instantiated. Returns null if this class is not a template instantiation.
1425 const CXXRecordDecl *getTemplateInstantiationPattern() const;
1426
1427 CXXRecordDecl *getTemplateInstantiationPattern() {
1428 return const_cast<CXXRecordDecl *>(const_cast<const CXXRecordDecl *>(this)
1429 ->getTemplateInstantiationPattern());
1430 }
1431
1432 /// Returns the destructor decl for this class.
1433 CXXDestructorDecl *getDestructor() const;
1434
1435 /// Returns true if the class destructor, or any implicitly invoked
1436 /// destructors are marked noreturn.
1437 bool isAnyDestructorNoReturn() const;
1438
1439 /// If the class is a local class [class.local], returns
1440 /// the enclosing function declaration.
1441 const FunctionDecl *isLocalClass() const {
1442 if (const auto *RD = dyn_cast<CXXRecordDecl>(getDeclContext()))
1443 return RD->isLocalClass();
1444
1445 return dyn_cast<FunctionDecl>(getDeclContext());
1446 }
1447
1448 FunctionDecl *isLocalClass() {
1449 return const_cast<FunctionDecl*>(
1450 const_cast<const CXXRecordDecl*>(this)->isLocalClass());
1451 }
1452
1453 /// Determine whether this dependent class is a current instantiation,
1454 /// when viewed from within the given context.
1455 bool isCurrentInstantiation(const DeclContext *CurContext) const;
1456
1457 /// Determine whether this class is derived from the class \p Base.
1458 ///
1459 /// This routine only determines whether this class is derived from \p Base,
1460 /// but does not account for factors that may make a Derived -> Base class
1461 /// ill-formed, such as private/protected inheritance or multiple, ambiguous
1462 /// base class subobjects.
1463 ///
1464 /// \param Base the base class we are searching for.
1465 ///
1466 /// \returns true if this class is derived from Base, false otherwise.
1467 bool isDerivedFrom(const CXXRecordDecl *Base) const;
1468
1469 /// Determine whether this class is derived from the type \p Base.
1470 ///
1471 /// This routine only determines whether this class is derived from \p Base,
1472 /// but does not account for factors that may make a Derived -> Base class
1473 /// ill-formed, such as private/protected inheritance or multiple, ambiguous
1474 /// base class subobjects.
1475 ///
1476 /// \param Base the base class we are searching for.
1477 ///
1478 /// \param Paths will contain the paths taken from the current class to the
1479 /// given \p Base class.
1480 ///
1481 /// \returns true if this class is derived from \p Base, false otherwise.
1482 ///
1483 /// \todo add a separate parameter to configure IsDerivedFrom, rather than
1484 /// tangling input and output in \p Paths
1485 bool isDerivedFrom(const CXXRecordDecl *Base, CXXBasePaths &Paths) const;
1486
1487 /// Determine whether this class is virtually derived from
1488 /// the class \p Base.
1489 ///
1490 /// This routine only determines whether this class is virtually
1491 /// derived from \p Base, but does not account for factors that may
1492 /// make a Derived -> Base class ill-formed, such as
1493 /// private/protected inheritance or multiple, ambiguous base class
1494 /// subobjects.
1495 ///
1496 /// \param Base the base class we are searching for.
1497 ///
1498 /// \returns true if this class is virtually derived from Base,
1499 /// false otherwise.
1500 bool isVirtuallyDerivedFrom(const CXXRecordDecl *Base) const;
1501
1502 /// Determine whether this class is provably not derived from
1503 /// the type \p Base.
1504 bool isProvablyNotDerivedFrom(const CXXRecordDecl *Base) const;
1505
1506 /// Function type used by forallBases() as a callback.
1507 ///
1508 /// \param BaseDefinition the definition of the base class
1509 ///
1510 /// \returns true if this base matched the search criteria
1511 using ForallBasesCallback =
1512 llvm::function_ref<bool(const CXXRecordDecl *BaseDefinition)>;
1513
1514 /// Determines if the given callback holds for all the direct
1515 /// or indirect base classes of this type.
1516 ///
1517 /// The class itself does not count as a base class. This routine
1518 /// returns false if the class has non-computable base classes.
1519 ///
1520 /// \param BaseMatches Callback invoked for each (direct or indirect) base
1521 /// class of this type, or if \p AllowShortCircuit is true then until a call
1522 /// returns false.
1523 ///
1524 /// \param AllowShortCircuit if false, forces the callback to be called
1525 /// for every base class, even if a dependent or non-matching base was
1526 /// found.
1527 bool forallBases(ForallBasesCallback BaseMatches,
1528 bool AllowShortCircuit = true) const;
1529
1530 /// Function type used by lookupInBases() to determine whether a
1531 /// specific base class subobject matches the lookup criteria.
1532 ///
1533 /// \param Specifier the base-class specifier that describes the inheritance
1534 /// from the base class we are trying to match.
1535 ///
1536 /// \param Path the current path, from the most-derived class down to the
1537 /// base named by the \p Specifier.
1538 ///
1539 /// \returns true if this base matched the search criteria, false otherwise.
1540 using BaseMatchesCallback =
1541 llvm::function_ref<bool(const CXXBaseSpecifier *Specifier,
1542 CXXBasePath &Path)>;
1543
1544 /// Look for entities within the base classes of this C++ class,
1545 /// transitively searching all base class subobjects.
1546 ///
1547 /// This routine uses the callback function \p BaseMatches to find base
1548 /// classes meeting some search criteria, walking all base class subobjects
1549 /// and populating the given \p Paths structure with the paths through the
1550 /// inheritance hierarchy that resulted in a match. On a successful search,
1551 /// the \p Paths structure can be queried to retrieve the matching paths and
1552 /// to determine if there were any ambiguities.
1553 ///
1554 /// \param BaseMatches callback function used to determine whether a given
1555 /// base matches the user-defined search criteria.
1556 ///
1557 /// \param Paths used to record the paths from this class to its base class
1558 /// subobjects that match the search criteria.
1559 ///
1560 /// \param LookupInDependent can be set to true to extend the search to
1561 /// dependent base classes.
1562 ///
1563 /// \returns true if there exists any path from this class to a base class
1564 /// subobject that matches the search criteria.
1565 bool lookupInBases(BaseMatchesCallback BaseMatches, CXXBasePaths &Paths,
1566 bool LookupInDependent = false) const;
1567
1568 /// Base-class lookup callback that determines whether the given
1569 /// base class specifier refers to a specific class declaration.
1570 ///
1571 /// This callback can be used with \c lookupInBases() to determine whether
1572 /// a given derived class has is a base class subobject of a particular type.
1573 /// The base record pointer should refer to the canonical CXXRecordDecl of the
1574 /// base class that we are searching for.
1575 static bool FindBaseClass(const CXXBaseSpecifier *Specifier,
1576 CXXBasePath &Path, const CXXRecordDecl *BaseRecord);
1577
1578 /// Base-class lookup callback that determines whether the
1579 /// given base class specifier refers to a specific class
1580 /// declaration and describes virtual derivation.
1581 ///
1582 /// This callback can be used with \c lookupInBases() to determine
1583 /// whether a given derived class has is a virtual base class
1584 /// subobject of a particular type. The base record pointer should
1585 /// refer to the canonical CXXRecordDecl of the base class that we
1586 /// are searching for.
1587 static bool FindVirtualBaseClass(const CXXBaseSpecifier *Specifier,
1588 CXXBasePath &Path,
1589 const CXXRecordDecl *BaseRecord);
1590
1591 /// Base-class lookup callback that determines whether there exists
1592 /// a tag with the given name.
1593 ///
1594 /// This callback can be used with \c lookupInBases() to find tag members
1595 /// of the given name within a C++ class hierarchy.
1596 static bool FindTagMember(const CXXBaseSpecifier *Specifier,
1597 CXXBasePath &Path, DeclarationName Name);
1598
1599 /// Base-class lookup callback that determines whether there exists
1600 /// a member with the given name.
1601 ///
1602 /// This callback can be used with \c lookupInBases() to find members
1603 /// of the given name within a C++ class hierarchy.
1604 static bool FindOrdinaryMember(const CXXBaseSpecifier *Specifier,
1605 CXXBasePath &Path, DeclarationName Name);
1606
1607 /// Base-class lookup callback that determines whether there exists
1608 /// a member with the given name.
1609 ///
1610 /// This callback can be used with \c lookupInBases() to find members
1611 /// of the given name within a C++ class hierarchy, including dependent
1612 /// classes.
1613 static bool
1614 FindOrdinaryMemberInDependentClasses(const CXXBaseSpecifier *Specifier,
1615 CXXBasePath &Path, DeclarationName Name);
1616
1617 /// Base-class lookup callback that determines whether there exists
1618 /// an OpenMP declare reduction member with the given name.
1619 ///
1620 /// This callback can be used with \c lookupInBases() to find members
1621 /// of the given name within a C++ class hierarchy.
1622 static bool FindOMPReductionMember(const CXXBaseSpecifier *Specifier,
1623 CXXBasePath &Path, DeclarationName Name);
1624
1625 /// Base-class lookup callback that determines whether there exists
1626 /// an OpenMP declare mapper member with the given name.
1627 ///
1628 /// This callback can be used with \c lookupInBases() to find members
1629 /// of the given name within a C++ class hierarchy.
1630 static bool FindOMPMapperMember(const CXXBaseSpecifier *Specifier,
1631 CXXBasePath &Path, DeclarationName Name);
1632
1633 /// Base-class lookup callback that determines whether there exists
1634 /// a member with the given name that can be used in a nested-name-specifier.
1635 ///
1636 /// This callback can be used with \c lookupInBases() to find members of
1637 /// the given name within a C++ class hierarchy that can occur within
1638 /// nested-name-specifiers.
1639 static bool FindNestedNameSpecifierMember(const CXXBaseSpecifier *Specifier,
1640 CXXBasePath &Path,
1641 DeclarationName Name);
1642
1643 /// Retrieve the final overriders for each virtual member
1644 /// function in the class hierarchy where this class is the
1645 /// most-derived class in the class hierarchy.
1646 void getFinalOverriders(CXXFinalOverriderMap &FinaOverriders) const;
1647
1648 /// Get the indirect primary bases for this class.
1649 void getIndirectPrimaryBases(CXXIndirectPrimaryBaseSet& Bases) const;
1650
1651 /// Performs an imprecise lookup of a dependent name in this class.
1652 ///
1653 /// This function does not follow strict semantic rules and should be used
1654 /// only when lookup rules can be relaxed, e.g. indexing.
1655 std::vector<const NamedDecl *>
1656 lookupDependentName(const DeclarationName &Name,
1657 llvm::function_ref<bool(const NamedDecl *ND)> Filter);
1658
1659 /// Renders and displays an inheritance diagram
1660 /// for this C++ class and all of its base classes (transitively) using
1661 /// GraphViz.
1662 void viewInheritance(ASTContext& Context) const;
1663
1664 /// Calculates the access of a decl that is reached
1665 /// along a path.
1666 static AccessSpecifier MergeAccess(AccessSpecifier PathAccess,
1667 AccessSpecifier DeclAccess) {
1668 assert(DeclAccess != AS_none)((DeclAccess != AS_none) ? static_cast<void> (0) : __assert_fail
("DeclAccess != AS_none", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclCXX.h"
, 1668, __PRETTY_FUNCTION__))
;
1669 if (DeclAccess == AS_private) return AS_none;
1670 return (PathAccess > DeclAccess ? PathAccess : DeclAccess);
1671 }
1672
1673 /// Indicates that the declaration of a defaulted or deleted special
1674 /// member function is now complete.
1675 void finishedDefaultedOrDeletedMember(CXXMethodDecl *MD);
1676
1677 void setTrivialForCallFlags(CXXMethodDecl *MD);
1678
1679 /// Indicates that the definition of this class is now complete.
1680 void completeDefinition() override;
1681
1682 /// Indicates that the definition of this class is now complete,
1683 /// and provides a final overrider map to help determine
1684 ///
1685 /// \param FinalOverriders The final overrider map for this class, which can
1686 /// be provided as an optimization for abstract-class checking. If NULL,
1687 /// final overriders will be computed if they are needed to complete the
1688 /// definition.
1689 void completeDefinition(CXXFinalOverriderMap *FinalOverriders);
1690
1691 /// Determine whether this class may end up being abstract, even though
1692 /// it is not yet known to be abstract.
1693 ///
1694 /// \returns true if this class is not known to be abstract but has any
1695 /// base classes that are abstract. In this case, \c completeDefinition()
1696 /// will need to compute final overriders to determine whether the class is
1697 /// actually abstract.
1698 bool mayBeAbstract() const;
1699
1700 /// If this is the closure type of a lambda expression, retrieve the
1701 /// number to be used for name mangling in the Itanium C++ ABI.
1702 ///
1703 /// Zero indicates that this closure type has internal linkage, so the
1704 /// mangling number does not matter, while a non-zero value indicates which
1705 /// lambda expression this is in this particular context.
1706 unsigned getLambdaManglingNumber() const {
1707 assert(isLambda() && "Not a lambda closure type!")((isLambda() && "Not a lambda closure type!") ? static_cast
<void> (0) : __assert_fail ("isLambda() && \"Not a lambda closure type!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclCXX.h"
, 1707, __PRETTY_FUNCTION__))
;
1708 return getLambdaData().ManglingNumber;
1709 }
1710
1711 /// The lambda is known to has internal linkage no matter whether it has name
1712 /// mangling number.
1713 bool hasKnownLambdaInternalLinkage() const {
1714 assert(isLambda() && "Not a lambda closure type!")((isLambda() && "Not a lambda closure type!") ? static_cast
<void> (0) : __assert_fail ("isLambda() && \"Not a lambda closure type!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclCXX.h"
, 1714, __PRETTY_FUNCTION__))
;
1715 return getLambdaData().HasKnownInternalLinkage;
1716 }
1717
1718 /// Retrieve the declaration that provides additional context for a
1719 /// lambda, when the normal declaration context is not specific enough.
1720 ///
1721 /// Certain contexts (default arguments of in-class function parameters and
1722 /// the initializers of data members) have separate name mangling rules for
1723 /// lambdas within the Itanium C++ ABI. For these cases, this routine provides
1724 /// the declaration in which the lambda occurs, e.g., the function parameter
1725 /// or the non-static data member. Otherwise, it returns NULL to imply that
1726 /// the declaration context suffices.
1727 Decl *getLambdaContextDecl() const;
1728
1729 /// Set the mangling number and context declaration for a lambda
1730 /// class.
1731 void setLambdaMangling(unsigned ManglingNumber, Decl *ContextDecl,
1732 bool HasKnownInternalLinkage = false) {
1733 assert(isLambda() && "Not a lambda closure type!")((isLambda() && "Not a lambda closure type!") ? static_cast
<void> (0) : __assert_fail ("isLambda() && \"Not a lambda closure type!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclCXX.h"
, 1733, __PRETTY_FUNCTION__))
;
1734 getLambdaData().ManglingNumber = ManglingNumber;
1735 getLambdaData().ContextDecl = ContextDecl;
1736 getLambdaData().HasKnownInternalLinkage = HasKnownInternalLinkage;
1737 }
1738
1739 /// Returns the inheritance model used for this record.
1740 MSInheritanceAttr::Spelling getMSInheritanceModel() const;
1741
1742 /// Calculate what the inheritance model would be for this class.
1743 MSInheritanceAttr::Spelling calculateInheritanceModel() const;
1744
1745 /// In the Microsoft C++ ABI, use zero for the field offset of a null data
1746 /// member pointer if we can guarantee that zero is not a valid field offset,
1747 /// or if the member pointer has multiple fields. Polymorphic classes have a
1748 /// vfptr at offset zero, so we can use zero for null. If there are multiple
1749 /// fields, we can use zero even if it is a valid field offset because
1750 /// null-ness testing will check the other fields.
1751 bool nullFieldOffsetIsZero() const {
1752 return !MSInheritanceAttr::hasOnlyOneField(/*IsMemberFunction=*/false,
1753 getMSInheritanceModel()) ||
1754 (hasDefinition() && isPolymorphic());
1755 }
1756
1757 /// Controls when vtordisps will be emitted if this record is used as a
1758 /// virtual base.
1759 MSVtorDispAttr::Mode getMSVtorDispMode() const;
1760
1761 /// Determine whether this lambda expression was known to be dependent
1762 /// at the time it was created, even if its context does not appear to be
1763 /// dependent.
1764 ///
1765 /// This flag is a workaround for an issue with parsing, where default
1766 /// arguments are parsed before their enclosing function declarations have
1767 /// been created. This means that any lambda expressions within those
1768 /// default arguments will have as their DeclContext the context enclosing
1769 /// the function declaration, which may be non-dependent even when the
1770 /// function declaration itself is dependent. This flag indicates when we
1771 /// know that the lambda is dependent despite that.
1772 bool isDependentLambda() const {
1773 return isLambda() && getLambdaData().Dependent;
1774 }
1775
1776 TypeSourceInfo *getLambdaTypeInfo() const {
1777 return getLambdaData().MethodTyInfo;
1778 }
1779
1780 // Determine whether this type is an Interface Like type for
1781 // __interface inheritance purposes.
1782 bool isInterfaceLike() const;
1783
1784 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1785 static bool classofKind(Kind K) {
1786 return K >= firstCXXRecord && K <= lastCXXRecord;
1787 }
1788};
1789
1790/// Store information needed for an explicit specifier.
1791/// used by CXXDeductionGuideDecl, CXXConstructorDecl and CXXConversionDecl.
1792class ExplicitSpecifier {
1793 llvm::PointerIntPair<Expr *, 2, ExplicitSpecKind> ExplicitSpec{
1794 nullptr, ExplicitSpecKind::ResolvedFalse};
1795
1796public:
1797 ExplicitSpecifier() = default;
1798 ExplicitSpecifier(Expr *Expression, ExplicitSpecKind Kind)
1799 : ExplicitSpec(Expression, Kind) {}
1800 ExplicitSpecKind getKind() const { return ExplicitSpec.getInt(); }
1801 const Expr *getExpr() const { return ExplicitSpec.getPointer(); }
1802 Expr *getExpr() { return ExplicitSpec.getPointer(); }
1803
1804 /// Return true if the ExplicitSpecifier isn't defaulted.
1805 bool isSpecified() const {
1806 return ExplicitSpec.getInt() != ExplicitSpecKind::ResolvedFalse ||
1807 ExplicitSpec.getPointer();
1808 }
1809
1810 /// Check for Equivalence of explicit specifiers.
1811 /// Return True if the explicit specifier are equivalent false otherwise.
1812 bool isEquivalent(const ExplicitSpecifier Other) const;
1813 /// Return true if the explicit specifier is already resolved to be explicit.
1814 bool isExplicit() const {
1815 return ExplicitSpec.getInt() == ExplicitSpecKind::ResolvedTrue;
1816 }
1817 /// Return true if the ExplicitSpecifier isn't valid.
1818 /// This state occurs after a substitution failures.
1819 bool isInvalid() const {
1820 return ExplicitSpec.getInt() == ExplicitSpecKind::Unresolved &&
1821 !ExplicitSpec.getPointer();
1822 }
1823 void setKind(ExplicitSpecKind Kind) { ExplicitSpec.setInt(Kind); }
1824 void setExpr(Expr *E) { ExplicitSpec.setPointer(E); }
1825 // getFromDecl - retrieve the explicit specifier in the given declaration.
1826 // if the given declaration has no explicit. the returned explicit specifier
1827 // is defaulted. .isSpecified() will be false.
1828 static ExplicitSpecifier getFromDecl(FunctionDecl *Function);
1829 static const ExplicitSpecifier getFromDecl(const FunctionDecl *Function) {
1830 return getFromDecl(const_cast<FunctionDecl *>(Function));
1831 }
1832 static ExplicitSpecifier Invalid() {
1833 return ExplicitSpecifier(nullptr, ExplicitSpecKind::Unresolved);
1834 }
1835};
1836
1837/// Represents a C++ deduction guide declaration.
1838///
1839/// \code
1840/// template<typename T> struct A { A(); A(T); };
1841/// A() -> A<int>;
1842/// \endcode
1843///
1844/// In this example, there will be an explicit deduction guide from the
1845/// second line, and implicit deduction guide templates synthesized from
1846/// the constructors of \c A.
1847class CXXDeductionGuideDecl : public FunctionDecl {
1848 void anchor() override;
1849
1850private:
1851 CXXDeductionGuideDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1852 ExplicitSpecifier ES,
1853 const DeclarationNameInfo &NameInfo, QualType T,
1854 TypeSourceInfo *TInfo, SourceLocation EndLocation)
1855 : FunctionDecl(CXXDeductionGuide, C, DC, StartLoc, NameInfo, T, TInfo,
1856 SC_None, false, CSK_unspecified),
1857 ExplicitSpec(ES) {
1858 if (EndLocation.isValid())
1859 setRangeEnd(EndLocation);
1860 setIsCopyDeductionCandidate(false);
1861 }
1862
1863 ExplicitSpecifier ExplicitSpec;
1864 void setExplicitSpecifier(ExplicitSpecifier ES) { ExplicitSpec = ES; }
1865
1866public:
1867 friend class ASTDeclReader;
1868 friend class ASTDeclWriter;
1869
1870 static CXXDeductionGuideDecl *
1871 Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1872 ExplicitSpecifier ES, const DeclarationNameInfo &NameInfo, QualType T,
1873 TypeSourceInfo *TInfo, SourceLocation EndLocation);
1874
1875 static CXXDeductionGuideDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1876
1877 ExplicitSpecifier getExplicitSpecifier() { return ExplicitSpec; }
1878 const ExplicitSpecifier getExplicitSpecifier() const { return ExplicitSpec; }
1879
1880 /// Return true if the declartion is already resolved to be explicit.
1881 bool isExplicit() const { return ExplicitSpec.isExplicit(); }
1882
1883 /// Get the template for which this guide performs deduction.
1884 TemplateDecl *getDeducedTemplate() const {
1885 return getDeclName().getCXXDeductionGuideTemplate();
1886 }
1887
1888 void setIsCopyDeductionCandidate(bool isCDC = true) {
1889 FunctionDeclBits.IsCopyDeductionCandidate = isCDC;
1890 }
1891
1892 bool isCopyDeductionCandidate() const {
1893 return FunctionDeclBits.IsCopyDeductionCandidate;
1894 }
1895
1896 // Implement isa/cast/dyncast/etc.
1897 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1898 static bool classofKind(Kind K) { return K == CXXDeductionGuide; }
1899};
1900
1901/// Represents a static or instance method of a struct/union/class.
1902///
1903/// In the terminology of the C++ Standard, these are the (static and
1904/// non-static) member functions, whether virtual or not.
1905class CXXMethodDecl : public FunctionDecl {
1906 void anchor() override;
1907
1908protected:
1909 CXXMethodDecl(Kind DK, ASTContext &C, CXXRecordDecl *RD,
1910 SourceLocation StartLoc, const DeclarationNameInfo &NameInfo,
1911 QualType T, TypeSourceInfo *TInfo, StorageClass SC,
1912 bool isInline, ConstexprSpecKind ConstexprKind,
1913 SourceLocation EndLocation)
1914 : FunctionDecl(DK, C, RD, StartLoc, NameInfo, T, TInfo, SC, isInline,
1915 ConstexprKind) {
1916 if (EndLocation.isValid())
1917 setRangeEnd(EndLocation);
1918 }
1919
1920public:
1921 static CXXMethodDecl *Create(ASTContext &C, CXXRecordDecl *RD,
1922 SourceLocation StartLoc,
1923 const DeclarationNameInfo &NameInfo, QualType T,
1924 TypeSourceInfo *TInfo, StorageClass SC,
1925 bool isInline, ConstexprSpecKind ConstexprKind,
1926 SourceLocation EndLocation);
1927
1928 static CXXMethodDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1929
1930 bool isStatic() const;
1931 bool isInstance() const { return !isStatic(); }
1932
1933 /// Returns true if the given operator is implicitly static in a record
1934 /// context.
1935 static bool isStaticOverloadedOperator(OverloadedOperatorKind OOK) {
1936 // [class.free]p1:
1937 // Any allocation function for a class T is a static member
1938 // (even if not explicitly declared static).
1939 // [class.free]p6 Any deallocation function for a class X is a static member
1940 // (even if not explicitly declared static).
1941 return OOK == OO_New || OOK == OO_Array_New || OOK == OO_Delete ||
1942 OOK == OO_Array_Delete;
1943 }
1944
1945 bool isConst() const { return getType()->castAs<FunctionType>()->isConst(); }
1946 bool isVolatile() const { return getType()->castAs<FunctionType>()->isVolatile(); }
1947
1948 bool isVirtual() const {
1949 CXXMethodDecl *CD = const_cast<CXXMethodDecl*>(this)->getCanonicalDecl();
1950
1951 // Member function is virtual if it is marked explicitly so, or if it is
1952 // declared in __interface -- then it is automatically pure virtual.
1953 if (CD->isVirtualAsWritten() || CD->isPure())
1954 return true;
1955
1956 return CD->size_overridden_methods() != 0;
1957 }
1958
1959 /// If it's possible to devirtualize a call to this method, return the called
1960 /// function. Otherwise, return null.
1961
1962 /// \param Base The object on which this virtual function is called.
1963 /// \param IsAppleKext True if we are compiling for Apple kext.
1964 CXXMethodDecl *getDevirtualizedMethod(const Expr *Base, bool IsAppleKext);
1965
1966 const CXXMethodDecl *getDevirtualizedMethod(const Expr *Base,
1967 bool IsAppleKext) const {
1968 return const_cast<CXXMethodDecl *>(this)->getDevirtualizedMethod(
1969 Base, IsAppleKext);
1970 }
1971
1972 /// Determine whether this is a usual deallocation function (C++
1973 /// [basic.stc.dynamic.deallocation]p2), which is an overloaded delete or
1974 /// delete[] operator with a particular signature. Populates \p PreventedBy
1975 /// with the declarations of the functions of the same kind if they were the
1976 /// reason for this function returning false. This is used by
1977 /// Sema::isUsualDeallocationFunction to reconsider the answer based on the
1978 /// context.
1979 bool isUsualDeallocationFunction(
1980 SmallVectorImpl<const FunctionDecl *> &PreventedBy) const;
1981
1982 /// Determine whether this is a copy-assignment operator, regardless
1983 /// of whether it was declared implicitly or explicitly.
1984 bool isCopyAssignmentOperator() const;
1985
1986 /// Determine whether this is a move assignment operator.
1987 bool isMoveAssignmentOperator() const;
1988
1989 CXXMethodDecl *getCanonicalDecl() override {
1990 return cast<CXXMethodDecl>(FunctionDecl::getCanonicalDecl());
1991 }
1992 const CXXMethodDecl *getCanonicalDecl() const {
1993 return const_cast<CXXMethodDecl*>(this)->getCanonicalDecl();
1994 }
1995
1996 CXXMethodDecl *getMostRecentDecl() {
1997 return cast<CXXMethodDecl>(
1998 static_cast<FunctionDecl *>(this)->getMostRecentDecl());
1999 }
2000 const CXXMethodDecl *getMostRecentDecl() const {
2001 return const_cast<CXXMethodDecl*>(this)->getMostRecentDecl();
2002 }
2003
2004 /// True if this method is user-declared and was not
2005 /// deleted or defaulted on its first declaration.
2006 bool isUserProvided() const {
2007 auto *DeclAsWritten = this;
2008 if (auto *Pattern = getTemplateInstantiationPattern())
2009 DeclAsWritten = cast<CXXMethodDecl>(Pattern);
2010 return !(DeclAsWritten->isDeleted() ||
2011 DeclAsWritten->getCanonicalDecl()->isDefaulted());
2012 }
2013
2014 void addOverriddenMethod(const CXXMethodDecl *MD);
2015
2016 using method_iterator = const CXXMethodDecl *const *;
2017
2018 method_iterator begin_overridden_methods() const;
2019 method_iterator end_overridden_methods() const;
2020 unsigned size_overridden_methods() const;
2021
2022 using overridden_method_range= ASTContext::overridden_method_range;
2023
2024 overridden_method_range overridden_methods() const;
2025
2026 /// Return the parent of this method declaration, which
2027 /// is the class in which this method is defined.
2028 const CXXRecordDecl *getParent() const {
2029 return cast<CXXRecordDecl>(FunctionDecl::getParent());
2030 }
2031
2032 /// Return the parent of this method declaration, which
2033 /// is the class in which this method is defined.
2034 CXXRecordDecl *getParent() {
2035 return const_cast<CXXRecordDecl *>(
2036 cast<CXXRecordDecl>(FunctionDecl::getParent()));
2037 }
2038
2039 /// Return the type of the \c this pointer.
2040 ///
2041 /// Should only be called for instance (i.e., non-static) methods. Note
2042 /// that for the call operator of a lambda closure type, this returns the
2043 /// desugared 'this' type (a pointer to the closure type), not the captured
2044 /// 'this' type.
2045 QualType getThisType() const;
2046
2047 /// Return the type of the object pointed by \c this.
2048 ///
2049 /// See getThisType() for usage restriction.
2050 QualType getThisObjectType() const;
2051
2052 static QualType getThisType(const FunctionProtoType *FPT,
2053 const CXXRecordDecl *Decl);
2054
2055 static QualType getThisObjectType(const FunctionProtoType *FPT,
2056 const CXXRecordDecl *Decl);
2057
2058 Qualifiers getMethodQualifiers() const {
2059 return getType()->castAs<FunctionProtoType>()->getMethodQuals();
2060 }
2061
2062 /// Retrieve the ref-qualifier associated with this method.
2063 ///
2064 /// In the following example, \c f() has an lvalue ref-qualifier, \c g()
2065 /// has an rvalue ref-qualifier, and \c h() has no ref-qualifier.
2066 /// @code
2067 /// struct X {
2068 /// void f() &;
2069 /// void g() &&;
2070 /// void h();
2071 /// };
2072 /// @endcode
2073 RefQualifierKind getRefQualifier() const {
2074 return getType()->castAs<FunctionProtoType>()->getRefQualifier();
2075 }
2076
2077 bool hasInlineBody() const;
2078
2079 /// Determine whether this is a lambda closure type's static member
2080 /// function that is used for the result of the lambda's conversion to
2081 /// function pointer (for a lambda with no captures).
2082 ///
2083 /// The function itself, if used, will have a placeholder body that will be
2084 /// supplied by IR generation to either forward to the function call operator
2085 /// or clone the function call operator.
2086 bool isLambdaStaticInvoker() const;
2087
2088 /// Find the method in \p RD that corresponds to this one.
2089 ///
2090 /// Find if \p RD or one of the classes it inherits from override this method.
2091 /// If so, return it. \p RD is assumed to be a subclass of the class defining
2092 /// this method (or be the class itself), unless \p MayBeBase is set to true.
2093 CXXMethodDecl *
2094 getCorrespondingMethodInClass(const CXXRecordDecl *RD,
2095 bool MayBeBase = false);
2096
2097 const CXXMethodDecl *
2098 getCorrespondingMethodInClass(const CXXRecordDecl *RD,
2099 bool MayBeBase = false) const {
2100 return const_cast<CXXMethodDecl *>(this)
2101 ->getCorrespondingMethodInClass(RD, MayBeBase);
2102 }
2103
2104 /// Find if \p RD declares a function that overrides this function, and if so,
2105 /// return it. Does not search base classes.
2106 CXXMethodDecl *getCorrespondingMethodDeclaredInClass(const CXXRecordDecl *RD,
2107 bool MayBeBase = false);
2108 const CXXMethodDecl *
2109 getCorrespondingMethodDeclaredInClass(const CXXRecordDecl *RD,
2110 bool MayBeBase = false) const {
2111 return const_cast<CXXMethodDecl *>(this)
2112 ->getCorrespondingMethodDeclaredInClass(RD, MayBeBase);
2113 }
2114
2115 // Implement isa/cast/dyncast/etc.
2116 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2117 static bool classofKind(Kind K) {
2118 return K >= firstCXXMethod && K <= lastCXXMethod;
2119 }
2120};
2121
2122/// Represents a C++ base or member initializer.
2123///
2124/// This is part of a constructor initializer that
2125/// initializes one non-static member variable or one base class. For
2126/// example, in the following, both 'A(a)' and 'f(3.14159)' are member
2127/// initializers:
2128///
2129/// \code
2130/// class A { };
2131/// class B : public A {
2132/// float f;
2133/// public:
2134/// B(A& a) : A(a), f(3.14159) { }
2135/// };
2136/// \endcode
2137class CXXCtorInitializer final {
2138 /// Either the base class name/delegating constructor type (stored as
2139 /// a TypeSourceInfo*), an normal field (FieldDecl), or an anonymous field
2140 /// (IndirectFieldDecl*) being initialized.
2141 llvm::PointerUnion3<TypeSourceInfo *, FieldDecl *, IndirectFieldDecl *>
2142 Initializee;
2143
2144 /// The source location for the field name or, for a base initializer
2145 /// pack expansion, the location of the ellipsis.
2146 ///
2147 /// In the case of a delegating
2148 /// constructor, it will still include the type's source location as the
2149 /// Initializee points to the CXXConstructorDecl (to allow loop detection).
2150 SourceLocation MemberOrEllipsisLocation;
2151
2152 /// The argument used to initialize the base or member, which may
2153 /// end up constructing an object (when multiple arguments are involved).
2154 Stmt *Init;
2155
2156 /// Location of the left paren of the ctor-initializer.
2157 SourceLocation LParenLoc;
2158
2159 /// Location of the right paren of the ctor-initializer.
2160 SourceLocation RParenLoc;
2161
2162 /// If the initializee is a type, whether that type makes this
2163 /// a delegating initialization.
2164 unsigned IsDelegating : 1;
2165
2166 /// If the initializer is a base initializer, this keeps track
2167 /// of whether the base is virtual or not.
2168 unsigned IsVirtual : 1;
2169
2170 /// Whether or not the initializer is explicitly written
2171 /// in the sources.
2172 unsigned IsWritten : 1;
2173
2174 /// If IsWritten is true, then this number keeps track of the textual order
2175 /// of this initializer in the original sources, counting from 0.
2176 unsigned SourceOrder : 13;
2177
2178public:
2179 /// Creates a new base-class initializer.
2180 explicit
2181 CXXCtorInitializer(ASTContext &Context, TypeSourceInfo *TInfo, bool IsVirtual,
2182 SourceLocation L, Expr *Init, SourceLocation R,
2183 SourceLocation EllipsisLoc);
2184
2185 /// Creates a new member initializer.
2186 explicit
2187 CXXCtorInitializer(ASTContext &Context, FieldDecl *Member,
2188 SourceLocation MemberLoc, SourceLocation L, Expr *Init,
2189 SourceLocation R);
2190
2191 /// Creates a new anonymous field initializer.
2192 explicit
2193 CXXCtorInitializer(ASTContext &Context, IndirectFieldDecl *Member,
2194 SourceLocation MemberLoc, SourceLocation L, Expr *Init,
2195 SourceLocation R);
2196
2197 /// Creates a new delegating initializer.
2198 explicit
2199 CXXCtorInitializer(ASTContext &Context, TypeSourceInfo *TInfo,
2200 SourceLocation L, Expr *Init, SourceLocation R);
2201
2202 /// \return Unique reproducible object identifier.
2203 int64_t getID(const ASTContext &Context) const;
2204
2205 /// Determine whether this initializer is initializing a base class.
2206 bool isBaseInitializer() const {
2207 return Initializee.is<TypeSourceInfo*>() && !IsDelegating;
2208 }
2209
2210 /// Determine whether this initializer is initializing a non-static
2211 /// data member.
2212 bool isMemberInitializer() const { return Initializee.is<FieldDecl*>(); }
2213
2214 bool isAnyMemberInitializer() const {
2215 return isMemberInitializer() || isIndirectMemberInitializer();
2216 }
2217
2218 bool isIndirectMemberInitializer() const {
2219 return Initializee.is<IndirectFieldDecl*>();
2220 }
2221
2222 /// Determine whether this initializer is an implicit initializer
2223 /// generated for a field with an initializer defined on the member
2224 /// declaration.
2225 ///
2226 /// In-class member initializers (also known as "non-static data member
2227 /// initializations", NSDMIs) were introduced in C++11.
2228 bool isInClassMemberInitializer() const {
2229 return Init->getStmtClass() == Stmt::CXXDefaultInitExprClass;
2230 }
2231
2232 /// Determine whether this initializer is creating a delegating
2233 /// constructor.
2234 bool isDelegatingInitializer() const {
2235 return Initializee.is<TypeSourceInfo*>() && IsDelegating;
2236 }
2237
2238 /// Determine whether this initializer is a pack expansion.
2239 bool isPackExpansion() const {
2240 return isBaseInitializer() && MemberOrEllipsisLocation.isValid();
2241 }
2242
2243 // For a pack expansion, returns the location of the ellipsis.
2244 SourceLocation getEllipsisLoc() const {
2245 assert(isPackExpansion() && "Initializer is not a pack expansion")((isPackExpansion() && "Initializer is not a pack expansion"
) ? static_cast<void> (0) : __assert_fail ("isPackExpansion() && \"Initializer is not a pack expansion\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclCXX.h"
, 2245, __PRETTY_FUNCTION__))
;
2246 return MemberOrEllipsisLocation;
2247 }
2248
2249 /// If this is a base class initializer, returns the type of the
2250 /// base class with location information. Otherwise, returns an NULL
2251 /// type location.
2252 TypeLoc getBaseClassLoc() const;
2253
2254 /// If this is a base class initializer, returns the type of the base class.
2255 /// Otherwise, returns null.
2256 const Type *getBaseClass() const;
2257
2258 /// Returns whether the base is virtual or not.
2259 bool isBaseVirtual() const {
2260 assert(isBaseInitializer() && "Must call this on base initializer!")((isBaseInitializer() && "Must call this on base initializer!"
) ? static_cast<void> (0) : __assert_fail ("isBaseInitializer() && \"Must call this on base initializer!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclCXX.h"
, 2260, __PRETTY_FUNCTION__))
;
2261
2262 return IsVirtual;
2263 }
2264
2265 /// Returns the declarator information for a base class or delegating
2266 /// initializer.
2267 TypeSourceInfo *getTypeSourceInfo() const {
2268 return Initializee.dyn_cast<TypeSourceInfo *>();
2269 }
2270
2271 /// If this is a member initializer, returns the declaration of the
2272 /// non-static data member being initialized. Otherwise, returns null.
2273 FieldDecl *getMember() const {
2274 if (isMemberInitializer())
2275 return Initializee.get<FieldDecl*>();
2276 return nullptr;
2277 }
2278
2279 FieldDecl *getAnyMember() const {
2280 if (isMemberInitializer())
2281 return Initializee.get<FieldDecl*>();
2282 if (isIndirectMemberInitializer())
2283 return Initializee.get<IndirectFieldDecl*>()->getAnonField();
2284 return nullptr;
2285 }
2286
2287 IndirectFieldDecl *getIndirectMember() const {
2288 if (isIndirectMemberInitializer())
2289 return Initializee.get<IndirectFieldDecl*>();
2290 return nullptr;
2291 }
2292
2293 SourceLocation getMemberLocation() const {
2294 return MemberOrEllipsisLocation;
2295 }
2296
2297 /// Determine the source location of the initializer.
2298 SourceLocation getSourceLocation() const;
2299
2300 /// Determine the source range covering the entire initializer.
2301 SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__));
2302
2303 /// Determine whether this initializer is explicitly written
2304 /// in the source code.
2305 bool isWritten() const { return IsWritten; }
2306
2307 /// Return the source position of the initializer, counting from 0.
2308 /// If the initializer was implicit, -1 is returned.
2309 int getSourceOrder() const {
2310 return IsWritten ? static_cast<int>(SourceOrder) : -1;
2311 }
2312
2313 /// Set the source order of this initializer.
2314 ///
2315 /// This can only be called once for each initializer; it cannot be called
2316 /// on an initializer having a positive number of (implicit) array indices.
2317 ///
2318 /// This assumes that the initializer was written in the source code, and
2319 /// ensures that isWritten() returns true.
2320 void setSourceOrder(int Pos) {
2321 assert(!IsWritten &&((!IsWritten && "setSourceOrder() used on implicit initializer"
) ? static_cast<void> (0) : __assert_fail ("!IsWritten && \"setSourceOrder() used on implicit initializer\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclCXX.h"
, 2322, __PRETTY_FUNCTION__))
2322 "setSourceOrder() used on implicit initializer")((!IsWritten && "setSourceOrder() used on implicit initializer"
) ? static_cast<void> (0) : __assert_fail ("!IsWritten && \"setSourceOrder() used on implicit initializer\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclCXX.h"
, 2322, __PRETTY_FUNCTION__))
;
2323 assert(SourceOrder == 0 &&((SourceOrder == 0 && "calling twice setSourceOrder() on the same initializer"
) ? static_cast<void> (0) : __assert_fail ("SourceOrder == 0 && \"calling twice setSourceOrder() on the same initializer\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclCXX.h"
, 2324, __PRETTY_FUNCTION__))
2324 "calling twice setSourceOrder() on the same initializer")((SourceOrder == 0 && "calling twice setSourceOrder() on the same initializer"
) ? static_cast<void> (0) : __assert_fail ("SourceOrder == 0 && \"calling twice setSourceOrder() on the same initializer\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclCXX.h"
, 2324, __PRETTY_FUNCTION__))
;
2325 assert(Pos >= 0 &&((Pos >= 0 && "setSourceOrder() used to make an initializer implicit"
) ? static_cast<void> (0) : __assert_fail ("Pos >= 0 && \"setSourceOrder() used to make an initializer implicit\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclCXX.h"
, 2326, __PRETTY_FUNCTION__))
2326 "setSourceOrder() used to make an initializer implicit")((Pos >= 0 && "setSourceOrder() used to make an initializer implicit"
) ? static_cast<void> (0) : __assert_fail ("Pos >= 0 && \"setSourceOrder() used to make an initializer implicit\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclCXX.h"
, 2326, __PRETTY_FUNCTION__))
;
2327 IsWritten = true;
2328 SourceOrder = static_cast<unsigned>(Pos);
2329 }
2330
2331 SourceLocation getLParenLoc() const { return LParenLoc; }
2332 SourceLocation getRParenLoc() const { return RParenLoc; }
2333
2334 /// Get the initializer.
2335 Expr *getInit() const { return static_cast<Expr *>(Init); }
2336};
2337
2338/// Description of a constructor that was inherited from a base class.
2339class InheritedConstructor {
2340 ConstructorUsingShadowDecl *Shadow = nullptr;
2341 CXXConstructorDecl *BaseCtor = nullptr;
2342
2343public:
2344 InheritedConstructor() = default;
2345 InheritedConstructor(ConstructorUsingShadowDecl *Shadow,
2346 CXXConstructorDecl *BaseCtor)
2347 : Shadow(Shadow), BaseCtor(BaseCtor) {}
2348
2349 explicit operator bool() const { return Shadow; }
2350
2351 ConstructorUsingShadowDecl *getShadowDecl() const { return Shadow; }
2352 CXXConstructorDecl *getConstructor() const { return BaseCtor; }
2353};
2354
2355/// Represents a C++ constructor within a class.
2356///
2357/// For example:
2358///
2359/// \code
2360/// class X {
2361/// public:
2362/// explicit X(int); // represented by a CXXConstructorDecl.
2363/// };
2364/// \endcode
2365class CXXConstructorDecl final
2366 : public CXXMethodDecl,
2367 private llvm::TrailingObjects<CXXConstructorDecl, InheritedConstructor,
2368 ExplicitSpecifier> {
2369 // This class stores some data in DeclContext::CXXConstructorDeclBits
2370 // to save some space. Use the provided accessors to access it.
2371
2372 /// \name Support for base and member initializers.
2373 /// \{
2374 /// The arguments used to initialize the base or member.
2375 LazyCXXCtorInitializersPtr CtorInitializers;
2376
2377 CXXConstructorDecl(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2378 const DeclarationNameInfo &NameInfo, QualType T,
2379 TypeSourceInfo *TInfo, ExplicitSpecifier ES, bool isInline,
2380 bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind,
2381 InheritedConstructor Inherited);
2382
2383 void anchor() override;
2384
2385 size_t numTrailingObjects(OverloadToken<InheritedConstructor>) const {
2386 return CXXConstructorDeclBits.IsInheritingConstructor;
2387 }
2388 size_t numTrailingObjects(OverloadToken<ExplicitSpecifier>) const {
2389 return CXXConstructorDeclBits.HasTrailingExplicitSpecifier;
2390 }
2391
2392 ExplicitSpecifier getExplicitSpecifierInternal() const {
2393 if (CXXConstructorDeclBits.HasTrailingExplicitSpecifier)
2394 return *getTrailingObjects<ExplicitSpecifier>();
2395 return ExplicitSpecifier(
2396 nullptr, CXXConstructorDeclBits.IsSimpleExplicit
2397 ? ExplicitSpecKind::ResolvedTrue
2398 : ExplicitSpecKind::ResolvedFalse);
2399 }
2400
2401 void setExplicitSpecifier(ExplicitSpecifier ES) {
2402 assert((!ES.getExpr() ||(((!ES.getExpr() || CXXConstructorDeclBits.HasTrailingExplicitSpecifier
) && "cannot set this explicit specifier. no trail-allocated space for "
"explicit") ? static_cast<void> (0) : __assert_fail ("(!ES.getExpr() || CXXConstructorDeclBits.HasTrailingExplicitSpecifier) && \"cannot set this explicit specifier. no trail-allocated space for \" \"explicit\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclCXX.h"
, 2405, __PRETTY_FUNCTION__))
2403 CXXConstructorDeclBits.HasTrailingExplicitSpecifier) &&(((!ES.getExpr() || CXXConstructorDeclBits.HasTrailingExplicitSpecifier
) && "cannot set this explicit specifier. no trail-allocated space for "
"explicit") ? static_cast<void> (0) : __assert_fail ("(!ES.getExpr() || CXXConstructorDeclBits.HasTrailingExplicitSpecifier) && \"cannot set this explicit specifier. no trail-allocated space for \" \"explicit\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclCXX.h"
, 2405, __PRETTY_FUNCTION__))
2404 "cannot set this explicit specifier. no trail-allocated space for "(((!ES.getExpr() || CXXConstructorDeclBits.HasTrailingExplicitSpecifier
) && "cannot set this explicit specifier. no trail-allocated space for "
"explicit") ? static_cast<void> (0) : __assert_fail ("(!ES.getExpr() || CXXConstructorDeclBits.HasTrailingExplicitSpecifier) && \"cannot set this explicit specifier. no trail-allocated space for \" \"explicit\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclCXX.h"
, 2405, __PRETTY_FUNCTION__))
2405 "explicit")(((!ES.getExpr() || CXXConstructorDeclBits.HasTrailingExplicitSpecifier
) && "cannot set this explicit specifier. no trail-allocated space for "
"explicit") ? static_cast<void> (0) : __assert_fail ("(!ES.getExpr() || CXXConstructorDeclBits.HasTrailingExplicitSpecifier) && \"cannot set this explicit specifier. no trail-allocated space for \" \"explicit\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclCXX.h"
, 2405, __PRETTY_FUNCTION__))
;
2406 if (ES.getExpr())
2407 *getCanonicalDecl()->getTrailingObjects<ExplicitSpecifier>() = ES;
2408 else
2409 CXXConstructorDeclBits.IsSimpleExplicit = ES.isExplicit();
2410 }
2411
2412 enum TraillingAllocKind {
2413 TAKInheritsConstructor = 1,
2414 TAKHasTailExplicit = 1 << 1,
2415 };
2416
2417 uint64_t getTraillingAllocKind() const {
2418 return numTrailingObjects(OverloadToken<InheritedConstructor>()) |
2419 (numTrailingObjects(OverloadToken<ExplicitSpecifier>()) << 1);
2420 }
2421
2422public:
2423 friend class ASTDeclReader;
2424 friend class ASTDeclWriter;
2425 friend TrailingObjects;
2426
2427 static CXXConstructorDecl *CreateDeserialized(ASTContext &C, unsigned ID,
2428 uint64_t AllocKind);
2429 static CXXConstructorDecl *
2430 Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2431 const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo,
2432 ExplicitSpecifier ES, bool isInline, bool isImplicitlyDeclared,
2433 ConstexprSpecKind ConstexprKind,
2434 InheritedConstructor Inherited = InheritedConstructor());
2435
2436 ExplicitSpecifier getExplicitSpecifier() {
2437 return getCanonicalDecl()->getExplicitSpecifierInternal();
2438 }
2439 const ExplicitSpecifier getExplicitSpecifier() const {
2440 return getCanonicalDecl()->getExplicitSpecifierInternal();
2441 }
2442
2443 /// Return true if the declartion is already resolved to be explicit.
2444 bool isExplicit() const { return getExplicitSpecifier().isExplicit(); }
2445
2446 /// Iterates through the member/base initializer list.
2447 using init_iterator = CXXCtorInitializer **;
2448
2449 /// Iterates through the member/base initializer list.
2450 using init_const_iterator = CXXCtorInitializer *const *;
2451
2452 using init_range = llvm::iterator_range<init_iterator>;
2453 using init_const_range = llvm::iterator_range<init_const_iterator>;
2454
2455 init_range inits() { return init_range(init_begin(), init_end()); }
2456 init_const_range inits() const {
2457 return init_const_range(init_begin(), init_end());
2458 }
2459
2460 /// Retrieve an iterator to the first initializer.
2461 init_iterator init_begin() {
2462 const auto *ConstThis = this;
2463 return const_cast<init_iterator>(ConstThis->init_begin());
2464 }
2465
2466 /// Retrieve an iterator to the first initializer.
2467 init_const_iterator init_begin() const;
2468
2469 /// Retrieve an iterator past the last initializer.
2470 init_iterator init_end() {
2471 return init_begin() + getNumCtorInitializers();
2472 }
2473
2474 /// Retrieve an iterator past the last initializer.
2475 init_const_iterator init_end() const {
2476 return init_begin() + getNumCtorInitializers();
2477 }
2478
2479 using init_reverse_iterator = std::reverse_iterator<init_iterator>;
2480 using init_const_reverse_iterator =
2481 std::reverse_iterator<init_const_iterator>;
2482
2483 init_reverse_iterator init_rbegin() {
2484 return init_reverse_iterator(init_end());
2485 }
2486 init_const_reverse_iterator init_rbegin() const {
2487 return init_const_reverse_iterator(init_end());
2488 }
2489
2490 init_reverse_iterator init_rend() {
2491 return init_reverse_iterator(init_begin());
2492 }
2493 init_const_reverse_iterator init_rend() const {
2494 return init_const_reverse_iterator(init_begin());
2495 }
2496
2497 /// Determine the number of arguments used to initialize the member
2498 /// or base.
2499 unsigned getNumCtorInitializers() const {
2500 return CXXConstructorDeclBits.NumCtorInitializers;
2501 }
2502
2503 void setNumCtorInitializers(unsigned numCtorInitializers) {
2504 CXXConstructorDeclBits.NumCtorInitializers = numCtorInitializers;
2505 // This assert added because NumCtorInitializers is stored
2506 // in CXXConstructorDeclBits as a bitfield and its width has
2507 // been shrunk from 32 bits to fit into CXXConstructorDeclBitfields.
2508 assert(CXXConstructorDeclBits.NumCtorInitializers ==((CXXConstructorDeclBits.NumCtorInitializers == numCtorInitializers
&& "NumCtorInitializers overflow!") ? static_cast<
void> (0) : __assert_fail ("CXXConstructorDeclBits.NumCtorInitializers == numCtorInitializers && \"NumCtorInitializers overflow!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclCXX.h"
, 2509, __PRETTY_FUNCTION__))
2509 numCtorInitializers && "NumCtorInitializers overflow!")((CXXConstructorDeclBits.NumCtorInitializers == numCtorInitializers
&& "NumCtorInitializers overflow!") ? static_cast<
void> (0) : __assert_fail ("CXXConstructorDeclBits.NumCtorInitializers == numCtorInitializers && \"NumCtorInitializers overflow!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/DeclCXX.h"
, 2509, __PRETTY_FUNCTION__))
;
2510 }
2511
2512 void setCtorInitializers(CXXCtorInitializer **Initializers) {
2513 CtorInitializers = Initializers;
2514 }
2515
2516 /// Determine whether this constructor is a delegating constructor.
2517 bool isDelegatingConstructor() const {
2518 return (getNumCtorInitializers() == 1) &&
2519 init_begin()[0]->isDelegatingInitializer();
2520 }
2521
2522 /// When this constructor delegates to another, retrieve the target.
2523 CXXConstructorDecl *getTargetConstructor() const;
2524
2525 /// Whether this constructor is a default
2526 /// constructor (C++ [class.ctor]p5), which can be used to
2527 /// default-initialize a class of this type.
2528 bool isDefaultConstructor() const;
2529
2530