Bug Summary

File:clang/lib/Sema/SemaTemplateInstantiate.cpp
Warning:line 954, 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-10/lib/clang/10.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/include -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-10/lib/clang/10.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd=. -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-01-13-084841-49055-1 -x c++ /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp

/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaTemplateInstantiate.cpp

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

/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/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-10~++20200112100611+7fa5290d5bd/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-10~++20200112100611+7fa5290d5bd/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-10~++20200112100611+7fa5290d5bd/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-10~++20200112100611+7fa5290d5bd/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-10~++20200112100611+7fa5290d5bd/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-10~++20200112100611+7fa5290d5bd/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-10~++20200112100611+7fa5290d5bd/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-10~++20200112100611+7fa5290d5bd/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-10~++20200112100611+7fa5290d5bd/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-10~++20200112100611+7fa5290d5bd/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-10~++20200112100611+7fa5290d5bd/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-10~++20200112100611+7fa5290d5bd/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-10~++20200112100611+7fa5290d5bd/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-10~++20200112100611+7fa5290d5bd/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-10~++20200112100611+7fa5290d5bd/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-10~++20200112100611+7fa5290d5bd/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-10~++20200112100611+7fa5290d5bd/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-10~++20200112100611+7fa5290d5bd/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-10~++20200112100611+7fa5290d5bd/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-10~++20200112100611+7fa5290d5bd/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-10~++20200112100611+7fa5290d5bd/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-10~++20200112100611+7fa5290d5bd/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-10~++20200112100611+7fa5290d5bd/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-10~++20200112100611+7fa5290d5bd/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-10~++20200112100611+7fa5290d5bd/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-10~++20200112100611+7fa5290d5bd/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, or if \p AllowShortCircuit is true then until a call
1521 /// returns false.
1522 ///
1523 /// \param AllowShortCircuit if false, forces the callback to be called
1524 /// for every base class, even if a dependent or non-matching base was
1525 /// found.
1526 bool forallBases(ForallBasesCallback BaseMatches,
1527 bool AllowShortCircuit = true) const;
1528
1529 /// Function type used by lookupInBases() to determine whether a
1530 /// specific base class subobject matches the lookup criteria.
1531 ///
1532 /// \param Specifier the base-class specifier that describes the inheritance
1533 /// from the base class we are trying to match.
1534 ///
1535 /// \param Path the current path, from the most-derived class down to the
1536 /// base named by the \p Specifier.
1537 ///
1538 /// \returns true if this base matched the search criteria, false otherwise.
1539 using BaseMatchesCallback =
1540 llvm::function_ref<bool(const CXXBaseSpecifier *Specifier,
1541 CXXBasePath &Path)>;
1542
1543 /// Look for entities within the base classes of this C++ class,
1544 /// transitively searching all base class subobjects.
1545 ///
1546 /// This routine uses the callback function \p BaseMatches to find base
1547 /// classes meeting some search criteria, walking all base class subobjects
1548 /// and populating the given \p Paths structure with the paths through the
1549 /// inheritance hierarchy that resulted in a match. On a successful search,
1550 /// the \p Paths structure can be queried to retrieve the matching paths and
1551 /// to determine if there were any ambiguities.
1552 ///
1553 /// \param BaseMatches callback function used to determine whether a given
1554 /// base matches the user-defined search criteria.
1555 ///
1556 /// \param Paths used to record the paths from this class to its base class
1557 /// subobjects that match the search criteria.
1558 ///
1559 /// \param LookupInDependent can be set to true to extend the search to
1560 /// dependent base classes.
1561 ///
1562 /// \returns true if there exists any path from this class to a base class
1563 /// subobject that matches the search criteria.
1564 bool lookupInBases(BaseMatchesCallback BaseMatches, CXXBasePaths &Paths,
1565 bool LookupInDependent = false) const;
1566
1567 /// Base-class lookup callback that determines whether the given
1568 /// base class specifier refers to a specific class declaration.
1569 ///
1570 /// This callback can be used with \c lookupInBases() to determine whether
1571 /// a given derived class has is a base class subobject of a particular type.
1572 /// The base record pointer should refer to the canonical CXXRecordDecl of the
1573 /// base class that we are searching for.
1574 static bool FindBaseClass(const CXXBaseSpecifier *Specifier,
1575 CXXBasePath &Path, const CXXRecordDecl *BaseRecord);
1576
1577 /// Base-class lookup callback that determines whether the
1578 /// given base class specifier refers to a specific class
1579 /// declaration and describes virtual derivation.
1580 ///
1581 /// This callback can be used with \c lookupInBases() to determine
1582 /// whether a given derived class has is a virtual base class
1583 /// subobject of a particular type. The base record pointer should
1584 /// refer to the canonical CXXRecordDecl of the base class that we
1585 /// are searching for.
1586 static bool FindVirtualBaseClass(const CXXBaseSpecifier *Specifier,
1587 CXXBasePath &Path,
1588 const CXXRecordDecl *BaseRecord);
1589
1590 /// Base-class lookup callback that determines whether there exists
1591 /// a tag with the given name.
1592 ///
1593 /// This callback can be used with \c lookupInBases() to find tag members
1594 /// of the given name within a C++ class hierarchy.
1595 static bool FindTagMember(const CXXBaseSpecifier *Specifier,
1596 CXXBasePath &Path, DeclarationName Name);
1597
1598 /// Base-class lookup callback that determines whether there exists
1599 /// a member with the given name.
1600 ///
1601 /// This callback can be used with \c lookupInBases() to find members
1602 /// of the given name within a C++ class hierarchy.
1603 static bool FindOrdinaryMember(const CXXBaseSpecifier *Specifier,
1604 CXXBasePath &Path, DeclarationName Name);
1605
1606 /// Base-class lookup callback that determines whether there exists
1607 /// a member with the given name.
1608 ///
1609 /// This callback can be used with \c lookupInBases() to find members
1610 /// of the given name within a C++ class hierarchy, including dependent
1611 /// classes.
1612 static bool
1613 FindOrdinaryMemberInDependentClasses(const CXXBaseSpecifier *Specifier,
1614 CXXBasePath &Path, DeclarationName Name);
1615
1616 /// Base-class lookup callback that determines whether there exists
1617 /// an OpenMP declare reduction member with the given name.
1618 ///
1619 /// This callback can be used with \c lookupInBases() to find members
1620 /// of the given name within a C++ class hierarchy.
1621 static bool FindOMPReductionMember(const CXXBaseSpecifier *Specifier,
1622 CXXBasePath &Path, DeclarationName Name);
1623
1624 /// Base-class lookup callback that determines whether there exists
1625 /// an OpenMP declare mapper member with the given name.
1626 ///
1627 /// This callback can be used with \c lookupInBases() to find members
1628 /// of the given name within a C++ class hierarchy.
1629 static bool FindOMPMapperMember(const CXXBaseSpecifier *Specifier,
1630 CXXBasePath &Path, DeclarationName Name);
1631
1632 /// Base-class lookup callback that determines whether there exists
1633 /// a member with the given name that can be used in a nested-name-specifier.
1634 ///
1635 /// This callback can be used with \c lookupInBases() to find members of
1636 /// the given name within a C++ class hierarchy that can occur within
1637 /// nested-name-specifiers.
1638 static bool FindNestedNameSpecifierMember(const CXXBaseSpecifier *Specifier,
1639 CXXBasePath &Path,
1640 DeclarationName Name);
1641
1642 /// Retrieve the final overriders for each virtual member
1643 /// function in the class hierarchy where this class is the
1644 /// most-derived class in the class hierarchy.
1645 void getFinalOverriders(CXXFinalOverriderMap &FinaOverriders) const;
1646
1647 /// Get the indirect primary bases for this class.
1648 void getIndirectPrimaryBases(CXXIndirectPrimaryBaseSet& Bases) const;
1649
1650 /// Performs an imprecise lookup of a dependent name in this class.
1651 ///
1652 /// This function does not follow strict semantic rules and should be used
1653 /// only when lookup rules can be relaxed, e.g. indexing.
1654 std::vector<const NamedDecl *>
1655 lookupDependentName(const DeclarationName &Name,
1656 llvm::function_ref<bool(const NamedDecl *ND)> Filter);
1657
1658 /// Renders and displays an inheritance diagram
1659 /// for this C++ class and all of its base classes (transitively) using
1660 /// GraphViz.
1661 void viewInheritance(ASTContext& Context) const;
1662
1663 /// Calculates the access of a decl that is reached
1664 /// along a path.
1665 static AccessSpecifier MergeAccess(AccessSpecifier PathAccess,
1666 AccessSpecifier DeclAccess) {
1667 assert(DeclAccess != AS_none)((DeclAccess != AS_none) ? static_cast<void> (0) : __assert_fail
("DeclAccess != AS_none", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/DeclCXX.h"
, 1667, __PRETTY_FUNCTION__))
;
1668 if (DeclAccess == AS_private) return AS_none;
1669 return (PathAccess > DeclAccess ? PathAccess : DeclAccess);
1670 }
1671
1672 /// Indicates that the declaration of a defaulted or deleted special
1673 /// member function is now complete.
1674 void finishedDefaultedOrDeletedMember(CXXMethodDecl *MD);
1675
1676 void setTrivialForCallFlags(CXXMethodDecl *MD);
1677
1678 /// Indicates that the definition of this class is now complete.
1679 void completeDefinition() override;
1680
1681 /// Indicates that the definition of this class is now complete,
1682 /// and provides a final overrider map to help determine
1683 ///
1684 /// \param FinalOverriders The final overrider map for this class, which can
1685 /// be provided as an optimization for abstract-class checking. If NULL,
1686 /// final overriders will be computed if they are needed to complete the
1687 /// definition.
1688 void completeDefinition(CXXFinalOverriderMap *FinalOverriders);
1689
1690 /// Determine whether this class may end up being abstract, even though
1691 /// it is not yet known to be abstract.
1692 ///
1693 /// \returns true if this class is not known to be abstract but has any
1694 /// base classes that are abstract. In this case, \c completeDefinition()
1695 /// will need to compute final overriders to determine whether the class is
1696 /// actually abstract.
1697 bool mayBeAbstract() const;
1698
1699 /// If this is the closure type of a lambda expression, retrieve the
1700 /// number to be used for name mangling in the Itanium C++ ABI.
1701 ///
1702 /// Zero indicates that this closure type has internal linkage, so the
1703 /// mangling number does not matter, while a non-zero value indicates which
1704 /// lambda expression this is in this particular context.
1705 unsigned getLambdaManglingNumber() const {
1706 assert(isLambda() && "Not a lambda closure type!")((isLambda() && "Not a lambda closure type!") ? static_cast
<void> (0) : __assert_fail ("isLambda() && \"Not a lambda closure type!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/DeclCXX.h"
, 1706, __PRETTY_FUNCTION__))
;
1707 return getLambdaData().ManglingNumber;
1708 }
1709
1710 /// The lambda is known to has internal linkage no matter whether it has name
1711 /// mangling number.
1712 bool hasKnownLambdaInternalLinkage() const {
1713 assert(isLambda() && "Not a lambda closure type!")((isLambda() && "Not a lambda closure type!") ? static_cast
<void> (0) : __assert_fail ("isLambda() && \"Not a lambda closure type!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/DeclCXX.h"
, 1713, __PRETTY_FUNCTION__))
;
1714 return getLambdaData().HasKnownInternalLinkage;
1715 }
1716
1717 /// Retrieve the declaration that provides additional context for a
1718 /// lambda, when the normal declaration context is not specific enough.
1719 ///
1720 /// Certain contexts (default arguments of in-class function parameters and
1721 /// the initializers of data members) have separate name mangling rules for
1722 /// lambdas within the Itanium C++ ABI. For these cases, this routine provides
1723 /// the declaration in which the lambda occurs, e.g., the function parameter
1724 /// or the non-static data member. Otherwise, it returns NULL to imply that
1725 /// the declaration context suffices.
1726 Decl *getLambdaContextDecl() const;
1727
1728 /// Set the mangling number and context declaration for a lambda
1729 /// class.
1730 void setLambdaMangling(unsigned ManglingNumber, Decl *ContextDecl,
1731 bool HasKnownInternalLinkage = false) {
1732 assert(isLambda() && "Not a lambda closure type!")((isLambda() && "Not a lambda closure type!") ? static_cast
<void> (0) : __assert_fail ("isLambda() && \"Not a lambda closure type!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/DeclCXX.h"
, 1732, __PRETTY_FUNCTION__))
;
1733 getLambdaData().ManglingNumber = ManglingNumber;
1734 getLambdaData().ContextDecl = ContextDecl;
1735 getLambdaData().HasKnownInternalLinkage = HasKnownInternalLinkage;
1736 }
1737
1738 /// Returns the inheritance model used for this record.
1739 MSInheritanceModel getMSInheritanceModel() const;
1740
1741 /// Calculate what the inheritance model would be for this class.
1742 MSInheritanceModel calculateInheritanceModel() const;
1743
1744 /// In the Microsoft C++ ABI, use zero for the field offset of a null data
1745 /// member pointer if we can guarantee that zero is not a valid field offset,
1746 /// or if the member pointer has multiple fields. Polymorphic classes have a
1747 /// vfptr at offset zero, so we can use zero for null. If there are multiple
1748 /// fields, we can use zero even if it is a valid field offset because
1749 /// null-ness testing will check the other fields.
1750 bool nullFieldOffsetIsZero() const;
1751
1752 /// Controls when vtordisps will be emitted if this record is used as a
1753 /// virtual base.
1754 MSVtorDispMode getMSVtorDispMode() const;
1755
1756 /// Determine whether this lambda expression was known to be dependent
1757 /// at the time it was created, even if its context does not appear to be
1758 /// dependent.
1759 ///
1760 /// This flag is a workaround for an issue with parsing, where default
1761 /// arguments are parsed before their enclosing function declarations have
1762 /// been created. This means that any lambda expressions within those
1763 /// default arguments will have as their DeclContext the context enclosing
1764 /// the function declaration, which may be non-dependent even when the
1765 /// function declaration itself is dependent. This flag indicates when we
1766 /// know that the lambda is dependent despite that.
1767 bool isDependentLambda() const {
1768 return isLambda() && getLambdaData().Dependent;
1769 }
1770
1771 TypeSourceInfo *getLambdaTypeInfo() const {
1772 return getLambdaData().MethodTyInfo;
1773 }
1774
1775 // Determine whether this type is an Interface Like type for
1776 // __interface inheritance purposes.
1777 bool isInterfaceLike() const;
1778
1779 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1780 static bool classofKind(Kind K) {
1781 return K >= firstCXXRecord && K <= lastCXXRecord;
1782 }
1783};
1784
1785/// Store information needed for an explicit specifier.
1786/// Used by CXXDeductionGuideDecl, CXXConstructorDecl and CXXConversionDecl.
1787class ExplicitSpecifier {
1788 llvm::PointerIntPair<Expr *, 2, ExplicitSpecKind> ExplicitSpec{
1789 nullptr, ExplicitSpecKind::ResolvedFalse};
1790
1791public:
1792 ExplicitSpecifier() = default;
1793 ExplicitSpecifier(Expr *Expression, ExplicitSpecKind Kind)
1794 : ExplicitSpec(Expression, Kind) {}
1795 ExplicitSpecKind getKind() const { return ExplicitSpec.getInt(); }
1796 const Expr *getExpr() const { return ExplicitSpec.getPointer(); }
1797 Expr *getExpr() { return ExplicitSpec.getPointer(); }
1798
1799 /// Determine if the declaration had an explicit specifier of any kind.
1800 bool isSpecified() const {
1801 return ExplicitSpec.getInt() != ExplicitSpecKind::ResolvedFalse ||
1802 ExplicitSpec.getPointer();
1803 }
1804
1805 /// Check for equivalence of explicit specifiers.
1806 /// \return true if the explicit specifier are equivalent, false otherwise.
1807 bool isEquivalent(const ExplicitSpecifier Other) const;
1808 /// Determine whether this specifier is known to correspond to an explicit
1809 /// declaration. Returns false if the specifier is absent or has an
1810 /// expression that is value-dependent or evaluates to false.
1811 bool isExplicit() const {
1812 return ExplicitSpec.getInt() == ExplicitSpecKind::ResolvedTrue;
1813 }
1814 /// Determine if the explicit specifier is invalid.
1815 /// This state occurs after a substitution failures.
1816 bool isInvalid() const {
1817 return ExplicitSpec.getInt() == ExplicitSpecKind::Unresolved &&
1818 !ExplicitSpec.getPointer();
1819 }
1820 void setKind(ExplicitSpecKind Kind) { ExplicitSpec.setInt(Kind); }
1821 void setExpr(Expr *E) { ExplicitSpec.setPointer(E); }
1822 // Retrieve the explicit specifier in the given declaration, if any.
1823 static ExplicitSpecifier getFromDecl(FunctionDecl *Function);
1824 static const ExplicitSpecifier getFromDecl(const FunctionDecl *Function) {
1825 return getFromDecl(const_cast<FunctionDecl *>(Function));
1826 }
1827 static ExplicitSpecifier Invalid() {
1828 return ExplicitSpecifier(nullptr, ExplicitSpecKind::Unresolved);
1829 }
1830};
1831
1832/// Represents a C++ deduction guide declaration.
1833///
1834/// \code
1835/// template<typename T> struct A { A(); A(T); };
1836/// A() -> A<int>;
1837/// \endcode
1838///
1839/// In this example, there will be an explicit deduction guide from the
1840/// second line, and implicit deduction guide templates synthesized from
1841/// the constructors of \c A.
1842class CXXDeductionGuideDecl : public FunctionDecl {
1843 void anchor() override;
1844
1845private:
1846 CXXDeductionGuideDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1847 ExplicitSpecifier ES,
1848 const DeclarationNameInfo &NameInfo, QualType T,
1849 TypeSourceInfo *TInfo, SourceLocation EndLocation)
1850 : FunctionDecl(CXXDeductionGuide, C, DC, StartLoc, NameInfo, T, TInfo,
1851 SC_None, false, CSK_unspecified),
1852 ExplicitSpec(ES) {
1853 if (EndLocation.isValid())
1854 setRangeEnd(EndLocation);
1855 setIsCopyDeductionCandidate(false);
1856 }
1857
1858 ExplicitSpecifier ExplicitSpec;
1859 void setExplicitSpecifier(ExplicitSpecifier ES) { ExplicitSpec = ES; }
1860
1861public:
1862 friend class ASTDeclReader;
1863 friend class ASTDeclWriter;
1864
1865 static CXXDeductionGuideDecl *
1866 Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1867 ExplicitSpecifier ES, const DeclarationNameInfo &NameInfo, QualType T,
1868 TypeSourceInfo *TInfo, SourceLocation EndLocation);
1869
1870 static CXXDeductionGuideDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1871
1872 ExplicitSpecifier getExplicitSpecifier() { return ExplicitSpec; }
1873 const ExplicitSpecifier getExplicitSpecifier() const { return ExplicitSpec; }
1874
1875 /// Return true if the declartion is already resolved to be explicit.
1876 bool isExplicit() const { return ExplicitSpec.isExplicit(); }
1877
1878 /// Get the template for which this guide performs deduction.
1879 TemplateDecl *getDeducedTemplate() const {
1880 return getDeclName().getCXXDeductionGuideTemplate();
1881 }
1882
1883 void setIsCopyDeductionCandidate(bool isCDC = true) {
1884 FunctionDeclBits.IsCopyDeductionCandidate = isCDC;
1885 }
1886
1887 bool isCopyDeductionCandidate() const {
1888 return FunctionDeclBits.IsCopyDeductionCandidate;
1889 }
1890
1891 // Implement isa/cast/dyncast/etc.
1892 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1893 static bool classofKind(Kind K) { return K == CXXDeductionGuide; }
1894};
1895
1896/// Represents a static or instance method of a struct/union/class.
1897///
1898/// In the terminology of the C++ Standard, these are the (static and
1899/// non-static) member functions, whether virtual or not.
1900class CXXMethodDecl : public FunctionDecl {
1901 void anchor() override;
1902
1903protected:
1904 CXXMethodDecl(Kind DK, ASTContext &C, CXXRecordDecl *RD,
1905 SourceLocation StartLoc, const DeclarationNameInfo &NameInfo,
1906 QualType T, TypeSourceInfo *TInfo, StorageClass SC,
1907 bool isInline, ConstexprSpecKind ConstexprKind,
1908 SourceLocation EndLocation,
1909 Expr *TrailingRequiresClause = nullptr)
1910 : FunctionDecl(DK, C, RD, StartLoc, NameInfo, T, TInfo, SC, isInline,
1911 ConstexprKind, TrailingRequiresClause) {
1912 if (EndLocation.isValid())
1913 setRangeEnd(EndLocation);
1914 }
1915
1916public:
1917 static CXXMethodDecl *Create(ASTContext &C, CXXRecordDecl *RD,
1918 SourceLocation StartLoc,
1919 const DeclarationNameInfo &NameInfo, QualType T,
1920 TypeSourceInfo *TInfo, StorageClass SC,
1921 bool isInline, ConstexprSpecKind ConstexprKind,
1922 SourceLocation EndLocation,
1923 Expr *TrailingRequiresClause = nullptr);
1924
1925 static CXXMethodDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1926
1927 bool isStatic() const;
1928 bool isInstance() const { return !isStatic(); }
1929
1930 /// Returns true if the given operator is implicitly static in a record
1931 /// context.
1932 static bool isStaticOverloadedOperator(OverloadedOperatorKind OOK) {
1933 // [class.free]p1:
1934 // Any allocation function for a class T is a static member
1935 // (even if not explicitly declared static).
1936 // [class.free]p6 Any deallocation function for a class X is a static member
1937 // (even if not explicitly declared static).
1938 return OOK == OO_New || OOK == OO_Array_New || OOK == OO_Delete ||
1939 OOK == OO_Array_Delete;
1940 }
1941
1942 bool isConst() const { return getType()->castAs<FunctionType>()->isConst(); }
1943 bool isVolatile() const { return getType()->castAs<FunctionType>()->isVolatile(); }
1944
1945 bool isVirtual() const {
1946 CXXMethodDecl *CD = const_cast<CXXMethodDecl*>(this)->getCanonicalDecl();
1947
1948 // Member function is virtual if it is marked explicitly so, or if it is
1949 // declared in __interface -- then it is automatically pure virtual.
1950 if (CD->isVirtualAsWritten() || CD->isPure())
1951 return true;
1952
1953 return CD->size_overridden_methods() != 0;
1954 }
1955
1956 /// If it's possible to devirtualize a call to this method, return the called
1957 /// function. Otherwise, return null.
1958
1959 /// \param Base The object on which this virtual function is called.
1960 /// \param IsAppleKext True if we are compiling for Apple kext.
1961 CXXMethodDecl *getDevirtualizedMethod(const Expr *Base, bool IsAppleKext);
1962
1963 const CXXMethodDecl *getDevirtualizedMethod(const Expr *Base,
1964 bool IsAppleKext) const {
1965 return const_cast<CXXMethodDecl *>(this)->getDevirtualizedMethod(
1966 Base, IsAppleKext);
1967 }
1968
1969 /// Determine whether this is a usual deallocation function (C++
1970 /// [basic.stc.dynamic.deallocation]p2), which is an overloaded delete or
1971 /// delete[] operator with a particular signature. Populates \p PreventedBy
1972 /// with the declarations of the functions of the same kind if they were the
1973 /// reason for this function returning false. This is used by
1974 /// Sema::isUsualDeallocationFunction to reconsider the answer based on the
1975 /// context.
1976 bool isUsualDeallocationFunction(
1977 SmallVectorImpl<const FunctionDecl *> &PreventedBy) const;
1978
1979 /// Determine whether this is a copy-assignment operator, regardless
1980 /// of whether it was declared implicitly or explicitly.
1981 bool isCopyAssignmentOperator() const;
1982
1983 /// Determine whether this is a move assignment operator.
1984 bool isMoveAssignmentOperator() const;
1985
1986 CXXMethodDecl *getCanonicalDecl() override {
1987 return cast<CXXMethodDecl>(FunctionDecl::getCanonicalDecl());
1988 }
1989 const CXXMethodDecl *getCanonicalDecl() const {
1990 return const_cast<CXXMethodDecl*>(this)->getCanonicalDecl();
1991 }
1992
1993 CXXMethodDecl *getMostRecentDecl() {
1994 return cast<CXXMethodDecl>(
1995 static_cast<FunctionDecl *>(this)->getMostRecentDecl());
1996 }
1997 const CXXMethodDecl *getMostRecentDecl() const {
1998 return const_cast<CXXMethodDecl*>(this)->getMostRecentDecl();
1999 }
2000
2001 void addOverriddenMethod(const CXXMethodDecl *MD);
2002
2003 using method_iterator = const CXXMethodDecl *const *;
2004
2005 method_iterator begin_overridden_methods() const;
2006 method_iterator end_overridden_methods() const;
2007 unsigned size_overridden_methods() const;
2008
2009 using overridden_method_range= ASTContext::overridden_method_range;
2010
2011 overridden_method_range overridden_methods() const;
2012
2013 /// Return the parent of this method declaration, which
2014 /// is the class in which this method is defined.
2015 const CXXRecordDecl *getParent() const {
2016 return cast<CXXRecordDecl>(FunctionDecl::getParent());
2017 }
2018
2019 /// Return the parent of this method declaration, which
2020 /// is the class in which this method is defined.
2021 CXXRecordDecl *getParent() {
2022 return const_cast<CXXRecordDecl *>(
2023 cast<CXXRecordDecl>(FunctionDecl::getParent()));
2024 }
2025
2026 /// Return the type of the \c this pointer.
2027 ///
2028 /// Should only be called for instance (i.e., non-static) methods. Note
2029 /// that for the call operator of a lambda closure type, this returns the
2030 /// desugared 'this' type (a pointer to the closure type), not the captured
2031 /// 'this' type.
2032 QualType getThisType() const;
2033
2034 /// Return the type of the object pointed by \c this.
2035 ///
2036 /// See getThisType() for usage restriction.
2037 QualType getThisObjectType() const;
2038
2039 static QualType getThisType(const FunctionProtoType *FPT,
2040 const CXXRecordDecl *Decl);
2041
2042 static QualType getThisObjectType(const FunctionProtoType *FPT,
2043 const CXXRecordDecl *Decl);
2044
2045 Qualifiers getMethodQualifiers() const {
2046 return getType()->castAs<FunctionProtoType>()->getMethodQuals();
2047 }
2048
2049 /// Retrieve the ref-qualifier associated with this method.
2050 ///
2051 /// In the following example, \c f() has an lvalue ref-qualifier, \c g()
2052 /// has an rvalue ref-qualifier, and \c h() has no ref-qualifier.
2053 /// @code
2054 /// struct X {
2055 /// void f() &;
2056 /// void g() &&;
2057 /// void h();
2058 /// };
2059 /// @endcode
2060 RefQualifierKind getRefQualifier() const {
2061 return getType()->castAs<FunctionProtoType>()->getRefQualifier();
2062 }
2063
2064 bool hasInlineBody() const;
2065
2066 /// Determine whether this is a lambda closure type's static member
2067 /// function that is used for the result of the lambda's conversion to
2068 /// function pointer (for a lambda with no captures).
2069 ///
2070 /// The function itself, if used, will have a placeholder body that will be
2071 /// supplied by IR generation to either forward to the function call operator
2072 /// or clone the function call operator.
2073 bool isLambdaStaticInvoker() const;
2074
2075 /// Find the method in \p RD that corresponds to this one.
2076 ///
2077 /// Find if \p RD or one of the classes it inherits from override this method.
2078 /// If so, return it. \p RD is assumed to be a subclass of the class defining
2079 /// this method (or be the class itself), unless \p MayBeBase is set to true.
2080 CXXMethodDecl *
2081 getCorrespondingMethodInClass(const CXXRecordDecl *RD,
2082 bool MayBeBase = false);
2083
2084 const CXXMethodDecl *
2085 getCorrespondingMethodInClass(const CXXRecordDecl *RD,
2086 bool MayBeBase = false) const {
2087 return const_cast<CXXMethodDecl *>(this)
2088 ->getCorrespondingMethodInClass(RD, MayBeBase);
2089 }
2090
2091 /// Find if \p RD declares a function that overrides this function, and if so,
2092 /// return it. Does not search base classes.
2093 CXXMethodDecl *getCorrespondingMethodDeclaredInClass(const CXXRecordDecl *RD,
2094 bool MayBeBase = false);
2095 const CXXMethodDecl *
2096 getCorrespondingMethodDeclaredInClass(const CXXRecordDecl *RD,
2097 bool MayBeBase = false) const {
2098 return const_cast<CXXMethodDecl *>(this)
2099 ->getCorrespondingMethodDeclaredInClass(RD, MayBeBase);
2100 }
2101
2102 // Implement isa/cast/dyncast/etc.
2103 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2104 static bool classofKind(Kind K) {
2105 return K >= firstCXXMethod && K <= lastCXXMethod;
2106 }
2107};
2108
2109/// Represents a C++ base or member initializer.
2110///
2111/// This is part of a constructor initializer that
2112/// initializes one non-static member variable or one base class. For
2113/// example, in the following, both 'A(a)' and 'f(3.14159)' are member
2114/// initializers:
2115///
2116/// \code
2117/// class A { };
2118/// class B : public A {
2119/// float f;
2120/// public:
2121/// B(A& a) : A(a), f(3.14159) { }
2122/// };
2123/// \endcode
2124class CXXCtorInitializer final {
2125 /// Either the base class name/delegating constructor type (stored as
2126 /// a TypeSourceInfo*), an normal field (FieldDecl), or an anonymous field
2127 /// (IndirectFieldDecl*) being initialized.
2128 llvm::PointerUnion3<TypeSourceInfo *, FieldDecl *, IndirectFieldDecl *>
2129 Initializee;
2130
2131 /// The source location for the field name or, for a base initializer
2132 /// pack expansion, the location of the ellipsis.
2133 ///
2134 /// In the case of a delegating
2135 /// constructor, it will still include the type's source location as the
2136 /// Initializee points to the CXXConstructorDecl (to allow loop detection).
2137 SourceLocation MemberOrEllipsisLocation;
2138
2139 /// The argument used to initialize the base or member, which may
2140 /// end up constructing an object (when multiple arguments are involved).
2141 Stmt *Init;
2142
2143 /// Location of the left paren of the ctor-initializer.
2144 SourceLocation LParenLoc;
2145
2146 /// Location of the right paren of the ctor-initializer.
2147 SourceLocation RParenLoc;
2148
2149 /// If the initializee is a type, whether that type makes this
2150 /// a delegating initialization.
2151 unsigned IsDelegating : 1;
2152
2153 /// If the initializer is a base initializer, this keeps track
2154 /// of whether the base is virtual or not.
2155 unsigned IsVirtual : 1;
2156
2157 /// Whether or not the initializer is explicitly written
2158 /// in the sources.
2159 unsigned IsWritten : 1;
2160
2161 /// If IsWritten is true, then this number keeps track of the textual order
2162 /// of this initializer in the original sources, counting from 0.
2163 unsigned SourceOrder : 13;
2164
2165public:
2166 /// Creates a new base-class initializer.
2167 explicit
2168 CXXCtorInitializer(ASTContext &Context, TypeSourceInfo *TInfo, bool IsVirtual,
2169 SourceLocation L, Expr *Init, SourceLocation R,
2170 SourceLocation EllipsisLoc);
2171
2172 /// Creates a new member initializer.
2173 explicit
2174 CXXCtorInitializer(ASTContext &Context, FieldDecl *Member,
2175 SourceLocation MemberLoc, SourceLocation L, Expr *Init,
2176 SourceLocation R);
2177
2178 /// Creates a new anonymous field initializer.
2179 explicit
2180 CXXCtorInitializer(ASTContext &Context, IndirectFieldDecl *Member,
2181 SourceLocation MemberLoc, SourceLocation L, Expr *Init,
2182 SourceLocation R);
2183
2184 /// Creates a new delegating initializer.
2185 explicit
2186 CXXCtorInitializer(ASTContext &Context, TypeSourceInfo *TInfo,
2187 SourceLocation L, Expr *Init, SourceLocation R);
2188
2189 /// \return Unique reproducible object identifier.
2190 int64_t getID(const ASTContext &Context) const;
2191
2192 /// Determine whether this initializer is initializing a base class.
2193 bool isBaseInitializer() const {
2194 return Initializee.is<TypeSourceInfo*>() && !IsDelegating;
2195 }
2196
2197 /// Determine whether this initializer is initializing a non-static
2198 /// data member.
2199 bool isMemberInitializer() const { return Initializee.is<FieldDecl*>(); }
2200
2201 bool isAnyMemberInitializer() const {
2202 return isMemberInitializer() || isIndirectMemberInitializer();
2203 }
2204
2205 bool isIndirectMemberInitializer() const {
2206 return Initializee.is<IndirectFieldDecl*>();
2207 }
2208
2209 /// Determine whether this initializer is an implicit initializer
2210 /// generated for a field with an initializer defined on the member
2211 /// declaration.
2212 ///
2213 /// In-class member initializers (also known as "non-static data member
2214 /// initializations", NSDMIs) were introduced in C++11.
2215 bool isInClassMemberInitializer() const {
2216 return Init->getStmtClass() == Stmt::CXXDefaultInitExprClass;
2217 }
2218
2219 /// Determine whether this initializer is creating a delegating
2220 /// constructor.
2221 bool isDelegatingInitializer() const {
2222 return Initializee.is<TypeSourceInfo*>() && IsDelegating;
2223 }
2224
2225 /// Determine whether this initializer is a pack expansion.
2226 bool isPackExpansion() const {
2227 return isBaseInitializer() && MemberOrEllipsisLocation.isValid();
2228 }
2229
2230 // For a pack expansion, returns the location of the ellipsis.
2231 SourceLocation getEllipsisLoc() const {
2232 assert(isPackExpansion() && "Initializer is not a pack expansion")((isPackExpansion() && "Initializer is not a pack expansion"
) ? static_cast<void> (0) : __assert_fail ("isPackExpansion() && \"Initializer is not a pack expansion\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/DeclCXX.h"
, 2232, __PRETTY_FUNCTION__))
;
2233 return MemberOrEllipsisLocation;
2234 }
2235
2236 /// If this is a base class initializer, returns the type of the
2237 /// base class with location information. Otherwise, returns an NULL
2238 /// type location.
2239 TypeLoc getBaseClassLoc() const;
2240
2241 /// If this is a base class initializer, returns the type of the base class.
2242 /// Otherwise, returns null.
2243 const Type *getBaseClass() const;
2244
2245 /// Returns whether the base is virtual or not.
2246 bool isBaseVirtual() const {
2247 assert(isBaseInitializer() && "Must call this on base initializer!")((isBaseInitializer() && "Must call this on base initializer!"
) ? static_cast<void> (0) : __assert_fail ("isBaseInitializer() && \"Must call this on base initializer!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/DeclCXX.h"
, 2247, __PRETTY_FUNCTION__))
;
2248
2249 return IsVirtual;
2250 }
2251
2252 /// Returns the declarator information for a base class or delegating
2253 /// initializer.
2254 TypeSourceInfo *getTypeSourceInfo() const {
2255 return Initializee.dyn_cast<TypeSourceInfo *>();
2256 }
2257
2258 /// If this is a member initializer, returns the declaration of the
2259 /// non-static data member being initialized. Otherwise, returns null.
2260 FieldDecl *getMember() const {
2261 if (isMemberInitializer())
2262 return Initializee.get<FieldDecl*>();
2263 return nullptr;
2264 }
2265
2266 FieldDecl *getAnyMember() const {
2267 if (isMemberInitializer())
2268 return Initializee.get<FieldDecl*>();
2269 if (isIndirectMemberInitializer())
2270 return Initializee.get<IndirectFieldDecl*>()->getAnonField();
2271 return nullptr;
2272 }
2273
2274 IndirectFieldDecl *getIndirectMember() const {
2275 if (isIndirectMemberInitializer())
2276 return Initializee.get<IndirectFieldDecl*>();
2277 return nullptr;
2278 }
2279
2280 SourceLocation getMemberLocation() const {
2281 return MemberOrEllipsisLocation;
2282 }
2283
2284 /// Determine the source location of the initializer.
2285 SourceLocation getSourceLocation() const;
2286
2287 /// Determine the source range covering the entire initializer.
2288 SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__));
2289
2290 /// Determine whether this initializer is explicitly written
2291 /// in the source code.
2292 bool isWritten() const { return IsWritten; }
2293
2294 /// Return the source position of the initializer, counting from 0.
2295 /// If the initializer was implicit, -1 is returned.
2296 int getSourceOrder() const {
2297 return IsWritten ? static_cast<int>(SourceOrder) : -1;
2298 }
2299
2300 /// Set the source order of this initializer.
2301 ///
2302 /// This can only be called once for each initializer; it cannot be called
2303 /// on an initializer having a positive number of (implicit) array indices.
2304 ///
2305 /// This assumes that the initializer was written in the source code, and
2306 /// ensures that isWritten() returns true.
2307 void setSourceOrder(int Pos) {
2308 assert(!IsWritten &&((!IsWritten && "setSourceOrder() used on implicit initializer"
) ? static_cast<void> (0) : __assert_fail ("!IsWritten && \"setSourceOrder() used on implicit initializer\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/DeclCXX.h"
, 2309, __PRETTY_FUNCTION__))
2309 "setSourceOrder() used on implicit initializer")((!IsWritten && "setSourceOrder() used on implicit initializer"
) ? static_cast<void> (0) : __assert_fail ("!IsWritten && \"setSourceOrder() used on implicit initializer\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/DeclCXX.h"
, 2309, __PRETTY_FUNCTION__))
;
2310 assert(SourceOrder == 0 &&((SourceOrder == 0 && "calling twice setSourceOrder() on the same initializer"
) ? static_cast<void> (0) : __assert_fail ("SourceOrder == 0 && \"calling twice setSourceOrder() on the same initializer\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/DeclCXX.h"
, 2311, __PRETTY_FUNCTION__))
2311 "calling twice setSourceOrder() on the same initializer")((SourceOrder == 0 && "calling twice setSourceOrder() on the same initializer"
) ? static_cast<void> (0) : __assert_fail ("SourceOrder == 0 && \"calling twice setSourceOrder() on the same initializer\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/DeclCXX.h"
, 2311, __PRETTY_FUNCTION__))
;
2312 assert(Pos >= 0 &&((Pos >= 0 && "setSourceOrder() used to make an initializer implicit"
) ? static_cast<void> (0) : __assert_fail ("Pos >= 0 && \"setSourceOrder() used to make an initializer implicit\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/DeclCXX.h"
, 2313, __PRETTY_FUNCTION__))
2313 "setSourceOrder() used to make an initializer implicit")((Pos >= 0 && "setSourceOrder() used to make an initializer implicit"
) ? static_cast<void> (0) : __assert_fail ("Pos >= 0 && \"setSourceOrder() used to make an initializer implicit\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/DeclCXX.h"
, 2313, __PRETTY_FUNCTION__))
;
2314 IsWritten = true;
2315 SourceOrder = static_cast<unsigned>(Pos);
2316 }
2317
2318 SourceLocation getLParenLoc() const { return LParenLoc; }
2319 SourceLocation getRParenLoc() const { return RParenLoc; }
2320
2321 /// Get the initializer.
2322 Expr *getInit() const { return static_cast<Expr *>(Init); }
2323};
2324
2325/// Description of a constructor that was inherited from a base class.
2326class InheritedConstructor {
2327 ConstructorUsingShadowDecl *Shadow = nullptr;
2328 CXXConstructorDecl *BaseCtor = nullptr;
2329
2330public:
2331 InheritedConstructor() = default;
2332 InheritedConstructor(ConstructorUsingShadowDecl *Shadow,
2333 CXXConstructorDecl *BaseCtor)
2334 : Shadow(Shadow), BaseCtor(BaseCtor) {}
2335
2336 explicit operator bool() const { return Shadow; }
2337
2338 ConstructorUsingShadowDecl *getShadowDecl() const { return Shadow; }
2339 CXXConstructorDecl *getConstructor() const { return BaseCtor; }
2340};
2341
2342/// Represents a C++ constructor within a class.
2343///
2344/// For example:
2345///
2346/// \code
2347/// class X {
2348/// public:
2349/// explicit X(int); // represented by a CXXConstructorDecl.
2350/// };
2351/// \endcode
2352class CXXConstructorDecl final
2353 : public CXXMethodDecl,
2354 private llvm::TrailingObjects<CXXConstructorDecl, InheritedConstructor,
2355 ExplicitSpecifier> {
2356 // This class stores some data in DeclContext::CXXConstructorDeclBits
2357 // to save some space. Use the provided accessors to access it.
2358
2359 /// \name Support for base and member initializers.
2360 /// \{
2361 /// The arguments used to initialize the base or member.
2362 LazyCXXCtorInitializersPtr CtorInitializers;
2363
2364 CXXConstructorDecl(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2365 const DeclarationNameInfo &NameInfo, QualType T,
2366 TypeSourceInfo *TInfo, ExplicitSpecifier ES, bool isInline,
2367 bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind,
2368 InheritedConstructor Inherited,
2369 Expr *TrailingRequiresClause);
2370
2371 void anchor() override;
2372
2373 size_t numTrailingObjects(OverloadToken<InheritedConstructor>) const {
2374 return CXXConstructorDeclBits.IsInheritingConstructor;
2375 }
2376 size_t numTrailingObjects(OverloadToken<ExplicitSpecifier>) const {
2377 return CXXConstructorDeclBits.HasTrailingExplicitSpecifier;
2378 }
2379
2380 ExplicitSpecifier getExplicitSpecifierInternal() const {
2381 if (CXXConstructorDeclBits.HasTrailingExplicitSpecifier)
2382 return *getTrailingObjects<ExplicitSpecifier>();
2383 return ExplicitSpecifier(
2384 nullptr, CXXConstructorDeclBits.IsSimpleExplicit
2385 ? ExplicitSpecKind::ResolvedTrue
2386 : ExplicitSpecKind::ResolvedFalse);
2387 }
2388
2389 void setExplicitSpecifier(ExplicitSpecifier ES) {
2390 assert((!ES.getExpr() ||(((!ES.getExpr() || CXXConstructorDeclBits.HasTrailingExplicitSpecifier
) && "cannot set this explicit specifier. no trail-allocated space for "
"explicit") ? static_cast<void> (0) : __assert_fail ("(!ES.getExpr() || CXXConstructorDeclBits.HasTrailingExplicitSpecifier) && \"cannot set this explicit specifier. no trail-allocated space for \" \"explicit\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/DeclCXX.h"
, 2393, __PRETTY_FUNCTION__))
2391 CXXConstructorDeclBits.HasTrailingExplicitSpecifier) &&(((!ES.getExpr() || CXXConstructorDeclBits.HasTrailingExplicitSpecifier
) && "cannot set this explicit specifier. no trail-allocated space for "
"explicit") ? static_cast<void> (0) : __assert_fail ("(!ES.getExpr() || CXXConstructorDeclBits.HasTrailingExplicitSpecifier) && \"cannot set this explicit specifier. no trail-allocated space for \" \"explicit\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/DeclCXX.h"
, 2393, __PRETTY_FUNCTION__))
2392 "cannot set this explicit specifier. no trail-allocated space for "(((!ES.getExpr() || CXXConstructorDeclBits.HasTrailingExplicitSpecifier
) && "cannot set this explicit specifier. no trail-allocated space for "
"explicit") ? static_cast<void> (0) : __assert_fail ("(!ES.getExpr() || CXXConstructorDeclBits.HasTrailingExplicitSpecifier) && \"cannot set this explicit specifier. no trail-allocated space for \" \"explicit\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/DeclCXX.h"
, 2393, __PRETTY_FUNCTION__))
2393 "explicit")(((!ES.getExpr() || CXXConstructorDeclBits.HasTrailingExplicitSpecifier
) && "cannot set this explicit specifier. no trail-allocated space for "
"explicit") ? static_cast<void> (0) : __assert_fail ("(!ES.getExpr() || CXXConstructorDeclBits.HasTrailingExplicitSpecifier) && \"cannot set this explicit specifier. no trail-allocated space for \" \"explicit\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/DeclCXX.h"
, 2393, __PRETTY_FUNCTION__))
;
2394 if (ES.getExpr())
2395 *getCanonicalDecl()->getTrailingObjects<ExplicitSpecifier>() = ES;
2396 else
2397 CXXConstructorDeclBits.IsSimpleExplicit = ES.isExplicit();
2398 }
2399
2400 enum TraillingAllocKind {
2401 TAKInheritsConstructor = 1,
2402 TAKHasTailExplicit = 1 << 1,
2403 };
2404
2405 uint64_t getTraillingAllocKind() const {
2406 return numTrailingObjects(OverloadToken<InheritedConstructor>()) |
2407 (numTrailingObjects(OverloadToken<ExplicitSpecifier>()) << 1);
2408 }
2409
2410public:
2411 friend class ASTDeclReader;
2412 friend class ASTDeclWriter;
2413 friend TrailingObjects;
2414
2415 static CXXConstructorDecl *CreateDeserialized(ASTContext &C, unsigned ID,
2416 uint64_t AllocKind);
2417 static CXXConstructorDecl *
2418 Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2419 const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo,
2420 ExplicitSpecifier ES, bool isInline, bool isImplicitlyDeclared,
2421 ConstexprSpecKind ConstexprKind,
2422 InheritedConstructor Inherited = InheritedConstructor(),
2423 Expr *TrailingRequiresClause = nullptr);
2424
2425 ExplicitSpecifier getExplicitSpecifier() {
2426 return getCanonicalDecl()->getExplicitSpecifierInternal();
2427 }
2428 const ExplicitSpecifier getExplicitSpecifier() const {
2429 return getCanonicalDecl()->getExplicitSpecifierInternal();
2430 }
2431
2432 /// Return true if the declartion is already resolved to be explicit.
2433 bool isExplicit() const { return getExplicitSpecifier().isExplicit(); }
2434
2435 /// Iterates through the member/base initializer list.
2436 using init_iterator = CXXCtorInitializer **;
2437
2438 /// Iterates through the member/base initializer list.
2439 using init_const_iterator = CXXCtorInitializer *const *;
2440
2441 using init_range = llvm::iterator_range<init_iterator>;
2442 using init_const_range = llvm::iterator_range<init_const_iterator>;
2443
2444 init_range inits() { return init_range(init_begin(), init_end()); }
2445 init_const_range inits() const {
2446 return init_const_range(init_begin(), init_end());
2447 }
2448
2449 /// Retrieve an iterator to the first initializer.
2450 init_iterator init_begin() {
2451 const auto *ConstThis = this;
2452 return const_cast<init_iterator>(ConstThis->init_begin());
2453 }
2454
2455 /// Retrieve an iterator to the first init