Bug Summary

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