Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -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 -mframe-pointer=none -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/build-llvm -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/clang/lib/Sema -I /build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/clang/include -I tools/clang/include -I include -I /build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-01-16-232930-107970-1 -x c++ /build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/clang/lib/Sema/SemaTemplateInstantiate.cpp

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

/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/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
67inline bool isGenericLambdaCallOperatorOrStaticInvokerSpecialization(
68 DeclContext *DC) {
69 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC);
70 if (!MD) return false;
71 const CXXRecordDecl *LambdaClass = MD->getParent();
72 if (LambdaClass && LambdaClass->isGenericLambda())
73 return (isLambdaCallOperator(MD) || MD->isLambdaStaticInvoker()) &&
74 MD->isFunctionTemplateSpecialization();
75 return false;
76}
77
78
79// This returns the parent DeclContext ensuring that the correct
80// parent DeclContext is returned for Lambdas
81inline DeclContext *getLambdaAwareParentOfDeclContext(DeclContext *DC) {
82 if (isLambdaCallOperator(DC))
83 return DC->getParent()->getParent();
84 else
85 return DC->getParent();
86}
87
88} // clang
89
90#endif

/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/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/ASTUnresolvedSet.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclBase.h"
21#include "clang/AST/DeclarationName.h"
22#include "clang/AST/Expr.h"
23#include "clang/AST/ExternalASTSource.h"
24#include "clang/AST/LambdaCapture.h"
25#include "clang/AST/NestedNameSpecifier.h"
26#include "clang/AST/Redeclarable.h"
27#include "clang/AST/Stmt.h"
28#include "clang/AST/Type.h"
29#include "clang/AST/TypeLoc.h"
30#include "clang/AST/UnresolvedSet.h"
31#include "clang/Basic/LLVM.h"
32#include "clang/Basic/Lambda.h"
33#include "clang/Basic/LangOptions.h"
34#include "clang/Basic/OperatorKinds.h"
35#include "clang/Basic/SourceLocation.h"
36#include "clang/Basic/Specifiers.h"
37#include "llvm/ADT/ArrayRef.h"
38#include "llvm/ADT/DenseMap.h"
39#include "llvm/ADT/PointerIntPair.h"
40#include "llvm/ADT/PointerUnion.h"
41#include "llvm/ADT/STLExtras.h"
42#include "llvm/ADT/TinyPtrVector.h"
43#include "llvm/ADT/iterator_range.h"
44#include "llvm/Support/Casting.h"
45#include "llvm/Support/Compiler.h"
46#include "llvm/Support/PointerLikeTypeTraits.h"
47#include "llvm/Support/TrailingObjects.h"
48#include <cassert>
49#include <cstddef>
50#include <iterator>
51#include <memory>
52#include <vector>
53
54namespace clang {
55
56class ASTContext;
57class ClassTemplateDecl;
58class ConstructorUsingShadowDecl;
59class CXXBasePath;
60class CXXBasePaths;
61class CXXConstructorDecl;
62class CXXDestructorDecl;
63class CXXFinalOverriderMap;
64class CXXIndirectPrimaryBaseSet;
65class CXXMethodDecl;
66class DecompositionDecl;
67class FriendDecl;
68class FunctionTemplateDecl;
69class IdentifierInfo;
70class MemberSpecializationInfo;
71class BaseUsingDecl;
72class TemplateDecl;
73class TemplateParameterList;
74class UsingDecl;
75
76/// Represents an access specifier followed by colon ':'.
77///
78/// An objects of this class represents sugar for the syntactic occurrence
79/// of an access specifier followed by a colon in the list of member
80/// specifiers of a C++ class definition.
81///
82/// Note that they do not represent other uses of access specifiers,
83/// such as those occurring in a list of base specifiers.
84/// Also note that this class has nothing to do with so-called
85/// "access declarations" (C++98 11.3 [class.access.dcl]).
86class AccessSpecDecl : public Decl {
87 /// The location of the ':'.
88 SourceLocation ColonLoc;
89
90 AccessSpecDecl(AccessSpecifier AS, DeclContext *DC,
91 SourceLocation ASLoc, SourceLocation ColonLoc)
92 : Decl(AccessSpec, DC, ASLoc), ColonLoc(ColonLoc) {
93 setAccess(AS);
94 }
95
96 AccessSpecDecl(EmptyShell Empty) : Decl(AccessSpec, Empty) {}
97
98 virtual void anchor();
99
100public:
101 /// The location of the access specifier.
102 SourceLocation getAccessSpecifierLoc() const { return getLocation(); }
103
104 /// Sets the location of the access specifier.
105 void setAccessSpecifierLoc(SourceLocation ASLoc) { setLocation(ASLoc); }
106
107 /// The location of the colon following the access specifier.
108 SourceLocation getColonLoc() const { return ColonLoc; }
109
110 /// Sets the location of the colon.
111 void setColonLoc(SourceLocation CLoc) { ColonLoc = CLoc; }
112
113 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
114 return SourceRange(getAccessSpecifierLoc(), getColonLoc());
115 }
116
117 static AccessSpecDecl *Create(ASTContext &C, AccessSpecifier AS,
118 DeclContext *DC, SourceLocation ASLoc,
119 SourceLocation ColonLoc) {
120 return new (C, DC) AccessSpecDecl(AS, DC, ASLoc, ColonLoc);
121 }
122
123 static AccessSpecDecl *CreateDeserialized(ASTContext &C, unsigned ID);
124
125 // Implement isa/cast/dyncast/etc.
126 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
127 static bool classofKind(Kind K) { return K == AccessSpec; }
128};
129
130/// Represents a base class of a C++ class.
131///
132/// Each CXXBaseSpecifier represents a single, direct base class (or
133/// struct) of a C++ class (or struct). It specifies the type of that
134/// base class, whether it is a virtual or non-virtual base, and what
135/// level of access (public, protected, private) is used for the
136/// derivation. For example:
137///
138/// \code
139/// class A { };
140/// class B { };
141/// class C : public virtual A, protected B { };
142/// \endcode
143///
144/// In this code, C will have two CXXBaseSpecifiers, one for "public
145/// virtual A" and the other for "protected B".
146class CXXBaseSpecifier {
147 /// The source code range that covers the full base
148 /// specifier, including the "virtual" (if present) and access
149 /// specifier (if present).
150 SourceRange Range;
151
152 /// The source location of the ellipsis, if this is a pack
153 /// expansion.
154 SourceLocation EllipsisLoc;
155
156 /// Whether this is a virtual base class or not.
157 unsigned Virtual : 1;
158
159 /// Whether this is the base of a class (true) or of a struct (false).
160 ///
161 /// This determines the mapping from the access specifier as written in the
162 /// source code to the access specifier used for semantic analysis.
163 unsigned BaseOfClass : 1;
164
165 /// Access specifier as written in the source code (may be AS_none).
166 ///
167 /// The actual type of data stored here is an AccessSpecifier, but we use
168 /// "unsigned" here to work around a VC++ bug.
169 unsigned Access : 2;
170
171 /// Whether the class contains a using declaration
172 /// to inherit the named class's constructors.
173 unsigned InheritConstructors : 1;
174
175 /// The type of the base class.
176 ///
177 /// This will be a class or struct (or a typedef of such). The source code
178 /// range does not include the \c virtual or the access specifier.
179 TypeSourceInfo *BaseTypeInfo;
180
181public:
182 CXXBaseSpecifier() = default;
183 CXXBaseSpecifier(SourceRange R, bool V, bool BC, AccessSpecifier A,
184 TypeSourceInfo *TInfo, SourceLocation EllipsisLoc)
185 : Range(R), EllipsisLoc(EllipsisLoc), Virtual(V), BaseOfClass(BC),
186 Access(A), InheritConstructors(false), BaseTypeInfo(TInfo) {}
187
188 /// Retrieves the source range that contains the entire base specifier.
189 SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) { return Range; }
190 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Range.getBegin(); }
191 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return Range.getEnd(); }
192
193 /// Get the location at which the base class type was written.
194 SourceLocation getBaseTypeLoc() const LLVM_READONLY__attribute__((__pure__)) {
195 return BaseTypeInfo->getTypeLoc().getBeginLoc();
196 }
197
198 /// Determines whether the base class is a virtual base class (or not).
199 bool isVirtual() const { return Virtual; }
200
201 /// Determine whether this base class is a base of a class declared
202 /// with the 'class' keyword (vs. one declared with the 'struct' keyword).
203 bool isBaseOfClass() const { return BaseOfClass; }
204
205 /// Determine whether this base specifier is a pack expansion.
206 bool isPackExpansion() const { return EllipsisLoc.isValid(); }
207
208 /// Determine whether this base class's constructors get inherited.
209 bool getInheritConstructors() const { return InheritConstructors; }
210
211 /// Set that this base class's constructors should be inherited.
212 void setInheritConstructors(bool Inherit = true) {
213 InheritConstructors = Inherit;
214 }
215
216 /// For a pack expansion, determine the location of the ellipsis.
217 SourceLocation getEllipsisLoc() const {
218 return EllipsisLoc;
219 }
220
221 /// Returns the access specifier for this base specifier.
222 ///
223 /// This is the actual base specifier as used for semantic analysis, so
224 /// the result can never be AS_none. To retrieve the access specifier as
225 /// written in the source code, use getAccessSpecifierAsWritten().
226 AccessSpecifier getAccessSpecifier() const {
227 if ((AccessSpecifier)Access == AS_none)
228 return BaseOfClass? AS_private : AS_public;
229 else
230 return (AccessSpecifier)Access;
231 }
232
233 /// Retrieves the access specifier as written in the source code
234 /// (which may mean that no access specifier was explicitly written).
235 ///
236 /// Use getAccessSpecifier() to retrieve the access specifier for use in
237 /// semantic analysis.
238 AccessSpecifier getAccessSpecifierAsWritten() const {
239 return (AccessSpecifier)Access;
240 }
241
242 /// Retrieves the type of the base class.
243 ///
244 /// This type will always be an unqualified class type.
245 QualType getType() const {
246 return BaseTypeInfo->getType().getUnqualifiedType();
247 }
248
249 /// Retrieves the type and source location of the base class.
250 TypeSourceInfo *getTypeSourceInfo() const { return BaseTypeInfo; }
251};
252
253/// Represents a C++ struct/union/class.
254class CXXRecordDecl : public RecordDecl {
255 friend class ASTDeclReader;
256 friend class ASTDeclWriter;
257 friend class ASTNodeImporter;
258 friend class ASTReader;
259 friend class ASTRecordWriter;
260 friend class ASTWriter;
261 friend class DeclContext;
262 friend class LambdaExpr;
263
264 friend void FunctionDecl::setPure(bool);
265 friend void TagDecl::startDefinition();
266
267 /// Values used in DefinitionData fields to represent special members.
268 enum SpecialMemberFlags {
269 SMF_DefaultConstructor = 0x1,
270 SMF_CopyConstructor = 0x2,
271 SMF_MoveConstructor = 0x4,
272 SMF_CopyAssignment = 0x8,
273 SMF_MoveAssignment = 0x10,
274 SMF_Destructor = 0x20,
275 SMF_All = 0x3f
276 };
277
278 struct DefinitionData {
279 #define FIELD(Name, Width, Merge) \
280 unsigned Name : Width;
281 #include "CXXRecordDeclDefinitionBits.def"
282
283 /// Whether this class describes a C++ lambda.
284 unsigned IsLambda : 1;
285
286 /// Whether we are currently parsing base specifiers.
287 unsigned IsParsingBaseSpecifiers : 1;
288
289 /// True when visible conversion functions are already computed
290 /// and are available.
291 unsigned ComputedVisibleConversions : 1;
292
293 unsigned HasODRHash : 1;
294
295 /// A hash of parts of the class to help in ODR checking.
296 unsigned ODRHash = 0;
297
298 /// The number of base class specifiers in Bases.
299 unsigned NumBases = 0;
300
301 /// The number of virtual base class specifiers in VBases.
302 unsigned NumVBases = 0;
303
304 /// Base classes of this class.
305 ///
306 /// FIXME: This is wasted space for a union.
307 LazyCXXBaseSpecifiersPtr Bases;
308
309 /// direct and indirect virtual base classes of this class.
310 LazyCXXBaseSpecifiersPtr VBases;
311
312 /// The conversion functions of this C++ class (but not its
313 /// inherited conversion functions).
314 ///
315 /// Each of the entries in this overload set is a CXXConversionDecl.
316 LazyASTUnresolvedSet Conversions;
317
318 /// The conversion functions of this C++ class and all those
319 /// inherited conversion functions that are visible in this class.
320 ///
321 /// Each of the entries in this overload set is a CXXConversionDecl or a
322 /// FunctionTemplateDecl.
323 LazyASTUnresolvedSet VisibleConversions;
324
325 /// The declaration which defines this record.
326 CXXRecordDecl *Definition;
327
328 /// The first friend declaration in this class, or null if there
329 /// aren't any.
330 ///
331 /// This is actually currently stored in reverse order.
332 LazyDeclPtr FirstFriend;
333
334 DefinitionData(CXXRecordDecl *D);
335
336 /// Retrieve the set of direct base classes.
337 CXXBaseSpecifier *getBases() const {
338 if (!Bases.isOffset())
339 return Bases.get(nullptr);
340 return getBasesSlowCase();
341 }
342
343 /// Retrieve the set of virtual base classes.
344 CXXBaseSpecifier *getVBases() const {
345 if (!VBases.isOffset())
346 return VBases.get(nullptr);
347 return getVBasesSlowCase();
348 }
349
350 ArrayRef<CXXBaseSpecifier> bases() const {
351 return llvm::makeArrayRef(getBases(), NumBases);
352 }
353
354 ArrayRef<CXXBaseSpecifier> vbases() const {
355 return llvm::makeArrayRef(getVBases(), NumVBases);
356 }
357
358 private:
359 CXXBaseSpecifier *getBasesSlowCase() const;
360 CXXBaseSpecifier *getVBasesSlowCase() const;
361 };
362
363 struct DefinitionData *DefinitionData;
364
365 /// Describes a C++ closure type (generated by a lambda expression).
366 struct LambdaDefinitionData : public DefinitionData {
367 using Capture = LambdaCapture;
368
369 /// Whether this lambda is known to be dependent, even if its
370 /// context isn't dependent.
371 ///
372 /// A lambda with a non-dependent context can be dependent if it occurs
373 /// within the default argument of a function template, because the
374 /// lambda will have been created with the enclosing context as its
375 /// declaration context, rather than function. This is an unfortunate
376 /// artifact of having to parse the default arguments before.
377 unsigned Dependent : 1;
378
379 /// Whether this lambda is a generic lambda.
380 unsigned IsGenericLambda : 1;
381
382 /// The Default Capture.
383 unsigned CaptureDefault : 2;
384
385 /// The number of captures in this lambda is limited 2^NumCaptures.
386 unsigned NumCaptures : 15;
387
388 /// The number of explicit captures in this lambda.
389 unsigned NumExplicitCaptures : 13;
390
391 /// Has known `internal` linkage.
392 unsigned HasKnownInternalLinkage : 1;
393
394 /// The number used to indicate this lambda expression for name
395 /// mangling in the Itanium C++ ABI.
396 unsigned ManglingNumber : 31;
397
398 /// The declaration that provides context for this lambda, if the
399 /// actual DeclContext does not suffice. This is used for lambdas that
400 /// occur within default arguments of function parameters within the class
401 /// or within a data member initializer.
402 LazyDeclPtr ContextDecl;
403
404 /// The list of captures, both explicit and implicit, for this
405 /// lambda.
406 Capture *Captures = nullptr;
407
408 /// The type of the call method.
409 TypeSourceInfo *MethodTyInfo;
410
411 LambdaDefinitionData(CXXRecordDecl *D, TypeSourceInfo *Info, bool Dependent,
412 bool IsGeneric, LambdaCaptureDefault CaptureDefault)
413 : DefinitionData(D), Dependent(Dependent), IsGenericLambda(IsGeneric),
414 CaptureDefault(CaptureDefault), NumCaptures(0),
415 NumExplicitCaptures(0), HasKnownInternalLinkage(0), ManglingNumber(0),
416 MethodTyInfo(Info) {
417 IsLambda = true;
418
419 // C++1z [expr.prim.lambda]p4:
420 // This class type is not an aggregate type.
421 Aggregate = false;
422 PlainOldData = false;
423 }
424 };
425
426 struct DefinitionData *dataPtr() const {
427 // Complete the redecl chain (if necessary).
428 getMostRecentDecl();
429 return DefinitionData;
430 }
431
432 struct DefinitionData &data() const {
433 auto *DD = dataPtr();
434 assert(DD && "queried property of class with no definition")(static_cast <bool> (DD && "queried property of class with no definition"
) ? void (0) : __assert_fail ("DD && \"queried property of class with no definition\""
, "clang/include/clang/AST/DeclCXX.h", 434, __extension__ __PRETTY_FUNCTION__
))
;
435 return *DD;
436 }
437
438 struct LambdaDefinitionData &getLambdaData() const {
439 // No update required: a merged definition cannot change any lambda
440 // properties.
441 auto *DD = DefinitionData;
442 assert(DD && DD->IsLambda && "queried lambda property of non-lambda class")(static_cast <bool> (DD && DD->IsLambda &&
"queried lambda property of non-lambda class") ? void (0) : __assert_fail
("DD && DD->IsLambda && \"queried lambda property of non-lambda class\""
, "clang/include/clang/AST/DeclCXX.h", 442, __extension__ __PRETTY_FUNCTION__
))
;
443 return static_cast<LambdaDefinitionData&>(*DD);
444 }
445
446 /// The template or declaration that this declaration
447 /// describes or was instantiated from, respectively.
448 ///
449 /// For non-templates, this value will be null. For record
450 /// declarations that describe a class template, this will be a
451 /// pointer to a ClassTemplateDecl. For member
452 /// classes of class template specializations, this will be the
453 /// MemberSpecializationInfo referring to the member class that was
454 /// instantiated or specialized.
455 llvm::PointerUnion<ClassTemplateDecl *, MemberSpecializationInfo *>
456 TemplateOrInstantiation;
457
458 /// Called from setBases and addedMember to notify the class that a
459 /// direct or virtual base class or a member of class type has been added.
460 void addedClassSubobject(CXXRecordDecl *Base);
461
462 /// Notify the class that member has been added.
463 ///
464 /// This routine helps maintain information about the class based on which
465 /// members have been added. It will be invoked by DeclContext::addDecl()
466 /// whenever a member is added to this record.
467 void addedMember(Decl *D);
468
469 void markedVirtualFunctionPure();
470
471 /// Get the head of our list of friend declarations, possibly
472 /// deserializing the friends from an external AST source.
473 FriendDecl *getFirstFriend() const;
474
475 /// Determine whether this class has an empty base class subobject of type X
476 /// or of one of the types that might be at offset 0 within X (per the C++
477 /// "standard layout" rules).
478 bool hasSubobjectAtOffsetZeroOfEmptyBaseType(ASTContext &Ctx,
479 const CXXRecordDecl *X);
480
481protected:
482 CXXRecordDecl(Kind K, TagKind TK, const ASTContext &C, DeclContext *DC,
483 SourceLocation StartLoc, SourceLocation IdLoc,
484 IdentifierInfo *Id, CXXRecordDecl *PrevDecl);
485
486public:
487 /// Iterator that traverses the base classes of a class.
488 using base_class_iterator = CXXBaseSpecifier *;
489
490 /// Iterator that traverses the base classes of a class.
491 using base_class_const_iterator = const CXXBaseSpecifier *;
492
493 CXXRecordDecl *getCanonicalDecl() override {
494 return cast<CXXRecordDecl>(RecordDecl::getCanonicalDecl());
495 }
496
497 const CXXRecordDecl *getCanonicalDecl() const {
498 return const_cast<CXXRecordDecl*>(this)->getCanonicalDecl();
499 }
500
501 CXXRecordDecl *getPreviousDecl() {
502 return cast_or_null<CXXRecordDecl>(
503 static_cast<RecordDecl *>(this)->getPreviousDecl());
504 }
505
506 const CXXRecordDecl *getPreviousDecl() const {
507 return const_cast<CXXRecordDecl*>(this)->getPreviousDecl();
508 }
509
510 CXXRecordDecl *getMostRecentDecl() {
511 return cast<CXXRecordDecl>(
512 static_cast<RecordDecl *>(this)->getMostRecentDecl());
513 }
514
515 const CXXRecordDecl *getMostRecentDecl() const {
516 return const_cast<CXXRecordDecl*>(this)->getMostRecentDecl();
517 }
518
519 CXXRecordDecl *getMostRecentNonInjectedDecl() {
520 CXXRecordDecl *Recent =
521 static_cast<CXXRecordDecl *>(this)->getMostRecentDecl();
522 while (Recent->isInjectedClassName()) {
523 // FIXME: Does injected class name need to be in the redeclarations chain?
524 assert(Recent->getPreviousDecl())(static_cast <bool> (Recent->getPreviousDecl()) ? void
(0) : __assert_fail ("Recent->getPreviousDecl()", "clang/include/clang/AST/DeclCXX.h"
, 524, __extension__ __PRETTY_FUNCTION__))
;
525 Recent = Recent->getPreviousDecl();
526 }
527 return Recent;
528 }
529
530 const CXXRecordDecl *getMostRecentNonInjectedDecl() const {
531 return const_cast<CXXRecordDecl*>(this)->getMostRecentNonInjectedDecl();
532 }
533
534 CXXRecordDecl *getDefinition() const {
535 // We only need an update if we don't already know which
536 // declaration is the definition.
537 auto *DD = DefinitionData ? DefinitionData : dataPtr();
538 return DD ? DD->Definition : nullptr;
539 }
540
541 bool hasDefinition() const { return DefinitionData || dataPtr(); }
542
543 static CXXRecordDecl *Create(const ASTContext &C, TagKind TK, DeclContext *DC,
544 SourceLocation StartLoc, SourceLocation IdLoc,
545 IdentifierInfo *Id,
546 CXXRecordDecl *PrevDecl = nullptr,
547 bool DelayTypeCreation = false);
548 static CXXRecordDecl *CreateLambda(const ASTContext &C, DeclContext *DC,
549 TypeSourceInfo *Info, SourceLocation Loc,
550 bool DependentLambda, bool IsGeneric,
551 LambdaCaptureDefault CaptureDefault);
552 static CXXRecordDecl *CreateDeserialized(const ASTContext &C, unsigned ID);
553
554 bool isDynamicClass() const {
555 return data().Polymorphic || data().NumVBases != 0;
556 }
557
558 /// @returns true if class is dynamic or might be dynamic because the
559 /// definition is incomplete of dependent.
560 bool mayBeDynamicClass() const {
561 return !hasDefinition() || isDynamicClass() || hasAnyDependentBases();
562 }
563
564 /// @returns true if class is non dynamic or might be non dynamic because the
565 /// definition is incomplete of dependent.
566 bool mayBeNonDynamicClass() const {
567 return !hasDefinition() || !isDynamicClass() || hasAnyDependentBases();
568 }
569
570 void setIsParsingBaseSpecifiers() { data().IsParsingBaseSpecifiers = true; }
571
572 bool isParsingBaseSpecifiers() const {
573 return data().IsParsingBaseSpecifiers;
574 }
575
576 unsigned getODRHash() const;
577
578 /// Sets the base classes of this struct or class.
579 void setBases(CXXBaseSpecifier const * const *Bases, unsigned NumBases);
580
581 /// Retrieves the number of base classes of this class.
582 unsigned getNumBases() const { return data().NumBases; }
583
584 using base_class_range = llvm::iterator_range<base_class_iterator>;
585 using base_class_const_range =
586 llvm::iterator_range<base_class_const_iterator>;
587
588 base_class_range bases() {
589 return base_class_range(bases_begin(), bases_end());
590 }
591 base_class_const_range bases() const {
592 return base_class_const_range(bases_begin(), bases_end());
593 }
594
595 base_class_iterator bases_begin() { return data().getBases(); }
596 base_class_const_iterator bases_begin() const { return data().getBases(); }
597 base_class_iterator bases_end() { return bases_begin() + data().NumBases; }
598 base_class_const_iterator bases_end() const {
599 return bases_begin() + data().NumBases;
600 }
601
602 /// Retrieves the number of virtual base classes of this class.
603 unsigned getNumVBases() const { return data().NumVBases; }
604
605 base_class_range vbases() {
606 return base_class_range(vbases_begin(), vbases_end());
607 }
608 base_class_const_range vbases() const {
609 return base_class_const_range(vbases_begin(), vbases_end());
610 }
611
612 base_class_iterator vbases_begin() { return data().getVBases(); }
613 base_class_const_iterator vbases_begin() const { return data().getVBases(); }
614 base_class_iterator vbases_end() { return vbases_begin() + data().NumVBases; }
615 base_class_const_iterator vbases_end() const {
616 return vbases_begin() + data().NumVBases;
617 }
618
619 /// Determine whether this class has any dependent base classes which
620 /// are not the current instantiation.
621 bool hasAnyDependentBases() const;
622
623 /// Iterator access to method members. The method iterator visits
624 /// all method members of the class, including non-instance methods,
625 /// special methods, etc.
626 using method_iterator = specific_decl_iterator<CXXMethodDecl>;
627 using method_range =
628 llvm::iterator_range<specific_decl_iterator<CXXMethodDecl>>;
629
630 method_range methods() const {
631 return method_range(method_begin(), method_end());
632 }
633
634 /// Method begin iterator. Iterates in the order the methods
635 /// were declared.
636 method_iterator method_begin() const {
637 return method_iterator(decls_begin());
638 }
639
640 /// Method past-the-end iterator.
641 method_iterator method_end() const {
642 return method_iterator(decls_end());
643 }
644
645 /// Iterator access to constructor members.
646 using ctor_iterator = specific_decl_iterator<CXXConstructorDecl>;
647 using ctor_range =
648 llvm::iterator_range<specific_decl_iterator<CXXConstructorDecl>>;
649
650 ctor_range ctors() const { return ctor_range(ctor_begin(), ctor_end()); }
651
652 ctor_iterator ctor_begin() const {
653 return ctor_iterator(decls_begin());
654 }
655
656 ctor_iterator ctor_end() const {
657 return ctor_iterator(decls_end());
658 }
659
660 /// An iterator over friend declarations. All of these are defined
661 /// in DeclFriend.h.
662 class friend_iterator;
663 using friend_range = llvm::iterator_range<friend_iterator>;
664
665 friend_range friends() const;
666 friend_iterator friend_begin() const;
667 friend_iterator friend_end() const;
668 void pushFriendDecl(FriendDecl *FD);
669
670 /// Determines whether this record has any friends.
671 bool hasFriends() const {
672 return data().FirstFriend.isValid();
673 }
674
675 /// \c true if a defaulted copy constructor for this class would be
676 /// deleted.
677 bool defaultedCopyConstructorIsDeleted() const {
678 assert((!needsOverloadResolutionForCopyConstructor() ||(static_cast <bool> ((!needsOverloadResolutionForCopyConstructor
() || (data().DeclaredSpecialMembers & SMF_CopyConstructor
)) && "this property has not yet been computed by Sema"
) ? void (0) : __assert_fail ("(!needsOverloadResolutionForCopyConstructor() || (data().DeclaredSpecialMembers & SMF_CopyConstructor)) && \"this property has not yet been computed by Sema\""
, "clang/include/clang/AST/DeclCXX.h", 680, __extension__ __PRETTY_FUNCTION__
))
679 (data().DeclaredSpecialMembers & SMF_CopyConstructor)) &&(static_cast <bool> ((!needsOverloadResolutionForCopyConstructor
() || (data().DeclaredSpecialMembers & SMF_CopyConstructor
)) && "this property has not yet been computed by Sema"
) ? void (0) : __assert_fail ("(!needsOverloadResolutionForCopyConstructor() || (data().DeclaredSpecialMembers & SMF_CopyConstructor)) && \"this property has not yet been computed by Sema\""
, "clang/include/clang/AST/DeclCXX.h", 680, __extension__ __PRETTY_FUNCTION__
))
680 "this property has not yet been computed by Sema")(static_cast <bool> ((!needsOverloadResolutionForCopyConstructor
() || (data().DeclaredSpecialMembers & SMF_CopyConstructor
)) && "this property has not yet been computed by Sema"
) ? void (0) : __assert_fail ("(!needsOverloadResolutionForCopyConstructor() || (data().DeclaredSpecialMembers & SMF_CopyConstructor)) && \"this property has not yet been computed by Sema\""
, "clang/include/clang/AST/DeclCXX.h", 680, __extension__ __PRETTY_FUNCTION__
))
;
681 return data().DefaultedCopyConstructorIsDeleted;
682 }
683
684 /// \c true if a defaulted move constructor for this class would be
685 /// deleted.
686 bool defaultedMoveConstructorIsDeleted() const {
687 assert((!needsOverloadResolutionForMoveConstructor() ||(static_cast <bool> ((!needsOverloadResolutionForMoveConstructor
() || (data().DeclaredSpecialMembers & SMF_MoveConstructor
)) && "this property has not yet been computed by Sema"
) ? void (0) : __assert_fail ("(!needsOverloadResolutionForMoveConstructor() || (data().DeclaredSpecialMembers & SMF_MoveConstructor)) && \"this property has not yet been computed by Sema\""
, "clang/include/clang/AST/DeclCXX.h", 689, __extension__ __PRETTY_FUNCTION__
))
688 (data().DeclaredSpecialMembers & SMF_MoveConstructor)) &&(static_cast <bool> ((!needsOverloadResolutionForMoveConstructor
() || (data().DeclaredSpecialMembers & SMF_MoveConstructor
)) && "this property has not yet been computed by Sema"
) ? void (0) : __assert_fail ("(!needsOverloadResolutionForMoveConstructor() || (data().DeclaredSpecialMembers & SMF_MoveConstructor)) && \"this property has not yet been computed by Sema\""
, "clang/include/clang/AST/DeclCXX.h", 689, __extension__ __PRETTY_FUNCTION__
))
689 "this property has not yet been computed by Sema")(static_cast <bool> ((!needsOverloadResolutionForMoveConstructor
() || (data().DeclaredSpecialMembers & SMF_MoveConstructor
)) && "this property has not yet been computed by Sema"
) ? void (0) : __assert_fail ("(!needsOverloadResolutionForMoveConstructor() || (data().DeclaredSpecialMembers & SMF_MoveConstructor)) && \"this property has not yet been computed by Sema\""
, "clang/include/clang/AST/DeclCXX.h", 689, __extension__ __PRETTY_FUNCTION__
))
;
690 return data().DefaultedMoveConstructorIsDeleted;
691 }
692
693 /// \c true if a defaulted destructor for this class would be deleted.
694 bool defaultedDestructorIsDeleted() const {
695 assert((!needsOverloadResolutionForDestructor() ||(static_cast <bool> ((!needsOverloadResolutionForDestructor
() || (data().DeclaredSpecialMembers & SMF_Destructor)) &&
"this property has not yet been computed by Sema") ? void (0
) : __assert_fail ("(!needsOverloadResolutionForDestructor() || (data().DeclaredSpecialMembers & SMF_Destructor)) && \"this property has not yet been computed by Sema\""
, "clang/include/clang/AST/DeclCXX.h", 697, __extension__ __PRETTY_FUNCTION__
))
696 (data().DeclaredSpecialMembers & SMF_Destructor)) &&(static_cast <bool> ((!needsOverloadResolutionForDestructor
() || (data().DeclaredSpecialMembers & SMF_Destructor)) &&
"this property has not yet been computed by Sema") ? void (0
) : __assert_fail ("(!needsOverloadResolutionForDestructor() || (data().DeclaredSpecialMembers & SMF_Destructor)) && \"this property has not yet been computed by Sema\""
, "clang/include/clang/AST/DeclCXX.h", 697, __extension__ __PRETTY_FUNCTION__
))
697 "this property has not yet been computed by Sema")(static_cast <bool> ((!needsOverloadResolutionForDestructor
() || (data().DeclaredSpecialMembers & SMF_Destructor)) &&
"this property has not yet been computed by Sema") ? void (0
) : __assert_fail ("(!needsOverloadResolutionForDestructor() || (data().DeclaredSpecialMembers & SMF_Destructor)) && \"this property has not yet been computed by Sema\""
, "clang/include/clang/AST/DeclCXX.h", 697, __extension__ __PRETTY_FUNCTION__
))
;
698 return data().DefaultedDestructorIsDeleted;
699 }
700
701 /// \c true if we know for sure that this class has a single,
702 /// accessible, unambiguous copy constructor that is not deleted.
703 bool hasSimpleCopyConstructor() const {
704 return !hasUserDeclaredCopyConstructor() &&
705 !data().DefaultedCopyConstructorIsDeleted;
706 }
707
708 /// \c true if we know for sure that this class has a single,
709 /// accessible, unambiguous move constructor that is not deleted.
710 bool hasSimpleMoveConstructor() const {
711 return !hasUserDeclaredMoveConstructor() && hasMoveConstructor() &&
712 !data().DefaultedMoveConstructorIsDeleted;
713 }
714
715 /// \c true if we know for sure that this class has a single,
716 /// accessible, unambiguous copy assignment operator that is not deleted.
717 bool hasSimpleCopyAssignment() const {
718 return !hasUserDeclaredCopyAssignment() &&
719 !data().DefaultedCopyAssignmentIsDeleted;
720 }
721
722 /// \c true if we know for sure that this class has a single,
723 /// accessible, unambiguous move assignment operator that is not deleted.
724 bool hasSimpleMoveAssignment() const {
725 return !hasUserDeclaredMoveAssignment() && hasMoveAssignment() &&
726 !data().DefaultedMoveAssignmentIsDeleted;
727 }
728
729 /// \c true if we know for sure that this class has an accessible
730 /// destructor that is not deleted.
731 bool hasSimpleDestructor() const {
732 return !hasUserDeclaredDestructor() &&
733 !data().DefaultedDestructorIsDeleted;
734 }
735
736 /// Determine whether this class has any default constructors.
737 bool hasDefaultConstructor() const {
738 return (data().DeclaredSpecialMembers & SMF_DefaultConstructor) ||
739 needsImplicitDefaultConstructor();
740 }
741
742 /// Determine if we need to declare a default constructor for
743 /// this class.
744 ///
745 /// This value is used for lazy creation of default constructors.
746 bool needsImplicitDefaultConstructor() const {
747 return (!data().UserDeclaredConstructor &&
748 !(data().DeclaredSpecialMembers & SMF_DefaultConstructor) &&
749 (!isLambda() || lambdaIsDefaultConstructibleAndAssignable())) ||
750 // FIXME: Proposed fix to core wording issue: if a class inherits
751 // a default constructor and doesn't explicitly declare one, one
752 // is declared implicitly.
753 (data().HasInheritedDefaultConstructor &&
754 !(data().DeclaredSpecialMembers & SMF_DefaultConstructor));
755 }
756
757 /// Determine whether this class has any user-declared constructors.
758 ///
759 /// When true, a default constructor will not be implicitly declared.
760 bool hasUserDeclaredConstructor() const {
761 return data().UserDeclaredConstructor;
762 }
763
764 /// Whether this class has a user-provided default constructor
765 /// per C++11.
766 bool hasUserProvidedDefaultConstructor() const {
767 return data().UserProvidedDefaultConstructor;
768 }
769
770 /// Determine whether this class has a user-declared copy constructor.
771 ///
772 /// When false, a copy constructor will be implicitly declared.
773 bool hasUserDeclaredCopyConstructor() const {
774 return data().UserDeclaredSpecialMembers & SMF_CopyConstructor;
775 }
776
777 /// Determine whether this class needs an implicit copy
778 /// constructor to be lazily declared.
779 bool needsImplicitCopyConstructor() const {
780 return !(data().DeclaredSpecialMembers & SMF_CopyConstructor);
781 }
782
783 /// Determine whether we need to eagerly declare a defaulted copy
784 /// constructor for this class.
785 bool needsOverloadResolutionForCopyConstructor() const {
786 // C++17 [class.copy.ctor]p6:
787 // If the class definition declares a move constructor or move assignment
788 // operator, the implicitly declared copy constructor is defined as
789 // deleted.
790 // In MSVC mode, sometimes a declared move assignment does not delete an
791 // implicit copy constructor, so defer this choice to Sema.
792 if (data().UserDeclaredSpecialMembers &
793 (SMF_MoveConstructor | SMF_MoveAssignment))
794 return true;
795 return data().NeedOverloadResolutionForCopyConstructor;
796 }
797
798 /// Determine whether an implicit copy constructor for this type
799 /// would have a parameter with a const-qualified reference type.
800 bool implicitCopyConstructorHasConstParam() const {
801 return data().ImplicitCopyConstructorCanHaveConstParamForNonVBase &&
802 (isAbstract() ||
803 data().ImplicitCopyConstructorCanHaveConstParamForVBase);
804 }
805
806 /// Determine whether this class has a copy constructor with
807 /// a parameter type which is a reference to a const-qualified type.
808 bool hasCopyConstructorWithConstParam() const {
809 return data().HasDeclaredCopyConstructorWithConstParam ||
810 (needsImplicitCopyConstructor() &&
811 implicitCopyConstructorHasConstParam());
812 }
813
814 /// Whether this class has a user-declared move constructor or
815 /// assignment operator.
816 ///
817 /// When false, a move constructor and assignment operator may be
818 /// implicitly declared.
819 bool hasUserDeclaredMoveOperation() const {
820 return data().UserDeclaredSpecialMembers &
821 (SMF_MoveConstructor | SMF_MoveAssignment);
822 }
823
824 /// Determine whether this class has had a move constructor
825 /// declared by the user.
826 bool hasUserDeclaredMoveConstructor() const {
827 return data().UserDeclaredSpecialMembers & SMF_MoveConstructor;
828 }
829
830 /// Determine whether this class has a move constructor.
831 bool hasMoveConstructor() const {
832 return (data().DeclaredSpecialMembers & SMF_MoveConstructor) ||
833 needsImplicitMoveConstructor();
834 }
835
836 /// Set that we attempted to declare an implicit copy
837 /// constructor, but overload resolution failed so we deleted it.
838 void setImplicitCopyConstructorIsDeleted() {
839 assert((data().DefaultedCopyConstructorIsDeleted ||(static_cast <bool> ((data().DefaultedCopyConstructorIsDeleted
|| needsOverloadResolutionForCopyConstructor()) && "Copy constructor should not be deleted"
) ? void (0) : __assert_fail ("(data().DefaultedCopyConstructorIsDeleted || needsOverloadResolutionForCopyConstructor()) && \"Copy constructor should not be deleted\""
, "clang/include/clang/AST/DeclCXX.h", 841, __extension__ __PRETTY_FUNCTION__
))
840 needsOverloadResolutionForCopyConstructor()) &&(static_cast <bool> ((data().DefaultedCopyConstructorIsDeleted
|| needsOverloadResolutionForCopyConstructor()) && "Copy constructor should not be deleted"
) ? void (0) : __assert_fail ("(data().DefaultedCopyConstructorIsDeleted || needsOverloadResolutionForCopyConstructor()) && \"Copy constructor should not be deleted\""
, "clang/include/clang/AST/DeclCXX.h", 841, __extension__ __PRETTY_FUNCTION__
))
841 "Copy constructor should not be deleted")(static_cast <bool> ((data().DefaultedCopyConstructorIsDeleted
|| needsOverloadResolutionForCopyConstructor()) && "Copy constructor should not be deleted"
) ? void (0) : __assert_fail ("(data().DefaultedCopyConstructorIsDeleted || needsOverloadResolutionForCopyConstructor()) && \"Copy constructor should not be deleted\""
, "clang/include/clang/AST/DeclCXX.h", 841, __extension__ __PRETTY_FUNCTION__
))
;
842 data().DefaultedCopyConstructorIsDeleted = true;
843 }
844
845 /// Set that we attempted to declare an implicit move
846 /// constructor, but overload resolution failed so we deleted it.
847 void setImplicitMoveConstructorIsDeleted() {
848 assert((data().DefaultedMoveConstructorIsDeleted ||(static_cast <bool> ((data().DefaultedMoveConstructorIsDeleted
|| needsOverloadResolutionForMoveConstructor()) && "move constructor should not be deleted"
) ? void (0) : __assert_fail ("(data().DefaultedMoveConstructorIsDeleted || needsOverloadResolutionForMoveConstructor()) && \"move constructor should not be deleted\""
, "clang/include/clang/AST/DeclCXX.h", 850, __extension__ __PRETTY_FUNCTION__
))
849 needsOverloadResolutionForMoveConstructor()) &&(static_cast <bool> ((data().DefaultedMoveConstructorIsDeleted
|| needsOverloadResolutionForMoveConstructor()) && "move constructor should not be deleted"
) ? void (0) : __assert_fail ("(data().DefaultedMoveConstructorIsDeleted || needsOverloadResolutionForMoveConstructor()) && \"move constructor should not be deleted\""
, "clang/include/clang/AST/DeclCXX.h", 850, __extension__ __PRETTY_FUNCTION__
))
850 "move constructor should not be deleted")(static_cast <bool> ((data().DefaultedMoveConstructorIsDeleted
|| needsOverloadResolutionForMoveConstructor()) && "move constructor should not be deleted"
) ? void (0) : __assert_fail ("(data().DefaultedMoveConstructorIsDeleted || needsOverloadResolutionForMoveConstructor()) && \"move constructor should not be deleted\""
, "clang/include/clang/AST/DeclCXX.h", 850, __extension__ __PRETTY_FUNCTION__
))
;
851 data().DefaultedMoveConstructorIsDeleted = true;
852 }
853
854 /// Set that we attempted to declare an implicit destructor,
855 /// but overload resolution failed so we deleted it.
856 void setImplicitDestructorIsDeleted() {
857 assert((data().DefaultedDestructorIsDeleted ||(static_cast <bool> ((data().DefaultedDestructorIsDeleted
|| needsOverloadResolutionForDestructor()) && "destructor should not be deleted"
) ? void (0) : __assert_fail ("(data().DefaultedDestructorIsDeleted || needsOverloadResolutionForDestructor()) && \"destructor should not be deleted\""
, "clang/include/clang/AST/DeclCXX.h", 859, __extension__ __PRETTY_FUNCTION__
))
858 needsOverloadResolutionForDestructor()) &&(static_cast <bool> ((data().DefaultedDestructorIsDeleted
|| needsOverloadResolutionForDestructor()) && "destructor should not be deleted"
) ? void (0) : __assert_fail ("(data().DefaultedDestructorIsDeleted || needsOverloadResolutionForDestructor()) && \"destructor should not be deleted\""
, "clang/include/clang/AST/DeclCXX.h", 859, __extension__ __PRETTY_FUNCTION__
))
859 "destructor should not be deleted")(static_cast <bool> ((data().DefaultedDestructorIsDeleted
|| needsOverloadResolutionForDestructor()) && "destructor should not be deleted"
) ? void (0) : __assert_fail ("(data().DefaultedDestructorIsDeleted || needsOverloadResolutionForDestructor()) && \"destructor should not be deleted\""
, "clang/include/clang/AST/DeclCXX.h", 859, __extension__ __PRETTY_FUNCTION__
))
;
860 data().DefaultedDestructorIsDeleted = true;
861 }
862
863 /// Determine whether this class should get an implicit move
864 /// constructor or if any existing special member function inhibits this.
865 bool needsImplicitMoveConstructor() const {
866 return !(data().DeclaredSpecialMembers & SMF_MoveConstructor) &&
867 !hasUserDeclaredCopyConstructor() &&
868 !hasUserDeclaredCopyAssignment() &&
869 !hasUserDeclaredMoveAssignment() &&
870 !hasUserDeclaredDestructor();
871 }
872
873 /// Determine whether we need to eagerly declare a defaulted move
874 /// constructor for this class.
875 bool needsOverloadResolutionForMoveConstructor() const {
876 return data().NeedOverloadResolutionForMoveConstructor;
877 }
878
879 /// Determine whether this class has a user-declared copy assignment
880 /// operator.
881 ///
882 /// When false, a copy assignment operator will be implicitly declared.
883 bool hasUserDeclaredCopyAssignment() const {
884 return data().UserDeclaredSpecialMembers & SMF_CopyAssignment;
885 }
886
887 /// Set that we attempted to declare an implicit copy assignment
888 /// operator, but overload resolution failed so we deleted it.
889 void setImplicitCopyAssignmentIsDeleted() {
890 assert((data().DefaultedCopyAssignmentIsDeleted ||(static_cast <bool> ((data().DefaultedCopyAssignmentIsDeleted
|| needsOverloadResolutionForCopyAssignment()) && "copy assignment should not be deleted"
) ? void (0) : __assert_fail ("(data().DefaultedCopyAssignmentIsDeleted || needsOverloadResolutionForCopyAssignment()) && \"copy assignment should not be deleted\""
, "clang/include/clang/AST/DeclCXX.h", 892, __extension__ __PRETTY_FUNCTION__
))
891 needsOverloadResolutionForCopyAssignment()) &&(static_cast <bool> ((data().DefaultedCopyAssignmentIsDeleted
|| needsOverloadResolutionForCopyAssignment()) && "copy assignment should not be deleted"
) ? void (0) : __assert_fail ("(data().DefaultedCopyAssignmentIsDeleted || needsOverloadResolutionForCopyAssignment()) && \"copy assignment should not be deleted\""
, "clang/include/clang/AST/DeclCXX.h", 892, __extension__ __PRETTY_FUNCTION__
))
892 "copy assignment should not be deleted")(static_cast <bool> ((data().DefaultedCopyAssignmentIsDeleted
|| needsOverloadResolutionForCopyAssignment()) && "copy assignment should not be deleted"
) ? void (0) : __assert_fail ("(data().DefaultedCopyAssignmentIsDeleted || needsOverloadResolutionForCopyAssignment()) && \"copy assignment should not be deleted\""
, "clang/include/clang/AST/DeclCXX.h", 892, __extension__ __PRETTY_FUNCTION__
))
;
893 data().DefaultedCopyAssignmentIsDeleted = true;
894 }
895
896 /// Determine whether this class needs an implicit copy
897 /// assignment operator to be lazily declared.
898 bool needsImplicitCopyAssignment() const {
899 return !(data().DeclaredSpecialMembers & SMF_CopyAssignment);
900 }
901
902 /// Determine whether we need to eagerly declare a defaulted copy
903 /// assignment operator for this class.
904 bool needsOverloadResolutionForCopyAssignment() const {
905 // C++20 [class.copy.assign]p2:
906 // If the class definition declares a move constructor or move assignment
907 // operator, the implicitly declared copy assignment operator is defined
908 // as deleted.
909 // In MSVC mode, sometimes a declared move constructor does not delete an
910 // implicit copy assignment, so defer this choice to Sema.
911 if (data().UserDeclaredSpecialMembers &
912 (SMF_MoveConstructor | SMF_MoveAssignment))
913 return true;
914 return data().NeedOverloadResolutionForCopyAssignment;
915 }
916
917 /// Determine whether an implicit copy assignment operator for this
918 /// type would have a parameter with a const-qualified reference type.
919 bool implicitCopyAssignmentHasConstParam() const {
920 return data().ImplicitCopyAssignmentHasConstParam;
921 }
922
923 /// Determine whether this class has a copy assignment operator with
924 /// a parameter type which is a reference to a const-qualified type or is not
925 /// a reference.
926 bool hasCopyAssignmentWithConstParam() const {
927 return data().HasDeclaredCopyAssignmentWithConstParam ||
928 (needsImplicitCopyAssignment() &&
929 implicitCopyAssignmentHasConstParam());
930 }
931
932 /// Determine whether this class has had a move assignment
933 /// declared by the user.
934 bool hasUserDeclaredMoveAssignment() const {
935 return data().UserDeclaredSpecialMembers & SMF_MoveAssignment;
936 }
937
938 /// Determine whether this class has a move assignment operator.
939 bool hasMoveAssignment() const {
940 return (data().DeclaredSpecialMembers & SMF_MoveAssignment) ||
941 needsImplicitMoveAssignment();
942 }
943
944 /// Set that we attempted to declare an implicit move assignment
945 /// operator, but overload resolution failed so we deleted it.
946 void setImplicitMoveAssignmentIsDeleted() {
947 assert((data().DefaultedMoveAssignmentIsDeleted ||(static_cast <bool> ((data().DefaultedMoveAssignmentIsDeleted
|| needsOverloadResolutionForMoveAssignment()) && "move assignment should not be deleted"
) ? void (0) : __assert_fail ("(data().DefaultedMoveAssignmentIsDeleted || needsOverloadResolutionForMoveAssignment()) && \"move assignment should not be deleted\""
, "clang/include/clang/AST/DeclCXX.h", 949, __extension__ __PRETTY_FUNCTION__
))
948 needsOverloadResolutionForMoveAssignment()) &&(static_cast <bool> ((data().DefaultedMoveAssignmentIsDeleted
|| needsOverloadResolutionForMoveAssignment()) && "move assignment should not be deleted"
) ? void (0) : __assert_fail ("(data().DefaultedMoveAssignmentIsDeleted || needsOverloadResolutionForMoveAssignment()) && \"move assignment should not be deleted\""
, "clang/include/clang/AST/DeclCXX.h", 949, __extension__ __PRETTY_FUNCTION__
))
949 "move assignment should not be deleted")(static_cast <bool> ((data().DefaultedMoveAssignmentIsDeleted
|| needsOverloadResolutionForMoveAssignment()) && "move assignment should not be deleted"
) ? void (0) : __assert_fail ("(data().DefaultedMoveAssignmentIsDeleted || needsOverloadResolutionForMoveAssignment()) && \"move assignment should not be deleted\""
, "clang/include/clang/AST/DeclCXX.h", 949, __extension__ __PRETTY_FUNCTION__
))
;
950 data().DefaultedMoveAssignmentIsDeleted = true;
951 }
952
953 /// Determine whether this class should get an implicit move
954 /// assignment operator or if any existing special member function inhibits
955 /// this.
956 bool needsImplicitMoveAssignment() const {
957 return !(data().DeclaredSpecialMembers & SMF_MoveAssignment) &&
958 !hasUserDeclaredCopyConstructor() &&
959 !hasUserDeclaredCopyAssignment() &&
960 !hasUserDeclaredMoveConstructor() &&
961 !hasUserDeclaredDestructor() &&
962 (!isLambda() || lambdaIsDefaultConstructibleAndAssignable());
963 }
964
965 /// Determine whether we need to eagerly declare a move assignment
966 /// operator for this class.
967 bool needsOverloadResolutionForMoveAssignment() const {
968 return data().NeedOverloadResolutionForMoveAssignment;
969 }
970
971 /// Determine whether this class has a user-declared destructor.
972 ///
973 /// When false, a destructor will be implicitly declared.
974 bool hasUserDeclaredDestructor() const {
975 return data().UserDeclaredSpecialMembers & SMF_Destructor;
976 }
977
978 /// Determine whether this class needs an implicit destructor to
979 /// be lazily declared.
980 bool needsImplicitDestructor() const {
981 return !(data().DeclaredSpecialMembers & SMF_Destructor);
982 }
983
984 /// Determine whether we need to eagerly declare a destructor for this
985 /// class.
986 bool needsOverloadResolutionForDestructor() const {
987 return data().NeedOverloadResolutionForDestructor;
988 }
989
990 /// Determine whether this class describes a lambda function object.
991 bool isLambda() const {
992 // An update record can't turn a non-lambda into a lambda.
993 auto *DD = DefinitionData;
994 return DD && DD->IsLambda;
8
Assuming 'DD' is non-null
9
Returning value, which participates in a condition later
995 }
996
997 /// Determine whether this class describes a generic
998 /// lambda function object (i.e. function call operator is
999 /// a template).
1000 bool isGenericLambda() const;
1001
1002 /// Determine whether this lambda should have an implicit default constructor
1003 /// and copy and move assignment operators.
1004 bool lambdaIsDefaultConstructibleAndAssignable() const;
1005
1006 /// Retrieve the lambda call operator of the closure type
1007 /// if this is a closure type.
1008 CXXMethodDecl *getLambdaCallOperator() const;
1009
1010 /// Retrieve the dependent lambda call operator of the closure type
1011 /// if this is a templated closure type.
1012 FunctionTemplateDecl *getDependentLambdaCallOperator() const;
1013
1014 /// Retrieve the lambda static invoker, the address of which
1015 /// is returned by the conversion operator, and the body of which
1016 /// is forwarded to the lambda call operator. The version that does not
1017 /// take a calling convention uses the 'default' calling convention for free
1018 /// functions if the Lambda's calling convention was not modified via
1019 /// attribute. Otherwise, it will return the calling convention specified for
1020 /// the lambda.
1021 CXXMethodDecl *getLambdaStaticInvoker() const;
1022 CXXMethodDecl *getLambdaStaticInvoker(CallingConv CC) const;
1023
1024 /// Retrieve the generic lambda's template parameter list.
1025 /// Returns null if the class does not represent a lambda or a generic
1026 /// lambda.
1027 TemplateParameterList *getGenericLambdaTemplateParameterList() const;
1028
1029 /// Retrieve the lambda template parameters that were specified explicitly.
1030 ArrayRef<NamedDecl *> getLambdaExplicitTemplateParameters() const;
1031
1032 LambdaCaptureDefault getLambdaCaptureDefault() const {
1033 assert(isLambda())(static_cast <bool> (isLambda()) ? void (0) : __assert_fail
("isLambda()", "clang/include/clang/AST/DeclCXX.h", 1033, __extension__
__PRETTY_FUNCTION__))
;
1034 return static_cast<LambdaCaptureDefault>(getLambdaData().CaptureDefault);
1035 }
1036
1037 /// Set the captures for this lambda closure type.
1038 void setCaptures(ASTContext &Context, ArrayRef<LambdaCapture> Captures);
1039
1040 /// For a closure type, retrieve the mapping from captured
1041 /// variables and \c this to the non-static data members that store the
1042 /// values or references of the captures.
1043 ///
1044 /// \param Captures Will be populated with the mapping from captured
1045 /// variables to the corresponding fields.
1046 ///
1047 /// \param ThisCapture Will be set to the field declaration for the
1048 /// \c this capture.
1049 ///
1050 /// \note No entries will be added for init-captures, as they do not capture
1051 /// variables.
1052 void getCaptureFields(llvm::DenseMap<const VarDecl *, FieldDecl *> &Captures,
1053 FieldDecl *&ThisCapture) const;
1054
1055 using capture_const_iterator = const LambdaCapture *;
1056 using capture_const_range = llvm::iterator_range<capture_const_iterator>;
1057
1058 capture_const_range captures() const {
1059 return capture_const_range(captures_begin(), captures_end());
1060 }
1061
1062 capture_const_iterator captures_begin() const {
1063 return isLambda() ? getLambdaData().Captures : nullptr;
1064 }
1065
1066 capture_const_iterator captures_end() const {
1067 return isLambda() ? captures_begin() + getLambdaData().NumCaptures
1068 : nullptr;
1069 }
1070
1071 unsigned capture_size() const { return getLambdaData().NumCaptures; }
1072
1073 using conversion_iterator = UnresolvedSetIterator;
1074
1075 conversion_iterator conversion_begin() const {
1076 return data().Conversions.get(getASTContext()).begin();
1077 }
1078
1079 conversion_iterator conversion_end() const {
1080 return data().Conversions.get(getASTContext()).end();
1081 }
1082
1083 /// Removes a conversion function from this class. The conversion
1084 /// function must currently be a member of this class. Furthermore,
1085 /// this class must currently be in the process of being defined.
1086 void removeConversion(const NamedDecl *Old);
1087
1088 /// Get all conversion functions visible in current class,
1089 /// including conversion function templates.
1090 llvm::iterator_range<conversion_iterator>
1091 getVisibleConversionFunctions() const;
1092
1093 /// Determine whether this class is an aggregate (C++ [dcl.init.aggr]),
1094 /// which is a class with no user-declared constructors, no private
1095 /// or protected non-static data members, no base classes, and no virtual
1096 /// functions (C++ [dcl.init.aggr]p1).
1097 bool isAggregate() const { return data().Aggregate; }
1098
1099 /// Whether this class has any in-class initializers
1100 /// for non-static data members (including those in anonymous unions or
1101 /// structs).
1102 bool hasInClassInitializer() const { return data().HasInClassInitializer; }
1103
1104 /// Whether this class or any of its subobjects has any members of
1105 /// reference type which would make value-initialization ill-formed.
1106 ///
1107 /// Per C++03 [dcl.init]p5:
1108 /// - if T is a non-union class type without a user-declared constructor,
1109 /// then every non-static data member and base-class component of T is
1110 /// value-initialized [...] A program that calls for [...]
1111 /// value-initialization of an entity of reference type is ill-formed.
1112 bool hasUninitializedReferenceMember() const {
1113 return !isUnion() && !hasUserDeclaredConstructor() &&
1114 data().HasUninitializedReferenceMember;
1115 }
1116
1117 /// Whether this class is a POD-type (C++ [class]p4)
1118 ///
1119 /// For purposes of this function a class is POD if it is an aggregate
1120 /// that has no non-static non-POD data members, no reference data
1121 /// members, no user-defined copy assignment operator and no
1122 /// user-defined destructor.
1123 ///
1124 /// Note that this is the C++ TR1 definition of POD.
1125 bool isPOD() const { return data().PlainOldData; }
1126
1127 /// True if this class is C-like, without C++-specific features, e.g.
1128 /// it contains only public fields, no bases, tag kind is not 'class', etc.
1129 bool isCLike() const;
1130
1131 /// Determine whether this is an empty class in the sense of
1132 /// (C++11 [meta.unary.prop]).
1133 ///
1134 /// The CXXRecordDecl is a class type, but not a union type,
1135 /// with no non-static data members other than bit-fields of length 0,
1136 /// no virtual member functions, no virtual base classes,
1137 /// and no base class B for which is_empty<B>::value is false.
1138 ///
1139 /// \note This does NOT include a check for union-ness.
1140 bool isEmpty() const { return data().Empty; }
1141
1142 bool hasPrivateFields() const {
1143 return data().HasPrivateFields;
1144 }
1145
1146 bool hasProtectedFields() const {
1147 return data().HasProtectedFields;
1148 }
1149
1150 /// Determine whether this class has direct non-static data members.
1151 bool hasDirectFields() const {
1152 auto &D = data();
1153 return D.HasPublicFields || D.HasProtectedFields || D.HasPrivateFields;
1154 }
1155
1156 /// Whether this class is polymorphic (C++ [class.virtual]),
1157 /// which means that the class contains or inherits a virtual function.
1158 bool isPolymorphic() const { return data().Polymorphic; }
1159
1160 /// Determine whether this class has a pure virtual function.
1161 ///
1162 /// The class is is abstract per (C++ [class.abstract]p2) if it declares
1163 /// a pure virtual function or inherits a pure virtual function that is
1164 /// not overridden.
1165 bool isAbstract() const { return data().Abstract; }
1166
1167 /// Determine whether this class is standard-layout per
1168 /// C++ [class]p7.
1169 bool isStandardLayout() const { return data().IsStandardLayout; }
1170
1171 /// Determine whether this class was standard-layout per
1172 /// C++11 [class]p7, specifically using the C++11 rules without any DRs.
1173 bool isCXX11StandardLayout() const { return data().IsCXX11StandardLayout; }
1174
1175 /// Determine whether this class, or any of its class subobjects,
1176 /// contains a mutable field.
1177 bool hasMutableFields() const { return data().HasMutableFields; }
1178
1179 /// Determine whether this class has any variant members.
1180 bool hasVariantMembers() const { return data().HasVariantMembers; }
1181
1182 /// Determine whether this class has a trivial default constructor
1183 /// (C++11 [class.ctor]p5).
1184 bool hasTrivialDefaultConstructor() const {
1185 return hasDefaultConstructor() &&
1186 (data().HasTrivialSpecialMembers & SMF_DefaultConstructor);
1187 }
1188
1189 /// Determine whether this class has a non-trivial default constructor
1190 /// (C++11 [class.ctor]p5).
1191 bool hasNonTrivialDefaultConstructor() const {
1192 return (data().DeclaredNonTrivialSpecialMembers & SMF_DefaultConstructor) ||
1193 (needsImplicitDefaultConstructor() &&
1194 !(data().HasTrivialSpecialMembers & SMF_DefaultConstructor));
1195 }
1196
1197 /// Determine whether this class has at least one constexpr constructor
1198 /// other than the copy or move constructors.
1199 bool hasConstexprNonCopyMoveConstructor() const {
1200 return data().HasConstexprNonCopyMoveConstructor ||
1201 (needsImplicitDefaultConstructor() &&
1202 defaultedDefaultConstructorIsConstexpr());
1203 }
1204
1205 /// Determine whether a defaulted default constructor for this class
1206 /// would be constexpr.
1207 bool defaultedDefaultConstructorIsConstexpr() const {
1208 return data().DefaultedDefaultConstructorIsConstexpr &&
1209 (!isUnion() || hasInClassInitializer() || !hasVariantMembers() ||
1210 getLangOpts().CPlusPlus20);
1211 }
1212
1213 /// Determine whether this class has a constexpr default constructor.
1214 bool hasConstexprDefaultConstructor() const {
1215 return data().HasConstexprDefaultConstructor ||
1216 (needsImplicitDefaultConstructor() &&
1217 defaultedDefaultConstructorIsConstexpr());
1218 }
1219
1220 /// Determine whether this class has a trivial copy constructor
1221 /// (C++ [class.copy]p6, C++11 [class.copy]p12)
1222 bool hasTrivialCopyConstructor() const {
1223 return data().HasTrivialSpecialMembers & SMF_CopyConstructor;
1224 }
1225
1226 bool hasTrivialCopyConstructorForCall() const {
1227 return data().HasTrivialSpecialMembersForCall & SMF_CopyConstructor;
1228 }
1229
1230 /// Determine whether this class has a non-trivial copy constructor
1231 /// (C++ [class.copy]p6, C++11 [class.copy]p12)
1232 bool hasNonTrivialCopyConstructor() const {
1233 return data().DeclaredNonTrivialSpecialMembers & SMF_CopyConstructor ||
1234 !hasTrivialCopyConstructor();
1235 }
1236
1237 bool hasNonTrivialCopyConstructorForCall() const {
1238 return (data().DeclaredNonTrivialSpecialMembersForCall &
1239 SMF_CopyConstructor) ||
1240 !hasTrivialCopyConstructorForCall();
1241 }
1242
1243 /// Determine whether this class has a trivial move constructor
1244 /// (C++11 [class.copy]p12)
1245 bool hasTrivialMoveConstructor() const {
1246 return hasMoveConstructor() &&
1247 (data().HasTrivialSpecialMembers & SMF_MoveConstructor);
1248 }
1249
1250 bool hasTrivialMoveConstructorForCall() const {
1251 return hasMoveConstructor() &&
1252 (data().HasTrivialSpecialMembersForCall & SMF_MoveConstructor);
1253 }
1254
1255 /// Determine whether this class has a non-trivial move constructor
1256 /// (C++11 [class.copy]p12)
1257 bool hasNonTrivialMoveConstructor() const {
1258 return (data().DeclaredNonTrivialSpecialMembers & SMF_MoveConstructor) ||
1259 (needsImplicitMoveConstructor() &&
1260 !(data().HasTrivialSpecialMembers & SMF_MoveConstructor));
1261 }
1262
1263 bool hasNonTrivialMoveConstructorForCall() const {
1264 return (data().DeclaredNonTrivialSpecialMembersForCall &
1265 SMF_MoveConstructor) ||
1266 (needsImplicitMoveConstructor() &&
1267 !(data().HasTrivialSpecialMembersForCall & SMF_MoveConstructor));
1268 }
1269
1270 /// Determine whether this class has a trivial copy assignment operator
1271 /// (C++ [class.copy]p11, C++11 [class.copy]p25)
1272 bool hasTrivialCopyAssignment() const {
1273 return data().HasTrivialSpecialMembers & SMF_CopyAssignment;
1274 }
1275
1276 /// Determine whether this class has a non-trivial copy assignment
1277 /// operator (C++ [class.copy]p11, C++11 [class.copy]p25)
1278 bool hasNonTrivialCopyAssignment() const {
1279 return data().DeclaredNonTrivialSpecialMembers & SMF_CopyAssignment ||
1280 !hasTrivialCopyAssignment();
1281 }
1282
1283 /// Determine whether this class has a trivial move assignment operator
1284 /// (C++11 [class.copy]p25)
1285 bool hasTrivialMoveAssignment() const {
1286 return hasMoveAssignment() &&
1287 (data().HasTrivialSpecialMembers & SMF_MoveAssignment);
1288 }
1289
1290 /// Determine whether this class has a non-trivial move assignment
1291 /// operator (C++11 [class.copy]p25)
1292 bool hasNonTrivialMoveAssignment() const {
1293 return (data().DeclaredNonTrivialSpecialMembers & SMF_MoveAssignment) ||
1294 (needsImplicitMoveAssignment() &&
1295 !(data().HasTrivialSpecialMembers & SMF_MoveAssignment));
1296 }
1297
1298 /// Determine whether a defaulted default constructor for this class
1299 /// would be constexpr.
1300 bool defaultedDestructorIsConstexpr() const {
1301 return data().DefaultedDestructorIsConstexpr &&
1302 getLangOpts().CPlusPlus20;
1303 }
1304
1305 /// Determine whether this class has a constexpr destructor.
1306 bool hasConstexprDestructor() const;
1307
1308 /// Determine whether this class has a trivial destructor
1309 /// (C++ [class.dtor]p3)
1310 bool hasTrivialDestructor() const {
1311 return data().HasTrivialSpecialMembers & SMF_Destructor;
1312 }
1313
1314 bool hasTrivialDestructorForCall() const {
1315 return data().HasTrivialSpecialMembersForCall & SMF_Destructor;
1316 }
1317
1318 /// Determine whether this class has a non-trivial destructor
1319 /// (C++ [class.dtor]p3)
1320 bool hasNonTrivialDestructor() const {
1321 return !(data().HasTrivialSpecialMembers & SMF_Destructor);
1322 }
1323
1324 bool hasNonTrivialDestructorForCall() const {
1325 return !(data().HasTrivialSpecialMembersForCall & SMF_Destructor);
1326 }
1327
1328 void setHasTrivialSpecialMemberForCall() {
1329 data().HasTrivialSpecialMembersForCall =
1330 (SMF_CopyConstructor | SMF_MoveConstructor | SMF_Destructor);
1331 }
1332
1333 /// Determine whether declaring a const variable with this type is ok
1334 /// per core issue 253.
1335 bool allowConstDefaultInit() const {
1336 return !data().HasUninitializedFields ||
1337 !(data().HasDefaultedDefaultConstructor ||
1338 needsImplicitDefaultConstructor());
1339 }
1340
1341 /// Determine whether this class has a destructor which has no
1342 /// semantic effect.
1343 ///
1344 /// Any such destructor will be trivial, public, defaulted and not deleted,
1345 /// and will call only irrelevant destructors.
1346 bool hasIrrelevantDestructor() const {
1347 return data().HasIrrelevantDestructor;
1348 }
1349
1350 /// Determine whether this class has a non-literal or/ volatile type
1351 /// non-static data member or base class.
1352 bool hasNonLiteralTypeFieldsOrBases() const {
1353 return data().HasNonLiteralTypeFieldsOrBases;
1354 }
1355
1356 /// Determine whether this class has a using-declaration that names
1357 /// a user-declared base class constructor.
1358 bool hasInheritedConstructor() const {
1359 return data().HasInheritedConstructor;
1360 }
1361
1362 /// Determine whether this class has a using-declaration that names
1363 /// a base class assignment operator.
1364 bool hasInheritedAssignment() const {
1365 return data().HasInheritedAssignment;
1366 }
1367
1368 /// Determine whether this class is considered trivially copyable per
1369 /// (C++11 [class]p6).
1370 bool isTriviallyCopyable() const;
1371
1372 /// Determine whether this class is considered trivial.
1373 ///
1374 /// C++11 [class]p6:
1375 /// "A trivial class is a class that has a trivial default constructor and
1376 /// is trivially copyable."
1377 bool isTrivial() const {
1378 return isTriviallyCopyable() && hasTrivialDefaultConstructor();
1379 }
1380
1381 /// Determine whether this class is a literal type.
1382 ///
1383 /// C++11 [basic.types]p10:
1384 /// A class type that has all the following properties:
1385 /// - it has a trivial destructor
1386 /// - every constructor call and full-expression in the
1387 /// brace-or-equal-intializers for non-static data members (if any) is
1388 /// a constant expression.
1389 /// - it is an aggregate type or has at least one constexpr constructor
1390 /// or constructor template that is not a copy or move constructor, and
1391 /// - all of its non-static data members and base classes are of literal
1392 /// types
1393 ///
1394 /// We resolve DR1361 by ignoring the second bullet. We resolve DR1452 by
1395 /// treating types with trivial default constructors as literal types.
1396 ///
1397 /// Only in C++17 and beyond, are lambdas literal types.
1398 bool isLiteral() const {
1399 const LangOptions &LangOpts = getLangOpts();
1400 return (LangOpts.CPlusPlus20 ? hasConstexprDestructor()
1401 : hasTrivialDestructor()) &&
1402 (!isLambda() || LangOpts.CPlusPlus17) &&
1403 !hasNonLiteralTypeFieldsOrBases() &&
1404 (isAggregate() || isLambda() ||
1405 hasConstexprNonCopyMoveConstructor() ||
1406 hasTrivialDefaultConstructor());
1407 }
1408
1409 /// Determine whether this is a structural type.
1410 bool isStructural() const {
1411 return isLiteral() && data().StructuralIfLiteral;
1412 }
1413
1414 /// If this record is an instantiation of a member class,
1415 /// retrieves the member class from which it was instantiated.
1416 ///
1417 /// This routine will return non-null for (non-templated) member
1418 /// classes of class templates. For example, given:
1419 ///
1420 /// \code
1421 /// template<typename T>
1422 /// struct X {
1423 /// struct A { };
1424 /// };
1425 /// \endcode
1426 ///
1427 /// The declaration for X<int>::A is a (non-templated) CXXRecordDecl
1428 /// whose parent is the class template specialization X<int>. For
1429 /// this declaration, getInstantiatedFromMemberClass() will return
1430 /// the CXXRecordDecl X<T>::A. When a complete definition of
1431 /// X<int>::A is required, it will be instantiated from the
1432 /// declaration returned by getInstantiatedFromMemberClass().
1433 CXXRecordDecl *getInstantiatedFromMemberClass() const;
1434
1435 /// If this class is an instantiation of a member class of a
1436 /// class template specialization, retrieves the member specialization
1437 /// information.
1438 MemberSpecializationInfo *getMemberSpecializationInfo() const;
1439
1440 /// Specify that this record is an instantiation of the
1441 /// member class \p RD.
1442 void setInstantiationOfMemberClass(CXXRecordDecl *RD,
1443 TemplateSpecializationKind TSK);
1444
1445 /// Retrieves the class template that is described by this
1446 /// class declaration.
1447 ///
1448 /// Every class template is represented as a ClassTemplateDecl and a
1449 /// CXXRecordDecl. The former contains template properties (such as
1450 /// the template parameter lists) while the latter contains the
1451 /// actual description of the template's
1452 /// contents. ClassTemplateDecl::getTemplatedDecl() retrieves the
1453 /// CXXRecordDecl that from a ClassTemplateDecl, while
1454 /// getDescribedClassTemplate() retrieves the ClassTemplateDecl from
1455 /// a CXXRecordDecl.
1456 ClassTemplateDecl *getDescribedClassTemplate() const;
1457
1458 void setDescribedClassTemplate(ClassTemplateDecl *Template);
1459
1460 /// Determine whether this particular class is a specialization or
1461 /// instantiation of a class template or member class of a class template,
1462 /// and how it was instantiated or specialized.
1463 TemplateSpecializationKind getTemplateSpecializationKind() const;
1464
1465 /// Set the kind of specialization or template instantiation this is.
1466 void setTemplateSpecializationKind(TemplateSpecializationKind TSK);
1467
1468 /// Retrieve the record declaration from which this record could be
1469 /// instantiated. Returns null if this class is not a template instantiation.
1470 const CXXRecordDecl *getTemplateInstantiationPattern() const;
1471
1472 CXXRecordDecl *getTemplateInstantiationPattern() {
1473 return const_cast<CXXRecordDecl *>(const_cast<const CXXRecordDecl *>(this)
1474 ->getTemplateInstantiationPattern());
1475 }
1476
1477 /// Returns the destructor decl for this class.
1478 CXXDestructorDecl *getDestructor() const;
1479
1480 /// Returns true if the class destructor, or any implicitly invoked
1481 /// destructors are marked noreturn.
1482 bool isAnyDestructorNoReturn() const { return data().IsAnyDestructorNoReturn; }
1483
1484 /// If the class is a local class [class.local], returns
1485 /// the enclosing function declaration.
1486 const FunctionDecl *isLocalClass() const {
1487 if (const auto *RD = dyn_cast<CXXRecordDecl>(getDeclContext()))
1488 return RD->isLocalClass();
1489
1490 return dyn_cast<FunctionDecl>(getDeclContext());
1491 }
1492
1493 FunctionDecl *isLocalClass() {
1494 return const_cast<FunctionDecl*>(
1495 const_cast<const CXXRecordDecl*>(this)->isLocalClass());
1496 }
1497
1498 /// Determine whether this dependent class is a current instantiation,
1499 /// when viewed from within the given context.
1500 bool isCurrentInstantiation(const DeclContext *CurContext) const;
1501
1502 /// Determine whether this class is derived from the class \p Base.
1503 ///
1504 /// This routine only determines whether this class is derived from \p Base,
1505 /// but does not account for factors that may make a Derived -> Base class
1506 /// ill-formed, such as private/protected inheritance or multiple, ambiguous
1507 /// base class subobjects.
1508 ///
1509 /// \param Base the base class we are searching for.
1510 ///
1511 /// \returns true if this class is derived from Base, false otherwise.
1512 bool isDerivedFrom(const CXXRecordDecl *Base) const;
1513
1514 /// Determine whether this class is derived from the type \p Base.
1515 ///
1516 /// This routine only determines whether this class is derived from \p Base,
1517 /// but does not account for factors that may make a Derived -> Base class
1518 /// ill-formed, such as private/protected inheritance or multiple, ambiguous
1519 /// base class subobjects.
1520 ///
1521 /// \param Base the base class we are searching for.
1522 ///
1523 /// \param Paths will contain the paths taken from the current class to the
1524 /// given \p Base class.
1525 ///
1526 /// \returns true if this class is derived from \p Base, false otherwise.
1527 ///
1528 /// \todo add a separate parameter to configure IsDerivedFrom, rather than
1529 /// tangling input and output in \p Paths
1530 bool isDerivedFrom(const CXXRecordDecl *Base, CXXBasePaths &Paths) const;
1531
1532 /// Determine whether this class is virtually derived from
1533 /// the class \p Base.
1534 ///
1535 /// This routine only determines whether this class is virtually
1536 /// derived from \p Base, but does not account for factors that may
1537 /// make a Derived -> Base class ill-formed, such as
1538 /// private/protected inheritance or multiple, ambiguous base class
1539 /// subobjects.
1540 ///
1541 /// \param Base the base class we are searching for.
1542 ///
1543 /// \returns true if this class is virtually derived from Base,
1544 /// false otherwise.
1545 bool isVirtuallyDerivedFrom(const CXXRecordDecl *Base) const;
1546
1547 /// Determine whether this class is provably not derived from
1548 /// the type \p Base.
1549 bool isProvablyNotDerivedFrom(const CXXRecordDecl *Base) const;
1550
1551 /// Function type used by forallBases() as a callback.
1552 ///
1553 /// \param BaseDefinition the definition of the base class
1554 ///
1555 /// \returns true if this base matched the search criteria
1556 using ForallBasesCallback =
1557 llvm::function_ref<bool(const CXXRecordDecl *BaseDefinition)>;
1558
1559 /// Determines if the given callback holds for all the direct
1560 /// or indirect base classes of this type.
1561 ///
1562 /// The class itself does not count as a base class. This routine
1563 /// returns false if the class has non-computable base classes.
1564 ///
1565 /// \param BaseMatches Callback invoked for each (direct or indirect) base
1566 /// class of this type until a call returns false.
1567 bool forallBases(ForallBasesCallback BaseMatches) const;
1568
1569 /// Function type used by lookupInBases() to determine whether a
1570 /// specific base class subobject matches the lookup criteria.
1571 ///
1572 /// \param Specifier the base-class specifier that describes the inheritance
1573 /// from the base class we are trying to match.
1574 ///
1575 /// \param Path the current path, from the most-derived class down to the
1576 /// base named by the \p Specifier.
1577 ///
1578 /// \returns true if this base matched the search criteria, false otherwise.
1579 using BaseMatchesCallback =
1580 llvm::function_ref<bool(const CXXBaseSpecifier *Specifier,
1581 CXXBasePath &Path)>;
1582
1583 /// Look for entities within the base classes of this C++ class,
1584 /// transitively searching all base class subobjects.
1585 ///
1586 /// This routine uses the callback function \p BaseMatches to find base
1587 /// classes meeting some search criteria, walking all base class subobjects
1588 /// and populating the given \p Paths structure with the paths through the
1589 /// inheritance hierarchy that resulted in a match. On a successful search,
1590 /// the \p Paths structure can be queried to retrieve the matching paths and
1591 /// to determine if there were any ambiguities.
1592 ///
1593 /// \param BaseMatches callback function used to determine whether a given
1594 /// base matches the user-defined search criteria.
1595 ///
1596 /// \param Paths used to record the paths from this class to its base class
1597 /// subobjects that match the search criteria.
1598 ///
1599 /// \param LookupInDependent can be set to true to extend the search to
1600 /// dependent base classes.
1601 ///
1602 /// \returns true if there exists any path from this class to a base class
1603 /// subobject that matches the search criteria.
1604 bool lookupInBases(BaseMatchesCallback BaseMatches, CXXBasePaths &Paths,
1605 bool LookupInDependent = false) const;
1606
1607 /// Base-class lookup callback that determines whether the given
1608 /// base class specifier refers to a specific class declaration.
1609 ///
1610 /// This callback can be used with \c lookupInBases() to determine whether
1611 /// a given derived class has is a base class subobject of a particular type.
1612 /// The base record pointer should refer to the canonical CXXRecordDecl of the
1613 /// base class that we are searching for.
1614 static bool FindBaseClass(const CXXBaseSpecifier *Specifier,
1615 CXXBasePath &Path, const CXXRecordDecl *BaseRecord);
1616
1617 /// Base-class lookup callback that determines whether the
1618 /// given base class specifier refers to a specific class
1619 /// declaration and describes virtual derivation.
1620 ///
1621 /// This callback can be used with \c lookupInBases() to determine
1622 /// whether a given derived class has is a virtual base class
1623 /// subobject of a particular type. The base record pointer should
1624 /// refer to the canonical CXXRecordDecl of the base class that we
1625 /// are searching for.
1626 static bool FindVirtualBaseClass(const CXXBaseSpecifier *Specifier,
1627 CXXBasePath &Path,
1628 const CXXRecordDecl *BaseRecord);
1629
1630 /// Retrieve the final overriders for each virtual member
1631 /// function in the class hierarchy where this class is the
1632 /// most-derived class in the class hierarchy.
1633 void getFinalOverriders(CXXFinalOverriderMap &FinaOverriders) const;
1634
1635 /// Get the indirect primary bases for this class.
1636 void getIndirectPrimaryBases(CXXIndirectPrimaryBaseSet& Bases) const;
1637
1638 /// Determine whether this class has a member with the given name, possibly
1639 /// in a non-dependent base class.
1640 ///
1641 /// No check for ambiguity is performed, so this should never be used when
1642 /// implementing language semantics, but it may be appropriate for warnings,
1643 /// static analysis, or similar.
1644 bool hasMemberName(DeclarationName N) const;
1645
1646 /// Performs an imprecise lookup of a dependent name in this class.
1647 ///
1648 /// This function does not follow strict semantic rules and should be used
1649 /// only when lookup rules can be relaxed, e.g. indexing.
1650 std::vector<const NamedDecl *>
1651 lookupDependentName(DeclarationName Name,
1652 llvm::function_ref<bool(const NamedDecl *ND)> Filter);
1653
1654 /// Renders and displays an inheritance diagram
1655 /// for this C++ class and all of its base classes (transitively) using
1656 /// GraphViz.
1657 void viewInheritance(ASTContext& Context) const;
1658
1659 /// Calculates the access of a decl that is reached
1660 /// along a path.
1661 static AccessSpecifier MergeAccess(AccessSpecifier PathAccess,
1662 AccessSpecifier DeclAccess) {
1663 assert(DeclAccess != AS_none)(static_cast <bool> (DeclAccess != AS_none) ? void (0) :
__assert_fail ("DeclAccess != AS_none", "clang/include/clang/AST/DeclCXX.h"
, 1663, __extension__ __PRETTY_FUNCTION__))
;
1664 if (DeclAccess == AS_private) return AS_none;
1665 return (PathAccess > DeclAccess ? PathAccess : DeclAccess);
1666 }
1667
1668 /// Indicates that the declaration of a defaulted or deleted special
1669 /// member function is now complete.
1670 void finishedDefaultedOrDeletedMember(CXXMethodDecl *MD);
1671
1672 void setTrivialForCallFlags(CXXMethodDecl *MD);
1673
1674 /// Indicates that the definition of this class is now complete.
1675 void completeDefinition() override;
1676
1677 /// Indicates that the definition of this class is now complete,
1678 /// and provides a final overrider map to help determine
1679 ///
1680 /// \param FinalOverriders The final overrider map for this class, which can
1681 /// be provided as an optimization for abstract-class checking. If NULL,
1682 /// final overriders will be computed if they are needed to complete the
1683 /// definition.
1684 void completeDefinition(CXXFinalOverriderMap *FinalOverriders);
1685
1686 /// Determine whether this class may end up being abstract, even though
1687 /// it is not yet known to be abstract.
1688 ///
1689 /// \returns true if this class is not known to be abstract but has any
1690 /// base classes that are abstract. In this case, \c completeDefinition()
1691 /// will need to compute final overriders to determine whether the class is
1692 /// actually abstract.
1693 bool mayBeAbstract() const;
1694
1695 /// Determine whether it's impossible for a class to be derived from this
1696 /// class. This is best-effort, and may conservatively return false.
1697 bool isEffectivelyFinal() const;
1698
1699 /// If this is the closure type of a lambda expression, retrieve the
1700 /// number to be used for name mangling in the Itanium C++ ABI.
1701 ///
1702 /// Zero indicates that this closure type has internal linkage, so the
1703 /// mangling number does not matter, while a non-zero value indicates which
1704 /// lambda expression this is in this particular context.
1705 unsigned getLambdaManglingNumber() const {
1706 assert(isLambda() && "Not a lambda closure type!")(static_cast <bool> (isLambda() && "Not a lambda closure type!"
) ? void (0) : __assert_fail ("isLambda() && \"Not a lambda closure type!\""
, "clang/include/clang/AST/DeclCXX.h", 1706, __extension__ __PRETTY_FUNCTION__
))
;
1707 return getLambdaData().ManglingNumber;
1708 }
1709
1710 /// The lambda is known to has internal linkage no matter whether it has name
1711 /// mangling number.
1712 bool hasKnownLambdaInternalLinkage() const {
1713 assert(isLambda() && "Not a lambda closure type!")(static_cast <bool> (isLambda() && "Not a lambda closure type!"
) ? void (0) : __assert_fail ("isLambda() && \"Not a lambda closure type!\""
, "clang/include/clang/AST/DeclCXX.h", 1713, __extension__ __PRETTY_FUNCTION__
))
;
1714 return getLambdaData().HasKnownInternalLinkage;
1715 }
1716
1717 /// Retrieve the declaration that provides additional context for a
1718 /// lambda, when the normal declaration context is not specific enough.
1719 ///
1720 /// Certain contexts (default arguments of in-class function parameters and
1721 /// the initializers of data members) have separate name mangling rules for
1722 /// lambdas within the Itanium C++ ABI. For these cases, this routine provides
1723 /// the declaration in which the lambda occurs, e.g., the function parameter
1724 /// or the non-static data member. Otherwise, it returns NULL to imply that
1725 /// the declaration context suffices.
1726 Decl *getLambdaContextDecl() const;
1727
1728 /// Set the mangling number and context declaration for a lambda
1729 /// class.
1730 void setLambdaMangling(unsigned ManglingNumber, Decl *ContextDecl,
1731 bool HasKnownInternalLinkage = false) {
1732 assert(isLambda() && "Not a lambda closure type!")(static_cast <bool> (isLambda() && "Not a lambda closure type!"
) ? void (0) : __assert_fail ("isLambda() && \"Not a lambda closure type!\""
, "clang/include/clang/AST/DeclCXX.h", 1732, __extension__ __PRETTY_FUNCTION__
))
;
1733 getLambdaData().ManglingNumber = ManglingNumber;
1734 getLambdaData().ContextDecl = ContextDecl;
1735 getLambdaData().HasKnownInternalLinkage = HasKnownInternalLinkage;
1736 }
1737
1738 /// Set the device side mangling number.
1739 void setDeviceLambdaManglingNumber(unsigned Num) const;
1740
1741 /// Retrieve the device side mangling number.
1742 unsigned getDeviceLambdaManglingNumber() const;
1743
1744 /// Returns the inheritance model used for this record.
1745 MSInheritanceModel getMSInheritanceModel() const;
1746
1747 /// Calculate what the inheritance model would be for this class.
1748 MSInheritanceModel calculateInheritanceModel() const;
1749
1750 /// In the Microsoft C++ ABI, use zero for the field offset of a null data
1751 /// member pointer if we can guarantee that zero is not a valid field offset,
1752 /// or if the member pointer has multiple fields. Polymorphic classes have a
1753 /// vfptr at offset zero, so we can use zero for null. If there are multiple
1754 /// fields, we can use zero even if it is a valid field offset because
1755 /// null-ness testing will check the other fields.
1756 bool nullFieldOffsetIsZero() const;
1757
1758 /// Controls when vtordisps will be emitted if this record is used as a
1759 /// virtual base.
1760 MSVtorDispMode getMSVtorDispMode() const;
1761
1762 /// Determine whether this lambda expression was known to be dependent
1763 /// at the time it was created, even if its context does not appear to be
1764 /// dependent.
1765 ///
1766 /// This flag is a workaround for an issue with parsing, where default
1767 /// arguments are parsed before their enclosing function declarations have
1768 /// been created. This means that any lambda expressions within those
1769 /// default arguments will have as their DeclContext the context enclosing
1770 /// the function declaration, which may be non-dependent even when the
1771 /// function declaration itself is dependent. This flag indicates when we
1772 /// know that the lambda is dependent despite that.
1773 bool isDependentLambda() const {
1774 return isLambda() && getLambdaData().Dependent;
1775 }
1776
1777 TypeSourceInfo *getLambdaTypeInfo() const {
1778 return getLambdaData().MethodTyInfo;
1779 }
1780
1781 // Determine whether this type is an Interface Like type for
1782 // __interface inheritance purposes.
1783 bool isInterfaceLike() const;
1784
1785 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1786 static bool classofKind(Kind K) {
1787 return K >= firstCXXRecord && K <= lastCXXRecord;
1788 }
1789 void markAbstract() { data().Abstract = true; }
1790};
1791
1792/// Store information needed for an explicit specifier.
1793/// Used by CXXDeductionGuideDecl, CXXConstructorDecl and CXXConversionDecl.
1794class ExplicitSpecifier {
1795 llvm::PointerIntPair<Expr *, 2, ExplicitSpecKind> ExplicitSpec{
1796 nullptr, ExplicitSpecKind::ResolvedFalse};
1797
1798public:
1799 ExplicitSpecifier() = default;
1800 ExplicitSpecifier(Expr *Expression, ExplicitSpecKind Kind)
1801 : ExplicitSpec(Expression, Kind) {}
1802 ExplicitSpecKind getKind() const { return ExplicitSpec.getInt(); }
1803 const Expr *getExpr() const { return ExplicitSpec.getPointer(); }
1804 Expr *getExpr() { return ExplicitSpec.getPointer(); }
1805
1806 /// Determine if the declaration had an explicit specifier of any kind.
1807 bool isSpecified() const {
1808 return ExplicitSpec.getInt() != ExplicitSpecKind::ResolvedFalse ||
1809 ExplicitSpec.getPointer();
1810 }
1811
1812 /// Check for equivalence of explicit specifiers.
1813 /// \return true if the explicit specifier are equivalent, false otherwise.
1814 bool isEquivalent(const ExplicitSpecifier Other) const;
1815 /// Determine whether this specifier is known to correspond to an explicit
1816 /// declaration. Returns false if the specifier is absent or has an
1817 /// expression that is value-dependent or evaluates to false.
1818 bool isExplicit() const {
1819 return ExplicitSpec.getInt() == ExplicitSpecKind::ResolvedTrue;
1820 }
1821 /// Determine if the explicit specifier is invalid.
1822 /// This state occurs after a substitution failures.
1823 bool isInvalid() const {
1824 return ExplicitSpec.getInt() == ExplicitSpecKind::Unresolved &&
1825 !ExplicitSpec.getPointer();
1826 }
1827 void setKind(ExplicitSpecKind Kind) { ExplicitSpec.setInt(Kind); }
1828 void setExpr(Expr *E) { ExplicitSpec.setPointer(E); }
1829 // Retrieve the explicit specifier in the given declaration, if any.
1830 static ExplicitSpecifier getFromDecl(FunctionDecl *Function);
1831 static const ExplicitSpecifier getFromDecl(const FunctionDecl *Function) {
1832 return getFromDecl(const_cast<FunctionDecl *>(Function));
1833 }
1834 static ExplicitSpecifier Invalid() {
1835 return ExplicitSpecifier(nullptr, ExplicitSpecKind::Unresolved);
1836 }
1837};
1838
1839/// Represents a C++ deduction guide declaration.
1840///
1841/// \code
1842/// template<typename T> struct A { A(); A(T); };
1843/// A() -> A<int>;
1844/// \endcode
1845///
1846/// In this example, there will be an explicit deduction guide from the
1847/// second line, and implicit deduction guide templates synthesized from
1848/// the constructors of \c A.
1849class CXXDeductionGuideDecl : public FunctionDecl {
1850 void anchor() override;
1851
1852private:
1853 CXXDeductionGuideDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1854 ExplicitSpecifier ES,
1855 const DeclarationNameInfo &NameInfo, QualType T,
1856 TypeSourceInfo *TInfo, SourceLocation EndLocation,
1857 CXXConstructorDecl *Ctor)
1858 : FunctionDecl(CXXDeductionGuide, C, DC, StartLoc, NameInfo, T, TInfo,
1859 SC_None, false, false, ConstexprSpecKind::Unspecified),
1860 Ctor(Ctor), ExplicitSpec(ES) {
1861 if (EndLocation.isValid())
1862 setRangeEnd(EndLocation);
1863 setIsCopyDeductionCandidate(false);