Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

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

/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaTemplateInstantiate.cpp

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

/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/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-11~++20200309111110+2c36c23f347/clang/include/clang/AST/DeclCXX.h

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