Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

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

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

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

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

1//===--- Sema.h - Semantic Analysis & AST Building --------------*- 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// This file defines the Sema class, which performs semantic analysis and
10// builds ASTs.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_SEMA_SEMA_H
15#define LLVM_CLANG_SEMA_SEMA_H
16
17#include "clang/AST/Attr.h"
18#include "clang/AST/Availability.h"
19#include "clang/AST/ComparisonCategories.h"
20#include "clang/AST/DeclTemplate.h"
21#include "clang/AST/DeclarationName.h"
22#include "clang/AST/Expr.h"
23#include "clang/AST/ExprCXX.h"
24#include "clang/AST/ExprObjC.h"
25#include "clang/AST/ExternalASTSource.h"
26#include "clang/AST/LocInfoType.h"
27#include "clang/AST/MangleNumberingContext.h"
28#include "clang/AST/NSAPI.h"
29#include "clang/AST/PrettyPrinter.h"
30#include "clang/AST/StmtCXX.h"
31#include "clang/AST/TypeLoc.h"
32#include "clang/AST/TypeOrdering.h"
33#include "clang/Basic/ExpressionTraits.h"
34#include "clang/Basic/Module.h"
35#include "clang/Basic/OpenMPKinds.h"
36#include "clang/Basic/PragmaKinds.h"
37#include "clang/Basic/Specifiers.h"
38#include "clang/Basic/TemplateKinds.h"
39#include "clang/Basic/TypeTraits.h"
40#include "clang/Sema/AnalysisBasedWarnings.h"
41#include "clang/Sema/CleanupInfo.h"
42#include "clang/Sema/DeclSpec.h"
43#include "clang/Sema/ExternalSemaSource.h"
44#include "clang/Sema/IdentifierResolver.h"
45#include "clang/Sema/ObjCMethodList.h"
46#include "clang/Sema/Ownership.h"
47#include "clang/Sema/Scope.h"
48#include "clang/Sema/TypoCorrection.h"
49#include "clang/Sema/Weak.h"
50#include "llvm/ADT/ArrayRef.h"
51#include "llvm/ADT/Optional.h"
52#include "llvm/ADT/SetVector.h"
53#include "llvm/ADT/SmallBitVector.h"
54#include "llvm/ADT/SmallPtrSet.h"
55#include "llvm/ADT/SmallVector.h"
56#include "llvm/ADT/TinyPtrVector.h"
57#include <deque>
58#include <memory>
59#include <string>
60#include <tuple>
61#include <vector>
62
63namespace llvm {
64 class APSInt;
65 template <typename ValueT> struct DenseMapInfo;
66 template <typename ValueT, typename ValueInfoT> class DenseSet;
67 class SmallBitVector;
68 struct InlineAsmIdentifierInfo;
69}
70
71namespace clang {
72 class ADLResult;
73 class ASTConsumer;
74 class ASTContext;
75 class ASTMutationListener;
76 class ASTReader;
77 class ASTWriter;
78 class ArrayType;
79 class ParsedAttr;
80 class BindingDecl;
81 class BlockDecl;
82 class CapturedDecl;
83 class CXXBasePath;
84 class CXXBasePaths;
85 class CXXBindTemporaryExpr;
86 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
87 class CXXConstructorDecl;
88 class CXXConversionDecl;
89 class CXXDeleteExpr;
90 class CXXDestructorDecl;
91 class CXXFieldCollector;
92 class CXXMemberCallExpr;
93 class CXXMethodDecl;
94 class CXXScopeSpec;
95 class CXXTemporary;
96 class CXXTryStmt;
97 class CallExpr;
98 class ClassTemplateDecl;
99 class ClassTemplatePartialSpecializationDecl;
100 class ClassTemplateSpecializationDecl;
101 class VarTemplatePartialSpecializationDecl;
102 class CodeCompleteConsumer;
103 class CodeCompletionAllocator;
104 class CodeCompletionTUInfo;
105 class CodeCompletionResult;
106 class CoroutineBodyStmt;
107 class Decl;
108 class DeclAccessPair;
109 class DeclContext;
110 class DeclRefExpr;
111 class DeclaratorDecl;
112 class DeducedTemplateArgument;
113 class DependentDiagnostic;
114 class DesignatedInitExpr;
115 class Designation;
116 class EnableIfAttr;
117 class EnumConstantDecl;
118 class Expr;
119 class ExtVectorType;
120 class FormatAttr;
121 class FriendDecl;
122 class FunctionDecl;
123 class FunctionProtoType;
124 class FunctionTemplateDecl;
125 class ImplicitConversionSequence;
126 typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList;
127 class InitListExpr;
128 class InitializationKind;
129 class InitializationSequence;
130 class InitializedEntity;
131 class IntegerLiteral;
132 class LabelStmt;
133 class LambdaExpr;
134 class LangOptions;
135 class LocalInstantiationScope;
136 class LookupResult;
137 class MacroInfo;
138 typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath;
139 class ModuleLoader;
140 class MultiLevelTemplateArgumentList;
141 class NamedDecl;
142 class ObjCCategoryDecl;
143 class ObjCCategoryImplDecl;
144 class ObjCCompatibleAliasDecl;
145 class ObjCContainerDecl;
146 class ObjCImplDecl;
147 class ObjCImplementationDecl;
148 class ObjCInterfaceDecl;
149 class ObjCIvarDecl;
150 template <class T> class ObjCList;
151 class ObjCMessageExpr;
152 class ObjCMethodDecl;
153 class ObjCPropertyDecl;
154 class ObjCProtocolDecl;
155 class OMPThreadPrivateDecl;
156 class OMPRequiresDecl;
157 class OMPDeclareReductionDecl;
158 class OMPDeclareSimdDecl;
159 class OMPClause;
160 struct OMPVarListLocTy;
161 struct OverloadCandidate;
162 enum class OverloadCandidateParamOrder : char;
163 enum OverloadCandidateRewriteKind : unsigned;
164 class OverloadCandidateSet;
165 class OverloadExpr;
166 class ParenListExpr;
167 class ParmVarDecl;
168 class Preprocessor;
169 class PseudoDestructorTypeStorage;
170 class PseudoObjectExpr;
171 class QualType;
172 class StandardConversionSequence;
173 class Stmt;
174 class StringLiteral;
175 class SwitchStmt;
176 class TemplateArgument;
177 class TemplateArgumentList;
178 class TemplateArgumentLoc;
179 class TemplateDecl;
180 class TemplateInstantiationCallback;
181 class TemplateParameterList;
182 class TemplatePartialOrderingContext;
183 class TemplateTemplateParmDecl;
184 class Token;
185 class TypeAliasDecl;
186 class TypedefDecl;
187 class TypedefNameDecl;
188 class TypeLoc;
189 class TypoCorrectionConsumer;
190 class UnqualifiedId;
191 class UnresolvedLookupExpr;
192 class UnresolvedMemberExpr;
193 class UnresolvedSetImpl;
194 class UnresolvedSetIterator;
195 class UsingDecl;
196 class UsingShadowDecl;
197 class ValueDecl;
198 class VarDecl;
199 class VarTemplateSpecializationDecl;
200 class VisibilityAttr;
201 class VisibleDeclConsumer;
202 class IndirectFieldDecl;
203 struct DeductionFailureInfo;
204 class TemplateSpecCandidateSet;
205
206namespace sema {
207 class AccessedEntity;
208 class BlockScopeInfo;
209 class Capture;
210 class CapturedRegionScopeInfo;
211 class CapturingScopeInfo;
212 class CompoundScopeInfo;
213 class DelayedDiagnostic;
214 class DelayedDiagnosticPool;
215 class FunctionScopeInfo;
216 class LambdaScopeInfo;
217 class PossiblyUnreachableDiag;
218 class SemaPPCallbacks;
219 class TemplateDeductionInfo;
220}
221
222namespace threadSafety {
223 class BeforeSet;
224 void threadSafetyCleanup(BeforeSet* Cache);
225}
226
227// FIXME: No way to easily map from TemplateTypeParmTypes to
228// TemplateTypeParmDecls, so we have this horrible PointerUnion.
229typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
230 SourceLocation> UnexpandedParameterPack;
231
232/// Describes whether we've seen any nullability information for the given
233/// file.
234struct FileNullability {
235 /// The first pointer declarator (of any pointer kind) in the file that does
236 /// not have a corresponding nullability annotation.
237 SourceLocation PointerLoc;
238
239 /// The end location for the first pointer declarator in the file. Used for
240 /// placing fix-its.
241 SourceLocation PointerEndLoc;
242
243 /// Which kind of pointer declarator we saw.
244 uint8_t PointerKind;
245
246 /// Whether we saw any type nullability annotations in the given file.
247 bool SawTypeNullability = false;
248};
249
250/// A mapping from file IDs to a record of whether we've seen nullability
251/// information in that file.
252class FileNullabilityMap {
253 /// A mapping from file IDs to the nullability information for each file ID.
254 llvm::DenseMap<FileID, FileNullability> Map;
255
256 /// A single-element cache based on the file ID.
257 struct {
258 FileID File;
259 FileNullability Nullability;
260 } Cache;
261
262public:
263 FileNullability &operator[](FileID file) {
264 // Check the single-element cache.
265 if (file == Cache.File)
266 return Cache.Nullability;
267
268 // It's not in the single-element cache; flush the cache if we have one.
269 if (!Cache.File.isInvalid()) {
270 Map[Cache.File] = Cache.Nullability;
271 }
272
273 // Pull this entry into the cache.
274 Cache.File = file;
275 Cache.Nullability = Map[file];
276 return Cache.Nullability;
277 }
278};
279
280/// Keeps track of expected type during expression parsing. The type is tied to
281/// a particular token, all functions that update or consume the type take a
282/// start location of the token they are looking at as a parameter. This allows
283/// to avoid updating the type on hot paths in the parser.
284class PreferredTypeBuilder {
285public:
286 PreferredTypeBuilder() = default;
287 explicit PreferredTypeBuilder(QualType Type) : Type(Type) {}
288
289 void enterCondition(Sema &S, SourceLocation Tok);
290 void enterReturn(Sema &S, SourceLocation Tok);
291 void enterVariableInit(SourceLocation Tok, Decl *D);
292 /// Computing a type for the function argument may require running
293 /// overloading, so we postpone its computation until it is actually needed.
294 ///
295 /// Clients should be very careful when using this funciton, as it stores a
296 /// function_ref, clients should make sure all calls to get() with the same
297 /// location happen while function_ref is alive.
298 void enterFunctionArgument(SourceLocation Tok,
299 llvm::function_ref<QualType()> ComputeType);
300
301 void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc);
302 void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind,
303 SourceLocation OpLoc);
304 void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op);
305 void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base);
306 void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS);
307 /// Handles all type casts, including C-style cast, C++ casts, etc.
308 void enterTypeCast(SourceLocation Tok, QualType CastType);
309
310 QualType get(SourceLocation Tok) const {
311 if (Tok != ExpectedLoc)
312 return QualType();
313 if (!Type.isNull())
314 return Type;
315 if (ComputeType)
316 return ComputeType();
317 return QualType();
318 }
319
320private:
321 /// Start position of a token for which we store expected type.
322 SourceLocation ExpectedLoc;
323 /// Expected type for a token starting at ExpectedLoc.
324 QualType Type;
325 /// A function to compute expected type at ExpectedLoc. It is only considered
326 /// if Type is null.
327 llvm::function_ref<QualType()> ComputeType;
328};
329
330/// Sema - This implements semantic analysis and AST building for C.
331class Sema {
332 Sema(const Sema &) = delete;
333 void operator=(const Sema &) = delete;
334
335 ///Source of additional semantic information.
336 ExternalSemaSource *ExternalSource;
337
338 ///Whether Sema has generated a multiplexer and has to delete it.
339 bool isMultiplexExternalSource;
340
341 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
342
343 bool isVisibleSlow(const NamedDecl *D);
344
345 /// Determine whether two declarations should be linked together, given that
346 /// the old declaration might not be visible and the new declaration might
347 /// not have external linkage.
348 bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
349 const NamedDecl *New) {
350 if (isVisible(Old))
351 return true;
352 // See comment in below overload for why it's safe to compute the linkage
353 // of the new declaration here.
354 if (New->isExternallyDeclarable()) {
355 assert(Old->isExternallyDeclarable() &&((Old->isExternallyDeclarable() && "should not have found a non-externally-declarable previous decl"
) ? static_cast<void> (0) : __assert_fail ("Old->isExternallyDeclarable() && \"should not have found a non-externally-declarable previous decl\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 356, __PRETTY_FUNCTION__))
356 "should not have found a non-externally-declarable previous decl")((Old->isExternallyDeclarable() && "should not have found a non-externally-declarable previous decl"
) ? static_cast<void> (0) : __assert_fail ("Old->isExternallyDeclarable() && \"should not have found a non-externally-declarable previous decl\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 356, __PRETTY_FUNCTION__))
;
357 return true;
358 }
359 return false;
360 }
361 bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
362
363 void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
364 QualType ResultTy,
365 ArrayRef<QualType> Args);
366
367public:
368 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
369 typedef OpaquePtr<TemplateName> TemplateTy;
370 typedef OpaquePtr<QualType> TypeTy;
371
372 OpenCLOptions OpenCLFeatures;
373 FPOptions FPFeatures;
374
375 const LangOptions &LangOpts;
376 Preprocessor &PP;
377 ASTContext &Context;
378 ASTConsumer &Consumer;
379 DiagnosticsEngine &Diags;
380 SourceManager &SourceMgr;
381
382 /// Flag indicating whether or not to collect detailed statistics.
383 bool CollectStats;
384
385 /// Code-completion consumer.
386 CodeCompleteConsumer *CodeCompleter;
387
388 /// CurContext - This is the current declaration context of parsing.
389 DeclContext *CurContext;
390
391 /// Generally null except when we temporarily switch decl contexts,
392 /// like in \see ActOnObjCTemporaryExitContainerContext.
393 DeclContext *OriginalLexicalContext;
394
395 /// VAListTagName - The declaration name corresponding to __va_list_tag.
396 /// This is used as part of a hack to omit that class from ADL results.
397 DeclarationName VAListTagName;
398
399 bool MSStructPragmaOn; // True when \#pragma ms_struct on
400
401 /// Controls member pointer representation format under the MS ABI.
402 LangOptions::PragmaMSPointersToMembersKind
403 MSPointerToMemberRepresentationMethod;
404
405 /// Stack of active SEH __finally scopes. Can be empty.
406 SmallVector<Scope*, 2> CurrentSEHFinally;
407
408 /// Source location for newly created implicit MSInheritanceAttrs
409 SourceLocation ImplicitMSInheritanceAttrLoc;
410
411 /// Holds TypoExprs that are created from `createDelayedTypo`. This is used by
412 /// `TransformTypos` in order to keep track of any TypoExprs that are created
413 /// recursively during typo correction and wipe them away if the correction
414 /// fails.
415 llvm::SmallVector<TypoExpr *, 2> TypoExprs;
416
417 /// pragma clang section kind
418 enum PragmaClangSectionKind {
419 PCSK_Invalid = 0,
420 PCSK_BSS = 1,
421 PCSK_Data = 2,
422 PCSK_Rodata = 3,
423 PCSK_Text = 4,
424 PCSK_Relro = 5
425 };
426
427 enum PragmaClangSectionAction {
428 PCSA_Set = 0,
429 PCSA_Clear = 1
430 };
431
432 struct PragmaClangSection {
433 std::string SectionName;
434 bool Valid = false;
435 SourceLocation PragmaLocation;
436
437 void Act(SourceLocation PragmaLocation,
438 PragmaClangSectionAction Action,
439 StringLiteral* Name);
440 };
441
442 PragmaClangSection PragmaClangBSSSection;
443 PragmaClangSection PragmaClangDataSection;
444 PragmaClangSection PragmaClangRodataSection;
445 PragmaClangSection PragmaClangRelroSection;
446 PragmaClangSection PragmaClangTextSection;
447
448 enum PragmaMsStackAction {
449 PSK_Reset = 0x0, // #pragma ()
450 PSK_Set = 0x1, // #pragma (value)
451 PSK_Push = 0x2, // #pragma (push[, id])
452 PSK_Pop = 0x4, // #pragma (pop[, id])
453 PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
454 PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
455 PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
456 };
457
458 template<typename ValueType>
459 struct PragmaStack {
460 struct Slot {
461 llvm::StringRef StackSlotLabel;
462 ValueType Value;
463 SourceLocation PragmaLocation;
464 SourceLocation PragmaPushLocation;
465 Slot(llvm::StringRef StackSlotLabel, ValueType Value,
466 SourceLocation PragmaLocation, SourceLocation PragmaPushLocation)
467 : StackSlotLabel(StackSlotLabel), Value(Value),
468 PragmaLocation(PragmaLocation),
469 PragmaPushLocation(PragmaPushLocation) {}
470 };
471 void Act(SourceLocation PragmaLocation,
472 PragmaMsStackAction Action,
473 llvm::StringRef StackSlotLabel,
474 ValueType Value);
475
476 // MSVC seems to add artificial slots to #pragma stacks on entering a C++
477 // method body to restore the stacks on exit, so it works like this:
478 //
479 // struct S {
480 // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
481 // void Method {}
482 // #pragma <name>(pop, InternalPragmaSlot)
483 // };
484 //
485 // It works even with #pragma vtordisp, although MSVC doesn't support
486 // #pragma vtordisp(push [, id], n)
487 // syntax.
488 //
489 // Push / pop a named sentinel slot.
490 void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
491 assert((Action == PSK_Push || Action == PSK_Pop) &&(((Action == PSK_Push || Action == PSK_Pop) && "Can only push / pop #pragma stack sentinels!"
) ? static_cast<void> (0) : __assert_fail ("(Action == PSK_Push || Action == PSK_Pop) && \"Can only push / pop #pragma stack sentinels!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 492, __PRETTY_FUNCTION__))
492 "Can only push / pop #pragma stack sentinels!")(((Action == PSK_Push || Action == PSK_Pop) && "Can only push / pop #pragma stack sentinels!"
) ? static_cast<void> (0) : __assert_fail ("(Action == PSK_Push || Action == PSK_Pop) && \"Can only push / pop #pragma stack sentinels!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 492, __PRETTY_FUNCTION__))
;
493 Act(CurrentPragmaLocation, Action, Label, CurrentValue);
494 }
495
496 // Constructors.
497 explicit PragmaStack(const ValueType &Default)
498 : DefaultValue(Default), CurrentValue(Default) {}
499
500 bool hasValue() const { return CurrentValue != DefaultValue; }
501
502 SmallVector<Slot, 2> Stack;
503 ValueType DefaultValue; // Value used for PSK_Reset action.
504 ValueType CurrentValue;
505 SourceLocation CurrentPragmaLocation;
506 };
507 // FIXME: We should serialize / deserialize these if they occur in a PCH (but
508 // we shouldn't do so if they're in a module).
509
510 /// Whether to insert vtordisps prior to virtual bases in the Microsoft
511 /// C++ ABI. Possible values are 0, 1, and 2, which mean:
512 ///
513 /// 0: Suppress all vtordisps
514 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
515 /// structors
516 /// 2: Always insert vtordisps to support RTTI on partially constructed
517 /// objects
518 PragmaStack<MSVtorDispAttr::Mode> VtorDispStack;
519 // #pragma pack.
520 // Sentinel to represent when the stack is set to mac68k alignment.
521 static const unsigned kMac68kAlignmentSentinel = ~0U;
522 PragmaStack<unsigned> PackStack;
523 // The current #pragma pack values and locations at each #include.
524 struct PackIncludeState {
525 unsigned CurrentValue;
526 SourceLocation CurrentPragmaLocation;
527 bool HasNonDefaultValue, ShouldWarnOnInclude;
528 };
529 SmallVector<PackIncludeState, 8> PackIncludeStack;
530 // Segment #pragmas.
531 PragmaStack<StringLiteral *> DataSegStack;
532 PragmaStack<StringLiteral *> BSSSegStack;
533 PragmaStack<StringLiteral *> ConstSegStack;
534 PragmaStack<StringLiteral *> CodeSegStack;
535
536 // RAII object to push / pop sentinel slots for all MS #pragma stacks.
537 // Actions should be performed only if we enter / exit a C++ method body.
538 class PragmaStackSentinelRAII {
539 public:
540 PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
541 ~PragmaStackSentinelRAII();
542
543 private:
544 Sema &S;
545 StringRef SlotLabel;
546 bool ShouldAct;
547 };
548
549 /// A mapping that describes the nullability we've seen in each header file.
550 FileNullabilityMap NullabilityMap;
551
552 /// Last section used with #pragma init_seg.
553 StringLiteral *CurInitSeg;
554 SourceLocation CurInitSegLoc;
555
556 /// VisContext - Manages the stack for \#pragma GCC visibility.
557 void *VisContext; // Really a "PragmaVisStack*"
558
559 /// This an attribute introduced by \#pragma clang attribute.
560 struct PragmaAttributeEntry {
561 SourceLocation Loc;
562 ParsedAttr *Attribute;
563 SmallVector<attr::SubjectMatchRule, 4> MatchRules;
564 bool IsUsed;
565 };
566
567 /// A push'd group of PragmaAttributeEntries.
568 struct PragmaAttributeGroup {
569 /// The location of the push attribute.
570 SourceLocation Loc;
571 /// The namespace of this push group.
572 const IdentifierInfo *Namespace;
573 SmallVector<PragmaAttributeEntry, 2> Entries;
574 };
575
576 SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack;
577
578 /// The declaration that is currently receiving an attribute from the
579 /// #pragma attribute stack.
580 const Decl *PragmaAttributeCurrentTargetDecl;
581
582 /// This represents the last location of a "#pragma clang optimize off"
583 /// directive if such a directive has not been closed by an "on" yet. If
584 /// optimizations are currently "on", this is set to an invalid location.
585 SourceLocation OptimizeOffPragmaLocation;
586
587 /// Flag indicating if Sema is building a recovery call expression.
588 ///
589 /// This flag is used to avoid building recovery call expressions
590 /// if Sema is already doing so, which would cause infinite recursions.
591 bool IsBuildingRecoveryCallExpr;
592
593 /// Used to control the generation of ExprWithCleanups.
594 CleanupInfo Cleanup;
595
596 /// ExprCleanupObjects - This is the stack of objects requiring
597 /// cleanup that are created by the current full expression. The
598 /// element type here is ExprWithCleanups::Object.
599 SmallVector<BlockDecl*, 8> ExprCleanupObjects;
600
601 /// Store a set of either DeclRefExprs or MemberExprs that contain a reference
602 /// to a variable (constant) that may or may not be odr-used in this Expr, and
603 /// we won't know until all lvalue-to-rvalue and discarded value conversions
604 /// have been applied to all subexpressions of the enclosing full expression.
605 /// This is cleared at the end of each full expression.
606 using MaybeODRUseExprSet = llvm::SmallPtrSet<Expr *, 2>;
607 MaybeODRUseExprSet MaybeODRUseExprs;
608
609 std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope;
610
611 /// Stack containing information about each of the nested
612 /// function, block, and method scopes that are currently active.
613 SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
614
615 typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
616 &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
617 ExtVectorDeclsType;
618
619 /// ExtVectorDecls - This is a list all the extended vector types. This allows
620 /// us to associate a raw vector type with one of the ext_vector type names.
621 /// This is only necessary for issuing pretty diagnostics.
622 ExtVectorDeclsType ExtVectorDecls;
623
624 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
625 std::unique_ptr<CXXFieldCollector> FieldCollector;
626
627 typedef llvm::SmallSetVector<NamedDecl *, 16> NamedDeclSetType;
628
629 /// Set containing all declared private fields that are not used.
630 NamedDeclSetType UnusedPrivateFields;
631
632 /// Set containing all typedefs that are likely unused.
633 llvm::SmallSetVector<const TypedefNameDecl *, 4>
634 UnusedLocalTypedefNameCandidates;
635
636 /// Delete-expressions to be analyzed at the end of translation unit
637 ///
638 /// This list contains class members, and locations of delete-expressions
639 /// that could not be proven as to whether they mismatch with new-expression
640 /// used in initializer of the field.
641 typedef std::pair<SourceLocation, bool> DeleteExprLoc;
642 typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
643 llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
644
645 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
646
647 /// PureVirtualClassDiagSet - a set of class declarations which we have
648 /// emitted a list of pure virtual functions. Used to prevent emitting the
649 /// same list more than once.
650 std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
651
652 /// ParsingInitForAutoVars - a set of declarations with auto types for which
653 /// we are currently parsing the initializer.
654 llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
655
656 /// Look for a locally scoped extern "C" declaration by the given name.
657 NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
658
659 typedef LazyVector<VarDecl *, ExternalSemaSource,
660 &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
661 TentativeDefinitionsType;
662
663 /// All the tentative definitions encountered in the TU.
664 TentativeDefinitionsType TentativeDefinitions;
665
666 typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
667 &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
668 UnusedFileScopedDeclsType;
669
670 /// The set of file scoped decls seen so far that have not been used
671 /// and must warn if not used. Only contains the first declaration.
672 UnusedFileScopedDeclsType UnusedFileScopedDecls;
673
674 typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
675 &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
676 DelegatingCtorDeclsType;
677
678 /// All the delegating constructors seen so far in the file, used for
679 /// cycle detection at the end of the TU.
680 DelegatingCtorDeclsType DelegatingCtorDecls;
681
682 /// All the overriding functions seen during a class definition
683 /// that had their exception spec checks delayed, plus the overridden
684 /// function.
685 SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2>
686 DelayedOverridingExceptionSpecChecks;
687
688 /// All the function redeclarations seen during a class definition that had
689 /// their exception spec checks delayed, plus the prior declaration they
690 /// should be checked against. Except during error recovery, the new decl
691 /// should always be a friend declaration, as that's the only valid way to
692 /// redeclare a special member before its class is complete.
693 SmallVector<std::pair<FunctionDecl*, FunctionDecl*>, 2>
694 DelayedEquivalentExceptionSpecChecks;
695
696 typedef llvm::MapVector<const FunctionDecl *,
697 std::unique_ptr<LateParsedTemplate>>
698 LateParsedTemplateMapT;
699 LateParsedTemplateMapT LateParsedTemplateMap;
700
701 /// Callback to the parser to parse templated functions when needed.
702 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
703 typedef void LateTemplateParserCleanupCB(void *P);
704 LateTemplateParserCB *LateTemplateParser;
705 LateTemplateParserCleanupCB *LateTemplateParserCleanup;
706 void *OpaqueParser;
707
708 void SetLateTemplateParser(LateTemplateParserCB *LTP,
709 LateTemplateParserCleanupCB *LTPCleanup,
710 void *P) {
711 LateTemplateParser = LTP;
712 LateTemplateParserCleanup = LTPCleanup;
713 OpaqueParser = P;
714 }
715
716 class DelayedDiagnostics;
717
718 class DelayedDiagnosticsState {
719 sema::DelayedDiagnosticPool *SavedPool;
720 friend class Sema::DelayedDiagnostics;
721 };
722 typedef DelayedDiagnosticsState ParsingDeclState;
723 typedef DelayedDiagnosticsState ProcessingContextState;
724
725 /// A class which encapsulates the logic for delaying diagnostics
726 /// during parsing and other processing.
727 class DelayedDiagnostics {
728 /// The current pool of diagnostics into which delayed
729 /// diagnostics should go.
730 sema::DelayedDiagnosticPool *CurPool;
731
732 public:
733 DelayedDiagnostics() : CurPool(nullptr) {}
734
735 /// Adds a delayed diagnostic.
736 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
737
738 /// Determines whether diagnostics should be delayed.
739 bool shouldDelayDiagnostics() { return CurPool != nullptr; }
740
741 /// Returns the current delayed-diagnostics pool.
742 sema::DelayedDiagnosticPool *getCurrentPool() const {
743 return CurPool;
744 }
745
746 /// Enter a new scope. Access and deprecation diagnostics will be
747 /// collected in this pool.
748 DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
749 DelayedDiagnosticsState state;
750 state.SavedPool = CurPool;
751 CurPool = &pool;
752 return state;
753 }
754
755 /// Leave a delayed-diagnostic state that was previously pushed.
756 /// Do not emit any of the diagnostics. This is performed as part
757 /// of the bookkeeping of popping a pool "properly".
758 void popWithoutEmitting(DelayedDiagnosticsState state) {
759 CurPool = state.SavedPool;
760 }
761
762 /// Enter a new scope where access and deprecation diagnostics are
763 /// not delayed.
764 DelayedDiagnosticsState pushUndelayed() {
765 DelayedDiagnosticsState state;
766 state.SavedPool = CurPool;
767 CurPool = nullptr;
768 return state;
769 }
770
771 /// Undo a previous pushUndelayed().
772 void popUndelayed(DelayedDiagnosticsState state) {
773 assert(CurPool == nullptr)((CurPool == nullptr) ? static_cast<void> (0) : __assert_fail
("CurPool == nullptr", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 773, __PRETTY_FUNCTION__))
;
774 CurPool = state.SavedPool;
775 }
776 } DelayedDiagnostics;
777
778 /// A RAII object to temporarily push a declaration context.
779 class ContextRAII {
780 private:
781 Sema &S;
782 DeclContext *SavedContext;
783 ProcessingContextState SavedContextState;
784 QualType SavedCXXThisTypeOverride;
785
786 public:
787 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
788 : S(S), SavedContext(S.CurContext),
789 SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
790 SavedCXXThisTypeOverride(S.CXXThisTypeOverride)
791 {
792 assert(ContextToPush && "pushing null context")((ContextToPush && "pushing null context") ? static_cast
<void> (0) : __assert_fail ("ContextToPush && \"pushing null context\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 792, __PRETTY_FUNCTION__))
;
793 S.CurContext = ContextToPush;
794 if (NewThisContext)
795 S.CXXThisTypeOverride = QualType();
796 }
797
798 void pop() {
799 if (!SavedContext) return;
800 S.CurContext = SavedContext;
801 S.DelayedDiagnostics.popUndelayed(SavedContextState);
802 S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
803 SavedContext = nullptr;
804 }
805
806 ~ContextRAII() {
807 pop();
808 }
809 };
810
811 /// Used to change context to isConstantEvaluated without pushing a heavy
812 /// ExpressionEvaluationContextRecord object.
813 bool isConstantEvaluatedOverride;
814
815 bool isConstantEvaluated() {
816 return ExprEvalContexts.back().isConstantEvaluated() ||
817 isConstantEvaluatedOverride;
818 }
819
820 /// RAII object to handle the state changes required to synthesize
821 /// a function body.
822 class SynthesizedFunctionScope {
823 Sema &S;
824 Sema::ContextRAII SavedContext;
825 bool PushedCodeSynthesisContext = false;
826
827 public:
828 SynthesizedFunctionScope(Sema &S, DeclContext *DC)
829 : S(S), SavedContext(S, DC) {
830 S.PushFunctionScope();
831 S.PushExpressionEvaluationContext(
832 Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
833 if (auto *FD = dyn_cast<FunctionDecl>(DC))
834 FD->setWillHaveBody(true);
835 else
836 assert(isa<ObjCMethodDecl>(DC))((isa<ObjCMethodDecl>(DC)) ? static_cast<void> (0
) : __assert_fail ("isa<ObjCMethodDecl>(DC)", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 836, __PRETTY_FUNCTION__))
;
837 }
838
839 void addContextNote(SourceLocation UseLoc) {
840 assert(!PushedCodeSynthesisContext)((!PushedCodeSynthesisContext) ? static_cast<void> (0) :
__assert_fail ("!PushedCodeSynthesisContext", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 840, __PRETTY_FUNCTION__))
;
841
842 Sema::CodeSynthesisContext Ctx;
843 Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction;
844 Ctx.PointOfInstantiation = UseLoc;
845 Ctx.Entity = cast<Decl>(S.CurContext);
846 S.pushCodeSynthesisContext(Ctx);
847
848 PushedCodeSynthesisContext = true;
849 }
850
851 ~SynthesizedFunctionScope() {
852 if (PushedCodeSynthesisContext)
853 S.popCodeSynthesisContext();
854 if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext))
855 FD->setWillHaveBody(false);
856 S.PopExpressionEvaluationContext();
857 S.PopFunctionScopeInfo();
858 }
859 };
860
861 /// WeakUndeclaredIdentifiers - Identifiers contained in
862 /// \#pragma weak before declared. rare. may alias another
863 /// identifier, declared or undeclared
864 llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers;
865
866 /// ExtnameUndeclaredIdentifiers - Identifiers contained in
867 /// \#pragma redefine_extname before declared. Used in Solaris system headers
868 /// to define functions that occur in multiple standards to call the version
869 /// in the currently selected standard.
870 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
871
872
873 /// Load weak undeclared identifiers from the external source.
874 void LoadExternalWeakUndeclaredIdentifiers();
875
876 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
877 /// \#pragma weak during processing of other Decls.
878 /// I couldn't figure out a clean way to generate these in-line, so
879 /// we store them here and handle separately -- which is a hack.
880 /// It would be best to refactor this.
881 SmallVector<Decl*,2> WeakTopLevelDecl;
882
883 IdentifierResolver IdResolver;
884
885 /// Translation Unit Scope - useful to Objective-C actions that need
886 /// to lookup file scope declarations in the "ordinary" C decl namespace.
887 /// For example, user-defined classes, built-in "id" type, etc.
888 Scope *TUScope;
889
890 /// The C++ "std" namespace, where the standard library resides.
891 LazyDeclPtr StdNamespace;
892
893 /// The C++ "std::bad_alloc" class, which is defined by the C++
894 /// standard library.
895 LazyDeclPtr StdBadAlloc;
896
897 /// The C++ "std::align_val_t" enum class, which is defined by the C++
898 /// standard library.
899 LazyDeclPtr StdAlignValT;
900
901 /// The C++ "std::experimental" namespace, where the experimental parts
902 /// of the standard library resides.
903 NamespaceDecl *StdExperimentalNamespaceCache;
904
905 /// The C++ "std::initializer_list" template, which is defined in
906 /// \<initializer_list>.
907 ClassTemplateDecl *StdInitializerList;
908
909 /// The C++ "std::coroutine_traits" template, which is defined in
910 /// \<coroutine_traits>
911 ClassTemplateDecl *StdCoroutineTraitsCache;
912
913 /// The C++ "type_info" declaration, which is defined in \<typeinfo>.
914 RecordDecl *CXXTypeInfoDecl;
915
916 /// The MSVC "_GUID" struct, which is defined in MSVC header files.
917 RecordDecl *MSVCGuidDecl;
918
919 /// Caches identifiers/selectors for NSFoundation APIs.
920 std::unique_ptr<NSAPI> NSAPIObj;
921
922 /// The declaration of the Objective-C NSNumber class.
923 ObjCInterfaceDecl *NSNumberDecl;
924
925 /// The declaration of the Objective-C NSValue class.
926 ObjCInterfaceDecl *NSValueDecl;
927
928 /// Pointer to NSNumber type (NSNumber *).
929 QualType NSNumberPointer;
930
931 /// Pointer to NSValue type (NSValue *).
932 QualType NSValuePointer;
933
934 /// The Objective-C NSNumber methods used to create NSNumber literals.
935 ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
936
937 /// The declaration of the Objective-C NSString class.
938 ObjCInterfaceDecl *NSStringDecl;
939
940 /// Pointer to NSString type (NSString *).
941 QualType NSStringPointer;
942
943 /// The declaration of the stringWithUTF8String: method.
944 ObjCMethodDecl *StringWithUTF8StringMethod;
945
946 /// The declaration of the valueWithBytes:objCType: method.
947 ObjCMethodDecl *ValueWithBytesObjCTypeMethod;
948
949 /// The declaration of the Objective-C NSArray class.
950 ObjCInterfaceDecl *NSArrayDecl;
951
952 /// The declaration of the arrayWithObjects:count: method.
953 ObjCMethodDecl *ArrayWithObjectsMethod;
954
955 /// The declaration of the Objective-C NSDictionary class.
956 ObjCInterfaceDecl *NSDictionaryDecl;
957
958 /// The declaration of the dictionaryWithObjects:forKeys:count: method.
959 ObjCMethodDecl *DictionaryWithObjectsMethod;
960
961 /// id<NSCopying> type.
962 QualType QIDNSCopying;
963
964 /// will hold 'respondsToSelector:'
965 Selector RespondsToSelectorSel;
966
967 /// A flag to remember whether the implicit forms of operator new and delete
968 /// have been declared.
969 bool GlobalNewDeleteDeclared;
970
971 /// A flag to indicate that we're in a context that permits abstract
972 /// references to fields. This is really a
973 bool AllowAbstractFieldReference;
974
975 /// Describes how the expressions currently being parsed are
976 /// evaluated at run-time, if at all.
977 enum class ExpressionEvaluationContext {
978 /// The current expression and its subexpressions occur within an
979 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
980 /// \c sizeof, where the type of the expression may be significant but
981 /// no code will be generated to evaluate the value of the expression at
982 /// run time.
983 Unevaluated,
984
985 /// The current expression occurs within a braced-init-list within
986 /// an unevaluated operand. This is mostly like a regular unevaluated
987 /// context, except that we still instantiate constexpr functions that are
988 /// referenced here so that we can perform narrowing checks correctly.
989 UnevaluatedList,
990
991 /// The current expression occurs within a discarded statement.
992 /// This behaves largely similarly to an unevaluated operand in preventing
993 /// definitions from being required, but not in other ways.
994 DiscardedStatement,
995
996 /// The current expression occurs within an unevaluated
997 /// operand that unconditionally permits abstract references to
998 /// fields, such as a SIZE operator in MS-style inline assembly.
999 UnevaluatedAbstract,
1000
1001 /// The current context is "potentially evaluated" in C++11 terms,
1002 /// but the expression is evaluated at compile-time (like the values of
1003 /// cases in a switch statement).
1004 ConstantEvaluated,
1005
1006 /// The current expression is potentially evaluated at run time,
1007 /// which means that code may be generated to evaluate the value of the
1008 /// expression at run time.
1009 PotentiallyEvaluated,
1010
1011 /// The current expression is potentially evaluated, but any
1012 /// declarations referenced inside that expression are only used if
1013 /// in fact the current expression is used.
1014 ///
1015 /// This value is used when parsing default function arguments, for which
1016 /// we would like to provide diagnostics (e.g., passing non-POD arguments
1017 /// through varargs) but do not want to mark declarations as "referenced"
1018 /// until the default argument is used.
1019 PotentiallyEvaluatedIfUsed
1020 };
1021
1022 /// Data structure used to record current or nested
1023 /// expression evaluation contexts.
1024 struct ExpressionEvaluationContextRecord {
1025 /// The expression evaluation context.
1026 ExpressionEvaluationContext Context;
1027
1028 /// Whether the enclosing context needed a cleanup.
1029 CleanupInfo ParentCleanup;
1030
1031 /// Whether we are in a decltype expression.
1032 bool IsDecltype;
1033
1034 /// The number of active cleanup objects when we entered
1035 /// this expression evaluation context.
1036 unsigned NumCleanupObjects;
1037
1038 /// The number of typos encountered during this expression evaluation
1039 /// context (i.e. the number of TypoExprs created).
1040 unsigned NumTypos;
1041
1042 MaybeODRUseExprSet SavedMaybeODRUseExprs;
1043
1044 /// The lambdas that are present within this context, if it
1045 /// is indeed an unevaluated context.
1046 SmallVector<LambdaExpr *, 2> Lambdas;
1047
1048 /// The declaration that provides context for lambda expressions
1049 /// and block literals if the normal declaration context does not
1050 /// suffice, e.g., in a default function argument.
1051 Decl *ManglingContextDecl;
1052
1053 /// If we are processing a decltype type, a set of call expressions
1054 /// for which we have deferred checking the completeness of the return type.
1055 SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
1056
1057 /// If we are processing a decltype type, a set of temporary binding
1058 /// expressions for which we have deferred checking the destructor.
1059 SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
1060
1061 llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs;
1062
1063 /// Expressions appearing as the LHS of a volatile assignment in this
1064 /// context. We produce a warning for these when popping the context if
1065 /// they are not discarded-value expressions nor unevaluated operands.
1066 SmallVector<Expr*, 2> VolatileAssignmentLHSs;
1067
1068 /// \brief Describes whether we are in an expression constext which we have
1069 /// to handle differently.
1070 enum ExpressionKind {
1071 EK_Decltype, EK_TemplateArgument, EK_Other
1072 } ExprContext;
1073
1074 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
1075 unsigned NumCleanupObjects,
1076 CleanupInfo ParentCleanup,
1077 Decl *ManglingContextDecl,
1078 ExpressionKind ExprContext)
1079 : Context(Context), ParentCleanup(ParentCleanup),
1080 NumCleanupObjects(NumCleanupObjects), NumTypos(0),
1081 ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext) {}
1082
1083 bool isUnevaluated() const {
1084 return Context == ExpressionEvaluationContext::Unevaluated ||
1085 Context == ExpressionEvaluationContext::UnevaluatedAbstract ||
1086 Context == ExpressionEvaluationContext::UnevaluatedList;
1087 }
1088 bool isConstantEvaluated() const {
1089 return Context == ExpressionEvaluationContext::ConstantEvaluated;
1090 }
1091 };
1092
1093 /// A stack of expression evaluation contexts.
1094 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
1095
1096 /// Emit a warning for all pending noderef expressions that we recorded.
1097 void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec);
1098
1099 /// Compute the mangling number context for a lambda expression or
1100 /// block literal. Also return the extra mangling decl if any.
1101 ///
1102 /// \param DC - The DeclContext containing the lambda expression or
1103 /// block literal.
1104 std::tuple<MangleNumberingContext *, Decl *>
1105 getCurrentMangleNumberContext(const DeclContext *DC);
1106
1107
1108 /// SpecialMemberOverloadResult - The overloading result for a special member
1109 /// function.
1110 ///
1111 /// This is basically a wrapper around PointerIntPair. The lowest bits of the
1112 /// integer are used to determine whether overload resolution succeeded.
1113 class SpecialMemberOverloadResult {
1114 public:
1115 enum Kind {
1116 NoMemberOrDeleted,
1117 Ambiguous,
1118 Success
1119 };
1120
1121 private:
1122 llvm::PointerIntPair<CXXMethodDecl*, 2> Pair;
1123
1124 public:
1125 SpecialMemberOverloadResult() : Pair() {}
1126 SpecialMemberOverloadResult(CXXMethodDecl *MD)
1127 : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
1128
1129 CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
1130 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
1131
1132 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
1133 void setKind(Kind K) { Pair.setInt(K); }
1134 };
1135
1136 class SpecialMemberOverloadResultEntry
1137 : public llvm::FastFoldingSetNode,
1138 public SpecialMemberOverloadResult {
1139 public:
1140 SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
1141 : FastFoldingSetNode(ID)
1142 {}
1143 };
1144
1145 /// A cache of special member function overload resolution results
1146 /// for C++ records.
1147 llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
1148
1149 /// A cache of the flags available in enumerations with the flag_bits
1150 /// attribute.
1151 mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
1152
1153 /// The kind of translation unit we are processing.
1154 ///
1155 /// When we're processing a complete translation unit, Sema will perform
1156 /// end-of-translation-unit semantic tasks (such as creating
1157 /// initializers for tentative definitions in C) once parsing has
1158 /// completed. Modules and precompiled headers perform different kinds of
1159 /// checks.
1160 TranslationUnitKind TUKind;
1161
1162 llvm::BumpPtrAllocator BumpAlloc;
1163
1164 /// The number of SFINAE diagnostics that have been trapped.
1165 unsigned NumSFINAEErrors;
1166
1167 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
1168 UnparsedDefaultArgInstantiationsMap;
1169
1170 /// A mapping from parameters with unparsed default arguments to the
1171 /// set of instantiations of each parameter.
1172 ///
1173 /// This mapping is a temporary data structure used when parsing
1174 /// nested class templates or nested classes of class templates,
1175 /// where we might end up instantiating an inner class before the
1176 /// default arguments of its methods have been parsed.
1177 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
1178
1179 // Contains the locations of the beginning of unparsed default
1180 // argument locations.
1181 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
1182
1183 /// UndefinedInternals - all the used, undefined objects which require a
1184 /// definition in this translation unit.
1185 llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
1186
1187 /// Determine if VD, which must be a variable or function, is an external
1188 /// symbol that nonetheless can't be referenced from outside this translation
1189 /// unit because its type has no linkage and it's not extern "C".
1190 bool isExternalWithNoLinkageType(ValueDecl *VD);
1191
1192 /// Obtain a sorted list of functions that are undefined but ODR-used.
1193 void getUndefinedButUsed(
1194 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
1195
1196 /// Retrieves list of suspicious delete-expressions that will be checked at
1197 /// the end of translation unit.
1198 const llvm::MapVector<FieldDecl *, DeleteLocs> &
1199 getMismatchingDeleteExpressions() const;
1200
1201 typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods;
1202 typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool;
1203
1204 /// Method Pool - allows efficient lookup when typechecking messages to "id".
1205 /// We need to maintain a list, since selectors can have differing signatures
1206 /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
1207 /// of selectors are "overloaded").
1208 /// At the head of the list it is recorded whether there were 0, 1, or >= 2
1209 /// methods inside categories with a particular selector.
1210 GlobalMethodPool MethodPool;
1211
1212 /// Method selectors used in a \@selector expression. Used for implementation
1213 /// of -Wselector.
1214 llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
1215
1216 /// List of SourceLocations where 'self' is implicitly retained inside a
1217 /// block.
1218 llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1>
1219 ImplicitlyRetainedSelfLocs;
1220
1221 /// Kinds of C++ special members.
1222 enum CXXSpecialMember {
1223 CXXDefaultConstructor,
1224 CXXCopyConstructor,
1225 CXXMoveConstructor,
1226 CXXCopyAssignment,
1227 CXXMoveAssignment,
1228 CXXDestructor,
1229 CXXInvalid
1230 };
1231
1232 typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember>
1233 SpecialMemberDecl;
1234
1235 /// The C++ special members which we are currently in the process of
1236 /// declaring. If this process recursively triggers the declaration of the
1237 /// same special member, we should act as if it is not yet declared.
1238 llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
1239
1240 /// Kinds of defaulted comparison operator functions.
1241 enum class DefaultedComparisonKind : unsigned char {
1242 /// This is not a defaultable comparison operator.
1243 None,
1244 /// This is an operator== that should be implemented as a series of
1245 /// subobject comparisons.
1246 Equal,
1247 /// This is an operator<=> that should be implemented as a series of
1248 /// subobject comparisons.
1249 ThreeWay,
1250 /// This is an operator!= that should be implemented as a rewrite in terms
1251 /// of a == comparison.
1252 NotEqual,
1253 /// This is an <, <=, >, or >= that should be implemented as a rewrite in
1254 /// terms of a <=> comparison.
1255 Relational,
1256 };
1257
1258 /// The function definitions which were renamed as part of typo-correction
1259 /// to match their respective declarations. We want to keep track of them
1260 /// to ensure that we don't emit a "redefinition" error if we encounter a
1261 /// correctly named definition after the renamed definition.
1262 llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions;
1263
1264 /// Stack of types that correspond to the parameter entities that are
1265 /// currently being copy-initialized. Can be empty.
1266 llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes;
1267
1268 void ReadMethodPool(Selector Sel);
1269 void updateOutOfDateSelector(Selector Sel);
1270
1271 /// Private Helper predicate to check for 'self'.
1272 bool isSelfExpr(Expr *RExpr);
1273 bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
1274
1275 /// Cause the active diagnostic on the DiagosticsEngine to be
1276 /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
1277 /// should not be used elsewhere.
1278 void EmitCurrentDiagnostic(unsigned DiagID);
1279
1280 /// Records and restores the FP_CONTRACT state on entry/exit of compound
1281 /// statements.
1282 class FPContractStateRAII {
1283 public:
1284 FPContractStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.FPFeatures) {}
1285 ~FPContractStateRAII() { S.FPFeatures = OldFPFeaturesState; }
1286
1287 private:
1288 Sema& S;
1289 FPOptions OldFPFeaturesState;
1290 };
1291
1292 void addImplicitTypedef(StringRef Name, QualType T);
1293
1294 bool WarnedStackExhausted = false;
1295
1296public:
1297 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1298 TranslationUnitKind TUKind = TU_Complete,
1299 CodeCompleteConsumer *CompletionConsumer = nullptr);
1300 ~Sema();
1301
1302 /// Perform initialization that occurs after the parser has been
1303 /// initialized but before it parses anything.
1304 void Initialize();
1305
1306 const LangOptions &getLangOpts() const { return LangOpts; }
1307 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
1308 FPOptions &getFPOptions() { return FPFeatures; }
1309
1310 DiagnosticsEngine &getDiagnostics() const { return Diags; }
1311 SourceManager &getSourceManager() const { return SourceMgr; }
1312 Preprocessor &getPreprocessor() const { return PP; }
1313 ASTContext &getASTContext() const { return Context; }
1314 ASTConsumer &getASTConsumer() const { return Consumer; }
1315 ASTMutationListener *getASTMutationListener() const;
1316 ExternalSemaSource* getExternalSource() const { return ExternalSource; }
1317
1318 ///Registers an external source. If an external source already exists,
1319 /// creates a multiplex external source and appends to it.
1320 ///
1321 ///\param[in] E - A non-null external sema source.
1322 ///
1323 void addExternalSource(ExternalSemaSource *E);
1324
1325 void PrintStats() const;
1326
1327 /// Warn that the stack is nearly exhausted.
1328 void warnStackExhausted(SourceLocation Loc);
1329
1330 /// Run some code with "sufficient" stack space. (Currently, at least 256K is
1331 /// guaranteed). Produces a warning if we're low on stack space and allocates
1332 /// more in that case. Use this in code that may recurse deeply (for example,
1333 /// in template instantiation) to avoid stack overflow.
1334 void runWithSufficientStackSpace(SourceLocation Loc,
1335 llvm::function_ref<void()> Fn);
1336
1337 /// Helper class that creates diagnostics with optional
1338 /// template instantiation stacks.
1339 ///
1340 /// This class provides a wrapper around the basic DiagnosticBuilder
1341 /// class that emits diagnostics. SemaDiagnosticBuilder is
1342 /// responsible for emitting the diagnostic (as DiagnosticBuilder
1343 /// does) and, if the diagnostic comes from inside a template
1344 /// instantiation, printing the template instantiation stack as
1345 /// well.
1346 class SemaDiagnosticBuilder : public DiagnosticBuilder {
1347 Sema &SemaRef;
1348 unsigned DiagID;
1349
1350 public:
1351 SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
1352 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { }
1353
1354 // This is a cunning lie. DiagnosticBuilder actually performs move
1355 // construction in its copy constructor (but due to varied uses, it's not
1356 // possible to conveniently express this as actual move construction). So
1357 // the default copy ctor here is fine, because the base class disables the
1358 // source anyway, so the user-defined ~SemaDiagnosticBuilder is a safe no-op
1359 // in that case anwyay.
1360 SemaDiagnosticBuilder(const SemaDiagnosticBuilder&) = default;
1361
1362 ~SemaDiagnosticBuilder() {
1363 // If we aren't active, there is nothing to do.
1364 if (!isActive()) return;
1365
1366 // Otherwise, we need to emit the diagnostic. First flush the underlying
1367 // DiagnosticBuilder data, and clear the diagnostic builder itself so it
1368 // won't emit the diagnostic in its own destructor.
1369 //
1370 // This seems wasteful, in that as written the DiagnosticBuilder dtor will
1371 // do its own needless checks to see if the diagnostic needs to be
1372 // emitted. However, because we take care to ensure that the builder
1373 // objects never escape, a sufficiently smart compiler will be able to
1374 // eliminate that code.
1375 FlushCounts();
1376 Clear();
1377
1378 // Dispatch to Sema to emit the diagnostic.
1379 SemaRef.EmitCurrentDiagnostic(DiagID);
1380 }
1381
1382 /// Teach operator<< to produce an object of the correct type.
1383 template<typename T>
1384 friend const SemaDiagnosticBuilder &operator<<(
1385 const SemaDiagnosticBuilder &Diag, const T &Value) {
1386 const DiagnosticBuilder &BaseDiag = Diag;
1387 BaseDiag << Value;
1388 return Diag;
1389 }
1390 };
1391
1392 /// Emit a diagnostic.
1393 SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) {
1394 DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
1395 return SemaDiagnosticBuilder(DB, *this, DiagID);
1396 }
1397
1398 /// Emit a partial diagnostic.
1399 SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD);
1400
1401 /// Build a partial diagnostic.
1402 PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1403
1404 bool findMacroSpelling(SourceLocation &loc, StringRef name);
1405
1406 /// Get a string to suggest for zero-initialization of a type.
1407 std::string
1408 getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
1409 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
1410
1411 /// Calls \c Lexer::getLocForEndOfToken()
1412 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1413
1414 /// Retrieve the module loader associated with the preprocessor.
1415 ModuleLoader &getModuleLoader() const;
1416
1417 void emitAndClearUnusedLocalTypedefWarnings();
1418
1419 enum TUFragmentKind {
1420 /// The global module fragment, between 'module;' and a module-declaration.
1421 Global,
1422 /// A normal translation unit fragment. For a non-module unit, this is the
1423 /// entire translation unit. Otherwise, it runs from the module-declaration
1424 /// to the private-module-fragment (if any) or the end of the TU (if not).
1425 Normal,
1426 /// The private module fragment, between 'module :private;' and the end of
1427 /// the translation unit.
1428 Private
1429 };
1430
1431 void ActOnStartOfTranslationUnit();
1432 void ActOnEndOfTranslationUnit();
1433 void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind);
1434
1435 void CheckDelegatingCtorCycles();
1436
1437 Scope *getScopeForContext(DeclContext *Ctx);
1438
1439 void PushFunctionScope();
1440 void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1441 sema::LambdaScopeInfo *PushLambdaScope();
1442
1443 /// This is used to inform Sema what the current TemplateParameterDepth
1444 /// is during Parsing. Currently it is used to pass on the depth
1445 /// when parsing generic lambda 'auto' parameters.
1446 void RecordParsingTemplateParameterDepth(unsigned Depth);
1447
1448 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1449 RecordDecl *RD, CapturedRegionKind K,
1450 unsigned OpenMPCaptureLevel = 0);
1451
1452 /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short
1453 /// time after they've been popped.
1454 class PoppedFunctionScopeDeleter {
1455 Sema *Self;
1456
1457 public:
1458 explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {}
1459 void operator()(sema::FunctionScopeInfo *Scope) const;
1460 };
1461
1462 using PoppedFunctionScopePtr =
1463 std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>;
1464
1465 PoppedFunctionScopePtr
1466 PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1467 const Decl *D = nullptr,
1468 QualType BlockType = QualType());
1469
1470 sema::FunctionScopeInfo *getCurFunction() const {
1471 return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
1472 }
1473
1474 sema::FunctionScopeInfo *getEnclosingFunction() const;
1475
1476 void setFunctionHasBranchIntoScope();
1477 void setFunctionHasBranchProtectedScope();
1478 void setFunctionHasIndirectGoto();
1479
1480 void PushCompoundScope(bool IsStmtExpr);
1481 void PopCompoundScope();
1482
1483 sema::CompoundScopeInfo &getCurCompoundScope() const;
1484
1485 bool hasAnyUnrecoverableErrorsInThisFunction() const;
1486
1487 /// Retrieve the current block, if any.
1488 sema::BlockScopeInfo *getCurBlock();
1489
1490 /// Get the innermost lambda enclosing the current location, if any. This
1491 /// looks through intervening non-lambda scopes such as local functions and
1492 /// blocks.
1493 sema::LambdaScopeInfo *getEnclosingLambda() const;
1494
1495 /// Retrieve the current lambda scope info, if any.
1496 /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
1497 /// lambda scope info ignoring all inner capturing scopes that are not
1498 /// lambda scopes.
1499 sema::LambdaScopeInfo *
1500 getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
1501
1502 /// Retrieve the current generic lambda info, if any.
1503 sema::LambdaScopeInfo *getCurGenericLambda();
1504
1505 /// Retrieve the current captured region, if any.
1506 sema::CapturedRegionScopeInfo *getCurCapturedRegion();
1507
1508 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
1509 SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
1510
1511 void ActOnComment(SourceRange Comment);
1512
1513 //===--------------------------------------------------------------------===//
1514 // Type Analysis / Processing: SemaType.cpp.
1515 //
1516
1517 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
1518 const DeclSpec *DS = nullptr);
1519 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
1520 const DeclSpec *DS = nullptr);
1521 QualType BuildPointerType(QualType T,
1522 SourceLocation Loc, DeclarationName Entity);
1523 QualType BuildReferenceType(QualType T, bool LValueRef,
1524 SourceLocation Loc, DeclarationName Entity);
1525 QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1526 Expr *ArraySize, unsigned Quals,
1527 SourceRange Brackets, DeclarationName Entity);
1528 QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc);
1529 QualType BuildExtVectorType(QualType T, Expr *ArraySize,
1530 SourceLocation AttrLoc);
1531 QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
1532 SourceLocation AttrLoc);
1533
1534 /// Same as above, but constructs the AddressSpace index if not provided.
1535 QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
1536 SourceLocation AttrLoc);
1537
1538 bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc);
1539
1540 bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
1541
1542 /// Build a function type.
1543 ///
1544 /// This routine checks the function type according to C++ rules and
1545 /// under the assumption that the result type and parameter types have
1546 /// just been instantiated from a template. It therefore duplicates
1547 /// some of the behavior of GetTypeForDeclarator, but in a much
1548 /// simpler form that is only suitable for this narrow use case.
1549 ///
1550 /// \param T The return type of the function.
1551 ///
1552 /// \param ParamTypes The parameter types of the function. This array
1553 /// will be modified to account for adjustments to the types of the
1554 /// function parameters.
1555 ///
1556 /// \param Loc The location of the entity whose type involves this
1557 /// function type or, if there is no such entity, the location of the
1558 /// type that will have function type.
1559 ///
1560 /// \param Entity The name of the entity that involves the function
1561 /// type, if known.
1562 ///
1563 /// \param EPI Extra information about the function type. Usually this will
1564 /// be taken from an existing function with the same prototype.
1565 ///
1566 /// \returns A suitable function type, if there are no errors. The
1567 /// unqualified type will always be a FunctionProtoType.
1568 /// Otherwise, returns a NULL type.
1569 QualType BuildFunctionType(QualType T,
1570 MutableArrayRef<QualType> ParamTypes,
1571 SourceLocation Loc, DeclarationName Entity,
1572 const FunctionProtoType::ExtProtoInfo &EPI);
1573
1574 QualType BuildMemberPointerType(QualType T, QualType Class,
1575 SourceLocation Loc,
1576 DeclarationName Entity);
1577 QualType BuildBlockPointerType(QualType T,
1578 SourceLocation Loc, DeclarationName Entity);
1579 QualType BuildParenType(QualType T);
1580 QualType BuildAtomicType(QualType T, SourceLocation Loc);
1581 QualType BuildReadPipeType(QualType T,
1582 SourceLocation Loc);
1583 QualType BuildWritePipeType(QualType T,
1584 SourceLocation Loc);
1585
1586 TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
1587 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
1588
1589 /// Package the given type and TSI into a ParsedType.
1590 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
1591 DeclarationNameInfo GetNameForDeclarator(Declarator &D);
1592 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
1593 static QualType GetTypeFromParser(ParsedType Ty,
1594 TypeSourceInfo **TInfo = nullptr);
1595 CanThrowResult canThrow(const Expr *E);
1596 const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
1597 const FunctionProtoType *FPT);
1598 void UpdateExceptionSpec(FunctionDecl *FD,
1599 const FunctionProtoType::ExceptionSpecInfo &ESI);
1600 bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
1601 bool CheckDistantExceptionSpec(QualType T);
1602 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
1603 bool CheckEquivalentExceptionSpec(
1604 const FunctionProtoType *Old, SourceLocation OldLoc,
1605 const FunctionProtoType *New, SourceLocation NewLoc);
1606 bool CheckEquivalentExceptionSpec(
1607 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
1608 const FunctionProtoType *Old, SourceLocation OldLoc,
1609 const FunctionProtoType *New, SourceLocation NewLoc);
1610 bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
1611 bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
1612 const PartialDiagnostic &NestedDiagID,
1613 const PartialDiagnostic &NoteID,
1614 const PartialDiagnostic &NoThrowDiagID,
1615 const FunctionProtoType *Superset,
1616 SourceLocation SuperLoc,
1617 const FunctionProtoType *Subset,
1618 SourceLocation SubLoc);
1619 bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID,
1620 const PartialDiagnostic &NoteID,
1621 const FunctionProtoType *Target,
1622 SourceLocation TargetLoc,
1623 const FunctionProtoType *Source,
1624 SourceLocation SourceLoc);
1625
1626 TypeResult ActOnTypeName(Scope *S, Declarator &D);
1627
1628 /// The parser has parsed the context-sensitive type 'instancetype'
1629 /// in an Objective-C message declaration. Return the appropriate type.
1630 ParsedType ActOnObjCInstanceType(SourceLocation Loc);
1631
1632 /// Abstract class used to diagnose incomplete types.
1633 struct TypeDiagnoser {
1634 TypeDiagnoser() {}
1635
1636 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
1637 virtual ~TypeDiagnoser() {}
1638 };
1639
1640 static int getPrintable(int I) { return I; }
1641 static unsigned getPrintable(unsigned I) { return I; }
1642 static bool getPrintable(bool B) { return B; }
1643 static const char * getPrintable(const char *S) { return S; }
1644 static StringRef getPrintable(StringRef S) { return S; }
1645 static const std::string &getPrintable(const std::string &S) { return S; }
1646 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
1647 return II;
1648 }
1649 static DeclarationName getPrintable(DeclarationName N) { return N; }
1650 static QualType getPrintable(QualType T) { return T; }
1651 static SourceRange getPrintable(SourceRange R) { return R; }
1652 static SourceRange getPrintable(SourceLocation L) { return L; }
1653 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
1654 static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
1655
1656 template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
1657 unsigned DiagID;
1658 std::tuple<const Ts &...> Args;
1659
1660 template <std::size_t... Is>
1661 void emit(const SemaDiagnosticBuilder &DB,
1662 std::index_sequence<Is...>) const {
1663 // Apply all tuple elements to the builder in order.
1664 bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
1665 (void)Dummy;
1666 }
1667
1668 public:
1669 BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
1670 : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
1671 assert(DiagID != 0 && "no diagnostic for type diagnoser")((DiagID != 0 && "no diagnostic for type diagnoser") ?
static_cast<void> (0) : __assert_fail ("DiagID != 0 && \"no diagnostic for type diagnoser\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 1671, __PRETTY_FUNCTION__))
;
1672 }
1673
1674 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
1675 const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
1676 emit(DB, std::index_sequence_for<Ts...>());
1677 DB << T;
1678 }
1679 };
1680
1681private:
1682 /// Methods for marking which expressions involve dereferencing a pointer
1683 /// marked with the 'noderef' attribute. Expressions are checked bottom up as
1684 /// they are parsed, meaning that a noderef pointer may not be accessed. For
1685 /// example, in `&*p` where `p` is a noderef pointer, we will first parse the
1686 /// `*p`, but need to check that `address of` is called on it. This requires
1687 /// keeping a container of all pending expressions and checking if the address
1688 /// of them are eventually taken.
1689 void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E);
1690 void CheckAddressOfNoDeref(const Expr *E);
1691 void CheckMemberAccessOfNoDeref(const MemberExpr *E);
1692
1693 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
1694 TypeDiagnoser *Diagnoser);
1695
1696 struct ModuleScope {
1697 SourceLocation BeginLoc;
1698 clang::Module *Module = nullptr;
1699 bool ModuleInterface = false;
1700 bool ImplicitGlobalModuleFragment = false;
1701 VisibleModuleSet OuterVisibleModules;
1702 };
1703 /// The modules we're currently parsing.
1704 llvm::SmallVector<ModuleScope, 16> ModuleScopes;
1705
1706 /// Namespace definitions that we will export when they finish.
1707 llvm::SmallPtrSet<const NamespaceDecl*, 8> DeferredExportedNamespaces;
1708
1709 /// Get the module whose scope we are currently within.
1710 Module *getCurrentModule() const {
1711 return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
1712 }
1713
1714 VisibleModuleSet VisibleModules;
1715
1716public:
1717 /// Get the module owning an entity.
1718 Module *getOwningModule(Decl *Entity) { return Entity->getOwningModule(); }
1719
1720 /// Make a merged definition of an existing hidden definition \p ND
1721 /// visible at the specified location.
1722 void makeMergedDefinitionVisible(NamedDecl *ND);
1723
1724 bool isModuleVisible(const Module *M, bool ModulePrivate = false);
1725
1726 /// Determine whether a declaration is visible to name lookup.
1727 bool isVisible(const NamedDecl *D) {
1728 return !D->isHidden() || isVisibleSlow(D);
1729 }
1730
1731 /// Determine whether any declaration of an entity is visible.
1732 bool
1733 hasVisibleDeclaration(const NamedDecl *D,
1734 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
1735 return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
1736 }
1737 bool hasVisibleDeclarationSlow(const NamedDecl *D,
1738 llvm::SmallVectorImpl<Module *> *Modules);
1739
1740 bool hasVisibleMergedDefinition(NamedDecl *Def);
1741 bool hasMergedDefinitionInCurrentModule(NamedDecl *Def);
1742
1743 /// Determine if \p D and \p Suggested have a structurally compatible
1744 /// layout as described in C11 6.2.7/1.
1745 bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
1746
1747 /// Determine if \p D has a visible definition. If not, suggest a declaration
1748 /// that should be made visible to expose the definition.
1749 bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
1750 bool OnlyNeedComplete = false);
1751 bool hasVisibleDefinition(const NamedDecl *D) {
1752 NamedDecl *Hidden;
1753 return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
1754 }
1755
1756 /// Determine if the template parameter \p D has a visible default argument.
1757 bool
1758 hasVisibleDefaultArgument(const NamedDecl *D,
1759 llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1760
1761 /// Determine if there is a visible declaration of \p D that is an explicit
1762 /// specialization declaration for a specialization of a template. (For a
1763 /// member specialization, use hasVisibleMemberSpecialization.)
1764 bool hasVisibleExplicitSpecialization(
1765 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1766
1767 /// Determine if there is a visible declaration of \p D that is a member
1768 /// specialization declaration (as opposed to an instantiated declaration).
1769 bool hasVisibleMemberSpecialization(
1770 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1771
1772 /// Determine if \p A and \p B are equivalent internal linkage declarations
1773 /// from different modules, and thus an ambiguity error can be downgraded to
1774 /// an extension warning.
1775 bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
1776 const NamedDecl *B);
1777 void diagnoseEquivalentInternalLinkageDeclarations(
1778 SourceLocation Loc, const NamedDecl *D,
1779 ArrayRef<const NamedDecl *> Equiv);
1780
1781 bool isUsualDeallocationFunction(const CXXMethodDecl *FD);
1782
1783 bool isCompleteType(SourceLocation Loc, QualType T) {
1784 return !RequireCompleteTypeImpl(Loc, T, nullptr);
1785 }
1786 bool RequireCompleteType(SourceLocation Loc, QualType T,
1787 TypeDiagnoser &Diagnoser);
1788 bool RequireCompleteType(SourceLocation Loc, QualType T,
1789 unsigned DiagID);
1790
1791 template <typename... Ts>
1792 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
1793 const Ts &...Args) {
1794 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1795 return RequireCompleteType(Loc, T, Diagnoser);
1796 }
1797
1798 void completeExprArrayBound(Expr *E);
1799 bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser);
1800 bool RequireCompleteExprType(Expr *E, unsigned DiagID);
1801
1802 template <typename... Ts>
1803 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
1804 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1805 return RequireCompleteExprType(E, Diagnoser);
1806 }
1807
1808 bool RequireLiteralType(SourceLocation Loc, QualType T,
1809 TypeDiagnoser &Diagnoser);
1810 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
1811
1812 template <typename... Ts>
1813 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
1814 const Ts &...Args) {
1815 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1816 return RequireLiteralType(Loc, T, Diagnoser);
1817 }
1818
1819 QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1820 const CXXScopeSpec &SS, QualType T,
1821 TagDecl *OwnedTagDecl = nullptr);
1822
1823 QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
1824 /// If AsUnevaluated is false, E is treated as though it were an evaluated
1825 /// context, such as when building a type for decltype(auto).
1826 QualType BuildDecltypeType(Expr *E, SourceLocation Loc,
1827 bool AsUnevaluated = true);
1828 QualType BuildUnaryTransformType(QualType BaseType,
1829 UnaryTransformType::UTTKind UKind,
1830 SourceLocation Loc);
1831
1832 //===--------------------------------------------------------------------===//
1833 // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
1834 //
1835
1836 struct SkipBodyInfo {
1837 SkipBodyInfo()
1838 : ShouldSkip(false), CheckSameAsPrevious(false), Previous(nullptr),
1839 New(nullptr) {}
1840 bool ShouldSkip;
1841 bool CheckSameAsPrevious;
1842 NamedDecl *Previous;
1843 NamedDecl *New;
1844 };
1845
1846 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
1847
1848 void DiagnoseUseOfUnimplementedSelectors();
1849
1850 bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
1851
1852 ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
1853 Scope *S, CXXScopeSpec *SS = nullptr,
1854 bool isClassName = false, bool HasTrailingDot = false,
1855 ParsedType ObjectType = nullptr,
1856 bool IsCtorOrDtorName = false,
1857 bool WantNontrivialTypeSourceInfo = false,
1858 bool IsClassTemplateDeductionContext = true,
1859 IdentifierInfo **CorrectedII = nullptr);
1860 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
1861 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
1862 void DiagnoseUnknownTypeName(IdentifierInfo *&II,
1863 SourceLocation IILoc,
1864 Scope *S,
1865 CXXScopeSpec *SS,
1866 ParsedType &SuggestedType,
1867 bool IsTemplateName = false);
1868
1869 /// Attempt to behave like MSVC in situations where lookup of an unqualified
1870 /// type name has failed in a dependent context. In these situations, we
1871 /// automatically form a DependentTypeName that will retry lookup in a related
1872 /// scope during instantiation.
1873 ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
1874 SourceLocation NameLoc,
1875 bool IsTemplateTypeArg);
1876
1877 /// Describes the result of the name lookup and resolution performed
1878 /// by \c ClassifyName().
1879 enum NameClassificationKind {
1880 /// This name is not a type or template in this context, but might be
1881 /// something else.
1882 NC_Unknown,
1883 /// Classification failed; an error has been produced.
1884 NC_Error,
1885 /// The name has been typo-corrected to a keyword.
1886 NC_Keyword,
1887 /// The name was classified as a type.
1888 NC_Type,
1889 /// The name was classified as a specific non-type, non-template
1890 /// declaration. ActOnNameClassifiedAsNonType should be called to
1891 /// convert the declaration to an expression.
1892 NC_NonType,
1893 /// The name was classified as an ADL-only function name.
1894 /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the
1895 /// result to an expression.
1896 NC_UndeclaredNonType,
1897 /// The name denotes a member of a dependent type that could not be
1898 /// resolved. ActOnNameClassifiedAsDependentNonType should be called to
1899 /// convert the result to an expression.
1900 NC_DependentNonType,
1901 /// The name was classified as a non-type, and an expression representing
1902 /// that name has been formed.
1903 NC_ContextIndependentExpr,
1904 /// The name was classified as a template whose specializations are types.
1905 NC_TypeTemplate,
1906 /// The name was classified as a variable template name.
1907 NC_VarTemplate,
1908 /// The name was classified as a function template name.
1909 NC_FunctionTemplate,
1910 /// The name was classified as an ADL-only function template name.
1911 NC_UndeclaredTemplate,
1912 };
1913
1914 class NameClassification {
1915 NameClassificationKind Kind;
1916 union {
1917 ExprResult Expr;
1918 NamedDecl *NonTypeDecl;
1919 TemplateName Template;
1920 ParsedType Type;
1921 };
1922
1923 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
1924
1925 public:
1926 NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
1927
1928 NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {}
1929
1930 static NameClassification Error() {
1931 return NameClassification(NC_Error);
1932 }
1933
1934 static NameClassification Unknown() {
1935 return NameClassification(NC_Unknown);
1936 }
1937
1938 static NameClassification ContextIndependentExpr(ExprResult E) {
1939 NameClassification Result(NC_ContextIndependentExpr);
1940 Result.Expr = E;
1941 return Result;
1942 }
1943
1944 static NameClassification NonType(NamedDecl *D) {
1945 NameClassification Result(NC_NonType);
1946 Result.NonTypeDecl = D;
1947 return Result;
1948 }
1949
1950 static NameClassification UndeclaredNonType() {
1951 return NameClassification(NC_UndeclaredNonType);
1952 }
1953
1954 static NameClassification DependentNonType() {
1955 return NameClassification(NC_DependentNonType);
1956 }
1957
1958 static NameClassification TypeTemplate(TemplateName Name) {
1959 NameClassification Result(NC_TypeTemplate);
1960 Result.Template = Name;
1961 return Result;
1962 }
1963
1964 static NameClassification VarTemplate(TemplateName Name) {
1965 NameClassification Result(NC_VarTemplate);
1966 Result.Template = Name;
1967 return Result;
1968 }
1969
1970 static NameClassification FunctionTemplate(TemplateName Name) {
1971 NameClassification Result(NC_FunctionTemplate);
1972 Result.Template = Name;
1973 return Result;
1974 }
1975
1976 static NameClassification UndeclaredTemplate(TemplateName Name) {
1977 NameClassification Result(NC_UndeclaredTemplate);
1978 Result.Template = Name;
1979 return Result;
1980 }
1981
1982 NameClassificationKind getKind() const { return Kind; }
1983
1984 ExprResult getExpression() const {
1985 assert(Kind == NC_ContextIndependentExpr)((Kind == NC_ContextIndependentExpr) ? static_cast<void>
(0) : __assert_fail ("Kind == NC_ContextIndependentExpr", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 1985, __PRETTY_FUNCTION__))
;
1986 return Expr;
1987 }
1988
1989 ParsedType getType() const {
1990 assert(Kind == NC_Type)((Kind == NC_Type) ? static_cast<void> (0) : __assert_fail
("Kind == NC_Type", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 1990, __PRETTY_FUNCTION__))
;
1991 return Type;
1992 }
1993
1994 NamedDecl *getNonTypeDecl() const {
1995 assert(Kind == NC_NonType)((Kind == NC_NonType) ? static_cast<void> (0) : __assert_fail
("Kind == NC_NonType", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 1995, __PRETTY_FUNCTION__))
;
1996 return NonTypeDecl;
1997 }
1998
1999 TemplateName getTemplateName() const {
2000 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||((Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind
== NC_VarTemplate || Kind == NC_UndeclaredTemplate) ? static_cast
<void> (0) : __assert_fail ("Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_UndeclaredTemplate"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 2001, __PRETTY_FUNCTION__))
2001 Kind == NC_VarTemplate || Kind == NC_UndeclaredTemplate)((Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind
== NC_VarTemplate || Kind == NC_UndeclaredTemplate) ? static_cast
<void> (0) : __assert_fail ("Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_UndeclaredTemplate"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 2001, __PRETTY_FUNCTION__))
;
2002 return Template;
2003 }
2004
2005 TemplateNameKind getTemplateNameKind() const {
2006 switch (Kind) {
2007 case NC_TypeTemplate:
2008 return TNK_Type_template;
2009 case NC_FunctionTemplate:
2010 return TNK_Function_template;
2011 case NC_VarTemplate:
2012 return TNK_Var_template;
2013 case NC_UndeclaredTemplate:
2014 return TNK_Undeclared_template;
2015 default:
2016 llvm_unreachable("unsupported name classification.")::llvm::llvm_unreachable_internal("unsupported name classification."
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/Sema/Sema.h"
, 2016)
;
2017 }
2018 }
2019 };
2020
2021 /// Perform name lookup on the given name, classifying it based on
2022 /// the results of name lookup and the following token.
2023 ///
2024 /// This routine is used by the parser to resolve identifiers and help direct
2025 /// parsing. When the identifier cannot be found, this routine will attempt
2026 /// to correct the typo and classify based on the resulting name.
2027 ///
2028 /// \param S The scope in which we're performing name lookup.
2029 ///
2030 /// \param SS The nested-name-specifier that precedes the name.
2031 ///
2032 /// \param Name The identifier. If typo correction finds an alternative name,
2033 /// this pointer parameter will be updated accordingly.
2034 ///
2035 /// \param NameLoc The location of the identifier.
2036 ///
2037 /// \param NextToken The token following the identifier. Used to help
2038 /// disambiguate the name.
2039 ///
2040 /// \param CCC The correction callback, if typo correction is desired.
2041 NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS,
2042 IdentifierInfo *&Name, SourceLocation NameLoc,
2043 const Token &NextToken,
2044 CorrectionCandidateCallback *CCC = nullptr);
2045
2046 /// Act on the result of classifying a name as an undeclared (ADL-only)
2047 /// non-type declaration.
2048 ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
2049 SourceLocation NameLoc);
2050 /// Act on the result of classifying a name as an undeclared member of a
2051 /// dependent base class.
2052 ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
2053 IdentifierInfo *Name,
2054 SourceLocation NameLoc,
2055 bool IsAddressOfOperand);
2056 /// Act on the result of classifying a name as a specific non-type
2057 /// declaration.
2058 ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
2059 NamedDecl *Found,
2060 SourceLocation NameLoc,
2061 const Token &NextToken);
2062
2063 /// Describes the detailed kind of a template name. Used in diagnostics.
2064 enum class TemplateNameKindForDiagnostics {
2065 ClassTemplate,
2066 FunctionTemplate,
2067 VarTemplate,
2068 AliasTemplate,
2069 TemplateTemplateParam,
2070 Concept,
2071 DependentTemplate
2072 };
2073 TemplateNameKindForDiagnostics
2074 getTemplateNameKindForDiagnostics(TemplateName Name);
2075
2076 /// Determine whether it's plausible that E was intended to be a
2077 /// template-name.
2078 bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) {
2079 if (!getLangOpts().CPlusPlus || E.isInvalid())
2080 return false;
2081 Dependent = false;
2082 if (auto *DRE = dyn_cast<DeclRefExpr>(E.get()))
2083 return !DRE->hasExplicitTemplateArgs();
2084 if (auto *ME = dyn_cast<MemberExpr>(E.get()))
2085 return !ME->hasExplicitTemplateArgs();
2086 Dependent = true;
2087 if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get()))
2088 return !DSDRE->hasExplicitTemplateArgs();
2089 if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get()))
2090 return !DSME->hasExplicitTemplateArgs();
2091 // Any additional cases recognized here should also be handled by
2092 // diagnoseExprIntendedAsTemplateName.
2093 return false;
2094 }
2095 void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
2096 SourceLocation Less,
2097 SourceLocation Greater);
2098
2099 Decl *ActOnDeclarator(Scope *S, Declarator &D);
2100
2101 NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
2102 MultiTemplateParamsArg TemplateParameterLists);
2103 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
2104 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
2105 bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
2106 DeclarationName Name, SourceLocation Loc,
2107 bool IsTemplateId);
2108 void
2109 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2110 SourceLocation FallbackLoc,
2111 SourceLocation ConstQualLoc = SourceLocation(),
2112 SourceLocation VolatileQualLoc = SourceLocation(),
2113 SourceLocation RestrictQualLoc = SourceLocation(),
2114 SourceLocation AtomicQualLoc = SourceLocation(),
2115 SourceLocation UnalignedQualLoc = SourceLocation());
2116
2117 static bool adjustContextForLocalExternDecl(DeclContext *&DC);
2118 void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
2119 NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D,
2120 const LookupResult &R);
2121 NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R);
2122 void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
2123 const LookupResult &R);
2124 void CheckShadow(Scope *S, VarDecl *D);
2125
2126 /// Warn if 'E', which is an expression that is about to be modified, refers
2127 /// to a shadowing declaration.
2128 void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
2129
2130 void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI);
2131
2132private:
2133 /// Map of current shadowing declarations to shadowed declarations. Warn if
2134 /// it looks like the user is trying to modify the shadowing declaration.
2135 llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
2136
2137public:
2138 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
2139 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
2140 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
2141 TypedefNameDecl *NewTD);
2142 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
2143 NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2144 TypeSourceInfo *TInfo,
2145 LookupResult &Previous);
2146 NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
2147 LookupResult &Previous, bool &Redeclaration);
2148 NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
2149 TypeSourceInfo *TInfo,
2150 LookupResult &Previous,
2151 MultiTemplateParamsArg TemplateParamLists,
2152 bool &AddToScope,
2153 ArrayRef<BindingDecl *> Bindings = None);
2154 NamedDecl *
2155 ActOnDecompositionDeclarator(Scope *S, Declarator &D,
2156 MultiTemplateParamsArg TemplateParamLists);
2157 // Returns true if the variable declaration is a redeclaration
2158 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
2159 void CheckVariableDeclarationType(VarDecl *NewVD);
2160 bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
2161 Expr *Init);
2162 void CheckCompleteVariableDeclaration(VarDecl *VD);
2163 void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD);
2164 void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
2165
2166 NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2167 TypeSourceInfo *TInfo,
2168 LookupResult &Previous,
2169 MultiTemplateParamsArg TemplateParamLists,
2170 bool &AddToScope);
2171 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
2172
2173 enum class CheckConstexprKind {
2174 /// Diagnose issues that are non-constant or that are extensions.
2175 Diagnose,
2176 /// Identify whether this function satisfies the formal rules for constexpr
2177 /// functions in the current lanugage mode (with no extensions).
2178 CheckValid
2179 };
2180
2181 bool CheckConstexprFunctionDefinition(const FunctionDecl *FD,
2182 CheckConstexprKind Kind);
2183
2184 void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
2185 void FindHiddenVirtualMethods(CXXMethodDecl *MD,
2186 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2187 void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
2188 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2189 // Returns true if the function declaration is a redeclaration
2190 bool CheckFunctionDeclaration(Scope *S,
2191 FunctionDecl *NewFD, LookupResult &Previous,
2192 bool IsMemberSpecialization);
2193 bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
2194 bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
2195 QualType NewT, QualType OldT);
2196 void CheckMain(FunctionDecl *FD, const DeclSpec &D);
2197 void CheckMSVCRTEntryPoint(FunctionDecl *FD);
2198 Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
2199 bool IsDefinition);
2200 void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D);
2201 Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
2202 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
2203 SourceLocation Loc,
2204 QualType T);
2205 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
2206 SourceLocation NameLoc, IdentifierInfo *Name,
2207 QualType T, TypeSourceInfo *TSInfo,
2208 StorageClass SC);
2209 void ActOnParamDefaultArgument(Decl *param,
2210 SourceLocation EqualLoc,
2211 Expr *defarg);
2212 void ActOnParamUnparsedDefaultArgument(Decl *param,
2213 SourceLocation EqualLoc,
2214 SourceLocation ArgLoc);
2215 void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
2216 bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
2217 SourceLocation EqualLoc);
2218
2219 // Contexts where using non-trivial C union types can be disallowed. This is
2220 // passed to err_non_trivial_c_union_in_invalid_context.
2221 enum NonTrivialCUnionContext {
2222 // Function parameter.
2223 NTCUC_FunctionParam,
2224 // Function return.
2225 NTCUC_FunctionReturn,
2226 // Default-initialized object.
2227 NTCUC_DefaultInitializedObject,
2228 // Variable with automatic storage duration.
2229 NTCUC_AutoVar,
2230 // Initializer expression that might copy from another object.
2231 NTCUC_CopyInit,
2232 // Assignment.
2233 NTCUC_Assignment,
2234 // Compound literal.
2235 NTCUC_CompoundLiteral,
2236 // Block capture.
2237 NTCUC_BlockCapture,
2238 // lvalue-to-rvalue conversion of volatile type.
2239 NTCUC_LValueToRValueVolatile,
2240 };
2241
2242 /// Emit diagnostics if the initializer or any of its explicit or
2243 /// implicitly-generated subexpressions require copying or
2244 /// default-initializing a type that is or contains a C union type that is
2245 /// non-trivial to copy or default-initialize.
2246 void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc);
2247
2248 // These flags are passed to checkNonTrivialCUnion.
2249 enum NonTrivialCUnionKind {
2250 NTCUK_Init = 0x1,
2251 NTCUK_Destruct = 0x2,
2252 NTCUK_Copy = 0x4,
2253 };
2254
2255 /// Emit diagnostics if a non-trivial C union type or a struct that contains
2256 /// a non-trivial C union is used in an invalid context.
2257 void checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
2258 NonTrivialCUnionContext UseContext,
2259 unsigned NonTrivialKind);
2260
2261 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
2262 void ActOnUninitializedDecl(Decl *dcl);
2263 void ActOnInitializerError(Decl *Dcl);
2264
2265 void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
2266 void ActOnCXXForRangeDecl(Decl *D);
2267 StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
2268 IdentifierInfo *Ident,
2269 ParsedAttributes &Attrs,
2270 SourceLocation AttrEnd);
2271 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
2272 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
2273 void CheckStaticLocalForDllExport(VarDecl *VD);
2274 void FinalizeDeclaration(Decl *D);
2275 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
2276 ArrayRef<Decl *> Group);
2277 DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group);
2278
2279 /// Should be called on all declarations that might have attached
2280 /// documentation comments.
2281 void ActOnDocumentableDecl(Decl *D);
2282 void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
2283
2284 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
2285 SourceLocation LocAfterDecls);
2286 void CheckForFunctionRedefinition(
2287 FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
2288 SkipBodyInfo *SkipBody = nullptr);
2289 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
2290 MultiTemplateParamsArg TemplateParamLists,
2291 SkipBodyInfo *SkipBody = nullptr);
2292 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
2293 SkipBodyInfo *SkipBody = nullptr);
2294 void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
2295 bool isObjCMethodDecl(Decl *D) {
2296 return D && isa<ObjCMethodDecl>(D);
2297 }
2298
2299 /// Determine whether we can delay parsing the body of a function or
2300 /// function template until it is used, assuming we don't care about emitting
2301 /// code for that function.
2302 ///
2303 /// This will be \c false if we may need the body of the function in the
2304 /// middle of parsing an expression (where it's impractical to switch to
2305 /// parsing a different function), for instance, if it's constexpr in C++11
2306 /// or has an 'auto' return type in C++14. These cases are essentially bugs.
2307 bool canDelayFunctionBody(const Declarator &D);
2308
2309 /// Determine whether we can skip parsing the body of a function
2310 /// definition, assuming we don't care about analyzing its body or emitting
2311 /// code for that function.
2312 ///
2313 /// This will be \c false only if we may need the body of the function in
2314 /// order to parse the rest of the program (for instance, if it is
2315 /// \c constexpr in C++11 or has an 'auto' return type in C++14).
2316 bool canSkipFunctionBody(Decl *D);
2317
2318 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
2319 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
2320 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
2321 Decl *ActOnSkippedFunctionBody(Decl *Decl);
2322 void ActOnFinishInlineFunctionDef(FunctionDecl *D);
2323
2324 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
2325 /// attribute for which parsing is delayed.
2326 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
2327
2328 /// Diagnose any unused parameters in the given sequence of
2329 /// ParmVarDecl pointers.
2330 void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
2331
2332 /// Diagnose whether the size of parameters or return value of a
2333 /// function or obj-c method definition is pass-by-value and larger than a
2334 /// specified threshold.
2335 void
2336 DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
2337 QualType ReturnTy, NamedDecl *D);
2338
2339 void DiagnoseInvalidJumps(Stmt *Body);
2340 Decl *ActOnFileScopeAsmDecl(Expr *expr,
2341 SourceLocation AsmLoc,
2342 SourceLocation RParenLoc);
2343
2344 /// Handle a C++11 empty-declaration and attribute-declaration.
2345 Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList,
2346 SourceLocation SemiLoc);
2347
2348 enum class ModuleDeclKind {
2349 Interface, ///< 'export module X;'
2350 Implementation, ///< 'module X;'
2351 };
2352
2353 /// The parser has processed a module-declaration that begins the definition
2354 /// of a module interface or implementation.
2355 DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc,
2356 SourceLocation ModuleLoc, ModuleDeclKind MDK,
2357 ModuleIdPath Path, bool IsFirstDecl);
2358
2359 /// The parser has processed a global-module-fragment declaration that begins
2360 /// the definition of the global module fragment of the current module unit.
2361 /// \param ModuleLoc The location of the 'module' keyword.
2362 DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc);
2363
2364 /// The parser has processed a private-module-fragment declaration that begins
2365 /// the definition of the private module fragment of the current module unit.
2366 /// \param ModuleLoc The location of the 'module' keyword.
2367 /// \param PrivateLoc The location of the 'private' keyword.
2368 DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc,
2369 SourceLocation PrivateLoc);
2370
2371 /// The parser has processed a module import declaration.
2372 ///
2373 /// \param StartLoc The location of the first token in the declaration. This
2374 /// could be the location of an '@', 'export', or 'import'.
2375 /// \param ExportLoc The location of the 'export' keyword, if any.
2376 /// \param ImportLoc The location of the 'import' keyword.
2377 /// \param Path The module access path.
2378 DeclResult ActOnModuleImport(SourceLocation StartLoc,
2379 SourceLocation ExportLoc,
2380 SourceLocation ImportLoc, ModuleIdPath Path);
2381 DeclResult ActOnModuleImport(SourceLocation StartLoc,
2382 SourceLocation ExportLoc,
2383 SourceLocation ImportLoc, Module *M,
2384 ModuleIdPath Path = {});
2385
2386 /// The parser has processed a module import translated from a
2387 /// #include or similar preprocessing directive.
2388 void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
2389 void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
2390
2391 /// The parsed has entered a submodule.
2392 void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
2393 /// The parser has left a submodule.
2394 void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
2395
2396 /// Create an implicit import of the given module at the given
2397 /// source location, for error recovery, if possible.
2398 ///
2399 /// This routine is typically used when an entity found by name lookup
2400 /// is actually hidden within a module that we know about but the user
2401 /// has forgotten to import.
2402 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
2403 Module *Mod);
2404
2405 /// Kinds of missing import. Note, the values of these enumerators correspond
2406 /// to %select values in diagnostics.
2407 enum class MissingImportKind {
2408 Declaration,
2409 Definition,
2410 DefaultArgument,
2411 ExplicitSpecialization,
2412 PartialSpecialization
2413 };
2414
2415 /// Diagnose that the specified declaration needs to be visible but
2416 /// isn't, and suggest a module import that would resolve the problem.
2417 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2418 MissingImportKind MIK, bool Recover = true);
2419 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2420 SourceLocation DeclLoc, ArrayRef<Module *> Modules,
2421 MissingImportKind MIK, bool Recover);
2422
2423 Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
2424 SourceLocation LBraceLoc);
2425 Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
2426 SourceLocation RBraceLoc);
2427
2428 /// We've found a use of a templated declaration that would trigger an
2429 /// implicit instantiation. Check that any relevant explicit specializations
2430 /// and partial specializations are visible, and diagnose if not.
2431 void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
2432
2433 /// We've found a use of a template specialization that would select a
2434 /// partial specialization. Check that the partial specialization is visible,
2435 /// and diagnose if not.
2436 void checkPartialSpecializationVisibility(SourceLocation Loc,
2437 NamedDecl *Spec);
2438
2439 /// Retrieve a suitable printing policy for diagnostics.
2440 PrintingPolicy getPrintingPolicy() const {
2441 return getPrintingPolicy(Context, PP);
2442 }
2443
2444 /// Retrieve a suitable printing policy for diagnostics.
2445 static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
2446 const Preprocessor &PP);
2447
2448 /// Scope actions.
2449 void ActOnPopScope(SourceLocation Loc, Scope *S);
2450 void ActOnTranslationUnitScope(Scope *S);
2451
2452 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2453 RecordDecl *&AnonRecord);
2454 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2455 MultiTemplateParamsArg TemplateParams,
2456 bool IsExplicitInstantiation,
2457 RecordDecl *&AnonRecord);
2458
2459 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
2460 AccessSpecifier AS,
2461 RecordDecl *Record,
2462 const PrintingPolicy &Policy);
2463
2464 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
2465 RecordDecl *Record);
2466
2467 /// Common ways to introduce type names without a tag for use in diagnostics.
2468 /// Keep in sync with err_tag_reference_non_tag.
2469 enum NonTagKind {
2470 NTK_NonStruct,
2471 NTK_NonClass,
2472 NTK_NonUnion,
2473 NTK_NonEnum,
2474 NTK_Typedef,
2475 NTK_TypeAlias,
2476 NTK_Template,
2477 NTK_TypeAliasTemplate,
2478 NTK_TemplateTemplateArgument,
2479 };
2480
2481 /// Given a non-tag type declaration, returns an enum useful for indicating
2482 /// what kind of non-tag type this is.
2483 NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
2484
2485 bool isAcceptableTagRedeclaration(const TagDecl *Previous,
2486 TagTypeKind NewTag, bool isDefinition,
2487 SourceLocation NewTagLoc,
2488 const IdentifierInfo *Name);
2489
2490 enum TagUseKind {
2491 TUK_Reference, // Reference to a tag: 'struct foo *X;'
2492 TUK_Declaration, // Fwd decl of a tag: 'struct foo;'
2493 TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;'
2494 TUK_Friend // Friend declaration: 'friend struct foo;'
2495 };
2496
2497 Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
2498 SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name,
2499 SourceLocation NameLoc, const ParsedAttributesView &Attr,
2500 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
2501 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
2502 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
2503 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
2504 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
2505 SkipBodyInfo *SkipBody = nullptr);
2506
2507 Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
2508 unsigned TagSpec, SourceLocation TagLoc,
2509 CXXScopeSpec &SS, IdentifierInfo *Name,
2510 SourceLocation NameLoc,
2511 const ParsedAttributesView &Attr,
2512 MultiTemplateParamsArg TempParamLists);
2513
2514 TypeResult ActOnDependentTag(Scope *S,
2515 unsigned TagSpec,
2516 TagUseKind TUK,
2517 const CXXScopeSpec &SS,
2518 IdentifierInfo *Name,
2519 SourceLocation TagLoc,
2520 SourceLocation NameLoc);
2521
2522 void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
2523 IdentifierInfo *ClassName,
2524 SmallVectorImpl<Decl *> &Decls);
2525 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
2526 Declarator &D, Expr *BitfieldWidth);
2527
2528 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
2529 Declarator &D, Expr *BitfieldWidth,
2530 InClassInitStyle InitStyle,
2531 AccessSpecifier AS);
2532 MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
2533 SourceLocation DeclStart, Declarator &D,
2534 Expr *BitfieldWidth,
2535 InClassInitStyle InitStyle,
2536 AccessSpecifier AS,
2537 const ParsedAttr &MSPropertyAttr);
2538
2539 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
2540 TypeSourceInfo *TInfo,
2541 RecordDecl *Record, SourceLocation Loc,
2542 bool Mutable, Expr *BitfieldWidth,
2543 InClassInitStyle InitStyle,
2544 SourceLocation TSSL,
2545 AccessSpecifier AS, NamedDecl *PrevDecl,
2546 Declarator *D = nullptr);
2547
2548 bool CheckNontrivialField(FieldDecl *FD);
2549 void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
2550
2551 enum TrivialABIHandling {
2552 /// The triviality of a method unaffected by "trivial_abi".
2553 TAH_IgnoreTrivialABI,
2554
2555 /// The triviality of a method affected by "trivial_abi".
2556 TAH_ConsiderTrivialABI
2557 };
2558
2559 bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
2560 TrivialABIHandling TAH = TAH_IgnoreTrivialABI,
2561 bool Diagnose = false);
2562
2563 /// For a defaulted function, the kind of defaulted function that it is.
2564 class DefaultedFunctionKind {
2565 CXXSpecialMember SpecialMember : 8;
2566 DefaultedComparisonKind Comparison : 8;
2567
2568 public:
2569 DefaultedFunctionKind()
2570 : SpecialMember(CXXInvalid), Comparison(DefaultedComparisonKind::None) {
2571 }
2572 DefaultedFunctionKind(CXXSpecialMember CSM)
2573 : SpecialMember(CSM), Comparison(DefaultedComparisonKind::None) {}
2574 DefaultedFunctionKind(DefaultedComparisonKind Comp)
2575 : SpecialMember(CXXInvalid), Comparison(Comp) {}
2576
2577 bool isSpecialMember() const { return SpecialMember != CXXInvalid; }
2578 bool isComparison() const {
2579 return Comparison != DefaultedComparisonKind::None;
2580 }
2581
2582 explicit operator bool() const {
2583 return isSpecialMember() || isComparison();
2584 }
2585
2586 CXXSpecialMember asSpecialMember() const { return SpecialMember; }
2587 DefaultedComparisonKind asComparison() const { return Comparison; }
2588
2589 /// Get the index of this function kind for use in diagnostics.
2590 unsigned getDiagnosticIndex() const {
2591 static_assert(CXXInvalid > CXXDestructor,
2592 "invalid should have highest index");
2593 static_assert((unsigned)DefaultedComparisonKind::None == 0,
2594 "none should be equal to zero");
2595 return SpecialMember + (unsigned)Comparison;
2596 }
2597 };
2598
2599 DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD);
2600
2601 CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD) {
2602 return getDefaultedFunctionKind(MD).asSpecialMember();
2603 }
2604 DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD) {
2605 return getDefaultedFunctionKind(FD).asComparison();
2606 }
2607
2608 void ActOnLastBitfield(SourceLocation DeclStart,
2609 SmallVectorImpl<Decl *> &AllIvarDecls);
2610 Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
2611 Declarator &D, Expr *BitfieldWidth,
2612 tok::ObjCKeywordKind visibility);
2613
2614 // This is used for both record definitions and ObjC interface declarations.
2615 void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl,