Bug Summary

File:tools/clang/lib/Sema/SemaTemplateInstantiate.cpp
Warning:line 849, 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 -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-10/lib/clang/10.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-10~svn374877/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include -I /build/llvm-toolchain-snapshot-10~svn374877/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-10~svn374877/build-llvm/include -I /build/llvm-toolchain-snapshot-10~svn374877/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~svn374877/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~svn374877=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2019-10-15-233810-7101-1 -x c++ /build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp

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

/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/ASTLambda.h

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

/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/DeclCXX.h

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