Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaTemplateInstantiate.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-12/lib/clang/12.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/clang/lib/Sema -I /build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/clang/include -I /build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/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-12/lib/clang/12.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-12~++20201129111111+e987fbdd85d/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-11-29-190409-37574-1 -x c++ /build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/clang/lib/Sema/SemaTemplateInstantiate.cpp

/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/clang/lib/Sema/SemaTemplateInstantiate.cpp

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

/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/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/ASTConcept.h"
18#include "clang/AST/ASTFwd.h"
19#include "clang/AST/Attr.h"
20#include "clang/AST/Availability.h"
21#include "clang/AST/ComparisonCategories.h"
22#include "clang/AST/DeclTemplate.h"
23#include "clang/AST/DeclarationName.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
26#include "clang/AST/ExprConcepts.h"
27#include "clang/AST/ExprObjC.h"
28#include "clang/AST/ExprOpenMP.h"
29#include "clang/AST/ExternalASTSource.h"
30#include "clang/AST/LocInfoType.h"
31#include "clang/AST/MangleNumberingContext.h"
32#include "clang/AST/NSAPI.h"
33#include "clang/AST/PrettyPrinter.h"
34#include "clang/AST/StmtCXX.h"
35#include "clang/AST/TypeLoc.h"
36#include "clang/AST/TypeOrdering.h"
37#include "clang/Basic/BitmaskEnum.h"
38#include "clang/Basic/ExpressionTraits.h"
39#include "clang/Basic/Module.h"
40#include "clang/Basic/OpenCLOptions.h"
41#include "clang/Basic/OpenMPKinds.h"
42#include "clang/Basic/PragmaKinds.h"
43#include "clang/Basic/Specifiers.h"
44#include "clang/Basic/TemplateKinds.h"
45#include "clang/Basic/TypeTraits.h"
46#include "clang/Sema/AnalysisBasedWarnings.h"
47#include "clang/Sema/CleanupInfo.h"
48#include "clang/Sema/DeclSpec.h"
49#include "clang/Sema/ExternalSemaSource.h"
50#include "clang/Sema/IdentifierResolver.h"
51#include "clang/Sema/ObjCMethodList.h"
52#include "clang/Sema/Ownership.h"
53#include "clang/Sema/Scope.h"
54#include "clang/Sema/SemaConcept.h"
55#include "clang/Sema/TypoCorrection.h"
56#include "clang/Sema/Weak.h"
57#include "llvm/ADT/ArrayRef.h"
58#include "llvm/ADT/Optional.h"
59#include "llvm/ADT/SetVector.h"
60#include "llvm/ADT/SmallBitVector.h"
61#include "llvm/ADT/SmallSet.h"
62#include "llvm/ADT/SmallPtrSet.h"
63#include "llvm/ADT/SmallVector.h"
64#include "llvm/ADT/TinyPtrVector.h"
65#include "llvm/Frontend/OpenMP/OMPConstants.h"
66#include <deque>
67#include <memory>
68#include <string>
69#include <tuple>
70#include <vector>
71
72namespace llvm {
73 class APSInt;
74 template <typename ValueT> struct DenseMapInfo;
75 template <typename ValueT, typename ValueInfoT> class DenseSet;
76 class SmallBitVector;
77 struct InlineAsmIdentifierInfo;
78}
79
80namespace clang {
81 class ADLResult;
82 class ASTConsumer;
83 class ASTContext;
84 class ASTMutationListener;
85 class ASTReader;
86 class ASTWriter;
87 class ArrayType;
88 class ParsedAttr;
89 class BindingDecl;
90 class BlockDecl;
91 class CapturedDecl;
92 class CXXBasePath;
93 class CXXBasePaths;
94 class CXXBindTemporaryExpr;
95 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
96 class CXXConstructorDecl;
97 class CXXConversionDecl;
98 class CXXDeleteExpr;
99 class CXXDestructorDecl;
100 class CXXFieldCollector;
101 class CXXMemberCallExpr;
102 class CXXMethodDecl;
103 class CXXScopeSpec;
104 class CXXTemporary;
105 class CXXTryStmt;
106 class CallExpr;
107 class ClassTemplateDecl;
108 class ClassTemplatePartialSpecializationDecl;
109 class ClassTemplateSpecializationDecl;
110 class VarTemplatePartialSpecializationDecl;
111 class CodeCompleteConsumer;
112 class CodeCompletionAllocator;
113 class CodeCompletionTUInfo;
114 class CodeCompletionResult;
115 class CoroutineBodyStmt;
116 class Decl;
117 class DeclAccessPair;
118 class DeclContext;
119 class DeclRefExpr;
120 class DeclaratorDecl;
121 class DeducedTemplateArgument;
122 class DependentDiagnostic;
123 class DesignatedInitExpr;
124 class Designation;
125 class EnableIfAttr;
126 class EnumConstantDecl;
127 class Expr;
128 class ExtVectorType;
129 class FormatAttr;
130 class FriendDecl;
131 class FunctionDecl;
132 class FunctionProtoType;
133 class FunctionTemplateDecl;
134 class ImplicitConversionSequence;
135 typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList;
136 class InitListExpr;
137 class InitializationKind;
138 class InitializationSequence;
139 class InitializedEntity;
140 class IntegerLiteral;
141 class LabelStmt;
142 class LambdaExpr;
143 class LangOptions;
144 class LocalInstantiationScope;
145 class LookupResult;
146 class MacroInfo;
147 typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath;
148 class ModuleLoader;
149 class MultiLevelTemplateArgumentList;
150 class NamedDecl;
151 class ObjCCategoryDecl;
152 class ObjCCategoryImplDecl;
153 class ObjCCompatibleAliasDecl;
154 class ObjCContainerDecl;
155 class ObjCImplDecl;
156 class ObjCImplementationDecl;
157 class ObjCInterfaceDecl;
158 class ObjCIvarDecl;
159 template <class T> class ObjCList;
160 class ObjCMessageExpr;
161 class ObjCMethodDecl;
162 class ObjCPropertyDecl;
163 class ObjCProtocolDecl;
164 class OMPThreadPrivateDecl;
165 class OMPRequiresDecl;
166 class OMPDeclareReductionDecl;
167 class OMPDeclareSimdDecl;
168 class OMPClause;
169 struct OMPVarListLocTy;
170 struct OverloadCandidate;
171 enum class OverloadCandidateParamOrder : char;
172 enum OverloadCandidateRewriteKind : unsigned;
173 class OverloadCandidateSet;
174 class OverloadExpr;
175 class ParenListExpr;
176 class ParmVarDecl;
177 class Preprocessor;
178 class PseudoDestructorTypeStorage;
179 class PseudoObjectExpr;
180 class QualType;
181 class StandardConversionSequence;
182 class Stmt;
183 class StringLiteral;
184 class SwitchStmt;
185 class TemplateArgument;
186 class TemplateArgumentList;
187 class TemplateArgumentLoc;
188 class TemplateDecl;
189 class TemplateInstantiationCallback;
190 class TemplateParameterList;
191 class TemplatePartialOrderingContext;
192 class TemplateTemplateParmDecl;
193 class Token;
194 class TypeAliasDecl;
195 class TypedefDecl;
196 class TypedefNameDecl;
197 class TypeLoc;
198 class TypoCorrectionConsumer;
199 class UnqualifiedId;
200 class UnresolvedLookupExpr;
201 class UnresolvedMemberExpr;
202 class UnresolvedSetImpl;
203 class UnresolvedSetIterator;
204 class UsingDecl;
205 class UsingShadowDecl;
206 class ValueDecl;
207 class VarDecl;
208 class VarTemplateSpecializationDecl;
209 class VisibilityAttr;
210 class VisibleDeclConsumer;
211 class IndirectFieldDecl;
212 struct DeductionFailureInfo;
213 class TemplateSpecCandidateSet;
214
215namespace sema {
216 class AccessedEntity;
217 class BlockScopeInfo;
218 class Capture;
219 class CapturedRegionScopeInfo;
220 class CapturingScopeInfo;
221 class CompoundScopeInfo;
222 class DelayedDiagnostic;
223 class DelayedDiagnosticPool;
224 class FunctionScopeInfo;
225 class LambdaScopeInfo;
226 class PossiblyUnreachableDiag;
227 class SemaPPCallbacks;
228 class TemplateDeductionInfo;
229}
230
231namespace threadSafety {
232 class BeforeSet;
233 void threadSafetyCleanup(BeforeSet* Cache);
234}
235
236// FIXME: No way to easily map from TemplateTypeParmTypes to
237// TemplateTypeParmDecls, so we have this horrible PointerUnion.
238typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
239 SourceLocation> UnexpandedParameterPack;
240
241/// Describes whether we've seen any nullability information for the given
242/// file.
243struct FileNullability {
244 /// The first pointer declarator (of any pointer kind) in the file that does
245 /// not have a corresponding nullability annotation.
246 SourceLocation PointerLoc;
247
248 /// The end location for the first pointer declarator in the file. Used for
249 /// placing fix-its.
250 SourceLocation PointerEndLoc;
251
252 /// Which kind of pointer declarator we saw.
253 uint8_t PointerKind;
254
255 /// Whether we saw any type nullability annotations in the given file.
256 bool SawTypeNullability = false;
257};
258
259/// A mapping from file IDs to a record of whether we've seen nullability
260/// information in that file.
261class FileNullabilityMap {
262 /// A mapping from file IDs to the nullability information for each file ID.
263 llvm::DenseMap<FileID, FileNullability> Map;
264
265 /// A single-element cache based on the file ID.
266 struct {
267 FileID File;
268 FileNullability Nullability;
269 } Cache;
270
271public:
272 FileNullability &operator[](FileID file) {
273 // Check the single-element cache.
274 if (file == Cache.File)
275 return Cache.Nullability;
276
277 // It's not in the single-element cache; flush the cache if we have one.
278 if (!Cache.File.isInvalid()) {
279 Map[Cache.File] = Cache.Nullability;
280 }
281
282 // Pull this entry into the cache.
283 Cache.File = file;
284 Cache.Nullability = Map[file];
285 return Cache.Nullability;
286 }
287};
288
289/// Keeps track of expected type during expression parsing. The type is tied to
290/// a particular token, all functions that update or consume the type take a
291/// start location of the token they are looking at as a parameter. This allows
292/// to avoid updating the type on hot paths in the parser.
293class PreferredTypeBuilder {
294public:
295 PreferredTypeBuilder() = default;
296 explicit PreferredTypeBuilder(QualType Type) : Type(Type) {}
297
298 void enterCondition(Sema &S, SourceLocation Tok);
299 void enterReturn(Sema &S, SourceLocation Tok);
300 void enterVariableInit(SourceLocation Tok, Decl *D);
301 /// Computing a type for the function argument may require running
302 /// overloading, so we postpone its computation until it is actually needed.
303 ///
304 /// Clients should be very careful when using this funciton, as it stores a
305 /// function_ref, clients should make sure all calls to get() with the same
306 /// location happen while function_ref is alive.
307 void enterFunctionArgument(SourceLocation Tok,
308 llvm::function_ref<QualType()> ComputeType);
309
310 void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc);
311 void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind,
312 SourceLocation OpLoc);
313 void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op);
314 void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base);
315 void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS);
316 /// Handles all type casts, including C-style cast, C++ casts, etc.
317 void enterTypeCast(SourceLocation Tok, QualType CastType);
318
319 QualType get(SourceLocation Tok) const {
320 if (Tok != ExpectedLoc)
321 return QualType();
322 if (!Type.isNull())
323 return Type;
324 if (ComputeType)
325 return ComputeType();
326 return QualType();
327 }
328
329private:
330 /// Start position of a token for which we store expected type.
331 SourceLocation ExpectedLoc;
332 /// Expected type for a token starting at ExpectedLoc.
333 QualType Type;
334 /// A function to compute expected type at ExpectedLoc. It is only considered
335 /// if Type is null.
336 llvm::function_ref<QualType()> ComputeType;
337};
338
339/// Sema - This implements semantic analysis and AST building for C.
340class Sema final {
341 Sema(const Sema &) = delete;
342 void operator=(const Sema &) = delete;
343
344 /// A key method to reduce duplicate debug info from Sema.
345 virtual void anchor();
346
347 ///Source of additional semantic information.
348 ExternalSemaSource *ExternalSource;
349
350 ///Whether Sema has generated a multiplexer and has to delete it.
351 bool isMultiplexExternalSource;
352
353 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
354
355 bool isVisibleSlow(const NamedDecl *D);
356
357 /// Determine whether two declarations should be linked together, given that
358 /// the old declaration might not be visible and the new declaration might
359 /// not have external linkage.
360 bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
361 const NamedDecl *New) {
362 if (isVisible(Old))
363 return true;
364 // See comment in below overload for why it's safe to compute the linkage
365 // of the new declaration here.
366 if (New->isExternallyDeclarable()) {
367 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-12~++20201129111111+e987fbdd85d/clang/include/clang/Sema/Sema.h"
, 368, __PRETTY_FUNCTION__))
368 "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-12~++20201129111111+e987fbdd85d/clang/include/clang/Sema/Sema.h"
, 368, __PRETTY_FUNCTION__))
;
369 return true;
370 }
371 return false;
372 }
373 bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
374
375 void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
376 QualType ResultTy,
377 ArrayRef<QualType> Args);
378
379public:
380 /// The maximum alignment, same as in llvm::Value. We duplicate them here
381 /// because that allows us not to duplicate the constants in clang code,
382 /// which we must to since we can't directly use the llvm constants.
383 /// The value is verified against llvm here: lib/CodeGen/CGDecl.cpp
384 ///
385 /// This is the greatest alignment value supported by load, store, and alloca
386 /// instructions, and global values.
387 static const unsigned MaxAlignmentExponent = 29;
388 static const unsigned MaximumAlignment = 1u << MaxAlignmentExponent;
389
390 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
391 typedef OpaquePtr<TemplateName> TemplateTy;
392 typedef OpaquePtr<QualType> TypeTy;
393
394 OpenCLOptions OpenCLFeatures;
395 FPOptions CurFPFeatures;
396
397 const LangOptions &LangOpts;
398 Preprocessor &PP;
399 ASTContext &Context;
400 ASTConsumer &Consumer;
401 DiagnosticsEngine &Diags;
402 SourceManager &SourceMgr;
403
404 /// Flag indicating whether or not to collect detailed statistics.
405 bool CollectStats;
406
407 /// Code-completion consumer.
408 CodeCompleteConsumer *CodeCompleter;
409
410 /// CurContext - This is the current declaration context of parsing.
411 DeclContext *CurContext;
412
413 /// Generally null except when we temporarily switch decl contexts,
414 /// like in \see ActOnObjCTemporaryExitContainerContext.
415 DeclContext *OriginalLexicalContext;
416
417 /// VAListTagName - The declaration name corresponding to __va_list_tag.
418 /// This is used as part of a hack to omit that class from ADL results.
419 DeclarationName VAListTagName;
420
421 bool MSStructPragmaOn; // True when \#pragma ms_struct on
422
423 /// Controls member pointer representation format under the MS ABI.
424 LangOptions::PragmaMSPointersToMembersKind
425 MSPointerToMemberRepresentationMethod;
426
427 /// Stack of active SEH __finally scopes. Can be empty.
428 SmallVector<Scope*, 2> CurrentSEHFinally;
429
430 /// Source location for newly created implicit MSInheritanceAttrs
431 SourceLocation ImplicitMSInheritanceAttrLoc;
432
433 /// Holds TypoExprs that are created from `createDelayedTypo`. This is used by
434 /// `TransformTypos` in order to keep track of any TypoExprs that are created
435 /// recursively during typo correction and wipe them away if the correction
436 /// fails.
437 llvm::SmallVector<TypoExpr *, 2> TypoExprs;
438
439 /// pragma clang section kind
440 enum PragmaClangSectionKind {
441 PCSK_Invalid = 0,
442 PCSK_BSS = 1,
443 PCSK_Data = 2,
444 PCSK_Rodata = 3,
445 PCSK_Text = 4,
446 PCSK_Relro = 5
447 };
448
449 enum PragmaClangSectionAction {
450 PCSA_Set = 0,
451 PCSA_Clear = 1
452 };
453
454 struct PragmaClangSection {
455 std::string SectionName;
456 bool Valid = false;
457 SourceLocation PragmaLocation;
458
459 void Act(SourceLocation PragmaLocation,
460 PragmaClangSectionAction Action,
461 StringLiteral* Name);
462 };
463
464 PragmaClangSection PragmaClangBSSSection;
465 PragmaClangSection PragmaClangDataSection;
466 PragmaClangSection PragmaClangRodataSection;
467 PragmaClangSection PragmaClangRelroSection;
468 PragmaClangSection PragmaClangTextSection;
469
470 enum PragmaMsStackAction {
471 PSK_Reset = 0x0, // #pragma ()
472 PSK_Set = 0x1, // #pragma (value)
473 PSK_Push = 0x2, // #pragma (push[, id])
474 PSK_Pop = 0x4, // #pragma (pop[, id])
475 PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
476 PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
477 PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
478 };
479
480 template<typename ValueType>
481 struct PragmaStack {
482 struct Slot {
483 llvm::StringRef StackSlotLabel;
484 ValueType Value;
485 SourceLocation PragmaLocation;
486 SourceLocation PragmaPushLocation;
487 Slot(llvm::StringRef StackSlotLabel, ValueType Value,
488 SourceLocation PragmaLocation, SourceLocation PragmaPushLocation)
489 : StackSlotLabel(StackSlotLabel), Value(Value),
490 PragmaLocation(PragmaLocation),
491 PragmaPushLocation(PragmaPushLocation) {}
492 };
493
494 void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action,
495 llvm::StringRef StackSlotLabel, ValueType Value) {
496 if (Action == PSK_Reset) {
497 CurrentValue = DefaultValue;
498 CurrentPragmaLocation = PragmaLocation;
499 return;
500 }
501 if (Action & PSK_Push)
502 Stack.emplace_back(StackSlotLabel, CurrentValue, CurrentPragmaLocation,
503 PragmaLocation);
504 else if (Action & PSK_Pop) {
505 if (!StackSlotLabel.empty()) {
506 // If we've got a label, try to find it and jump there.
507 auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
508 return x.StackSlotLabel == StackSlotLabel;
509 });
510 // If we found the label so pop from there.
511 if (I != Stack.rend()) {
512 CurrentValue = I->Value;
513 CurrentPragmaLocation = I->PragmaLocation;
514 Stack.erase(std::prev(I.base()), Stack.end());
515 }
516 } else if (!Stack.empty()) {
517 // We do not have a label, just pop the last entry.
518 CurrentValue = Stack.back().Value;
519 CurrentPragmaLocation = Stack.back().PragmaLocation;
520 Stack.pop_back();
521 }
522 }
523 if (Action & PSK_Set) {
524 CurrentValue = Value;
525 CurrentPragmaLocation = PragmaLocation;
526 }
527 }
528
529 // MSVC seems to add artificial slots to #pragma stacks on entering a C++
530 // method body to restore the stacks on exit, so it works like this:
531 //
532 // struct S {
533 // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
534 // void Method {}
535 // #pragma <name>(pop, InternalPragmaSlot)
536 // };
537 //
538 // It works even with #pragma vtordisp, although MSVC doesn't support
539 // #pragma vtordisp(push [, id], n)
540 // syntax.
541 //
542 // Push / pop a named sentinel slot.
543 void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
544 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-12~++20201129111111+e987fbdd85d/clang/include/clang/Sema/Sema.h"
, 545, __PRETTY_FUNCTION__))
545 "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-12~++20201129111111+e987fbdd85d/clang/include/clang/Sema/Sema.h"
, 545, __PRETTY_FUNCTION__))
;
546 Act(CurrentPragmaLocation, Action, Label, CurrentValue);
547 }
548
549 // Constructors.
550 explicit PragmaStack(const ValueType &Default)
551 : DefaultValue(Default), CurrentValue(Default) {}
552
553 bool hasValue() const { return CurrentValue != DefaultValue; }
554
555 SmallVector<Slot, 2> Stack;
556 ValueType DefaultValue; // Value used for PSK_Reset action.
557 ValueType CurrentValue;
558 SourceLocation CurrentPragmaLocation;
559 };
560 // FIXME: We should serialize / deserialize these if they occur in a PCH (but
561 // we shouldn't do so if they're in a module).
562
563 /// Whether to insert vtordisps prior to virtual bases in the Microsoft
564 /// C++ ABI. Possible values are 0, 1, and 2, which mean:
565 ///
566 /// 0: Suppress all vtordisps
567 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
568 /// structors
569 /// 2: Always insert vtordisps to support RTTI on partially constructed
570 /// objects
571 PragmaStack<MSVtorDispMode> VtorDispStack;
572 // #pragma pack.
573 // Sentinel to represent when the stack is set to mac68k alignment.
574 static const unsigned kMac68kAlignmentSentinel = ~0U;
575 PragmaStack<unsigned> PackStack;
576 // The current #pragma pack values and locations at each #include.
577 struct PackIncludeState {
578 unsigned CurrentValue;
579 SourceLocation CurrentPragmaLocation;
580 bool HasNonDefaultValue, ShouldWarnOnInclude;
581 };
582 SmallVector<PackIncludeState, 8> PackIncludeStack;
583 // Segment #pragmas.
584 PragmaStack<StringLiteral *> DataSegStack;
585 PragmaStack<StringLiteral *> BSSSegStack;
586 PragmaStack<StringLiteral *> ConstSegStack;
587 PragmaStack<StringLiteral *> CodeSegStack;
588
589 // This stack tracks the current state of Sema.CurFPFeatures.
590 PragmaStack<FPOptionsOverride> FpPragmaStack;
591 FPOptionsOverride CurFPFeatureOverrides() {
592 FPOptionsOverride result;
593 if (!FpPragmaStack.hasValue()) {
594 result = FPOptionsOverride();
595 } else {
596 result = FpPragmaStack.CurrentValue;
597 }
598 return result;
599 }
600
601 // RAII object to push / pop sentinel slots for all MS #pragma stacks.
602 // Actions should be performed only if we enter / exit a C++ method body.
603 class PragmaStackSentinelRAII {
604 public:
605 PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
606 ~PragmaStackSentinelRAII();
607
608 private:
609 Sema &S;
610 StringRef SlotLabel;
611 bool ShouldAct;
612 };
613
614 /// A mapping that describes the nullability we've seen in each header file.
615 FileNullabilityMap NullabilityMap;
616
617 /// Last section used with #pragma init_seg.
618 StringLiteral *CurInitSeg;
619 SourceLocation CurInitSegLoc;
620
621 /// VisContext - Manages the stack for \#pragma GCC visibility.
622 void *VisContext; // Really a "PragmaVisStack*"
623
624 /// This an attribute introduced by \#pragma clang attribute.
625 struct PragmaAttributeEntry {
626 SourceLocation Loc;
627 ParsedAttr *Attribute;
628 SmallVector<attr::SubjectMatchRule, 4> MatchRules;
629 bool IsUsed;
630 };
631
632 /// A push'd group of PragmaAttributeEntries.
633 struct PragmaAttributeGroup {
634 /// The location of the push attribute.
635 SourceLocation Loc;
636 /// The namespace of this push group.
637 const IdentifierInfo *Namespace;
638 SmallVector<PragmaAttributeEntry, 2> Entries;
639 };
640
641 SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack;
642
643 /// The declaration that is currently receiving an attribute from the
644 /// #pragma attribute stack.
645 const Decl *PragmaAttributeCurrentTargetDecl;
646
647 /// This represents the last location of a "#pragma clang optimize off"
648 /// directive if such a directive has not been closed by an "on" yet. If
649 /// optimizations are currently "on", this is set to an invalid location.
650 SourceLocation OptimizeOffPragmaLocation;
651
652 /// Flag indicating if Sema is building a recovery call expression.
653 ///
654 /// This flag is used to avoid building recovery call expressions
655 /// if Sema is already doing so, which would cause infinite recursions.
656 bool IsBuildingRecoveryCallExpr;
657
658 /// Used to control the generation of ExprWithCleanups.
659 CleanupInfo Cleanup;
660
661 /// ExprCleanupObjects - This is the stack of objects requiring
662 /// cleanup that are created by the current full expression.
663 SmallVector<ExprWithCleanups::CleanupObject, 8> ExprCleanupObjects;
664
665 /// Store a set of either DeclRefExprs or MemberExprs that contain a reference
666 /// to a variable (constant) that may or may not be odr-used in this Expr, and
667 /// we won't know until all lvalue-to-rvalue and discarded value conversions
668 /// have been applied to all subexpressions of the enclosing full expression.
669 /// This is cleared at the end of each full expression.
670 using MaybeODRUseExprSet = llvm::SetVector<Expr *, SmallVector<Expr *, 4>,
671 llvm::SmallPtrSet<Expr *, 4>>;
672 MaybeODRUseExprSet MaybeODRUseExprs;
673
674 std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope;
675
676 /// Stack containing information about each of the nested
677 /// function, block, and method scopes that are currently active.
678 SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
679
680 /// The index of the first FunctionScope that corresponds to the current
681 /// context.
682 unsigned FunctionScopesStart = 0;
683
684 ArrayRef<sema::FunctionScopeInfo*> getFunctionScopes() const {
685 return llvm::makeArrayRef(FunctionScopes.begin() + FunctionScopesStart,
686 FunctionScopes.end());
687 }
688
689 /// Stack containing information needed when in C++2a an 'auto' is encountered
690 /// in a function declaration parameter type specifier in order to invent a
691 /// corresponding template parameter in the enclosing abbreviated function
692 /// template. This information is also present in LambdaScopeInfo, stored in
693 /// the FunctionScopes stack.
694 SmallVector<InventedTemplateParameterInfo, 4> InventedParameterInfos;
695
696 /// The index of the first InventedParameterInfo that refers to the current
697 /// context.
698 unsigned InventedParameterInfosStart = 0;
699
700 ArrayRef<InventedTemplateParameterInfo> getInventedParameterInfos() const {
701 return llvm::makeArrayRef(InventedParameterInfos.begin() +
702 InventedParameterInfosStart,
703 InventedParameterInfos.end());
704 }
705
706 typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
707 &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
708 ExtVectorDeclsType;
709
710 /// ExtVectorDecls - This is a list all the extended vector types. This allows
711 /// us to associate a raw vector type with one of the ext_vector type names.
712 /// This is only necessary for issuing pretty diagnostics.
713 ExtVectorDeclsType ExtVectorDecls;
714
715 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
716 std::unique_ptr<CXXFieldCollector> FieldCollector;
717
718 typedef llvm::SmallSetVector<NamedDecl *, 16> NamedDeclSetType;
719
720 /// Set containing all declared private fields that are not used.
721 NamedDeclSetType UnusedPrivateFields;
722
723 /// Set containing all typedefs that are likely unused.
724 llvm::SmallSetVector<const TypedefNameDecl *, 4>
725 UnusedLocalTypedefNameCandidates;
726
727 /// Delete-expressions to be analyzed at the end of translation unit
728 ///
729 /// This list contains class members, and locations of delete-expressions
730 /// that could not be proven as to whether they mismatch with new-expression
731 /// used in initializer of the field.
732 typedef std::pair<SourceLocation, bool> DeleteExprLoc;
733 typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
734 llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
735
736 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
737
738 /// PureVirtualClassDiagSet - a set of class declarations which we have
739 /// emitted a list of pure virtual functions. Used to prevent emitting the
740 /// same list more than once.
741 std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
742
743 /// ParsingInitForAutoVars - a set of declarations with auto types for which
744 /// we are currently parsing the initializer.
745 llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
746
747 /// Look for a locally scoped extern "C" declaration by the given name.
748 NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
749
750 typedef LazyVector<VarDecl *, ExternalSemaSource,
751 &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
752 TentativeDefinitionsType;
753
754 /// All the tentative definitions encountered in the TU.
755 TentativeDefinitionsType TentativeDefinitions;
756
757 /// All the external declarations encoutered and used in the TU.
758 SmallVector<VarDecl *, 4> ExternalDeclarations;
759
760 typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
761 &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
762 UnusedFileScopedDeclsType;
763
764 /// The set of file scoped decls seen so far that have not been used
765 /// and must warn if not used. Only contains the first declaration.
766 UnusedFileScopedDeclsType UnusedFileScopedDecls;
767
768 typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
769 &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
770 DelegatingCtorDeclsType;
771
772 /// All the delegating constructors seen so far in the file, used for
773 /// cycle detection at the end of the TU.
774 DelegatingCtorDeclsType DelegatingCtorDecls;
775
776 /// All the overriding functions seen during a class definition
777 /// that had their exception spec checks delayed, plus the overridden
778 /// function.
779 SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2>
780 DelayedOverridingExceptionSpecChecks;
781
782 /// All the function redeclarations seen during a class definition that had
783 /// their exception spec checks delayed, plus the prior declaration they
784 /// should be checked against. Except during error recovery, the new decl
785 /// should always be a friend declaration, as that's the only valid way to
786 /// redeclare a special member before its class is complete.
787 SmallVector<std::pair<FunctionDecl*, FunctionDecl*>, 2>
788 DelayedEquivalentExceptionSpecChecks;
789
790 typedef llvm::MapVector<const FunctionDecl *,
791 std::unique_ptr<LateParsedTemplate>>
792 LateParsedTemplateMapT;
793 LateParsedTemplateMapT LateParsedTemplateMap;
794
795 /// Callback to the parser to parse templated functions when needed.
796 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
797 typedef void LateTemplateParserCleanupCB(void *P);
798 LateTemplateParserCB *LateTemplateParser;
799 LateTemplateParserCleanupCB *LateTemplateParserCleanup;
800 void *OpaqueParser;
801
802 void SetLateTemplateParser(LateTemplateParserCB *LTP,
803 LateTemplateParserCleanupCB *LTPCleanup,
804 void *P) {
805 LateTemplateParser = LTP;
806 LateTemplateParserCleanup = LTPCleanup;
807 OpaqueParser = P;
808 }
809
810 class DelayedDiagnostics;
811
812 class DelayedDiagnosticsState {
813 sema::DelayedDiagnosticPool *SavedPool;
814 friend class Sema::DelayedDiagnostics;
815 };
816 typedef DelayedDiagnosticsState ParsingDeclState;
817 typedef DelayedDiagnosticsState ProcessingContextState;
818
819 /// A class which encapsulates the logic for delaying diagnostics
820 /// during parsing and other processing.
821 class DelayedDiagnostics {
822 /// The current pool of diagnostics into which delayed
823 /// diagnostics should go.
824 sema::DelayedDiagnosticPool *CurPool;
825
826 public:
827 DelayedDiagnostics() : CurPool(nullptr) {}
828
829 /// Adds a delayed diagnostic.
830 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
831
832 /// Determines whether diagnostics should be delayed.
833 bool shouldDelayDiagnostics() { return CurPool != nullptr; }
834
835 /// Returns the current delayed-diagnostics pool.
836 sema::DelayedDiagnosticPool *getCurrentPool() const {
837 return CurPool;
838 }
839
840 /// Enter a new scope. Access and deprecation diagnostics will be
841 /// collected in this pool.
842 DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
843 DelayedDiagnosticsState state;
844 state.SavedPool = CurPool;
845 CurPool = &pool;
846 return state;
847 }
848
849 /// Leave a delayed-diagnostic state that was previously pushed.
850 /// Do not emit any of the diagnostics. This is performed as part
851 /// of the bookkeeping of popping a pool "properly".
852 void popWithoutEmitting(DelayedDiagnosticsState state) {
853 CurPool = state.SavedPool;
854 }
855
856 /// Enter a new scope where access and deprecation diagnostics are
857 /// not delayed.
858 DelayedDiagnosticsState pushUndelayed() {
859 DelayedDiagnosticsState state;
860 state.SavedPool = CurPool;
861 CurPool = nullptr;
862 return state;
863 }
864
865 /// Undo a previous pushUndelayed().
866 void popUndelayed(DelayedDiagnosticsState state) {
867 assert(CurPool == nullptr)((CurPool == nullptr) ? static_cast<void> (0) : __assert_fail
("CurPool == nullptr", "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/clang/include/clang/Sema/Sema.h"
, 867, __PRETTY_FUNCTION__))
;
868 CurPool = state.SavedPool;
869 }
870 } DelayedDiagnostics;
871
872 /// A RAII object to temporarily push a declaration context.
873 class ContextRAII {
874 private:
875 Sema &S;
876 DeclContext *SavedContext;
877 ProcessingContextState SavedContextState;
878 QualType SavedCXXThisTypeOverride;
879 unsigned SavedFunctionScopesStart;
880 unsigned SavedInventedParameterInfosStart;
881
882 public:
883 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
884 : S(S), SavedContext(S.CurContext),
885 SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
886 SavedCXXThisTypeOverride(S.CXXThisTypeOverride),
887 SavedFunctionScopesStart(S.FunctionScopesStart),
888 SavedInventedParameterInfosStart(S.InventedParameterInfosStart)
889 {
890 assert(ContextToPush && "pushing null context")((ContextToPush && "pushing null context") ? static_cast
<void> (0) : __assert_fail ("ContextToPush && \"pushing null context\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/clang/include/clang/Sema/Sema.h"
, 890, __PRETTY_FUNCTION__))
;
891 S.CurContext = ContextToPush;
892 if (NewThisContext)
893 S.CXXThisTypeOverride = QualType();
894 // Any saved FunctionScopes do not refer to this context.
895 S.FunctionScopesStart = S.FunctionScopes.size();
896 S.InventedParameterInfosStart = S.InventedParameterInfos.size();
897 }
898
899 void pop() {
900 if (!SavedContext) return;
901 S.CurContext = SavedContext;
902 S.DelayedDiagnostics.popUndelayed(SavedContextState);
903 S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
904 S.FunctionScopesStart = SavedFunctionScopesStart;
905 S.InventedParameterInfosStart = SavedInventedParameterInfosStart;
906 SavedContext = nullptr;
907 }
908
909 ~ContextRAII() {
910 pop();
911 }
912 };
913
914 /// Whether the AST is currently being rebuilt to correct immediate
915 /// invocations. Immediate invocation candidates and references to consteval
916 /// functions aren't tracked when this is set.
917 bool RebuildingImmediateInvocation = false;
918
919 /// Used to change context to isConstantEvaluated without pushing a heavy
920 /// ExpressionEvaluationContextRecord object.
921 bool isConstantEvaluatedOverride;
922
923 bool isConstantEvaluated() {
924 return ExprEvalContexts.back().isConstantEvaluated() ||
925 isConstantEvaluatedOverride;
926 }
927
928 /// RAII object to handle the state changes required to synthesize
929 /// a function body.
930 class SynthesizedFunctionScope {
931 Sema &S;
932 Sema::ContextRAII SavedContext;
933 bool PushedCodeSynthesisContext = false;
934
935 public:
936 SynthesizedFunctionScope(Sema &S, DeclContext *DC)
937 : S(S), SavedContext(S, DC) {
938 S.PushFunctionScope();
939 S.PushExpressionEvaluationContext(
940 Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
941 if (auto *FD = dyn_cast<FunctionDecl>(DC))
942 FD->setWillHaveBody(true);
943 else
944 assert(isa<ObjCMethodDecl>(DC))((isa<ObjCMethodDecl>(DC)) ? static_cast<void> (0
) : __assert_fail ("isa<ObjCMethodDecl>(DC)", "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/clang/include/clang/Sema/Sema.h"
, 944, __PRETTY_FUNCTION__))
;
945 }
946
947 void addContextNote(SourceLocation UseLoc) {
948 assert(!PushedCodeSynthesisContext)((!PushedCodeSynthesisContext) ? static_cast<void> (0) :
__assert_fail ("!PushedCodeSynthesisContext", "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/clang/include/clang/Sema/Sema.h"
, 948, __PRETTY_FUNCTION__))
;
949
950 Sema::CodeSynthesisContext Ctx;
951 Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction;
952 Ctx.PointOfInstantiation = UseLoc;
953 Ctx.Entity = cast<Decl>(S.CurContext);
954 S.pushCodeSynthesisContext(Ctx);
955
956 PushedCodeSynthesisContext = true;
957 }
958
959 ~SynthesizedFunctionScope() {
960 if (PushedCodeSynthesisContext)
961 S.popCodeSynthesisContext();
962 if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext))
963 FD->setWillHaveBody(false);
964 S.PopExpressionEvaluationContext();
965 S.PopFunctionScopeInfo();
966 }
967 };
968
969 /// WeakUndeclaredIdentifiers - Identifiers contained in
970 /// \#pragma weak before declared. rare. may alias another
971 /// identifier, declared or undeclared
972 llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers;
973
974 /// ExtnameUndeclaredIdentifiers - Identifiers contained in
975 /// \#pragma redefine_extname before declared. Used in Solaris system headers
976 /// to define functions that occur in multiple standards to call the version
977 /// in the currently selected standard.
978 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
979
980
981 /// Load weak undeclared identifiers from the external source.
982 void LoadExternalWeakUndeclaredIdentifiers();
983
984 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
985 /// \#pragma weak during processing of other Decls.
986 /// I couldn't figure out a clean way to generate these in-line, so
987 /// we store them here and handle separately -- which is a hack.
988 /// It would be best to refactor this.
989 SmallVector<Decl*,2> WeakTopLevelDecl;
990
991 IdentifierResolver IdResolver;
992
993 /// Translation Unit Scope - useful to Objective-C actions that need
994 /// to lookup file scope declarations in the "ordinary" C decl namespace.
995 /// For example, user-defined classes, built-in "id" type, etc.
996 Scope *TUScope;
997
998 /// The C++ "std" namespace, where the standard library resides.
999 LazyDeclPtr StdNamespace;
1000
1001 /// The C++ "std::bad_alloc" class, which is defined by the C++
1002 /// standard library.
1003 LazyDeclPtr StdBadAlloc;
1004
1005 /// The C++ "std::align_val_t" enum class, which is defined by the C++
1006 /// standard library.
1007 LazyDeclPtr StdAlignValT;
1008
1009 /// The C++ "std::experimental" namespace, where the experimental parts
1010 /// of the standard library resides.
1011 NamespaceDecl *StdExperimentalNamespaceCache;
1012
1013 /// The C++ "std::initializer_list" template, which is defined in
1014 /// \<initializer_list>.
1015 ClassTemplateDecl *StdInitializerList;
1016
1017 /// The C++ "std::coroutine_traits" template, which is defined in
1018 /// \<coroutine_traits>
1019 ClassTemplateDecl *StdCoroutineTraitsCache;
1020
1021 /// The C++ "type_info" declaration, which is defined in \<typeinfo>.
1022 RecordDecl *CXXTypeInfoDecl;
1023
1024 /// The MSVC "_GUID" struct, which is defined in MSVC header files.
1025 RecordDecl *MSVCGuidDecl;
1026
1027 /// Caches identifiers/selectors for NSFoundation APIs.
1028 std::unique_ptr<NSAPI> NSAPIObj;
1029
1030 /// The declaration of the Objective-C NSNumber class.
1031 ObjCInterfaceDecl *NSNumberDecl;
1032
1033 /// The declaration of the Objective-C NSValue class.
1034 ObjCInterfaceDecl *NSValueDecl;
1035
1036 /// Pointer to NSNumber type (NSNumber *).
1037 QualType NSNumberPointer;
1038
1039 /// Pointer to NSValue type (NSValue *).
1040 QualType NSValuePointer;
1041
1042 /// The Objective-C NSNumber methods used to create NSNumber literals.
1043 ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
1044
1045 /// The declaration of the Objective-C NSString class.
1046 ObjCInterfaceDecl *NSStringDecl;
1047
1048 /// Pointer to NSString type (NSString *).
1049 QualType NSStringPointer;
1050
1051 /// The declaration of the stringWithUTF8String: method.
1052 ObjCMethodDecl *StringWithUTF8StringMethod;
1053
1054 /// The declaration of the valueWithBytes:objCType: method.
1055 ObjCMethodDecl *ValueWithBytesObjCTypeMethod;
1056
1057 /// The declaration of the Objective-C NSArray class.
1058 ObjCInterfaceDecl *NSArrayDecl;
1059
1060 /// The declaration of the arrayWithObjects:count: method.
1061 ObjCMethodDecl *ArrayWithObjectsMethod;
1062
1063 /// The declaration of the Objective-C NSDictionary class.
1064 ObjCInterfaceDecl *NSDictionaryDecl;
1065
1066 /// The declaration of the dictionaryWithObjects:forKeys:count: method.
1067 ObjCMethodDecl *DictionaryWithObjectsMethod;
1068
1069 /// id<NSCopying> type.
1070 QualType QIDNSCopying;
1071
1072 /// will hold 'respondsToSelector:'
1073 Selector RespondsToSelectorSel;
1074
1075 /// A flag to remember whether the implicit forms of operator new and delete
1076 /// have been declared.
1077 bool GlobalNewDeleteDeclared;
1078
1079 /// A flag to indicate that we're in a context that permits abstract
1080 /// references to fields. This is really a
1081 bool AllowAbstractFieldReference;
1082
1083 /// Describes how the expressions currently being parsed are
1084 /// evaluated at run-time, if at all.
1085 enum class ExpressionEvaluationContext {
1086 /// The current expression and its subexpressions occur within an
1087 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
1088 /// \c sizeof, where the type of the expression may be significant but
1089 /// no code will be generated to evaluate the value of the expression at
1090 /// run time.
1091 Unevaluated,
1092
1093 /// The current expression occurs within a braced-init-list within
1094 /// an unevaluated operand. This is mostly like a regular unevaluated
1095 /// context, except that we still instantiate constexpr functions that are
1096 /// referenced here so that we can perform narrowing checks correctly.
1097 UnevaluatedList,
1098
1099 /// The current expression occurs within a discarded statement.
1100 /// This behaves largely similarly to an unevaluated operand in preventing
1101 /// definitions from being required, but not in other ways.
1102 DiscardedStatement,
1103
1104 /// The current expression occurs within an unevaluated
1105 /// operand that unconditionally permits abstract references to
1106 /// fields, such as a SIZE operator in MS-style inline assembly.
1107 UnevaluatedAbstract,
1108
1109 /// The current context is "potentially evaluated" in C++11 terms,
1110 /// but the expression is evaluated at compile-time (like the values of
1111 /// cases in a switch statement).
1112 ConstantEvaluated,
1113
1114 /// The current expression is potentially evaluated at run time,
1115 /// which means that code may be generated to evaluate the value of the
1116 /// expression at run time.
1117 PotentiallyEvaluated,
1118
1119 /// The current expression is potentially evaluated, but any
1120 /// declarations referenced inside that expression are only used if
1121 /// in fact the current expression is used.
1122 ///
1123 /// This value is used when parsing default function arguments, for which
1124 /// we would like to provide diagnostics (e.g., passing non-POD arguments
1125 /// through varargs) but do not want to mark declarations as "referenced"
1126 /// until the default argument is used.
1127 PotentiallyEvaluatedIfUsed
1128 };
1129
1130 using ImmediateInvocationCandidate = llvm::PointerIntPair<ConstantExpr *, 1>;
1131
1132 /// Data structure used to record current or nested
1133 /// expression evaluation contexts.
1134 struct ExpressionEvaluationContextRecord {
1135 /// The expression evaluation context.
1136 ExpressionEvaluationContext Context;
1137
1138 /// Whether the enclosing context needed a cleanup.
1139 CleanupInfo ParentCleanup;
1140
1141 /// Whether we are in a decltype expression.
1142 bool IsDecltype;
1143
1144 /// The number of active cleanup objects when we entered
1145 /// this expression evaluation context.
1146 unsigned NumCleanupObjects;
1147
1148 /// The number of typos encountered during this expression evaluation
1149 /// context (i.e. the number of TypoExprs created).
1150 unsigned NumTypos;
1151
1152 MaybeODRUseExprSet SavedMaybeODRUseExprs;
1153
1154 /// The lambdas that are present within this context, if it
1155 /// is indeed an unevaluated context.
1156 SmallVector<LambdaExpr *, 2> Lambdas;
1157
1158 /// The declaration that provides context for lambda expressions
1159 /// and block literals if the normal declaration context does not
1160 /// suffice, e.g., in a default function argument.
1161 Decl *ManglingContextDecl;
1162
1163 /// If we are processing a decltype type, a set of call expressions
1164 /// for which we have deferred checking the completeness of the return type.
1165 SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
1166
1167 /// If we are processing a decltype type, a set of temporary binding
1168 /// expressions for which we have deferred checking the destructor.
1169 SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
1170
1171 llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs;
1172
1173 /// Expressions appearing as the LHS of a volatile assignment in this
1174 /// context. We produce a warning for these when popping the context if
1175 /// they are not discarded-value expressions nor unevaluated operands.
1176 SmallVector<Expr*, 2> VolatileAssignmentLHSs;
1177
1178 /// Set of candidates for starting an immediate invocation.
1179 llvm::SmallVector<ImmediateInvocationCandidate, 4> ImmediateInvocationCandidates;
1180
1181 /// Set of DeclRefExprs referencing a consteval function when used in a
1182 /// context not already known to be immediately invoked.
1183 llvm::SmallPtrSet<DeclRefExpr *, 4> ReferenceToConsteval;
1184
1185 /// \brief Describes whether we are in an expression constext which we have
1186 /// to handle differently.
1187 enum ExpressionKind {
1188 EK_Decltype, EK_TemplateArgument, EK_Other
1189 } ExprContext;
1190
1191 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
1192 unsigned NumCleanupObjects,
1193 CleanupInfo ParentCleanup,
1194 Decl *ManglingContextDecl,
1195 ExpressionKind ExprContext)
1196 : Context(Context), ParentCleanup(ParentCleanup),
1197 NumCleanupObjects(NumCleanupObjects), NumTypos(0),
1198 ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext) {}
1199
1200 bool isUnevaluated() const {
1201 return Context == ExpressionEvaluationContext::Unevaluated ||
1202 Context == ExpressionEvaluationContext::UnevaluatedAbstract ||
1203 Context == ExpressionEvaluationContext::UnevaluatedList;
1204 }
1205 bool isConstantEvaluated() const {
1206 return Context == ExpressionEvaluationContext::ConstantEvaluated;
1207 }
1208 };
1209
1210 /// A stack of expression evaluation contexts.
1211 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
1212
1213 /// Emit a warning for all pending noderef expressions that we recorded.
1214 void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec);
1215
1216 /// Compute the mangling number context for a lambda expression or
1217 /// block literal. Also return the extra mangling decl if any.
1218 ///
1219 /// \param DC - The DeclContext containing the lambda expression or
1220 /// block literal.
1221 std::tuple<MangleNumberingContext *, Decl *>
1222 getCurrentMangleNumberContext(const DeclContext *DC);
1223
1224
1225 /// SpecialMemberOverloadResult - The overloading result for a special member
1226 /// function.
1227 ///
1228 /// This is basically a wrapper around PointerIntPair. The lowest bits of the
1229 /// integer are used to determine whether overload resolution succeeded.
1230 class SpecialMemberOverloadResult {
1231 public:
1232 enum Kind {
1233 NoMemberOrDeleted,
1234 Ambiguous,
1235 Success
1236 };
1237
1238 private:
1239 llvm::PointerIntPair<CXXMethodDecl*, 2> Pair;
1240
1241 public:
1242 SpecialMemberOverloadResult() : Pair() {}
1243 SpecialMemberOverloadResult(CXXMethodDecl *MD)
1244 : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
1245
1246 CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
1247 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
1248
1249 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
1250 void setKind(Kind K) { Pair.setInt(K); }
1251 };
1252
1253 class SpecialMemberOverloadResultEntry
1254 : public llvm::FastFoldingSetNode,
1255 public SpecialMemberOverloadResult {
1256 public:
1257 SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
1258 : FastFoldingSetNode(ID)
1259 {}
1260 };
1261
1262 /// A cache of special member function overload resolution results
1263 /// for C++ records.
1264 llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
1265
1266 /// A cache of the flags available in enumerations with the flag_bits
1267 /// attribute.
1268 mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
1269
1270 /// The kind of translation unit we are processing.
1271 ///
1272 /// When we're processing a complete translation unit, Sema will perform
1273 /// end-of-translation-unit semantic tasks (such as creating
1274 /// initializers for tentative definitions in C) once parsing has
1275 /// completed. Modules and precompiled headers perform different kinds of
1276 /// checks.
1277 TranslationUnitKind TUKind;
1278
1279 llvm::BumpPtrAllocator BumpAlloc;
1280
1281 /// The number of SFINAE diagnostics that have been trapped.
1282 unsigned NumSFINAEErrors;
1283
1284 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
1285 UnparsedDefaultArgInstantiationsMap;
1286
1287 /// A mapping from parameters with unparsed default arguments to the
1288 /// set of instantiations of each parameter.
1289 ///
1290 /// This mapping is a temporary data structure used when parsing
1291 /// nested class templates or nested classes of class templates,
1292 /// where we might end up instantiating an inner class before the
1293 /// default arguments of its methods have been parsed.
1294 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
1295
1296 // Contains the locations of the beginning of unparsed default
1297 // argument locations.
1298 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
1299
1300 /// UndefinedInternals - all the used, undefined objects which require a
1301 /// definition in this translation unit.
1302 llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
1303
1304 /// Determine if VD, which must be a variable or function, is an external
1305 /// symbol that nonetheless can't be referenced from outside this translation
1306 /// unit because its type has no linkage and it's not extern "C".
1307 bool isExternalWithNoLinkageType(ValueDecl *VD);
1308
1309 /// Obtain a sorted list of functions that are undefined but ODR-used.
1310 void getUndefinedButUsed(
1311 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
1312
1313 /// Retrieves list of suspicious delete-expressions that will be checked at
1314 /// the end of translation unit.
1315 const llvm::MapVector<FieldDecl *, DeleteLocs> &
1316 getMismatchingDeleteExpressions() const;
1317
1318 typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods;
1319 typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool;
1320
1321 /// Method Pool - allows efficient lookup when typechecking messages to "id".
1322 /// We need to maintain a list, since selectors can have differing signatures
1323 /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
1324 /// of selectors are "overloaded").
1325 /// At the head of the list it is recorded whether there were 0, 1, or >= 2
1326 /// methods inside categories with a particular selector.
1327 GlobalMethodPool MethodPool;
1328
1329 /// Method selectors used in a \@selector expression. Used for implementation
1330 /// of -Wselector.
1331 llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
1332
1333 /// List of SourceLocations where 'self' is implicitly retained inside a
1334 /// block.
1335 llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1>
1336 ImplicitlyRetainedSelfLocs;
1337
1338 /// Kinds of C++ special members.
1339 enum CXXSpecialMember {
1340 CXXDefaultConstructor,
1341 CXXCopyConstructor,
1342 CXXMoveConstructor,
1343 CXXCopyAssignment,
1344 CXXMoveAssignment,
1345 CXXDestructor,
1346 CXXInvalid
1347 };
1348
1349 typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember>
1350 SpecialMemberDecl;
1351
1352 /// The C++ special members which we are currently in the process of
1353 /// declaring. If this process recursively triggers the declaration of the
1354 /// same special member, we should act as if it is not yet declared.
1355 llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
1356
1357 /// Kinds of defaulted comparison operator functions.
1358 enum class DefaultedComparisonKind : unsigned char {
1359 /// This is not a defaultable comparison operator.
1360 None,
1361 /// This is an operator== that should be implemented as a series of
1362 /// subobject comparisons.
1363 Equal,
1364 /// This is an operator<=> that should be implemented as a series of
1365 /// subobject comparisons.
1366 ThreeWay,
1367 /// This is an operator!= that should be implemented as a rewrite in terms
1368 /// of a == comparison.
1369 NotEqual,
1370 /// This is an <, <=, >, or >= that should be implemented as a rewrite in
1371 /// terms of a <=> comparison.
1372 Relational,
1373 };
1374
1375 /// The function definitions which were renamed as part of typo-correction
1376 /// to match their respective declarations. We want to keep track of them
1377 /// to ensure that we don't emit a "redefinition" error if we encounter a
1378 /// correctly named definition after the renamed definition.
1379 llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions;
1380
1381 /// Stack of types that correspond to the parameter entities that are
1382 /// currently being copy-initialized. Can be empty.
1383 llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes;
1384
1385 void ReadMethodPool(Selector Sel);
1386 void updateOutOfDateSelector(Selector Sel);
1387
1388 /// Private Helper predicate to check for 'self'.
1389 bool isSelfExpr(Expr *RExpr);
1390 bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
1391
1392 /// Cause the active diagnostic on the DiagosticsEngine to be
1393 /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
1394 /// should not be used elsewhere.
1395 void EmitCurrentDiagnostic(unsigned DiagID);
1396
1397 /// Records and restores the CurFPFeatures state on entry/exit of compound
1398 /// statements.
1399 class FPFeaturesStateRAII {
1400 public:
1401 FPFeaturesStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.CurFPFeatures) {
1402 OldOverrides = S.FpPragmaStack.CurrentValue;
1403 }
1404 ~FPFeaturesStateRAII() {
1405 S.CurFPFeatures = OldFPFeaturesState;
1406 S.FpPragmaStack.CurrentValue = OldOverrides;
1407 }
1408 FPOptionsOverride getOverrides() { return OldOverrides; }
1409
1410 private:
1411 Sema& S;
1412 FPOptions OldFPFeaturesState;
1413 FPOptionsOverride OldOverrides;
1414 };
1415
1416 void addImplicitTypedef(StringRef Name, QualType T);
1417
1418 bool WarnedStackExhausted = false;
1419
1420public:
1421 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1422 TranslationUnitKind TUKind = TU_Complete,
1423 CodeCompleteConsumer *CompletionConsumer = nullptr);
1424 ~Sema();
1425
1426 /// Perform initialization that occurs after the parser has been
1427 /// initialized but before it parses anything.
1428 void Initialize();
1429
1430 const LangOptions &getLangOpts() const { return LangOpts; }
1431 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
1432 FPOptions &getCurFPFeatures() { return CurFPFeatures; }
1433
1434 DiagnosticsEngine &getDiagnostics() const { return Diags; }
1435 SourceManager &getSourceManager() const { return SourceMgr; }
1436 Preprocessor &getPreprocessor() const { return PP; }
1437 ASTContext &getASTContext() const { return Context; }
1438 ASTConsumer &getASTConsumer() const { return Consumer; }
1439 ASTMutationListener *getASTMutationListener() const;
1440 ExternalSemaSource* getExternalSource() const { return ExternalSource; }
1441
1442 ///Registers an external source. If an external source already exists,
1443 /// creates a multiplex external source and appends to it.
1444 ///
1445 ///\param[in] E - A non-null external sema source.
1446 ///
1447 void addExternalSource(ExternalSemaSource *E);
1448
1449 void PrintStats() const;
1450
1451 /// Warn that the stack is nearly exhausted.
1452 void warnStackExhausted(SourceLocation Loc);
1453
1454 /// Run some code with "sufficient" stack space. (Currently, at least 256K is
1455 /// guaranteed). Produces a warning if we're low on stack space and allocates
1456 /// more in that case. Use this in code that may recurse deeply (for example,
1457 /// in template instantiation) to avoid stack overflow.
1458 void runWithSufficientStackSpace(SourceLocation Loc,
1459 llvm::function_ref<void()> Fn);
1460
1461 /// Helper class that creates diagnostics with optional
1462 /// template instantiation stacks.
1463 ///
1464 /// This class provides a wrapper around the basic DiagnosticBuilder
1465 /// class that emits diagnostics. ImmediateDiagBuilder is
1466 /// responsible for emitting the diagnostic (as DiagnosticBuilder
1467 /// does) and, if the diagnostic comes from inside a template
1468 /// instantiation, printing the template instantiation stack as
1469 /// well.
1470 class ImmediateDiagBuilder : public DiagnosticBuilder {
1471 Sema &SemaRef;
1472 unsigned DiagID;
1473
1474 public:
1475 ImmediateDiagBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
1476 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {}
1477 ImmediateDiagBuilder(DiagnosticBuilder &&DB, Sema &SemaRef, unsigned DiagID)
1478 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {}
1479
1480 // This is a cunning lie. DiagnosticBuilder actually performs move
1481 // construction in its copy constructor (but due to varied uses, it's not
1482 // possible to conveniently express this as actual move construction). So
1483 // the default copy ctor here is fine, because the base class disables the
1484 // source anyway, so the user-defined ~ImmediateDiagBuilder is a safe no-op
1485 // in that case anwyay.
1486 ImmediateDiagBuilder(const ImmediateDiagBuilder &) = default;
1487
1488 ~ImmediateDiagBuilder() {
1489 // If we aren't active, there is nothing to do.
1490 if (!isActive()) return;
1491
1492 // Otherwise, we need to emit the diagnostic. First clear the diagnostic
1493 // builder itself so it won't emit the diagnostic in its own destructor.
1494 //
1495 // This seems wasteful, in that as written the DiagnosticBuilder dtor will
1496 // do its own needless checks to see if the diagnostic needs to be
1497 // emitted. However, because we take care to ensure that the builder
1498 // objects never escape, a sufficiently smart compiler will be able to
1499 // eliminate that code.
1500 Clear();
1501
1502 // Dispatch to Sema to emit the diagnostic.
1503 SemaRef.EmitCurrentDiagnostic(DiagID);
1504 }
1505
1506 /// Teach operator<< to produce an object of the correct type.
1507 template <typename T>
1508 friend const ImmediateDiagBuilder &
1509 operator<<(const ImmediateDiagBuilder &Diag, const T &Value) {
1510 const DiagnosticBuilder &BaseDiag = Diag;
1511 BaseDiag << Value;
1512 return Diag;
1513 }
1514
1515 // It is necessary to limit this to rvalue reference to avoid calling this
1516 // function with a bitfield lvalue argument since non-const reference to
1517 // bitfield is not allowed.
1518 template <typename T, typename = typename std::enable_if<
1519 !std::is_lvalue_reference<T>::value>::type>
1520 const ImmediateDiagBuilder &operator<<(T &&V) const {
1521 const DiagnosticBuilder &BaseDiag = *this;
1522 BaseDiag << std::move(V);
1523 return *this;
1524 }
1525 };
1526
1527 /// A generic diagnostic builder for errors which may or may not be deferred.
1528 ///
1529 /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch)
1530 /// which are not allowed to appear inside __device__ functions and are
1531 /// allowed to appear in __host__ __device__ functions only if the host+device
1532 /// function is never codegen'ed.
1533 ///
1534 /// To handle this, we use the notion of "deferred diagnostics", where we
1535 /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed.
1536 ///
1537 /// This class lets you emit either a regular diagnostic, a deferred
1538 /// diagnostic, or no diagnostic at all, according to an argument you pass to
1539 /// its constructor, thus simplifying the process of creating these "maybe
1540 /// deferred" diagnostics.
1541 class SemaDiagnosticBuilder {
1542 public:
1543 enum Kind {
1544 /// Emit no diagnostics.
1545 K_Nop,
1546 /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()).
1547 K_Immediate,
1548 /// Emit the diagnostic immediately, and, if it's a warning or error, also
1549 /// emit a call stack showing how this function can be reached by an a
1550 /// priori known-emitted function.
1551 K_ImmediateWithCallStack,
1552 /// Create a deferred diagnostic, which is emitted only if the function
1553 /// it's attached to is codegen'ed. Also emit a call stack as with
1554 /// K_ImmediateWithCallStack.
1555 K_Deferred
1556 };
1557
1558 SemaDiagnosticBuilder(Kind K, SourceLocation Loc, unsigned DiagID,
1559 FunctionDecl *Fn, Sema &S);
1560 SemaDiagnosticBuilder(SemaDiagnosticBuilder &&D);
1561 SemaDiagnosticBuilder(const SemaDiagnosticBuilder &) = default;
1562 ~SemaDiagnosticBuilder();
1563
1564 bool isImmediate() const { return ImmediateDiag.hasValue(); }
1565
1566 /// Convertible to bool: True if we immediately emitted an error, false if
1567 /// we didn't emit an error or we created a deferred error.
1568 ///
1569 /// Example usage:
1570 ///
1571 /// if (SemaDiagnosticBuilder(...) << foo << bar)
1572 /// return ExprError();
1573 ///
1574 /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably
1575 /// want to use these instead of creating a SemaDiagnosticBuilder yourself.
1576 operator bool() const { return isImmediate(); }
1577
1578 template <typename T>
1579 friend const SemaDiagnosticBuilder &
1580 operator<<(const SemaDiagnosticBuilder &Diag, const T &Value) {
1581 if (Diag.ImmediateDiag.hasValue())
1582 *Diag.ImmediateDiag << Value;
1583 else if (Diag.PartialDiagId.hasValue())
1584 Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second
1585 << Value;
1586 return Diag;
1587 }
1588
1589 // It is necessary to limit this to rvalue reference to avoid calling this
1590 // function with a bitfield lvalue argument since non-const reference to
1591 // bitfield is not allowed.
1592 template <typename T, typename = typename std::enable_if<
1593 !std::is_lvalue_reference<T>::value>::type>
1594 const SemaDiagnosticBuilder &operator<<(T &&V) const {
1595 if (ImmediateDiag.hasValue())
1596 *ImmediateDiag << std::move(V);
1597 else if (PartialDiagId.hasValue())
1598 S.DeviceDeferredDiags[Fn][*PartialDiagId].second << std::move(V);
1599 return *this;
1600 }
1601
1602 friend const SemaDiagnosticBuilder &
1603 operator<<(const SemaDiagnosticBuilder &Diag, const PartialDiagnostic &PD) {
1604 if (Diag.ImmediateDiag.hasValue())
1605 PD.Emit(*Diag.ImmediateDiag);
1606 else if (Diag.PartialDiagId.hasValue())
1607 Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second = PD;
1608 return Diag;
1609 }
1610
1611 void AddFixItHint(const FixItHint &Hint) const {
1612 if (ImmediateDiag.hasValue())
1613 ImmediateDiag->AddFixItHint(Hint);
1614 else if (PartialDiagId.hasValue())
1615 S.DeviceDeferredDiags[Fn][*PartialDiagId].second.AddFixItHint(Hint);
1616 }
1617
1618 friend ExprResult ExprError(const SemaDiagnosticBuilder &) {
1619 return ExprError();
1620 }
1621 friend StmtResult StmtError(const SemaDiagnosticBuilder &) {
1622 return StmtError();
1623 }
1624 operator ExprResult() const { return ExprError(); }
1625 operator StmtResult() const { return StmtError(); }
1626 operator TypeResult() const { return TypeError(); }
1627 operator DeclResult() const { return DeclResult(true); }
1628 operator MemInitResult() const { return MemInitResult(true); }
1629
1630 private:
1631 Sema &S;
1632 SourceLocation Loc;
1633 unsigned DiagID;
1634 FunctionDecl *Fn;
1635 bool ShowCallStack;
1636
1637 // Invariant: At most one of these Optionals has a value.
1638 // FIXME: Switch these to a Variant once that exists.
1639 llvm::Optional<ImmediateDiagBuilder> ImmediateDiag;
1640 llvm::Optional<unsigned> PartialDiagId;
1641 };
1642 using DiagBuilderT = SemaDiagnosticBuilder;
1643
1644 /// Is the last error level diagnostic immediate. This is used to determined
1645 /// whether the next info diagnostic should be immediate.
1646 bool IsLastErrorImmediate = true;
1647
1648 /// Emit a diagnostic.
1649 SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID,
1650 bool DeferHint = false);
1651
1652 /// Emit a partial diagnostic.
1653 SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic &PD,
1654 bool DeferHint = false);
1655
1656 /// Build a partial diagnostic.
1657 PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1658
1659 /// Whether uncompilable error has occurred. This includes error happens
1660 /// in deferred diagnostics.
1661 bool hasUncompilableErrorOccurred() const;
1662
1663 bool findMacroSpelling(SourceLocation &loc, StringRef name);
1664
1665 /// Get a string to suggest for zero-initialization of a type.
1666 std::string
1667 getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
1668 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
1669
1670 /// Calls \c Lexer::getLocForEndOfToken()
1671 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1672
1673 /// Retrieve the module loader associated with the preprocessor.
1674 ModuleLoader &getModuleLoader() const;
1675
1676 /// Invent a new identifier for parameters of abbreviated templates.
1677 IdentifierInfo *
1678 InventAbbreviatedTemplateParameterTypeName(IdentifierInfo *ParamName,
1679 unsigned Index);
1680
1681 void emitAndClearUnusedLocalTypedefWarnings();
1682
1683 private:
1684 /// Function or variable declarations to be checked for whether the deferred
1685 /// diagnostics should be emitted.
1686 SmallVector<Decl *, 4> DeclsToCheckForDeferredDiags;
1687
1688 public:
1689 // Emit all deferred diagnostics.
1690 void emitDeferredDiags();
1691
1692 enum TUFragmentKind {
1693 /// The global module fragment, between 'module;' and a module-declaration.
1694 Global,
1695 /// A normal translation unit fragment. For a non-module unit, this is the
1696 /// entire translation unit. Otherwise, it runs from the module-declaration
1697 /// to the private-module-fragment (if any) or the end of the TU (if not).
1698 Normal,
1699 /// The private module fragment, between 'module :private;' and the end of
1700 /// the translation unit.
1701 Private
1702 };
1703
1704 void ActOnStartOfTranslationUnit();
1705 void ActOnEndOfTranslationUnit();
1706 void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind);
1707
1708 void CheckDelegatingCtorCycles();
1709
1710 Scope *getScopeForContext(DeclContext *Ctx);
1711
1712 void PushFunctionScope();
1713 void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1714 sema::LambdaScopeInfo *PushLambdaScope();
1715
1716 /// This is used to inform Sema what the current TemplateParameterDepth
1717 /// is during Parsing. Currently it is used to pass on the depth
1718 /// when parsing generic lambda 'auto' parameters.
1719 void RecordParsingTemplateParameterDepth(unsigned Depth);
1720
1721 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1722 RecordDecl *RD, CapturedRegionKind K,
1723 unsigned OpenMPCaptureLevel = 0);
1724
1725 /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short
1726 /// time after they've been popped.
1727 class PoppedFunctionScopeDeleter {
1728 Sema *Self;
1729
1730 public:
1731 explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {}
1732 void operator()(sema::FunctionScopeInfo *Scope) const;
1733 };
1734
1735 using PoppedFunctionScopePtr =
1736 std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>;
1737
1738 PoppedFunctionScopePtr
1739 PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1740 const Decl *D = nullptr,
1741 QualType BlockType = QualType());
1742
1743 sema::FunctionScopeInfo *getCurFunction() const {
1744 return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
1745 }
1746
1747 sema::FunctionScopeInfo *getEnclosingFunction() const;
1748
1749 void setFunctionHasBranchIntoScope();
1750 void setFunctionHasBranchProtectedScope();
1751 void setFunctionHasIndirectGoto();
1752
1753 void PushCompoundScope(bool IsStmtExpr);
1754 void PopCompoundScope();
1755
1756 sema::CompoundScopeInfo &getCurCompoundScope() const;
1757
1758 bool hasAnyUnrecoverableErrorsInThisFunction() const;
1759
1760 /// Retrieve the current block, if any.
1761 sema::BlockScopeInfo *getCurBlock();
1762
1763 /// Get the innermost lambda enclosing the current location, if any. This
1764 /// looks through intervening non-lambda scopes such as local functions and
1765 /// blocks.
1766 sema::LambdaScopeInfo *getEnclosingLambda() const;
1767
1768 /// Retrieve the current lambda scope info, if any.
1769 /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
1770 /// lambda scope info ignoring all inner capturing scopes that are not
1771 /// lambda scopes.
1772 sema::LambdaScopeInfo *
1773 getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
1774
1775 /// Retrieve the current generic lambda info, if any.
1776 sema::LambdaScopeInfo *getCurGenericLambda();
1777
1778 /// Retrieve the current captured region, if any.
1779 sema::CapturedRegionScopeInfo *getCurCapturedRegion();
1780
1781 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
1782 SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
1783
1784 /// Called before parsing a function declarator belonging to a function
1785 /// declaration.
1786 void ActOnStartFunctionDeclarationDeclarator(Declarator &D,
1787 unsigned TemplateParameterDepth);
1788
1789 /// Called after parsing a function declarator belonging to a function
1790 /// declaration.
1791 void ActOnFinishFunctionDeclarationDeclarator(Declarator &D);
1792
1793 void ActOnComment(SourceRange Comment);
1794
1795 //===--------------------------------------------------------------------===//
1796 // Type Analysis / Processing: SemaType.cpp.
1797 //
1798
1799 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
1800 const DeclSpec *DS = nullptr);
1801 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
1802 const DeclSpec *DS = nullptr);
1803 QualType BuildPointerType(QualType T,
1804 SourceLocation Loc, DeclarationName Entity);
1805 QualType BuildReferenceType(QualType T, bool LValueRef,
1806 SourceLocation Loc, DeclarationName Entity);
1807 QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1808 Expr *ArraySize, unsigned Quals,
1809 SourceRange Brackets, DeclarationName Entity);
1810 QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc);
1811 QualType BuildExtVectorType(QualType T, Expr *ArraySize,
1812 SourceLocation AttrLoc);
1813 QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns,
1814 SourceLocation AttrLoc);
1815
1816 QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
1817 SourceLocation AttrLoc);
1818
1819 /// Same as above, but constructs the AddressSpace index if not provided.
1820 QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
1821 SourceLocation AttrLoc);
1822
1823 bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc);
1824
1825 bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
1826
1827 /// Build a function type.
1828 ///
1829 /// This routine checks the function type according to C++ rules and
1830 /// under the assumption that the result type and parameter types have
1831 /// just been instantiated from a template. It therefore duplicates
1832 /// some of the behavior of GetTypeForDeclarator, but in a much
1833 /// simpler form that is only suitable for this narrow use case.
1834 ///
1835 /// \param T The return type of the function.
1836 ///
1837 /// \param ParamTypes The parameter types of the function. This array
1838 /// will be modified to account for adjustments to the types of the
1839 /// function parameters.
1840 ///
1841 /// \param Loc The location of the entity whose type involves this
1842 /// function type or, if there is no such entity, the location of the
1843 /// type that will have function type.
1844 ///
1845 /// \param Entity The name of the entity that involves the function
1846 /// type, if known.
1847 ///
1848 /// \param EPI Extra information about the function type. Usually this will
1849 /// be taken from an existing function with the same prototype.
1850 ///
1851 /// \returns A suitable function type, if there are no errors. The
1852 /// unqualified type will always be a FunctionProtoType.
1853 /// Otherwise, returns a NULL type.
1854 QualType BuildFunctionType(QualType T,
1855 MutableArrayRef<QualType> ParamTypes,
1856 SourceLocation Loc, DeclarationName Entity,
1857 const FunctionProtoType::ExtProtoInfo &EPI);
1858
1859 QualType BuildMemberPointerType(QualType T, QualType Class,
1860 SourceLocation Loc,
1861 DeclarationName Entity);
1862 QualType BuildBlockPointerType(QualType T,
1863 SourceLocation Loc, DeclarationName Entity);
1864 QualType BuildParenType(QualType T);
1865 QualType BuildAtomicType(QualType T, SourceLocation Loc);
1866 QualType BuildReadPipeType(QualType T,
1867 SourceLocation Loc);
1868 QualType BuildWritePipeType(QualType T,
1869 SourceLocation Loc);
1870 QualType BuildExtIntType(bool IsUnsigned, Expr *BitWidth, SourceLocation Loc);
1871
1872 TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
1873 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
1874
1875 /// Package the given type and TSI into a ParsedType.
1876 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
1877 DeclarationNameInfo GetNameForDeclarator(Declarator &D);
1878 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
1879 static QualType GetTypeFromParser(ParsedType Ty,
1880 TypeSourceInfo **TInfo = nullptr);
1881 CanThrowResult canThrow(const Stmt *E);
1882 /// Determine whether the callee of a particular function call can throw.
1883 /// E, D and Loc are all optional.
1884 static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D,
1885 SourceLocation Loc = SourceLocation());
1886 const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
1887 const FunctionProtoType *FPT);
1888 void UpdateExceptionSpec(FunctionDecl *FD,
1889 const FunctionProtoType::ExceptionSpecInfo &ESI);
1890 bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
1891 bool CheckDistantExceptionSpec(QualType T);
1892 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
1893 bool CheckEquivalentExceptionSpec(
1894 const FunctionProtoType *Old, SourceLocation OldLoc,
1895 const FunctionProtoType *New, SourceLocation NewLoc);
1896 bool CheckEquivalentExceptionSpec(
1897 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
1898 const FunctionProtoType *Old, SourceLocation OldLoc,
1899 const FunctionProtoType *New, SourceLocation NewLoc);
1900 bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
1901 bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
1902 const PartialDiagnostic &NestedDiagID,
1903 const PartialDiagnostic &NoteID,
1904 const PartialDiagnostic &NoThrowDiagID,
1905 const FunctionProtoType *Superset,
1906 SourceLocation SuperLoc,
1907 const FunctionProtoType *Subset,
1908 SourceLocation SubLoc);
1909 bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID,
1910 const PartialDiagnostic &NoteID,
1911 const FunctionProtoType *Target,
1912 SourceLocation TargetLoc,
1913 const FunctionProtoType *Source,
1914 SourceLocation SourceLoc);
1915
1916 TypeResult ActOnTypeName(Scope *S, Declarator &D);
1917
1918 /// The parser has parsed the context-sensitive type 'instancetype'
1919 /// in an Objective-C message declaration. Return the appropriate type.
1920 ParsedType ActOnObjCInstanceType(SourceLocation Loc);
1921
1922 /// Abstract class used to diagnose incomplete types.
1923 struct TypeDiagnoser {
1924 TypeDiagnoser() {}
1925
1926 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
1927 virtual ~TypeDiagnoser() {}
1928 };
1929
1930 static int getPrintable(int I) { return I; }
1931 static unsigned getPrintable(unsigned I) { return I; }
1932 static bool getPrintable(bool B) { return B; }
1933 static const char * getPrintable(const char *S) { return S; }
1934 static StringRef getPrintable(StringRef S) { return S; }
1935 static const std::string &getPrintable(const std::string &S) { return S; }
1936 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
1937 return II;
1938 }
1939 static DeclarationName getPrintable(DeclarationName N) { return N; }
1940 static QualType getPrintable(QualType T) { return T; }
1941 static SourceRange getPrintable(SourceRange R) { return R; }
1942 static SourceRange getPrintable(SourceLocation L) { return L; }
1943 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
1944 static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
1945
1946 template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
1947 protected:
1948 unsigned DiagID;
1949 std::tuple<const Ts &...> Args;
1950
1951 template <std::size_t... Is>
1952 void emit(const SemaDiagnosticBuilder &DB,
1953 std::index_sequence<Is...>) const {
1954 // Apply all tuple elements to the builder in order.
1955 bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
1956 (void)Dummy;
1957 }
1958
1959 public:
1960 BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
1961 : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
1962 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-12~++20201129111111+e987fbdd85d/clang/include/clang/Sema/Sema.h"
, 1962, __PRETTY_FUNCTION__))
;
1963 }
1964
1965 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
1966 const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
1967 emit(DB, std::index_sequence_for<Ts...>());
1968 DB << T;
1969 }
1970 };
1971
1972 /// Do a check to make sure \p Name looks like a legal argument for the
1973 /// swift_name attribute applied to decl \p D. Raise a diagnostic if the name
1974 /// is invalid for the given declaration.
1975 ///
1976 /// \p AL is used to provide caret diagnostics in case of a malformed name.
1977 ///
1978 /// \returns true if the name is a valid swift name for \p D, false otherwise.
1979 bool DiagnoseSwiftName(Decl *D, StringRef Name, SourceLocation Loc,
1980 const ParsedAttr &AL);
1981
1982 /// A derivative of BoundTypeDiagnoser for which the diagnostic's type
1983 /// parameter is preceded by a 0/1 enum that is 1 if the type is sizeless.
1984 /// For example, a diagnostic with no other parameters would generally have
1985 /// the form "...%select{incomplete|sizeless}0 type %1...".
1986 template <typename... Ts>
1987 class SizelessTypeDiagnoser : public BoundTypeDiagnoser<Ts...> {
1988 public:
1989 SizelessTypeDiagnoser(unsigned DiagID, const Ts &... Args)
1990 : BoundTypeDiagnoser<Ts...>(DiagID, Args...) {}
1991
1992 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
1993 const SemaDiagnosticBuilder &DB = S.Diag(Loc, this->DiagID);
1994 this->emit(DB, std::index_sequence_for<Ts...>());
1995 DB << T->isSizelessType() << T;
1996 }
1997 };
1998
1999 enum class CompleteTypeKind {
2000 /// Apply the normal rules for complete types. In particular,
2001 /// treat all sizeless types as incomplete.
2002 Normal,
2003
2004 /// Relax the normal rules for complete types so that they include
2005 /// sizeless built-in types.
2006 AcceptSizeless,
2007
2008 // FIXME: Eventually we should flip the default to Normal and opt in
2009 // to AcceptSizeless rather than opt out of it.
2010 Default = AcceptSizeless
2011 };
2012