1 //===------- SemaTemplateInstantiate.cpp - C++ Template Instantiation ------===/
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 //===----------------------------------------------------------------------===/
8 // This file implements C++ template instantiation.
10 //===----------------------------------------------------------------------===/
12 #include "clang/Sema/SemaInternal.h"
13 #include "TreeTransform.h"
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
17 #include "clang/AST/ASTMutationListener.h"
18 #include "clang/AST/DeclTemplate.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/AST/PrettyDeclStackTrace.h"
21 #include "clang/Basic/LangOptions.h"
22 #include "clang/Basic/Stack.h"
23 #include "clang/Sema/DeclSpec.h"
24 #include "clang/Sema/Initialization.h"
25 #include "clang/Sema/Lookup.h"
26 #include "clang/Sema/Template.h"
27 #include "clang/Sema/TemplateDeduction.h"
28 #include "clang/Sema/TemplateInstCallback.h"
29 #include "clang/Sema/SemaConcept.h"
30 #include "llvm/Support/TimeProfiler.h"
32 using namespace clang;
35 //===----------------------------------------------------------------------===/
36 // Template Instantiation Support
37 //===----------------------------------------------------------------------===/
39 /// Retrieve the template argument list(s) that should be used to
40 /// instantiate the definition of the given declaration.
42 /// \param D the declaration for which we are computing template instantiation
45 /// \param Innermost if non-NULL, the innermost template argument list.
47 /// \param RelativeToPrimary true if we should get the template
48 /// arguments relative to the primary template, even when we're
49 /// dealing with a specialization. This is only relevant for function
50 /// template specializations.
52 /// \param Pattern If non-NULL, indicates the pattern from which we will be
53 /// instantiating the definition of the given declaration, \p D. This is
54 /// used to determine the proper set of template instantiation arguments for
55 /// friend function template specializations.
56 MultiLevelTemplateArgumentList
57 Sema::getTemplateInstantiationArgs(NamedDecl *D,
58 const TemplateArgumentList *Innermost,
59 bool RelativeToPrimary,
60 const FunctionDecl *Pattern) {
61 // Accumulate the set of template argument lists in this structure.
62 MultiLevelTemplateArgumentList Result;
65 Result.addOuterTemplateArguments(Innermost);
67 DeclContext *Ctx = dyn_cast<DeclContext>(D);
69 Ctx = D->getDeclContext();
71 // Add template arguments from a variable template instantiation. For a
72 // class-scope explicit specialization, there are no template arguments
73 // at this level, but there may be enclosing template arguments.
74 VarTemplateSpecializationDecl *Spec =
75 dyn_cast<VarTemplateSpecializationDecl>(D);
76 if (Spec && !Spec->isClassScopeExplicitSpecialization()) {
77 // We're done when we hit an explicit specialization.
78 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
79 !isa<VarTemplatePartialSpecializationDecl>(Spec))
82 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
84 // If this variable template specialization was instantiated from a
85 // specialized member that is a variable template, we're done.
86 assert(Spec->getSpecializedTemplate() && "No variable template?");
87 llvm::PointerUnion<VarTemplateDecl*,
88 VarTemplatePartialSpecializationDecl*> Specialized
89 = Spec->getSpecializedTemplateOrPartial();
90 if (VarTemplatePartialSpecializationDecl *Partial =
91 Specialized.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
92 if (Partial->isMemberSpecialization())
95 VarTemplateDecl *Tmpl = Specialized.get<VarTemplateDecl *>();
96 if (Tmpl->isMemberSpecialization())
101 // If we have a template template parameter with translation unit context,
102 // then we're performing substitution into a default template argument of
103 // this template template parameter before we've constructed the template
104 // that will own this template template parameter. In this case, we
105 // use empty template parameter lists for all of the outer templates
106 // to avoid performing any substitutions.
107 if (Ctx->isTranslationUnit()) {
108 if (TemplateTemplateParmDecl *TTP
109 = dyn_cast<TemplateTemplateParmDecl>(D)) {
110 for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
111 Result.addOuterTemplateArguments(None);
117 while (!Ctx->isFileContext()) {
118 // Add template arguments from a class template instantiation.
119 ClassTemplateSpecializationDecl *Spec
120 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx);
121 if (Spec && !Spec->isClassScopeExplicitSpecialization()) {
122 // We're done when we hit an explicit specialization.
123 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
124 !isa<ClassTemplatePartialSpecializationDecl>(Spec))
127 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
129 // If this class template specialization was instantiated from a
130 // specialized member that is a class template, we're done.
131 assert(Spec->getSpecializedTemplate() && "No class template?");
132 if (Spec->getSpecializedTemplate()->isMemberSpecialization())
135 // Add template arguments from a function template specialization.
136 else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) {
137 if (!RelativeToPrimary &&
138 Function->getTemplateSpecializationKindForInstantiation() ==
139 TSK_ExplicitSpecialization)
142 if (const TemplateArgumentList *TemplateArgs
143 = Function->getTemplateSpecializationArgs()) {
144 // Add the template arguments for this specialization.
145 Result.addOuterTemplateArguments(TemplateArgs);
147 // If this function was instantiated from a specialized member that is
148 // a function template, we're done.
149 assert(Function->getPrimaryTemplate() && "No function template?");
150 if (Function->getPrimaryTemplate()->isMemberSpecialization())
153 // If this function is a generic lambda specialization, we are done.
154 if (isGenericLambdaCallOperatorOrStaticInvokerSpecialization(Function))
157 } else if (FunctionTemplateDecl *FunTmpl
158 = Function->getDescribedFunctionTemplate()) {
159 // Add the "injected" template arguments.
160 Result.addOuterTemplateArguments(FunTmpl->getInjectedTemplateArgs());
163 // If this is a friend declaration and it declares an entity at
164 // namespace scope, take arguments from its lexical parent
165 // instead of its semantic parent, unless of course the pattern we're
166 // instantiating actually comes from the file's context!
167 if (Function->getFriendObjectKind() &&
168 Function->getDeclContext()->isFileContext() &&
169 (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
170 Ctx = Function->getLexicalDeclContext();
171 RelativeToPrimary = false;
174 } else if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Ctx)) {
175 if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
176 QualType T = ClassTemplate->getInjectedClassNameSpecialization();
177 const TemplateSpecializationType *TST =
178 cast<TemplateSpecializationType>(Context.getCanonicalType(T));
179 Result.addOuterTemplateArguments(
180 llvm::makeArrayRef(TST->getArgs(), TST->getNumArgs()));
181 if (ClassTemplate->isMemberSpecialization())
186 Ctx = Ctx->getParent();
187 RelativeToPrimary = false;
193 bool Sema::CodeSynthesisContext::isInstantiationRecord() const {
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:
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:
218 // This function should never be called when Kind's value is Memoization.
223 llvm_unreachable("Invalid SynthesisKind!");
226 Sema::InstantiatingTemplate::InstantiatingTemplate(
227 Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
228 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
229 Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
230 sema::TemplateDeductionInfo *DeductionInfo)
232 // Don't allow further instantiation if a fatal error and an uncompilable
233 // error have occurred. Any diagnostics we might have raised will not be
234 // visible, and we do not need to construct a correct AST.
235 if (SemaRef.Diags.hasFatalErrorOccurred() &&
236 SemaRef.Diags.hasUncompilableErrorOccurred()) {
240 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
242 CodeSynthesisContext Inst;
244 Inst.PointOfInstantiation = PointOfInstantiation;
245 Inst.Entity = Entity;
246 Inst.Template = Template;
247 Inst.TemplateArgs = TemplateArgs.data();
248 Inst.NumTemplateArgs = TemplateArgs.size();
249 Inst.DeductionInfo = DeductionInfo;
250 Inst.InstantiationRange = InstantiationRange;
251 SemaRef.pushCodeSynthesisContext(Inst);
253 AlreadyInstantiating = !Inst.Entity ? false :
254 !SemaRef.InstantiatingSpecializations
255 .insert(std::make_pair(Inst.Entity->getCanonicalDecl(), Inst.Kind))
257 atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, Inst);
261 Sema::InstantiatingTemplate::InstantiatingTemplate(
262 Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity,
263 SourceRange InstantiationRange)
264 : InstantiatingTemplate(SemaRef,
265 CodeSynthesisContext::TemplateInstantiation,
266 PointOfInstantiation, InstantiationRange, Entity) {}
268 Sema::InstantiatingTemplate::InstantiatingTemplate(
269 Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity,
270 ExceptionSpecification, SourceRange InstantiationRange)
271 : InstantiatingTemplate(
272 SemaRef, CodeSynthesisContext::ExceptionSpecInstantiation,
273 PointOfInstantiation, InstantiationRange, Entity) {}
275 Sema::InstantiatingTemplate::InstantiatingTemplate(
276 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param,
277 TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
278 SourceRange InstantiationRange)
279 : InstantiatingTemplate(
281 CodeSynthesisContext::DefaultTemplateArgumentInstantiation,
282 PointOfInstantiation, InstantiationRange, getAsNamedDecl(Param),
283 Template, TemplateArgs) {}
285 Sema::InstantiatingTemplate::InstantiatingTemplate(
286 Sema &SemaRef, SourceLocation PointOfInstantiation,
287 FunctionTemplateDecl *FunctionTemplate,
288 ArrayRef<TemplateArgument> TemplateArgs,
289 CodeSynthesisContext::SynthesisKind Kind,
290 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
291 : InstantiatingTemplate(SemaRef, Kind, PointOfInstantiation,
292 InstantiationRange, FunctionTemplate, nullptr,
293 TemplateArgs, &DeductionInfo) {
295 Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution ||
296 Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution);
299 Sema::InstantiatingTemplate::InstantiatingTemplate(
300 Sema &SemaRef, SourceLocation PointOfInstantiation,
301 TemplateDecl *Template,
302 ArrayRef<TemplateArgument> TemplateArgs,
303 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
304 : InstantiatingTemplate(
306 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
307 PointOfInstantiation, InstantiationRange, Template, nullptr,
308 TemplateArgs, &DeductionInfo) {}
310 Sema::InstantiatingTemplate::InstantiatingTemplate(
311 Sema &SemaRef, SourceLocation PointOfInstantiation,
312 ClassTemplatePartialSpecializationDecl *PartialSpec,
313 ArrayRef<TemplateArgument> TemplateArgs,
314 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
315 : InstantiatingTemplate(
317 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
318 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
319 TemplateArgs, &DeductionInfo) {}
321 Sema::InstantiatingTemplate::InstantiatingTemplate(
322 Sema &SemaRef, SourceLocation PointOfInstantiation,
323 VarTemplatePartialSpecializationDecl *PartialSpec,
324 ArrayRef<TemplateArgument> TemplateArgs,
325 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
326 : InstantiatingTemplate(
328 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
329 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
330 TemplateArgs, &DeductionInfo) {}
332 Sema::InstantiatingTemplate::InstantiatingTemplate(
333 Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param,
334 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
335 : InstantiatingTemplate(
337 CodeSynthesisContext::DefaultFunctionArgumentInstantiation,
338 PointOfInstantiation, InstantiationRange, Param, nullptr,
341 Sema::InstantiatingTemplate::InstantiatingTemplate(
342 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
343 NonTypeTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
344 SourceRange InstantiationRange)
345 : InstantiatingTemplate(
347 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
348 PointOfInstantiation, InstantiationRange, Param, Template,
351 Sema::InstantiatingTemplate::InstantiatingTemplate(
352 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
353 TemplateTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
354 SourceRange InstantiationRange)
355 : InstantiatingTemplate(
357 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
358 PointOfInstantiation, InstantiationRange, Param, Template,
361 Sema::InstantiatingTemplate::InstantiatingTemplate(
362 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template,
363 NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
364 SourceRange InstantiationRange)
365 : InstantiatingTemplate(
366 SemaRef, CodeSynthesisContext::DefaultTemplateArgumentChecking,
367 PointOfInstantiation, InstantiationRange, Param, Template,
370 Sema::InstantiatingTemplate::InstantiatingTemplate(
371 Sema &SemaRef, SourceLocation PointOfInstantiation,
372 concepts::Requirement *Req, sema::TemplateDeductionInfo &DeductionInfo,
373 SourceRange InstantiationRange)
374 : InstantiatingTemplate(
375 SemaRef, CodeSynthesisContext::RequirementInstantiation,
376 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
377 /*Template=*/nullptr, /*TemplateArgs=*/None, &DeductionInfo) {}
380 Sema::InstantiatingTemplate::InstantiatingTemplate(
381 Sema &SemaRef, SourceLocation PointOfInstantiation,
382 concepts::NestedRequirement *Req, ConstraintsCheck,
383 SourceRange InstantiationRange)
384 : InstantiatingTemplate(
385 SemaRef, CodeSynthesisContext::NestedRequirementConstraintsCheck,
386 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
387 /*Template=*/nullptr, /*TemplateArgs=*/None) {}
390 Sema::InstantiatingTemplate::InstantiatingTemplate(
391 Sema &SemaRef, SourceLocation PointOfInstantiation,
392 ConstraintsCheck, NamedDecl *Template,
393 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
394 : InstantiatingTemplate(
395 SemaRef, CodeSynthesisContext::ConstraintsCheck,
396 PointOfInstantiation, InstantiationRange, Template, nullptr,
399 Sema::InstantiatingTemplate::InstantiatingTemplate(
400 Sema &SemaRef, SourceLocation PointOfInstantiation,
401 ConstraintSubstitution, NamedDecl *Template,
402 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
403 : InstantiatingTemplate(
404 SemaRef, CodeSynthesisContext::ConstraintSubstitution,
405 PointOfInstantiation, InstantiationRange, Template, nullptr,
406 {}, &DeductionInfo) {}
408 Sema::InstantiatingTemplate::InstantiatingTemplate(
409 Sema &SemaRef, SourceLocation PointOfInstantiation,
410 ConstraintNormalization, NamedDecl *Template,
411 SourceRange InstantiationRange)
412 : InstantiatingTemplate(
413 SemaRef, CodeSynthesisContext::ConstraintNormalization,
414 PointOfInstantiation, InstantiationRange, Template) {}
416 Sema::InstantiatingTemplate::InstantiatingTemplate(
417 Sema &SemaRef, SourceLocation PointOfInstantiation,
418 ParameterMappingSubstitution, NamedDecl *Template,
419 SourceRange InstantiationRange)
420 : InstantiatingTemplate(
421 SemaRef, CodeSynthesisContext::ParameterMappingSubstitution,
422 PointOfInstantiation, InstantiationRange, Template) {}
424 void Sema::pushCodeSynthesisContext(CodeSynthesisContext Ctx) {
425 Ctx.SavedInNonInstantiationSFINAEContext = InNonInstantiationSFINAEContext;
426 InNonInstantiationSFINAEContext = false;
428 CodeSynthesisContexts.push_back(Ctx);
430 if (!Ctx.isInstantiationRecord())
431 ++NonInstantiationEntries;
433 // Check to see if we're low on stack space. We can't do anything about this
434 // from here, but we can at least warn the user.
435 if (isStackNearlyExhausted())
436 warnStackExhausted(Ctx.PointOfInstantiation);
439 void Sema::popCodeSynthesisContext() {
440 auto &Active = CodeSynthesisContexts.back();
441 if (!Active.isInstantiationRecord()) {
442 assert(NonInstantiationEntries > 0);
443 --NonInstantiationEntries;
446 InNonInstantiationSFINAEContext = Active.SavedInNonInstantiationSFINAEContext;
448 // Name lookup no longer looks in this template's defining module.
449 assert(CodeSynthesisContexts.size() >=
450 CodeSynthesisContextLookupModules.size() &&
451 "forgot to remove a lookup module for a template instantiation");
452 if (CodeSynthesisContexts.size() ==
453 CodeSynthesisContextLookupModules.size()) {
454 if (Module *M = CodeSynthesisContextLookupModules.back())
455 LookupModulesCache.erase(M);
456 CodeSynthesisContextLookupModules.pop_back();
459 // If we've left the code synthesis context for the current context stack,
460 // stop remembering that we've emitted that stack.
461 if (CodeSynthesisContexts.size() ==
462 LastEmittedCodeSynthesisContextDepth)
463 LastEmittedCodeSynthesisContextDepth = 0;
465 CodeSynthesisContexts.pop_back();
468 void Sema::InstantiatingTemplate::Clear() {
470 if (!AlreadyInstantiating) {
471 auto &Active = SemaRef.CodeSynthesisContexts.back();
473 SemaRef.InstantiatingSpecializations.erase(
474 std::make_pair(Active.Entity, Active.Kind));
477 atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef,
478 SemaRef.CodeSynthesisContexts.back());
480 SemaRef.popCodeSynthesisContext();
485 bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
486 SourceLocation PointOfInstantiation,
487 SourceRange InstantiationRange) {
488 assert(SemaRef.NonInstantiationEntries <=
489 SemaRef.CodeSynthesisContexts.size());
490 if ((SemaRef.CodeSynthesisContexts.size() -
491 SemaRef.NonInstantiationEntries)
492 <= SemaRef.getLangOpts().InstantiationDepth)
495 SemaRef.Diag(PointOfInstantiation,
496 diag::err_template_recursion_depth_exceeded)
497 << SemaRef.getLangOpts().InstantiationDepth
498 << InstantiationRange;
499 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
500 << SemaRef.getLangOpts().InstantiationDepth;
504 /// Prints the current instantiation stack through a series of
506 void Sema::PrintInstantiationStack() {
507 // Determine which template instantiations to skip, if any.
508 unsigned SkipStart = CodeSynthesisContexts.size(), SkipEnd = SkipStart;
509 unsigned Limit = Diags.getTemplateBacktraceLimit();
510 if (Limit && Limit < CodeSynthesisContexts.size()) {
511 SkipStart = Limit / 2 + Limit % 2;
512 SkipEnd = CodeSynthesisContexts.size() - Limit / 2;
515 // FIXME: In all of these cases, we need to show the template arguments
516 unsigned InstantiationIdx = 0;
517 for (SmallVectorImpl<CodeSynthesisContext>::reverse_iterator
518 Active = CodeSynthesisContexts.rbegin(),
519 ActiveEnd = CodeSynthesisContexts.rend();
521 ++Active, ++InstantiationIdx) {
522 // Skip this instantiation?
523 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
524 if (InstantiationIdx == SkipStart) {
525 // Note that we're skipping instantiations.
526 Diags.Report(Active->PointOfInstantiation,
527 diag::note_instantiation_contexts_suppressed)
528 << unsigned(CodeSynthesisContexts.size() - Limit);
533 switch (Active->Kind) {
534 case CodeSynthesisContext::TemplateInstantiation: {
535 Decl *D = Active->Entity;
536 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
537 unsigned DiagID = diag::note_template_member_class_here;
538 if (isa<ClassTemplateSpecializationDecl>(Record))
539 DiagID = diag::note_template_class_instantiation_here;
540 Diags.Report(Active->PointOfInstantiation, DiagID)
541 << Record << Active->InstantiationRange;
542 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
544 if (Function->getPrimaryTemplate())
545 DiagID = diag::note_function_template_spec_here;
547 DiagID = diag::note_template_member_function_here;
548 Diags.Report(Active->PointOfInstantiation, DiagID)
550 << Active->InstantiationRange;
551 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
552 Diags.Report(Active->PointOfInstantiation,
553 VD->isStaticDataMember()?
554 diag::note_template_static_data_member_def_here
555 : diag::note_template_variable_def_here)
557 << Active->InstantiationRange;
558 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
559 Diags.Report(Active->PointOfInstantiation,
560 diag::note_template_enum_def_here)
562 << Active->InstantiationRange;
563 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
564 Diags.Report(Active->PointOfInstantiation,
565 diag::note_template_nsdmi_here)
566 << FD << Active->InstantiationRange;
568 Diags.Report(Active->PointOfInstantiation,
569 diag::note_template_type_alias_instantiation_here)
570 << cast<TypeAliasTemplateDecl>(D)
571 << Active->InstantiationRange;
576 case CodeSynthesisContext::DefaultTemplateArgumentInstantiation: {
577 TemplateDecl *Template = cast<TemplateDecl>(Active->Template);
578 SmallVector<char, 128> TemplateArgsStr;
579 llvm::raw_svector_ostream OS(TemplateArgsStr);
580 Template->printName(OS);
581 printTemplateArgumentList(OS, Active->template_arguments(),
582 getPrintingPolicy());
583 Diags.Report(Active->PointOfInstantiation,
584 diag::note_default_arg_instantiation_here)
586 << Active->InstantiationRange;
590 case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution: {
591 FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
592 Diags.Report(Active->PointOfInstantiation,
593 diag::note_explicit_template_arg_substitution_here)
595 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
596 Active->TemplateArgs,
597 Active->NumTemplateArgs)
598 << Active->InstantiationRange;
602 case CodeSynthesisContext::DeducedTemplateArgumentSubstitution: {
603 if (FunctionTemplateDecl *FnTmpl =
604 dyn_cast<FunctionTemplateDecl>(Active->Entity)) {
605 Diags.Report(Active->PointOfInstantiation,
606 diag::note_function_template_deduction_instantiation_here)
608 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
609 Active->TemplateArgs,
610 Active->NumTemplateArgs)
611 << Active->InstantiationRange;
613 bool IsVar = isa<VarTemplateDecl>(Active->Entity) ||
614 isa<VarTemplateSpecializationDecl>(Active->Entity);
615 bool IsTemplate = false;
616 TemplateParameterList *Params;
617 if (auto *D = dyn_cast<TemplateDecl>(Active->Entity)) {
619 Params = D->getTemplateParameters();
620 } else if (auto *D = dyn_cast<ClassTemplatePartialSpecializationDecl>(
622 Params = D->getTemplateParameters();
623 } else if (auto *D = dyn_cast<VarTemplatePartialSpecializationDecl>(
625 Params = D->getTemplateParameters();
627 llvm_unreachable("unexpected template kind");
630 Diags.Report(Active->PointOfInstantiation,
631 diag::note_deduced_template_arg_substitution_here)
632 << IsVar << IsTemplate << cast<NamedDecl>(Active->Entity)
633 << getTemplateArgumentBindingsText(Params, Active->TemplateArgs,
634 Active->NumTemplateArgs)
635 << Active->InstantiationRange;
640 case CodeSynthesisContext::DefaultFunctionArgumentInstantiation: {
641 ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
642 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
644 SmallVector<char, 128> TemplateArgsStr;
645 llvm::raw_svector_ostream OS(TemplateArgsStr);
647 printTemplateArgumentList(OS, Active->template_arguments(),
648 getPrintingPolicy());
649 Diags.Report(Active->PointOfInstantiation,
650 diag::note_default_function_arg_instantiation_here)
652 << Active->InstantiationRange;
656 case CodeSynthesisContext::PriorTemplateArgumentSubstitution: {
657 NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
659 if (!Parm->getName().empty())
660 Name = std::string(" '") + Parm->getName().str() + "'";
662 TemplateParameterList *TemplateParams = nullptr;
663 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
664 TemplateParams = Template->getTemplateParameters();
667 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
668 ->getTemplateParameters();
669 Diags.Report(Active->PointOfInstantiation,
670 diag::note_prior_template_arg_substitution)
671 << isa<TemplateTemplateParmDecl>(Parm)
673 << getTemplateArgumentBindingsText(TemplateParams,
674 Active->TemplateArgs,
675 Active->NumTemplateArgs)
676 << Active->InstantiationRange;
680 case CodeSynthesisContext::DefaultTemplateArgumentChecking: {
681 TemplateParameterList *TemplateParams = nullptr;
682 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
683 TemplateParams = Template->getTemplateParameters();
686 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
687 ->getTemplateParameters();
689 Diags.Report(Active->PointOfInstantiation,
690 diag::note_template_default_arg_checking)
691 << getTemplateArgumentBindingsText(TemplateParams,
692 Active->TemplateArgs,
693 Active->NumTemplateArgs)
694 << Active->InstantiationRange;
698 case CodeSynthesisContext::ExceptionSpecEvaluation:
699 Diags.Report(Active->PointOfInstantiation,
700 diag::note_evaluating_exception_spec_here)
701 << cast<FunctionDecl>(Active->Entity);
704 case CodeSynthesisContext::ExceptionSpecInstantiation:
705 Diags.Report(Active->PointOfInstantiation,
706 diag::note_template_exception_spec_instantiation_here)
707 << cast<FunctionDecl>(Active->Entity)
708 << Active->InstantiationRange;
711 case CodeSynthesisContext::RequirementInstantiation:
712 Diags.Report(Active->PointOfInstantiation,
713 diag::note_template_requirement_instantiation_here)
714 << Active->InstantiationRange;
717 case CodeSynthesisContext::NestedRequirementConstraintsCheck:
718 Diags.Report(Active->PointOfInstantiation,
719 diag::note_nested_requirement_here)
720 << Active->InstantiationRange;
723 case CodeSynthesisContext::DeclaringSpecialMember:
724 Diags.Report(Active->PointOfInstantiation,
725 diag::note_in_declaration_of_implicit_special_member)
726 << cast<CXXRecordDecl>(Active->Entity) << Active->SpecialMember;
729 case CodeSynthesisContext::DeclaringImplicitEqualityComparison:
730 Diags.Report(Active->Entity->getLocation(),
731 diag::note_in_declaration_of_implicit_equality_comparison);
734 case CodeSynthesisContext::DefiningSynthesizedFunction: {
735 // FIXME: For synthesized functions that are not defaulted,
737 auto *FD = dyn_cast<FunctionDecl>(Active->Entity);
738 DefaultedFunctionKind DFK =
739 FD ? getDefaultedFunctionKind(FD) : DefaultedFunctionKind();
740 if (DFK.isSpecialMember()) {
741 auto *MD = cast<CXXMethodDecl>(FD);
742 Diags.Report(Active->PointOfInstantiation,
743 diag::note_member_synthesized_at)
744 << MD->isExplicitlyDefaulted() << DFK.asSpecialMember()
745 << Context.getTagDeclType(MD->getParent());
746 } else if (DFK.isComparison()) {
747 Diags.Report(Active->PointOfInstantiation,
748 diag::note_comparison_synthesized_at)
749 << (int)DFK.asComparison()
750 << Context.getTagDeclType(
751 cast<CXXRecordDecl>(FD->getLexicalDeclContext()));
756 case CodeSynthesisContext::RewritingOperatorAsSpaceship:
757 Diags.Report(Active->Entity->getLocation(),
758 diag::note_rewriting_operator_as_spaceship);
761 case CodeSynthesisContext::Memoization:
764 case CodeSynthesisContext::ConstraintsCheck: {
766 if (isa<ConceptDecl>(Active->Entity))
767 DiagID = diag::note_concept_specialization_here;
768 else if (isa<TemplateDecl>(Active->Entity))
769 DiagID = diag::note_checking_constraints_for_template_id_here;
770 else if (isa<VarTemplatePartialSpecializationDecl>(Active->Entity))
771 DiagID = diag::note_checking_constraints_for_var_spec_id_here;
773 assert(isa<ClassTemplatePartialSpecializationDecl>(Active->Entity));
774 DiagID = diag::note_checking_constraints_for_class_spec_id_here;
776 SmallVector<char, 128> TemplateArgsStr;
777 llvm::raw_svector_ostream OS(TemplateArgsStr);
778 cast<NamedDecl>(Active->Entity)->printName(OS);
779 printTemplateArgumentList(OS, Active->template_arguments(),
780 getPrintingPolicy());
781 Diags.Report(Active->PointOfInstantiation, DiagID) << OS.str()
782 << Active->InstantiationRange;
785 case CodeSynthesisContext::ConstraintSubstitution:
786 Diags.Report(Active->PointOfInstantiation,
787 diag::note_constraint_substitution_here)
788 << Active->InstantiationRange;
790 case CodeSynthesisContext::ConstraintNormalization:
791 Diags.Report(Active->PointOfInstantiation,
792 diag::note_constraint_normalization_here)
793 << cast<NamedDecl>(Active->Entity)->getName()
794 << Active->InstantiationRange;
796 case CodeSynthesisContext::ParameterMappingSubstitution:
797 Diags.Report(Active->PointOfInstantiation,
798 diag::note_parameter_mapping_substitution_here)
799 << Active->InstantiationRange;
805 Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
806 if (InNonInstantiationSFINAEContext)
807 return Optional<TemplateDeductionInfo *>(nullptr);
809 for (SmallVectorImpl<CodeSynthesisContext>::const_reverse_iterator
810 Active = CodeSynthesisContexts.rbegin(),
811 ActiveEnd = CodeSynthesisContexts.rend();
815 switch (Active->Kind) {
816 case CodeSynthesisContext::TemplateInstantiation:
817 // An instantiation of an alias template may or may not be a SFINAE
818 // context, depending on what else is on the stack.
819 if (isa<TypeAliasTemplateDecl>(Active->Entity))
822 case CodeSynthesisContext::DefaultFunctionArgumentInstantiation:
823 case CodeSynthesisContext::ExceptionSpecInstantiation:
824 case CodeSynthesisContext::ConstraintsCheck:
825 case CodeSynthesisContext::ParameterMappingSubstitution:
826 case CodeSynthesisContext::ConstraintNormalization:
827 case CodeSynthesisContext::NestedRequirementConstraintsCheck:
828 // This is a template instantiation, so there is no SFINAE.
831 case CodeSynthesisContext::DefaultTemplateArgumentInstantiation:
832 case CodeSynthesisContext::PriorTemplateArgumentSubstitution:
833 case CodeSynthesisContext::DefaultTemplateArgumentChecking:
834 // A default template argument instantiation and substitution into
835 // template parameters with arguments for prior parameters may or may
836 // not be a SFINAE context; look further up the stack.
839 case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution:
840 case CodeSynthesisContext::DeducedTemplateArgumentSubstitution:
841 case CodeSynthesisContext::ConstraintSubstitution:
842 case CodeSynthesisContext::RequirementInstantiation:
843 // We're either substituting explicitly-specified template arguments,
844 // deduced template arguments, a constraint expression or a requirement
845 // in a requires expression, so SFINAE applies.
846 assert(Active->DeductionInfo && "Missing deduction info pointer");
847 return Active->DeductionInfo;
849 case CodeSynthesisContext::DeclaringSpecialMember:
850 case CodeSynthesisContext::DeclaringImplicitEqualityComparison:
851 case CodeSynthesisContext::DefiningSynthesizedFunction:
852 case CodeSynthesisContext::RewritingOperatorAsSpaceship:
853 // This happens in a context unrelated to template instantiation, so
854 // there is no SFINAE.
857 case CodeSynthesisContext::ExceptionSpecEvaluation:
858 // FIXME: This should not be treated as a SFINAE context, because
859 // we will cache an incorrect exception specification. However, clang
860 // bootstrap relies this! See PR31692.
863 case CodeSynthesisContext::Memoization:
867 // The inner context was transparent for SFINAE. If it occurred within a
868 // non-instantiation SFINAE context, then SFINAE applies.
869 if (Active->SavedInNonInstantiationSFINAEContext)
870 return Optional<TemplateDeductionInfo *>(nullptr);
876 //===----------------------------------------------------------------------===/
877 // Template Instantiation for Types
878 //===----------------------------------------------------------------------===/
880 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
881 const MultiLevelTemplateArgumentList &TemplateArgs;
883 DeclarationName Entity;
886 typedef TreeTransform<TemplateInstantiator> inherited;
888 TemplateInstantiator(Sema &SemaRef,
889 const MultiLevelTemplateArgumentList &TemplateArgs,
891 DeclarationName Entity)
892 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
895 /// Determine whether the given type \p T has already been
898 /// For the purposes of template instantiation, a type has already been
899 /// transformed if it is NULL or if it is not dependent.
900 bool AlreadyTransformed(QualType T);
902 /// Returns the location of the entity being instantiated, if known.
903 SourceLocation getBaseLocation() { return Loc; }
905 /// Returns the name of the entity being instantiated, if any.
906 DeclarationName getBaseEntity() { return Entity; }
908 /// Sets the "base" location and entity when that
909 /// information is known based on another transformation.
910 void setBase(SourceLocation Loc, DeclarationName Entity) {
912 this->Entity = Entity;
915 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
916 SourceRange PatternRange,
917 ArrayRef<UnexpandedParameterPack> Unexpanded,
918 bool &ShouldExpand, bool &RetainExpansion,
919 Optional<unsigned> &NumExpansions) {
920 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
921 PatternRange, Unexpanded,
928 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
929 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
932 TemplateArgument ForgetPartiallySubstitutedPack() {
933 TemplateArgument Result;
934 if (NamedDecl *PartialPack
935 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
936 MultiLevelTemplateArgumentList &TemplateArgs
937 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
938 unsigned Depth, Index;
939 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
940 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
941 Result = TemplateArgs(Depth, Index);
942 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
949 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
953 if (NamedDecl *PartialPack
954 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
955 MultiLevelTemplateArgumentList &TemplateArgs
956 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
957 unsigned Depth, Index;
958 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
959 TemplateArgs.setArgument(Depth, Index, Arg);
963 /// Transform the given declaration by instantiating a reference to
964 /// this declaration.
965 Decl *TransformDecl(SourceLocation Loc, Decl *D);
967 void transformAttrs(Decl *Old, Decl *New) {
968 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
971 void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> NewDecls) {
972 if (Old->isParameterPack()) {
973 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Old);
974 for (auto *New : NewDecls)
975 SemaRef.CurrentInstantiationScope->InstantiatedLocalPackArg(
976 Old, cast<VarDecl>(New));
980 assert(NewDecls.size() == 1 &&
981 "should only have multiple expansions for a pack");
982 Decl *New = NewDecls.front();
984 // If we've instantiated the call operator of a lambda or the call
985 // operator template of a generic lambda, update the "instantiation of"
987 auto *NewMD = dyn_cast<CXXMethodDecl>(New);
988 if (NewMD && isLambdaCallOperator(NewMD)) {
989 auto *OldMD = dyn_cast<CXXMethodDecl>(Old);
990 if (auto *NewTD = NewMD->getDescribedFunctionTemplate())
991 NewTD->setInstantiatedFromMemberTemplate(
992 OldMD->getDescribedFunctionTemplate());
994 NewMD->setInstantiationOfMemberFunction(OldMD,
995 TSK_ImplicitInstantiation);
998 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);
1000 // We recreated a local declaration, but not by instantiating it. There
1001 // may be pending dependent diagnostics to produce.
1002 if (auto *DC = dyn_cast<DeclContext>(Old))
1003 SemaRef.PerformDependentDiagnostics(DC, TemplateArgs);
1006 /// Transform the definition of the given declaration by
1007 /// instantiating it.
1008 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
1010 /// Transform the first qualifier within a scope by instantiating the
1012 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
1014 /// Rebuild the exception declaration and register the declaration
1015 /// as an instantiated local.
1016 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
1017 TypeSourceInfo *Declarator,
1018 SourceLocation StartLoc,
1019 SourceLocation NameLoc,
1020 IdentifierInfo *Name);
1022 /// Rebuild the Objective-C exception declaration and register the
1023 /// declaration as an instantiated local.
1024 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1025 TypeSourceInfo *TSInfo, QualType T);
1027 /// Check for tag mismatches when instantiating an
1028 /// elaborated type.
1029 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
1030 ElaboratedTypeKeyword Keyword,
1031 NestedNameSpecifierLoc QualifierLoc,
1035 TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
1036 SourceLocation NameLoc,
1037 QualType ObjectType = QualType(),
1038 NamedDecl *FirstQualifierInScope = nullptr,
1039 bool AllowInjectedClassName = false);
1041 const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
1043 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
1044 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
1045 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
1047 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
1048 NonTypeTemplateParmDecl *D);
1049 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
1050 SubstNonTypeTemplateParmPackExpr *E);
1052 /// Rebuild a DeclRefExpr for a VarDecl reference.
1053 ExprResult RebuildVarDeclRefExpr(VarDecl *PD, SourceLocation Loc);
1055 /// Transform a reference to a function or init-capture parameter pack.
1056 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E, VarDecl *PD);
1058 /// Transform a FunctionParmPackExpr which was built when we couldn't
1059 /// expand a function parameter pack reference which refers to an expanded
1061 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
1063 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1064 FunctionProtoTypeLoc TL) {
1065 // Call the base version; it will forward to our overridden version below.
1066 return inherited::TransformFunctionProtoType(TLB, TL);
1069 template<typename Fn>
1070 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1071 FunctionProtoTypeLoc TL,
1072 CXXRecordDecl *ThisContext,
1073 Qualifiers ThisTypeQuals,
1074 Fn TransformExceptionSpec);
1076 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
1077 int indexAdjustment,
1078 Optional<unsigned> NumExpansions,
1079 bool ExpectParameterPack);
1081 /// Transforms a template type parameter type by performing
1082 /// substitution of the corresponding template type argument.
1083 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1084 TemplateTypeParmTypeLoc TL);
1086 /// Transforms an already-substituted template type parameter pack
1087 /// into either itself (if we aren't substituting into its pack expansion)
1088 /// or the appropriate substituted argument.
1089 QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
1090 SubstTemplateTypeParmPackTypeLoc TL);
1092 ExprResult TransformLambdaExpr(LambdaExpr *E) {
1093 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1094 return TreeTransform<TemplateInstantiator>::TransformLambdaExpr(E);
1097 ExprResult TransformRequiresExpr(RequiresExpr *E) {
1098 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1099 return TreeTransform<TemplateInstantiator>::TransformRequiresExpr(E);
1102 bool TransformRequiresExprRequirements(
1103 ArrayRef<concepts::Requirement *> Reqs,
1104 SmallVectorImpl<concepts::Requirement *> &Transformed) {
1105 bool SatisfactionDetermined = false;
1106 for (concepts::Requirement *Req : Reqs) {
1107 concepts::Requirement *TransReq = nullptr;
1108 if (!SatisfactionDetermined) {
1109 if (auto *TypeReq = dyn_cast<concepts::TypeRequirement>(Req))
1110 TransReq = TransformTypeRequirement(TypeReq);
1111 else if (auto *ExprReq = dyn_cast<concepts::ExprRequirement>(Req))
1112 TransReq = TransformExprRequirement(ExprReq);
1114 TransReq = TransformNestedRequirement(
1115 cast<concepts::NestedRequirement>(Req));
1118 if (!TransReq->isDependent() && !TransReq->isSatisfied())
1119 // [expr.prim.req]p6
1120 // [...] The substitution and semantic constraint checking
1121 // proceeds in lexical order and stops when a condition that
1122 // determines the result of the requires-expression is
1123 // encountered. [..]
1124 SatisfactionDetermined = true;
1127 Transformed.push_back(TransReq);
1132 TemplateParameterList *TransformTemplateParameterList(
1133 TemplateParameterList *OrigTPL) {
1134 if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
1136 DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
1137 TemplateDeclInstantiator DeclInstantiator(getSema(),
1138 /* DeclContext *Owner */ Owner, TemplateArgs);
1139 return DeclInstantiator.SubstTemplateParams(OrigTPL);
1142 concepts::TypeRequirement *
1143 TransformTypeRequirement(concepts::TypeRequirement *Req);
1144 concepts::ExprRequirement *
1145 TransformExprRequirement(concepts::ExprRequirement *Req);
1146 concepts::NestedRequirement *
1147 TransformNestedRequirement(concepts::NestedRequirement *Req);
1150 ExprResult transformNonTypeTemplateParmRef(NonTypeTemplateParmDecl *parm,
1152 TemplateArgument arg);
1156 bool TemplateInstantiator::AlreadyTransformed(QualType T) {
1160 if (T->isInstantiationDependentType() || T->isVariablyModifiedType())
1163 getSema().MarkDeclarationsReferencedInType(Loc, T);
1167 static TemplateArgument
1168 getPackSubstitutedTemplateArgument(Sema &S, TemplateArgument Arg) {
1169 assert(S.ArgumentPackSubstitutionIndex >= 0);
1170 assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
1171 Arg = Arg.pack_begin()[S.ArgumentPackSubstitutionIndex];
1172 if (Arg.isPackExpansion())
1173 Arg = Arg.getPackExpansionPattern();
1177 Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
1181 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
1182 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1183 // If the corresponding template argument is NULL or non-existent, it's
1184 // because we are performing instantiation from explicitly-specified
1185 // template arguments in a function template, but there were some
1186 // arguments left unspecified.
1187 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1188 TTP->getPosition()))
1191 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1193 if (TTP->isParameterPack()) {
1194 assert(Arg.getKind() == TemplateArgument::Pack &&
1195 "Missing argument pack");
1196 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1199 TemplateName Template = Arg.getAsTemplate().getNameToSubstitute();
1200 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
1201 "Wrong kind of template template argument");
1202 return Template.getAsTemplateDecl();
1205 // Fall through to find the instantiated declaration for this template
1206 // template parameter.
1209 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
1212 Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
1213 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
1217 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1222 TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
1223 SourceLocation Loc) {
1224 // If the first part of the nested-name-specifier was a template type
1225 // parameter, instantiate that type parameter down to a tag type.
1226 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
1227 const TemplateTypeParmType *TTP
1228 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
1230 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1231 // FIXME: This needs testing w/ member access expressions.
1232 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
1234 if (TTP->isParameterPack()) {
1235 assert(Arg.getKind() == TemplateArgument::Pack &&
1236 "Missing argument pack");
1238 if (getSema().ArgumentPackSubstitutionIndex == -1)
1241 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1244 QualType T = Arg.getAsType();
1246 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1248 if (const TagType *Tag = T->getAs<TagType>())
1249 return Tag->getDecl();
1251 // The resulting type is not a tag; complain.
1252 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
1257 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1261 TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
1262 TypeSourceInfo *Declarator,
1263 SourceLocation StartLoc,
1264 SourceLocation NameLoc,
1265 IdentifierInfo *Name) {
1266 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
1267 StartLoc, NameLoc, Name);
1269 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1273 VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1274 TypeSourceInfo *TSInfo,
1276 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
1278 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1283 TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
1284 ElaboratedTypeKeyword Keyword,
1285 NestedNameSpecifierLoc QualifierLoc,
1287 if (const TagType *TT = T->getAs<TagType>()) {
1288 TagDecl* TD = TT->getDecl();
1290 SourceLocation TagLocation = KeywordLoc;
1292 IdentifierInfo *Id = TD->getIdentifier();
1294 // TODO: should we even warn on struct/class mismatches for this? Seems
1295 // like it's likely to produce a lot of spurious errors.
1296 if (Id && Keyword != ETK_None && Keyword != ETK_Typename) {
1297 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
1298 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
1300 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
1302 << FixItHint::CreateReplacement(SourceRange(TagLocation),
1304 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
1309 return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(KeywordLoc,
1315 TemplateName TemplateInstantiator::TransformTemplateName(
1316 CXXScopeSpec &SS, TemplateName Name, SourceLocation NameLoc,
1317 QualType ObjectType, NamedDecl *FirstQualifierInScope,
1318 bool AllowInjectedClassName) {
1319 if (TemplateTemplateParmDecl *TTP
1320 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
1321 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1322 // If the corresponding template argument is NULL or non-existent, it's
1323 // because we are performing instantiation from explicitly-specified
1324 // template arguments in a function template, but there were some
1325 // arguments left unspecified.
1326 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1327 TTP->getPosition()))
1330 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1332 if (TTP->isParameterPack()) {
1333 assert(Arg.getKind() == TemplateArgument::Pack &&
1334 "Missing argument pack");
1336 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1337 // We have the template argument pack to substitute, but we're not
1338 // actually expanding the enclosing pack expansion yet. So, just
1339 // keep the entire argument pack.
1340 return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg);
1343 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1346 TemplateName Template = Arg.getAsTemplate().getNameToSubstitute();
1347 assert(!Template.isNull() && "Null template template argument");
1348 assert(!Template.getAsQualifiedTemplateName() &&
1349 "template decl to substitute is qualified?");
1351 Template = getSema().Context.getSubstTemplateTemplateParm(TTP, Template);
1356 if (SubstTemplateTemplateParmPackStorage *SubstPack
1357 = Name.getAsSubstTemplateTemplateParmPack()) {
1358 if (getSema().ArgumentPackSubstitutionIndex == -1)
1361 TemplateArgument Arg = SubstPack->getArgumentPack();
1362 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1363 return Arg.getAsTemplate().getNameToSubstitute();
1366 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
1367 FirstQualifierInScope,
1368 AllowInjectedClassName);
1372 TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
1373 if (!E->isTypeDependent())
1376 return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentKind());
1380 TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
1381 NonTypeTemplateParmDecl *NTTP) {
1382 // If the corresponding template argument is NULL or non-existent, it's
1383 // because we are performing instantiation from explicitly-specified
1384 // template arguments in a function template, but there were some
1385 // arguments left unspecified.
1386 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
1387 NTTP->getPosition()))
1390 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
1392 if (TemplateArgs.getNumLevels() != TemplateArgs.getNumSubstitutedLevels()) {
1393 // We're performing a partial substitution, so the substituted argument
1394 // could be dependent. As a result we can't create a SubstNonType*Expr
1395 // node now, since that represents a fully-substituted argument.
1396 // FIXME: We should have some AST representation for this.
1397 if (Arg.getKind() == TemplateArgument::Pack) {
1398 // FIXME: This won't work for alias templates.
1399 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
1400 "unexpected pack arguments in partial substitution");
1401 Arg = Arg.pack_begin()->getPackExpansionPattern();
1403 assert(Arg.getKind() == TemplateArgument::Expression &&
1404 "unexpected nontype template argument kind in partial substitution");
1405 return Arg.getAsExpr();
1408 if (NTTP->isParameterPack()) {
1409 assert(Arg.getKind() == TemplateArgument::Pack &&
1410 "Missing argument pack");
1412 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1413 // We have an argument pack, but we can't select a particular argument
1414 // out of it yet. Therefore, we'll build an expression to hold on to that
1416 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1418 NTTP->getDeclName());
1419 if (TargetType.isNull())
1422 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(
1423 TargetType.getNonLValueExprType(SemaRef.Context),
1424 TargetType->isReferenceType() ? VK_LValue : VK_RValue, NTTP,
1425 E->getLocation(), Arg);
1428 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1431 return transformNonTypeTemplateParmRef(NTTP, E->getLocation(), Arg);
1434 const LoopHintAttr *
1435 TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
1436 Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get();
1438 if (TransformedExpr == LH->getValue())
1441 // Generate error if there is a problem with the value.
1442 if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation()))
1445 // Create new LoopHintValueAttr with integral expression in place of the
1446 // non-type template parameter.
1447 return LoopHintAttr::CreateImplicit(getSema().Context, LH->getOption(),
1448 LH->getState(), TransformedExpr, *LH);
1451 ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
1452 NonTypeTemplateParmDecl *parm,
1454 TemplateArgument arg) {
1458 // The template argument itself might be an expression, in which
1459 // case we just return that expression.
1460 if (arg.getKind() == TemplateArgument::Expression) {
1461 Expr *argExpr = arg.getAsExpr();
1463 type = argExpr->getType();
1465 } else if (arg.getKind() == TemplateArgument::Declaration ||
1466 arg.getKind() == TemplateArgument::NullPtr) {
1468 if (arg.getKind() == TemplateArgument::Declaration) {
1469 VD = arg.getAsDecl();
1471 // Find the instantiation of the template argument. This is
1472 // required for nested templates.
1473 VD = cast_or_null<ValueDecl>(
1474 getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
1478 // Propagate NULL template argument.
1482 // Derive the type we want the substituted decl to have. This had
1483 // better be non-dependent, or these checks will have serious problems.
1484 if (parm->isExpandedParameterPack()) {
1485 type = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex);
1486 } else if (parm->isParameterPack() &&
1487 isa<PackExpansionType>(parm->getType())) {
1488 type = SemaRef.SubstType(
1489 cast<PackExpansionType>(parm->getType())->getPattern(),
1490 TemplateArgs, loc, parm->getDeclName());
1492 type = SemaRef.SubstType(VD ? arg.getParamTypeForDecl() : arg.getNullPtrType(),
1493 TemplateArgs, loc, parm->getDeclName());
1495 assert(!type.isNull() && "type substitution failed for param type");
1496 assert(!type->isDependentType() && "param type still dependent");
1497 result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, type, loc);
1499 if (!result.isInvalid()) type = result.get()->getType();
1501 result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc);
1503 // Note that this type can be different from the type of 'result',
1504 // e.g. if it's an enum type.
1505 type = arg.getIntegralType();
1507 if (result.isInvalid()) return ExprError();
1509 Expr *resultExpr = result.get();
1510 return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
1511 type, resultExpr->getValueKind(), loc, parm, resultExpr);
1515 TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
1516 SubstNonTypeTemplateParmPackExpr *E) {
1517 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1518 // We aren't expanding the parameter pack, so just return ourselves.
1522 TemplateArgument Arg = E->getArgumentPack();
1523 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1524 return transformNonTypeTemplateParmRef(E->getParameterPack(),
1525 E->getParameterPackLocation(),
1529 ExprResult TemplateInstantiator::RebuildVarDeclRefExpr(VarDecl *PD,
1530 SourceLocation Loc) {
1531 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
1532 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
1536 TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
1537 if (getSema().ArgumentPackSubstitutionIndex != -1) {
1538 // We can expand this parameter pack now.
1539 VarDecl *D = E->getExpansion(getSema().ArgumentPackSubstitutionIndex);
1540 VarDecl *VD = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), D));
1543 return RebuildVarDeclRefExpr(VD, E->getExprLoc());
1546 QualType T = TransformType(E->getType());
1550 // Transform each of the parameter expansions into the corresponding
1551 // parameters in the instantiation of the function decl.
1552 SmallVector<VarDecl *, 8> Vars;
1553 Vars.reserve(E->getNumExpansions());
1554 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
1556 VarDecl *D = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), *I));
1563 FunctionParmPackExpr::Create(getSema().Context, T, E->getParameterPack(),
1564 E->getParameterPackLocation(), Vars);
1565 getSema().MarkFunctionParmPackReferenced(PackExpr);
1570 TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
1572 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
1573 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
1574 = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
1575 assert(Found && "no instantiation for parameter pack");
1577 Decl *TransformedDecl;
1578 if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
1579 // If this is a reference to a function parameter pack which we can
1580 // substitute but can't yet expand, build a FunctionParmPackExpr for it.
1581 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1582 QualType T = TransformType(E->getType());
1585 auto *PackExpr = FunctionParmPackExpr::Create(getSema().Context, T, PD,
1586 E->getExprLoc(), *Pack);
1587 getSema().MarkFunctionParmPackReferenced(PackExpr);
1591 TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
1593 TransformedDecl = Found->get<Decl*>();
1596 // We have either an unexpanded pack or a specific expansion.
1597 return RebuildVarDeclRefExpr(cast<VarDecl>(TransformedDecl), E->getExprLoc());
1601 TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
1602 NamedDecl *D = E->getDecl();
1604 // Handle references to non-type template parameters and non-type template
1606 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
1607 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
1608 return TransformTemplateParmRefExpr(E, NTTP);
1610 // We have a non-type template parameter that isn't fully substituted;
1611 // FindInstantiatedDecl will find it in the local instantiation scope.
1614 // Handle references to function parameter packs.
1615 if (VarDecl *PD = dyn_cast<VarDecl>(D))
1616 if (PD->isParameterPack())
1617 return TransformFunctionParmPackRefExpr(E, PD);
1619 return TreeTransform<TemplateInstantiator>::TransformDeclRefExpr(E);
1622 ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
1623 CXXDefaultArgExpr *E) {
1624 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
1625 getDescribedFunctionTemplate() &&
1626 "Default arg expressions are never formed in dependent cases.");
1627 return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
1628 cast<FunctionDecl>(E->getParam()->getDeclContext()),
1632 template<typename Fn>
1633 QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
1634 FunctionProtoTypeLoc TL,
1635 CXXRecordDecl *ThisContext,
1636 Qualifiers ThisTypeQuals,
1637 Fn TransformExceptionSpec) {
1638 // We need a local instantiation scope for this function prototype.
1639 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1640 return inherited::TransformFunctionProtoType(
1641 TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
1645 TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
1646 int indexAdjustment,
1647 Optional<unsigned> NumExpansions,
1648 bool ExpectParameterPack) {
1650 SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment,
1651 NumExpansions, ExpectParameterPack);
1652 if (NewParm && SemaRef.getLangOpts().OpenCL)
1653 SemaRef.deduceOpenCLAddressSpace(NewParm);
1658 TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1659 TemplateTypeParmTypeLoc TL) {
1660 const TemplateTypeParmType *T = TL.getTypePtr();
1661 if (T->getDepth() < TemplateArgs.getNumLevels()) {
1662 // Replace the template type parameter with its corresponding
1663 // template argument.
1665 // If the corresponding template argument is NULL or doesn't exist, it's
1666 // because we are performing instantiation from explicitly-specified
1667 // template arguments in a function template class, but there were some
1668 // arguments left unspecified.
1669 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
1670 TemplateTypeParmTypeLoc NewTL
1671 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
1672 NewTL.setNameLoc(TL.getNameLoc());
1673 return TL.getType();
1676 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
1678 if (T->isParameterPack()) {
1679 assert(Arg.getKind() == TemplateArgument::Pack &&
1680 "Missing argument pack");
1682 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1683 // We have the template argument pack, but we're not expanding the
1684 // enclosing pack expansion yet. Just save the template argument
1685 // pack for later substitution.
1687 = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg);
1688 SubstTemplateTypeParmPackTypeLoc NewTL
1689 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
1690 NewTL.setNameLoc(TL.getNameLoc());
1694 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1697 assert(Arg.getKind() == TemplateArgument::Type &&
1698 "Template argument kind mismatch");
1700 QualType Replacement = Arg.getAsType();
1702 // TODO: only do this uniquing once, at the start of instantiation.
1704 = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
1705 SubstTemplateTypeParmTypeLoc NewTL
1706 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1707 NewTL.setNameLoc(TL.getNameLoc());
1711 // The template type parameter comes from an inner template (e.g.,
1712 // the template parameter list of a member template inside the
1713 // template we are instantiating). Create a new template type
1714 // parameter with the template "level" reduced by one.
1715 TemplateTypeParmDecl *NewTTPDecl = nullptr;
1716 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
1717 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
1718 TransformDecl(TL.getNameLoc(), OldTTPDecl));
1720 QualType Result = getSema().Context.getTemplateTypeParmType(
1721 T->getDepth() - TemplateArgs.getNumSubstitutedLevels(), T->getIndex(),
1722 T->isParameterPack(), NewTTPDecl);
1723 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
1724 NewTL.setNameLoc(TL.getNameLoc());
1729 TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
1730 TypeLocBuilder &TLB,
1731 SubstTemplateTypeParmPackTypeLoc TL) {
1732 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1733 // We aren't expanding the parameter pack, so just return ourselves.
1734 SubstTemplateTypeParmPackTypeLoc NewTL
1735 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(TL.getType());
1736 NewTL.setNameLoc(TL.getNameLoc());
1737 return TL.getType();
1740 TemplateArgument Arg = TL.getTypePtr()->getArgumentPack();
1741 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1742 QualType Result = Arg.getAsType();
1744 Result = getSema().Context.getSubstTemplateTypeParmType(
1745 TL.getTypePtr()->getReplacedParameter(),
1747 SubstTemplateTypeParmTypeLoc NewTL
1748 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1749 NewTL.setNameLoc(TL.getNameLoc());
1753 template<typename EntityPrinter>
1754 static concepts::Requirement::SubstitutionDiagnostic *
1755 createSubstDiag(Sema &S, TemplateDeductionInfo &Info, EntityPrinter Printer) {
1756 SmallString<128> Message;
1757 SourceLocation ErrorLoc;
1758 if (Info.hasSFINAEDiagnostic()) {
1759 PartialDiagnosticAt PDA(SourceLocation(),
1760 PartialDiagnostic::NullDiagnostic{});
1761 Info.takeSFINAEDiagnostic(PDA);
1762 PDA.second.EmitToString(S.getDiagnostics(), Message);
1763 ErrorLoc = PDA.first;
1765 ErrorLoc = Info.getLocation();
1767 char *MessageBuf = new (S.Context) char[Message.size()];
1768 std::copy(Message.begin(), Message.end(), MessageBuf);
1769 SmallString<128> Entity;
1770 llvm::raw_svector_ostream OS(Entity);
1772 char *EntityBuf = new (S.Context) char[Entity.size()];
1773 std::copy(Entity.begin(), Entity.end(), EntityBuf);
1774 return new (S.Context) concepts::Requirement::SubstitutionDiagnostic{
1775 StringRef(EntityBuf, Entity.size()), ErrorLoc,
1776 StringRef(MessageBuf, Message.size())};
1779 concepts::TypeRequirement *
1780 TemplateInstantiator::TransformTypeRequirement(concepts::TypeRequirement *Req) {
1781 if (!Req->isDependent() && !AlwaysRebuild())
1783 if (Req->isSubstitutionFailure()) {
1784 if (AlwaysRebuild())
1785 return RebuildTypeRequirement(
1786 Req->getSubstitutionDiagnostic());
1790 Sema::SFINAETrap Trap(SemaRef);
1791 TemplateDeductionInfo Info(Req->getType()->getTypeLoc().getBeginLoc());
1792 Sema::InstantiatingTemplate TypeInst(SemaRef,
1793 Req->getType()->getTypeLoc().getBeginLoc(), Req, Info,
1794 Req->getType()->getTypeLoc().getSourceRange());
1795 if (TypeInst.isInvalid())
1797 TypeSourceInfo *TransType = TransformType(Req->getType());
1798 if (!TransType || Trap.hasErrorOccurred())
1799 return RebuildTypeRequirement(createSubstDiag(SemaRef, Info,
1800 [&] (llvm::raw_ostream& OS) {
1801 Req->getType()->getType().print(OS, SemaRef.getPrintingPolicy());
1803 return RebuildTypeRequirement(TransType);
1806 concepts::ExprRequirement *
1807 TemplateInstantiator::TransformExprRequirement(concepts::ExprRequirement *Req) {
1808 if (!Req->isDependent() && !AlwaysRebuild())
1811 Sema::SFINAETrap Trap(SemaRef);
1812 TemplateDeductionInfo Info(Req->getExpr()->getBeginLoc());
1814 llvm::PointerUnion<Expr *, concepts::Requirement::SubstitutionDiagnostic *>
1816 if (Req->isExprSubstitutionFailure())
1817 TransExpr = Req->getExprSubstitutionDiagnostic();
1819 Sema::InstantiatingTemplate ExprInst(SemaRef, Req->getExpr()->getBeginLoc(),
1821 Req->getExpr()->getSourceRange());
1822 if (ExprInst.isInvalid())
1824 ExprResult TransExprRes = TransformExpr(Req->getExpr());
1825 if (TransExprRes.isInvalid() || Trap.hasErrorOccurred())
1826 TransExpr = createSubstDiag(SemaRef, Info,
1827 [&] (llvm::raw_ostream& OS) {
1828 Req->getExpr()->printPretty(OS, nullptr,
1829 SemaRef.getPrintingPolicy());
1832 TransExpr = TransExprRes.get();
1835 llvm::Optional<concepts::ExprRequirement::ReturnTypeRequirement> TransRetReq;
1836 const auto &RetReq = Req->getReturnTypeRequirement();
1837 if (RetReq.isEmpty())
1838 TransRetReq.emplace();
1839 else if (RetReq.isSubstitutionFailure())
1840 TransRetReq.emplace(RetReq.getSubstitutionDiagnostic());
1841 else if (RetReq.isTypeConstraint()) {
1842 TemplateParameterList *OrigTPL =
1843 RetReq.getTypeConstraintTemplateParameterList();
1844 Sema::InstantiatingTemplate TPLInst(SemaRef, OrigTPL->getTemplateLoc(),
1845 Req, Info, OrigTPL->getSourceRange());
1846 if (TPLInst.isInvalid())
1848 TemplateParameterList *TPL =
1849 TransformTemplateParameterList(OrigTPL);
1851 TransRetReq.emplace(createSubstDiag(SemaRef, Info,
1852 [&] (llvm::raw_ostream& OS) {
1853 RetReq.getTypeConstraint()->getImmediatelyDeclaredConstraint()
1854 ->printPretty(OS, nullptr, SemaRef.getPrintingPolicy());
1858 TransRetReq.emplace(TPL);
1861 assert(TransRetReq.hasValue() &&
1862 "All code paths leading here must set TransRetReq");
1863 if (Expr *E = TransExpr.dyn_cast<Expr *>())
1864 return RebuildExprRequirement(E, Req->isSimple(), Req->getNoexceptLoc(),
1865 std::move(*TransRetReq));
1866 return RebuildExprRequirement(
1867 TransExpr.get<concepts::Requirement::SubstitutionDiagnostic *>(),
1868 Req->isSimple(), Req->getNoexceptLoc(), std::move(*TransRetReq));
1871 concepts::NestedRequirement *
1872 TemplateInstantiator::TransformNestedRequirement(
1873 concepts::NestedRequirement *Req) {
1874 if (!Req->isDependent() && !AlwaysRebuild())
1876 if (Req->isSubstitutionFailure()) {
1877 if (AlwaysRebuild())
1878 return RebuildNestedRequirement(
1879 Req->getSubstitutionDiagnostic());
1882 Sema::InstantiatingTemplate ReqInst(SemaRef,
1883 Req->getConstraintExpr()->getBeginLoc(), Req,
1884 Sema::InstantiatingTemplate::ConstraintsCheck{},
1885 Req->getConstraintExpr()->getSourceRange());
1887 ExprResult TransConstraint;
1888 TemplateDeductionInfo Info(Req->getConstraintExpr()->getBeginLoc());
1890 EnterExpressionEvaluationContext ContextRAII(
1891 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1892 Sema::SFINAETrap Trap(SemaRef);
1893 Sema::InstantiatingTemplate ConstrInst(SemaRef,
1894 Req->getConstraintExpr()->getBeginLoc(), Req, Info,
1895 Req->getConstraintExpr()->getSourceRange());
1896 if (ConstrInst.isInvalid())
1898 TransConstraint = TransformExpr(Req->getConstraintExpr());
1899 if (TransConstraint.isInvalid() || Trap.hasErrorOccurred())
1900 return RebuildNestedRequirement(createSubstDiag(SemaRef, Info,
1901 [&] (llvm::raw_ostream& OS) {
1902 Req->getConstraintExpr()->printPretty(OS, nullptr,
1903 SemaRef.getPrintingPolicy());
1906 return RebuildNestedRequirement(TransConstraint.get());
1910 /// Perform substitution on the type T with a given set of template
1913 /// This routine substitutes the given template arguments into the
1914 /// type T and produces the instantiated type.
1916 /// \param T the type into which the template arguments will be
1917 /// substituted. If this type is not dependent, it will be returned
1920 /// \param Args the template arguments that will be
1921 /// substituted for the top-level template parameters within T.
1923 /// \param Loc the location in the source code where this substitution
1924 /// is being performed. It will typically be the location of the
1925 /// declarator (if we're instantiating the type of some declaration)
1926 /// or the location of the type in the source code (if, e.g., we're
1927 /// instantiating the type of a cast expression).
1929 /// \param Entity the name of the entity associated with a declaration
1930 /// being instantiated (if any). May be empty to indicate that there
1931 /// is no such entity (if, e.g., this is a type that occurs as part of
1932 /// a cast expression) or that the entity has no name (e.g., an
1933 /// unnamed function parameter).
1935 /// \param AllowDeducedTST Whether a DeducedTemplateSpecializationType is
1936 /// acceptable as the top level type of the result.
1938 /// \returns If the instantiation succeeds, the instantiated
1939 /// type. Otherwise, produces diagnostics and returns a NULL type.
1940 TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
1941 const MultiLevelTemplateArgumentList &Args,
1943 DeclarationName Entity,
1944 bool AllowDeducedTST) {
1945 assert(!CodeSynthesisContexts.empty() &&
1946 "Cannot perform an instantiation without some context on the "
1947 "instantiation stack");
1949 if (!T->getType()->isInstantiationDependentType() &&
1950 !T->getType()->isVariablyModifiedType())
1953 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1954 return AllowDeducedTST ? Instantiator.TransformTypeWithDeducedTST(T)
1955 : Instantiator.TransformType(T);
1958 TypeSourceInfo *Sema::SubstType(TypeLoc TL,
1959 const MultiLevelTemplateArgumentList &Args,
1961 DeclarationName Entity) {
1962 assert(!CodeSynthesisContexts.empty() &&
1963 "Cannot perform an instantiation without some context on the "
1964 "instantiation stack");
1966 if (TL.getType().isNull())
1969 if (!TL.getType()->isInstantiationDependentType() &&
1970 !TL.getType()->isVariablyModifiedType()) {
1971 // FIXME: Make a copy of the TypeLoc data here, so that we can
1972 // return a new TypeSourceInfo. Inefficient!
1974 TLB.pushFullCopy(TL);
1975 return TLB.getTypeSourceInfo(Context, TL.getType());
1978 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1980 TLB.reserve(TL.getFullDataSize());
1981 QualType Result = Instantiator.TransformType(TLB, TL);
1982 if (Result.isNull())
1985 return TLB.getTypeSourceInfo(Context, Result);
1988 /// Deprecated form of the above.
1989 QualType Sema::SubstType(QualType T,
1990 const MultiLevelTemplateArgumentList &TemplateArgs,
1991 SourceLocation Loc, DeclarationName Entity) {
1992 assert(!CodeSynthesisContexts.empty() &&
1993 "Cannot perform an instantiation without some context on the "
1994 "instantiation stack");
1996 // If T is not a dependent type or a variably-modified type, there
1997 // is nothing to do.
1998 if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
2001 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
2002 return Instantiator.TransformType(T);
2005 static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
2006 if (T->getType()->isInstantiationDependentType() ||
2007 T->getType()->isVariablyModifiedType())
2010 TypeLoc TL = T->getTypeLoc().IgnoreParens();
2011 if (!TL.getAs<FunctionProtoTypeLoc>())
2014 FunctionProtoTypeLoc FP = TL.castAs<FunctionProtoTypeLoc>();
2015 for (ParmVarDecl *P : FP.getParams()) {
2016 // This must be synthesized from a typedef.
2019 // If there are any parameters, a new TypeSourceInfo that refers to the
2020 // instantiated parameters must be built.
2027 /// A form of SubstType intended specifically for instantiating the
2028 /// type of a FunctionDecl. Its purpose is solely to force the
2029 /// instantiation of default-argument expressions and to avoid
2030 /// instantiating an exception-specification.
2031 TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
2032 const MultiLevelTemplateArgumentList &Args,
2034 DeclarationName Entity,
2035 CXXRecordDecl *ThisContext,
2036 Qualifiers ThisTypeQuals) {
2037 assert(!CodeSynthesisContexts.empty() &&
2038 "Cannot perform an instantiation without some context on the "
2039 "instantiation stack");
2041 if (!NeedsInstantiationAsFunctionType(T))
2044 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2048 TypeLoc TL = T->getTypeLoc();
2049 TLB.reserve(TL.getFullDataSize());
2053 if (FunctionProtoTypeLoc Proto =
2054 TL.IgnoreParens().getAs<FunctionProtoTypeLoc>()) {
2055 // Instantiate the type, other than its exception specification. The
2056 // exception specification is instantiated in InitFunctionInstantiation
2057 // once we've built the FunctionDecl.
2058 // FIXME: Set the exception specification to EST_Uninstantiated here,
2059 // instead of rebuilding the function type again later.
2060 Result = Instantiator.TransformFunctionProtoType(
2061 TLB, Proto, ThisContext, ThisTypeQuals,
2062 [](FunctionProtoType::ExceptionSpecInfo &ESI,
2063 bool &Changed) { return false; });
2065 Result = Instantiator.TransformType(TLB, TL);
2067 if (Result.isNull())
2070 return TLB.getTypeSourceInfo(Context, Result);
2073 bool Sema::SubstExceptionSpec(SourceLocation Loc,
2074 FunctionProtoType::ExceptionSpecInfo &ESI,
2075 SmallVectorImpl<QualType> &ExceptionStorage,
2076 const MultiLevelTemplateArgumentList &Args) {
2077 assert(ESI.Type != EST_Uninstantiated);
2079 bool Changed = false;
2080 TemplateInstantiator Instantiator(*this, Args, Loc, DeclarationName());
2081 return Instantiator.TransformExceptionSpec(Loc, ESI, ExceptionStorage,
2085 void Sema::SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
2086 const MultiLevelTemplateArgumentList &Args) {
2087 FunctionProtoType::ExceptionSpecInfo ESI =
2088 Proto->getExtProtoInfo().ExceptionSpec;
2090 SmallVector<QualType, 4> ExceptionStorage;
2091 if (SubstExceptionSpec(New->getTypeSourceInfo()->getTypeLoc().getEndLoc(),
2092 ESI, ExceptionStorage, Args))
2093 // On error, recover by dropping the exception specification.
2094 ESI.Type = EST_None;
2096 UpdateExceptionSpec(New, ESI);
2099 ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm,
2100 const MultiLevelTemplateArgumentList &TemplateArgs,
2101 int indexAdjustment,
2102 Optional<unsigned> NumExpansions,
2103 bool ExpectParameterPack) {
2104 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
2105 TypeSourceInfo *NewDI = nullptr;
2107 TypeLoc OldTL = OldDI->getTypeLoc();
2108 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
2110 // We have a function parameter pack. Substitute into the pattern of the
2112 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
2113 OldParm->getLocation(), OldParm->getDeclName());
2117 if (NewDI->getType()->containsUnexpandedParameterPack()) {
2118 // We still have unexpanded parameter packs, which means that
2119 // our function parameter is still a function parameter pack.
2120 // Therefore, make its type a pack expansion type.
2121 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
2123 } else if (ExpectParameterPack) {
2124 // We expected to get a parameter pack but didn't (because the type
2125 // itself is not a pack expansion type), so complain. This can occur when
2126 // the substitution goes through an alias template that "loses" the
2128 Diag(OldParm->getLocation(),
2129 diag::err_function_parameter_pack_without_parameter_packs)
2130 << NewDI->getType();
2134 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
2135 OldParm->getDeclName());
2141 if (NewDI->getType()->isVoidType()) {
2142 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
2146 ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
2147 OldParm->getInnerLocStart(),
2148 OldParm->getLocation(),
2149 OldParm->getIdentifier(),
2150 NewDI->getType(), NewDI,
2151 OldParm->getStorageClass());
2155 // Mark the (new) default argument as uninstantiated (if any).
2156 if (OldParm->hasUninstantiatedDefaultArg()) {
2157 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
2158 NewParm->setUninstantiatedDefaultArg(Arg);
2159 } else if (OldParm->hasUnparsedDefaultArg()) {
2160 NewParm->setUnparsedDefaultArg();
2161 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
2162 } else if (Expr *Arg = OldParm->getDefaultArg()) {
2163 FunctionDecl *OwningFunc = cast<FunctionDecl>(OldParm->getDeclContext());
2164 if (OwningFunc->isLexicallyWithinFunctionOrMethod()) {
2165 // Instantiate default arguments for methods of local classes (DR1484)
2166 // and non-defining declarations.
2167 Sema::ContextRAII SavedContext(*this, OwningFunc);
2168 LocalInstantiationScope Local(*this, true);
2169 ExprResult NewArg = SubstExpr(Arg, TemplateArgs);
2170 if (NewArg.isUsable()) {
2171 // It would be nice if we still had this.
2172 SourceLocation EqualLoc = NewArg.get()->getBeginLoc();
2173 SetParamDefaultArgument(NewParm, NewArg.get(), EqualLoc);
2176 // FIXME: if we non-lazily instantiated non-dependent default args for
2177 // non-dependent parameter types we could remove a bunch of duplicate
2178 // conversion warnings for such arguments.
2179 NewParm->setUninstantiatedDefaultArg(Arg);
2183 NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
2185 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
2186 // Add the new parameter to the instantiated parameter pack.
2187 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
2189 // Introduce an Old -> New mapping
2190 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
2193 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
2194 // can be anything, is this right ?
2195 NewParm->setDeclContext(CurContext);
2197 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
2198 OldParm->getFunctionScopeIndex() + indexAdjustment);
2200 InstantiateAttrs(TemplateArgs, OldParm, NewParm);
2205 /// Substitute the given template arguments into the given set of
2206 /// parameters, producing the set of parameter types that would be generated
2207 /// from such a substitution.
2208 bool Sema::SubstParmTypes(
2209 SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
2210 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
2211 const MultiLevelTemplateArgumentList &TemplateArgs,
2212 SmallVectorImpl<QualType> &ParamTypes,
2213 SmallVectorImpl<ParmVarDecl *> *OutParams,
2214 ExtParameterInfoBuilder &ParamInfos) {
2215 assert(!CodeSynthesisContexts.empty() &&
2216 "Cannot perform an instantiation without some context on the "
2217 "instantiation stack");
2219 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
2221 return Instantiator.TransformFunctionTypeParams(
2222 Loc, Params, nullptr, ExtParamInfos, ParamTypes, OutParams, ParamInfos);
2225 /// Perform substitution on the base class specifiers of the
2226 /// given class template specialization.
2228 /// Produces a diagnostic and returns true on error, returns false and
2229 /// attaches the instantiated base classes to the class template
2230 /// specialization if successful.
2232 Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
2233 CXXRecordDecl *Pattern,
2234 const MultiLevelTemplateArgumentList &TemplateArgs) {
2235 bool Invalid = false;
2236 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
2237 for (const auto &Base : Pattern->bases()) {
2238 if (!Base.getType()->isDependentType()) {
2239 if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
2240 if (RD->isInvalidDecl())
2241 Instantiation->setInvalidDecl();
2243 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
2247 SourceLocation EllipsisLoc;
2248 TypeSourceInfo *BaseTypeLoc;
2249 if (Base.isPackExpansion()) {
2250 // This is a pack expansion. See whether we should expand it now, or
2251 // wait until later.
2252 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2253 collectUnexpandedParameterPacks(Base.getTypeSourceInfo()->getTypeLoc(),
2255 bool ShouldExpand = false;
2256 bool RetainExpansion = false;
2257 Optional<unsigned> NumExpansions;
2258 if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(),
2259 Base.getSourceRange(),
2261 TemplateArgs, ShouldExpand,
2268 // If we should expand this pack expansion now, do so.
2270 for (unsigned I = 0; I != *NumExpansions; ++I) {
2271 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
2273 TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
2275 Base.getSourceRange().getBegin(),
2282 if (CXXBaseSpecifier *InstantiatedBase
2283 = CheckBaseSpecifier(Instantiation,
2284 Base.getSourceRange(),
2286 Base.getAccessSpecifierAsWritten(),
2289 InstantiatedBases.push_back(InstantiatedBase);
2297 // The resulting base specifier will (still) be a pack expansion.
2298 EllipsisLoc = Base.getEllipsisLoc();
2299 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
2300 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
2302 Base.getSourceRange().getBegin(),
2305 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
2307 Base.getSourceRange().getBegin(),
2316 if (CXXBaseSpecifier *InstantiatedBase
2317 = CheckBaseSpecifier(Instantiation,
2318 Base.getSourceRange(),
2320 Base.getAccessSpecifierAsWritten(),
2323 InstantiatedBases.push_back(InstantiatedBase);
2328 if (!Invalid && AttachBaseSpecifiers(Instantiation, InstantiatedBases))
2334 // Defined via #include from SemaTemplateInstantiateDecl.cpp
2337 Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S,
2338 const MultiLevelTemplateArgumentList &TemplateArgs);
2339 Attr *instantiateTemplateAttributeForDecl(
2340 const Attr *At, ASTContext &C, Sema &S,
2341 const MultiLevelTemplateArgumentList &TemplateArgs);
2345 /// Instantiate the definition of a class from a given pattern.
2347 /// \param PointOfInstantiation The point of instantiation within the
2350 /// \param Instantiation is the declaration whose definition is being
2351 /// instantiated. This will be either a class template specialization
2352 /// or a member class of a class template specialization.
2354 /// \param Pattern is the pattern from which the instantiation
2355 /// occurs. This will be either the declaration of a class template or
2356 /// the declaration of a member class of a class template.
2358 /// \param TemplateArgs The template arguments to be substituted into
2361 /// \param TSK the kind of implicit or explicit instantiation to perform.
2363 /// \param Complain whether to complain if the class cannot be instantiated due
2364 /// to the lack of a definition.
2366 /// \returns true if an error occurred, false otherwise.
2368 Sema::InstantiateClass(SourceLocation PointOfInstantiation,
2369 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
2370 const MultiLevelTemplateArgumentList &TemplateArgs,
2371 TemplateSpecializationKind TSK,
2373 CXXRecordDecl *PatternDef
2374 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
2375 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
2376 Instantiation->getInstantiatedFromMemberClass(),
2377 Pattern, PatternDef, TSK, Complain))
2380 llvm::TimeTraceScope TimeScope("InstantiateClass", [&]() {
2382 llvm::raw_string_ostream OS(Name);
2383 Instantiation->getNameForDiagnostic(OS, getPrintingPolicy(),
2384 /*Qualified=*/true);
2388 Pattern = PatternDef;
2390 // Record the point of instantiation.
2391 if (MemberSpecializationInfo *MSInfo
2392 = Instantiation->getMemberSpecializationInfo()) {
2393 MSInfo->setTemplateSpecializationKind(TSK);
2394 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2395 } else if (ClassTemplateSpecializationDecl *Spec
2396 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
2397 Spec->setTemplateSpecializationKind(TSK);
2398 Spec->setPointOfInstantiation(PointOfInstantiation);
2401 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2402 if (Inst.isInvalid())
2404 assert(!Inst.isAlreadyInstantiating() && "should have been caught by caller");
2405 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
2406 "instantiating class definition");
2408 // Enter the scope of this instantiation. We don't use
2409 // PushDeclContext because we don't have a scope.
2410 ContextRAII SavedContext(*this, Instantiation);
2411 EnterExpressionEvaluationContext EvalContext(
2412 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
2414 // If this is an instantiation of a local class, merge this local
2415 // instantiation scope with the enclosing scope. Otherwise, every
2416 // instantiation of a class has its own local instantiation scope.
2417 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
2418 LocalInstantiationScope Scope(*this, MergeWithParentScope);
2420 // Some class state isn't processed immediately but delayed till class
2421 // instantiation completes. We may not be ready to handle any delayed state
2422 // already on the stack as it might correspond to a different class, so save
2423 // it now and put it back later.
2424 SavePendingParsedClassStateRAII SavedPendingParsedClassState(*this);
2426 // Pull attributes from the pattern onto the instantiation.
2427 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2429 // Start the definition of this instantiation.
2430 Instantiation->startDefinition();
2432 // The instantiation is visible here, even if it was first declared in an
2433 // unimported module.
2434 Instantiation->setVisibleDespiteOwningModule();
2436 // FIXME: This loses the as-written tag kind for an explicit instantiation.
2437 Instantiation->setTagKind(Pattern->getTagKind());
2439 // Do substitution on the base class specifiers.
2440 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
2441 Instantiation->setInvalidDecl();
2443 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2444 SmallVector<Decl*, 4> Fields;
2445 // Delay instantiation of late parsed attributes.
2446 LateInstantiatedAttrVec LateAttrs;
2447 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
2449 bool MightHaveConstexprVirtualFunctions = false;
2450 for (auto *Member : Pattern->decls()) {
2451 // Don't instantiate members not belonging in this semantic context.
2454 // template <int i> class A {
2458 // 'class B' has the template as lexical context but semantically it is
2459 // introduced in namespace scope.
2460 if (Member->getDeclContext() != Pattern)
2463 // BlockDecls can appear in a default-member-initializer. They must be the
2464 // child of a BlockExpr, so we only know how to instantiate them from there.
2465 if (isa<BlockDecl>(Member))
2468 if (Member->isInvalidDecl()) {
2469 Instantiation->setInvalidDecl();
2473 Decl *NewMember = Instantiator.Visit(Member);
2475 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
2476 Fields.push_back(Field);
2477 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
2478 // C++11 [temp.inst]p1: The implicit instantiation of a class template
2479 // specialization causes the implicit instantiation of the definitions
2480 // of unscoped member enumerations.
2481 // Record a point of instantiation for this implicit instantiation.
2482 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
2483 Enum->isCompleteDefinition()) {
2484 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
2485 assert(MSInfo && "no spec info for member enum specialization");
2486 MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation);
2487 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2489 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
2490 if (SA->isFailed()) {
2491 // A static_assert failed. Bail out; instantiating this
2492 // class is probably not meaningful.
2493 Instantiation->setInvalidDecl();
2496 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewMember)) {
2497 if (MD->isConstexpr() && !MD->getFriendObjectKind() &&
2498 (MD->isVirtualAsWritten() || Instantiation->getNumBases()))
2499 MightHaveConstexprVirtualFunctions = true;
2502 if (NewMember->isInvalidDecl())
2503 Instantiation->setInvalidDecl();
2505 // FIXME: Eventually, a NULL return will mean that one of the
2506 // instantiations was a semantic disaster, and we'll want to mark the
2507 // declaration invalid.
2508 // For now, we expect to skip some members that we can't yet handle.
2512 // Finish checking fields.
2513 ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
2514 SourceLocation(), SourceLocation(), ParsedAttributesView());
2515 CheckCompletedCXXClass(nullptr, Instantiation);
2517 // Default arguments are parsed, if not instantiated. We can go instantiate
2518 // default arg exprs for default constructors if necessary now. Unless we're
2519 // parsing a class, in which case wait until that's finished.
2520 if (ParsingClassDepth == 0)
2521 ActOnFinishCXXNonNestedClass();
2523 // Instantiate late parsed attributes, and attach them to their decls.
2524 // See Sema::InstantiateAttrs
2525 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
2526 E = LateAttrs.end(); I != E; ++I) {
2527 assert(CurrentInstantiationScope == Instantiator.getStartingScope());
2528 CurrentInstantiationScope = I->Scope;
2530 // Allow 'this' within late-parsed attributes.
2531 NamedDecl *ND = dyn_cast<NamedDecl>(I->NewDecl);
2532 CXXRecordDecl *ThisContext =
2533 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
2534 CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
2535 ND && ND->isCXXInstanceMember());
2538 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
2539 I->NewDecl->addAttr(NewAttr);
2540 LocalInstantiationScope::deleteScopes(I->Scope,
2541 Instantiator.getStartingScope());
2543 Instantiator.disableLateAttributeInstantiation();
2546 ActOnFinishDelayedMemberInitializers(Instantiation);
2548 // FIXME: We should do something similar for explicit instantiations so they
2549 // end up in the right module.
2550 if (TSK == TSK_ImplicitInstantiation) {
2551 Instantiation->setLocation(Pattern->getLocation());
2552 Instantiation->setLocStart(Pattern->getInnerLocStart());
2553 Instantiation->setBraceRange(Pattern->getBraceRange());
2556 if (!Instantiation->isInvalidDecl()) {
2557 // Perform any dependent diagnostics from the pattern.
2558 PerformDependentDiagnostics(Pattern, TemplateArgs);
2560 // Instantiate any out-of-line class template partial
2561 // specializations now.
2562 for (TemplateDeclInstantiator::delayed_partial_spec_iterator
2563 P = Instantiator.delayed_partial_spec_begin(),
2564 PEnd = Instantiator.delayed_partial_spec_end();
2566 if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
2567 P->first, P->second)) {
2568 Instantiation->setInvalidDecl();
2573 // Instantiate any out-of-line variable template partial
2574 // specializations now.
2575 for (TemplateDeclInstantiator::delayed_var_partial_spec_iterator
2576 P = Instantiator.delayed_var_partial_spec_begin(),
2577 PEnd = Instantiator.delayed_var_partial_spec_end();
2579 if (!Instantiator.InstantiateVarTemplatePartialSpecialization(
2580 P->first, P->second)) {
2581 Instantiation->setInvalidDecl();
2587 // Exit the scope of this instantiation.
2590 if (!Instantiation->isInvalidDecl()) {
2591 Consumer.HandleTagDeclDefinition(Instantiation);
2593 // Always emit the vtable for an explicit instantiation definition
2594 // of a polymorphic class template specialization. Otherwise, eagerly
2595 // instantiate only constexpr virtual functions in preparation for their use
2596 // in constant evaluation.
2597 if (TSK == TSK_ExplicitInstantiationDefinition)
2598 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
2599 else if (MightHaveConstexprVirtualFunctions)
2600 MarkVirtualMembersReferenced(PointOfInstantiation, Instantiation,
2601 /*ConstexprOnly*/ true);
2604 return Instantiation->isInvalidDecl();
2607 /// Instantiate the definition of an enum from a given pattern.
2609 /// \param PointOfInstantiation The point of instantiation within the
2611 /// \param Instantiation is the declaration whose definition is being
2612 /// instantiated. This will be a member enumeration of a class
2613 /// temploid specialization, or a local enumeration within a
2614 /// function temploid specialization.
2615 /// \param Pattern The templated declaration from which the instantiation
2617 /// \param TemplateArgs The template arguments to be substituted into
2619 /// \param TSK The kind of implicit or explicit instantiation to perform.
2621 /// \return \c true if an error occurred, \c false otherwise.
2622 bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
2623 EnumDecl *Instantiation, EnumDecl *Pattern,
2624 const MultiLevelTemplateArgumentList &TemplateArgs,
2625 TemplateSpecializationKind TSK) {
2626 EnumDecl *PatternDef = Pattern->getDefinition();
2627 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
2628 Instantiation->getInstantiatedFromMemberEnum(),
2629 Pattern, PatternDef, TSK,/*Complain*/true))
2631 Pattern = PatternDef;
2633 // Record the point of instantiation.
2634 if (MemberSpecializationInfo *MSInfo
2635 = Instantiation->getMemberSpecializationInfo()) {
2636 MSInfo->setTemplateSpecializationKind(TSK);
2637 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2640 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2641 if (Inst.isInvalid())
2643 if (Inst.isAlreadyInstantiating())
2645 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
2646 "instantiating enum definition");
2648 // The instantiation is visible here, even if it was first declared in an
2649 // unimported module.
2650 Instantiation->setVisibleDespiteOwningModule();
2652 // Enter the scope of this instantiation. We don't use
2653 // PushDeclContext because we don't have a scope.
2654 ContextRAII SavedContext(*this, Instantiation);
2655 EnterExpressionEvaluationContext EvalContext(
2656 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
2658 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
2660 // Pull attributes from the pattern onto the instantiation.
2661 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2663 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2664 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
2666 // Exit the scope of this instantiation.
2669 return Instantiation->isInvalidDecl();
2673 /// Instantiate the definition of a field from the given pattern.
2675 /// \param PointOfInstantiation The point of instantiation within the
2677 /// \param Instantiation is the declaration whose definition is being
2678 /// instantiated. This will be a class of a class temploid
2679 /// specialization, or a local enumeration within a function temploid
2681 /// \param Pattern The templated declaration from which the instantiation
2683 /// \param TemplateArgs The template arguments to be substituted into
2686 /// \return \c true if an error occurred, \c false otherwise.
2687 bool Sema::InstantiateInClassInitializer(
2688 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
2689 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
2690 // If there is no initializer, we don't need to do anything.
2691 if (!Pattern->hasInClassInitializer())
2694 assert(Instantiation->getInClassInitStyle() ==
2695 Pattern->getInClassInitStyle() &&
2696 "pattern and instantiation disagree about init style");
2698 // Error out if we haven't parsed the initializer of the pattern yet because
2699 // we are waiting for the closing brace of the outer class.
2700 Expr *OldInit = Pattern->getInClassInitializer();
2702 RecordDecl *PatternRD = Pattern->getParent();
2703 RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext();
2704 Diag(PointOfInstantiation,
2705 diag::err_in_class_initializer_not_yet_parsed)
2706 << OutermostClass << Pattern;
2707 Diag(Pattern->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed);
2708 Instantiation->setInvalidDecl();
2712 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2713 if (Inst.isInvalid())
2715 if (Inst.isAlreadyInstantiating()) {
2716 // Error out if we hit an instantiation cycle for this initializer.
2717 Diag(PointOfInstantiation, diag::err_in_class_initializer_cycle)
2721 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
2722 "instantiating default member init");
2724 // Enter the scope of this instantiation. We don't use PushDeclContext because
2725 // we don't have a scope.
2726 ContextRAII SavedContext(*this, Instantiation->getParent());
2727 EnterExpressionEvaluationContext EvalContext(
2728 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
2730 LocalInstantiationScope Scope(*this, true);
2732 // Instantiate the initializer.
2733 ActOnStartCXXInClassMemberInitializer();
2734 CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), Qualifiers());
2736 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
2737 /*CXXDirectInit=*/false);
2738 Expr *Init = NewInit.get();
2739 assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class");
2740 ActOnFinishCXXInClassMemberInitializer(
2741 Instantiation, Init ? Init->getBeginLoc() : SourceLocation(), Init);
2743 if (auto *L = getASTMutationListener())
2744 L->DefaultMemberInitializerInstantiated(Instantiation);
2746 // Return true if the in-class initializer is still missing.
2747 return !Instantiation->getInClassInitializer();
2751 /// A partial specialization whose template arguments have matched
2752 /// a given template-id.
2753 struct PartialSpecMatchResult {
2754 ClassTemplatePartialSpecializationDecl *Partial;
2755 TemplateArgumentList *Args;
2759 bool Sema::usesPartialOrExplicitSpecialization(
2760 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec) {
2761 if (ClassTemplateSpec->getTemplateSpecializationKind() ==
2762 TSK_ExplicitSpecialization)
2765 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2766 ClassTemplateSpec->getSpecializedTemplate()
2767 ->getPartialSpecializations(PartialSpecs);
2768 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2769 TemplateDeductionInfo Info(Loc);
2770 if (!DeduceTemplateArguments(PartialSpecs[I],
2771 ClassTemplateSpec->getTemplateArgs(), Info))
2778 /// Get the instantiation pattern to use to instantiate the definition of a
2779 /// given ClassTemplateSpecializationDecl (either the pattern of the primary
2780 /// template or of a partial specialization).
2781 static CXXRecordDecl *
2782 getPatternForClassTemplateSpecialization(
2783 Sema &S, SourceLocation PointOfInstantiation,
2784 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2785 TemplateSpecializationKind TSK, bool Complain) {
2786 Sema::InstantiatingTemplate Inst(S, PointOfInstantiation, ClassTemplateSpec);
2787 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
2790 llvm::PointerUnion<ClassTemplateDecl *,
2791 ClassTemplatePartialSpecializationDecl *>
2792 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
2793 if (!Specialized.is<ClassTemplatePartialSpecializationDecl *>()) {
2794 // Find best matching specialization.
2795 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
2797 // C++ [temp.class.spec.match]p1:
2798 // When a class template is used in a context that requires an
2799 // instantiation of the class, it is necessary to determine
2800 // whether the instantiation is to be generated using the primary
2801 // template or one of the partial specializations. This is done by
2802 // matching the template arguments of the class template
2803 // specialization with the template argument lists of the partial
2805 typedef PartialSpecMatchResult MatchResult;
2806 SmallVector<MatchResult, 4> Matched;
2807 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2808 Template->getPartialSpecializations(PartialSpecs);
2809 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
2810 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2811 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
2812 TemplateDeductionInfo Info(FailedCandidates.getLocation());
2813 if (Sema::TemplateDeductionResult Result = S.DeduceTemplateArguments(
2814 Partial, ClassTemplateSpec->getTemplateArgs(), Info)) {
2815 // Store the failed-deduction information for use in diagnostics, later.
2816 // TODO: Actually use the failed-deduction info?
2817 FailedCandidates.addCandidate().set(
2818 DeclAccessPair::make(Template, AS_public), Partial,
2819 MakeDeductionFailureInfo(S.Context, Result, Info));
2822 Matched.push_back(PartialSpecMatchResult());
2823 Matched.back().Partial = Partial;
2824 Matched.back().Args = Info.take();
2828 // If we're dealing with a member template where the template parameters
2829 // have been instantiated, this provides the original template parameters
2830 // from which the member template's parameters were instantiated.
2832 if (Matched.size() >= 1) {
2833 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
2834 if (Matched.size() == 1) {
2835 // -- If exactly one matching specialization is found, the
2836 // instantiation is generated from that specialization.
2837 // We don't need to do anything for this.
2839 // -- If more than one matching specialization is found, the
2840 // partial order rules (14.5.4.2) are used to determine
2841 // whether one of the specializations is more specialized
2842 // than the others. If none of the specializations is more
2843 // specialized than all of the other matching
2844 // specializations, then the use of the class template is
2845 // ambiguous and the program is ill-formed.
2846 for (SmallVectorImpl<MatchResult>::iterator P = Best + 1,
2847 PEnd = Matched.end();
2849 if (S.getMoreSpecializedPartialSpecialization(
2850 P->Partial, Best->Partial, PointOfInstantiation) ==
2855 // Determine if the best partial specialization is more specialized than
2857 bool Ambiguous = false;
2858 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2859 PEnd = Matched.end();
2861 if (P != Best && S.getMoreSpecializedPartialSpecialization(
2862 P->Partial, Best->Partial,
2863 PointOfInstantiation) != Best->Partial) {
2870 // Partial ordering did not produce a clear winner. Complain.
2872 ClassTemplateSpec->setInvalidDecl();
2873 S.Diag(PointOfInstantiation,
2874 diag::err_partial_spec_ordering_ambiguous)
2875 << ClassTemplateSpec;
2877 // Print the matching partial specializations.
2878 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2879 PEnd = Matched.end();
2881 S.Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2882 << S.getTemplateArgumentBindingsText(
2883 P->Partial->getTemplateParameters(), *P->Args);
2889 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
2891 // -- If no matches are found, the instantiation is generated
2892 // from the primary template.
2896 CXXRecordDecl *Pattern = nullptr;
2897 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
2898 if (auto *PartialSpec =
2899 Specialized.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
2900 // Instantiate using the best class template partial specialization.
2901 while (PartialSpec->getInstantiatedFromMember()) {
2902 // If we've found an explicit specialization of this class template,
2903 // stop here and use that as the pattern.
2904 if (PartialSpec->isMemberSpecialization())
2907 PartialSpec = PartialSpec->getInstantiatedFromMember();
2909 Pattern = PartialSpec;
2911 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
2912 while (Template->getInstantiatedFromMemberTemplate()) {
2913 // If we've found an explicit specialization of this class template,
2914 // stop here and use that as the pattern.
2915 if (Template->isMemberSpecialization())
2918 Template = Template->getInstantiatedFromMemberTemplate();
2920 Pattern = Template->getTemplatedDecl();
2926 bool Sema::InstantiateClassTemplateSpecialization(
2927 SourceLocation PointOfInstantiation,
2928 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2929 TemplateSpecializationKind TSK, bool Complain) {
2930 // Perform the actual instantiation on the canonical declaration.
2931 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
2932 ClassTemplateSpec->getCanonicalDecl());
2933 if (ClassTemplateSpec->isInvalidDecl())
2936 CXXRecordDecl *Pattern = getPatternForClassTemplateSpecialization(
2937 *this, PointOfInstantiation, ClassTemplateSpec, TSK, Complain);
2941 return InstantiateClass(PointOfInstantiation, ClassTemplateSpec, Pattern,
2942 getTemplateInstantiationArgs(ClassTemplateSpec), TSK,
2946 /// Instantiates the definitions of all of the member
2947 /// of the given class, which is an instantiation of a class template
2948 /// or a member class of a template.
2950 Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
2951 CXXRecordDecl *Instantiation,
2952 const MultiLevelTemplateArgumentList &TemplateArgs,
2953 TemplateSpecializationKind TSK) {
2954 // FIXME: We need to notify the ASTMutationListener that we did all of these
2955 // things, in case we have an explicit instantiation definition in a PCM, a
2956 // module, or preamble, and the declaration is in an imported AST.
2958 (TSK == TSK_ExplicitInstantiationDefinition ||
2959 TSK == TSK_ExplicitInstantiationDeclaration ||
2960 (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&
2961 "Unexpected template specialization kind!");
2962 for (auto *D : Instantiation->decls()) {
2963 bool SuppressNew = false;
2964 if (auto *Function = dyn_cast<FunctionDecl>(D)) {
2965 if (FunctionDecl *Pattern =
2966 Function->getInstantiatedFromMemberFunction()) {
2968 if (Function->hasAttr<ExcludeFromExplicitInstantiationAttr>())
2971 MemberSpecializationInfo *MSInfo =
2972 Function->getMemberSpecializationInfo();
2973 assert(MSInfo && "No member specialization information?");
2974 if (MSInfo->getTemplateSpecializationKind()
2975 == TSK_ExplicitSpecialization)
2978 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2980 MSInfo->getTemplateSpecializationKind(),
2981 MSInfo->getPointOfInstantiation(),
2986 // C++11 [temp.explicit]p8:
2987 // An explicit instantiation definition that names a class template
2988 // specialization explicitly instantiates the class template
2989 // specialization and is only an explicit instantiation definition
2990 // of members whose definition is visible at the point of
2992 if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())
2995 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2997 if (Function->isDefined()) {
2998 // Let the ASTConsumer know that this function has been explicitly
2999 // instantiated now, and its linkage might have changed.
3000 Consumer.HandleTopLevelDecl(DeclGroupRef(Function));
3001 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
3002 InstantiateFunctionDefinition(PointOfInstantiation, Function);
3003 } else if (TSK == TSK_ImplicitInstantiation) {
3004 PendingLocalImplicitInstantiations.push_back(
3005 std::make_pair(Function, PointOfInstantiation));
3008 } else if (auto *Var = dyn_cast<VarDecl>(D)) {
3009 if (isa<VarTemplateSpecializationDecl>(Var))
3012 if (Var->isStaticDataMember()) {
3013 if (Var->hasAttr<ExcludeFromExplicitInstantiationAttr>())
3016 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
3017 assert(MSInfo && "No member specialization information?");
3018 if (MSInfo->getTemplateSpecializationKind()
3019 == TSK_ExplicitSpecialization)
3022 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
3024 MSInfo->getTemplateSpecializationKind(),
3025 MSInfo->getPointOfInstantiation(),
3030 if (TSK == TSK_ExplicitInstantiationDefinition) {
3031 // C++0x [temp.explicit]p8:
3032 // An explicit instantiation definition that names a class template
3033 // specialization explicitly instantiates the class template
3034 // specialization and is only an explicit instantiation definition
3035 // of members whose definition is visible at the point of
3037 if (!Var->getInstantiatedFromStaticDataMember()->getDefinition())
3040 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
3041 InstantiateVariableDefinition(PointOfInstantiation, Var);
3043 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
3046 } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
3047 if (Record->hasAttr<ExcludeFromExplicitInstantiationAttr>())
3050 // Always skip the injected-class-name, along with any
3051 // redeclarations of nested classes, since both would cause us
3052 // to try to instantiate the members of a class twice.
3053 // Skip closure types; they'll get instantiated when we instantiate
3054 // the corresponding lambda-expression.
3055 if (Record->isInjectedClassName() || Record->getPreviousDecl() ||
3059 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
3060 assert(MSInfo && "No member specialization information?");
3062 if (MSInfo->getTemplateSpecializationKind()
3063 == TSK_ExplicitSpecialization)
3066 if (Context.getTargetInfo().getTriple().isOSWindows() &&
3067 TSK == TSK_ExplicitInstantiationDeclaration) {
3068 // On Windows, explicit instantiation decl of the outer class doesn't
3069 // affect the inner class. Typically extern template declarations are
3070 // used in combination with dll import/export annotations, but those
3071 // are not propagated from the outer class templates to inner classes.
3072 // Therefore, do not instantiate inner classes on this platform, so
3073 // that users don't end up with undefined symbols during linking.
3077 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
3079 MSInfo->getTemplateSpecializationKind(),
3080 MSInfo->getPointOfInstantiation(),
3085 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
3086 assert(Pattern && "Missing instantiated-from-template information");
3088 if (!Record->getDefinition()) {
3089 if (!Pattern->getDefinition()) {
3090 // C++0x [temp.explicit]p8:
3091 // An explicit instantiation definition that names a class template
3092 // specialization explicitly instantiates the class template
3093 // specialization and is only an explicit instantiation definition
3094 // of members whose definition is visible at the point of
3096 if (TSK == TSK_ExplicitInstantiationDeclaration) {
3097 MSInfo->setTemplateSpecializationKind(TSK);
3098 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3104 InstantiateClass(PointOfInstantiation, Record, Pattern,
3108 if (TSK == TSK_ExplicitInstantiationDefinition &&
3109 Record->getTemplateSpecializationKind() ==
3110 TSK_ExplicitInstantiationDeclaration) {
3111 Record->setTemplateSpecializationKind(TSK);
3112 MarkVTableUsed(PointOfInstantiation, Record, true);
3116 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
3118 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
3120 } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
3121 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
3122 assert(MSInfo && "No member specialization information?");
3124 if (MSInfo->getTemplateSpecializationKind()
3125 == TSK_ExplicitSpecialization)
3128 if (CheckSpecializationInstantiationRedecl(
3129 PointOfInstantiation, TSK, Enum,
3130 MSInfo->getTemplateSpecializationKind(),
3131 MSInfo->getPointOfInstantiation(), SuppressNew) ||
3135 if (Enum->getDefinition())
3138 EnumDecl *Pattern = Enum->getTemplateInstantiationPattern();
3139 assert(Pattern && "Missing instantiated-from-template information");
3141 if (TSK == TSK_ExplicitInstantiationDefinition) {
3142 if (!Pattern->getDefinition())
3145 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
3147 MSInfo->setTemplateSpecializationKind(TSK);
3148 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3150 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
3151 // No need to instantiate in-class initializers during explicit
3153 if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) {
3154 CXXRecordDecl *ClassPattern =
3155 Instantiation->getTemplateInstantiationPattern();
3156 DeclContext::lookup_result Lookup =
3157 ClassPattern->lookup(Field->getDeclName());
3158 FieldDecl *Pattern = cast<FieldDecl>(Lookup.front());
3159 InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern,
3166 /// Instantiate the definitions of all of the members of the
3167 /// given class template specialization, which was named as part of an
3168 /// explicit instantiation.
3170 Sema::InstantiateClassTemplateSpecializationMembers(
3171 SourceLocation PointOfInstantiation,
3172 ClassTemplateSpecializationDecl *ClassTemplateSpec,
3173 TemplateSpecializationKind TSK) {
3174 // C++0x [temp.explicit]p7:
3175 // An explicit instantiation that names a class template
3176 // specialization is an explicit instantion of the same kind
3177 // (declaration or definition) of each of its members (not
3178 // including members inherited from base classes) that has not
3179 // been previously explicitly specialized in the translation unit
3180 // containing the explicit instantiation, except as described
3182 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
3183 getTemplateInstantiationArgs(ClassTemplateSpec),
3188 Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
3192 TemplateInstantiator Instantiator(*this, TemplateArgs,
3195 return Instantiator.TransformStmt(S);
3198 bool Sema::SubstTemplateArguments(
3199 ArrayRef<TemplateArgumentLoc> Args,
3200 const MultiLevelTemplateArgumentList &TemplateArgs,
3201 TemplateArgumentListInfo &Out) {
3202 TemplateInstantiator Instantiator(*this, TemplateArgs,
3205 return Instantiator.TransformTemplateArguments(Args.begin(), Args.end(),
3210 Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
3214 TemplateInstantiator Instantiator(*this, TemplateArgs,
3217 return Instantiator.TransformExpr(E);
3220 ExprResult Sema::SubstInitializer(Expr *Init,
3221 const MultiLevelTemplateArgumentList &TemplateArgs,
3222 bool CXXDirectInit) {
3223 TemplateInstantiator Instantiator(*this, TemplateArgs,
3226 return Instantiator.TransformInitializer(Init, CXXDirectInit);
3229 bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
3230 const MultiLevelTemplateArgumentList &TemplateArgs,
3231 SmallVectorImpl<Expr *> &Outputs) {
3235 TemplateInstantiator Instantiator(*this, TemplateArgs,
3238 return Instantiator.TransformExprs(Exprs.data(), Exprs.size(),
3242 NestedNameSpecifierLoc
3243 Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
3244 const MultiLevelTemplateArgumentList &TemplateArgs) {
3246 return NestedNameSpecifierLoc();
3248 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
3250 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
3253 /// Do template substitution on declaration name info.
3255 Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
3256 const MultiLevelTemplateArgumentList &TemplateArgs) {
3257 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
3258 NameInfo.getName());
3259 return Instantiator.TransformDeclarationNameInfo(NameInfo);
3263 Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,
3264 TemplateName Name, SourceLocation Loc,
3265 const MultiLevelTemplateArgumentList &TemplateArgs) {
3266 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
3269 SS.Adopt(QualifierLoc);
3270 return Instantiator.TransformTemplateName(SS, Name, Loc);
3273 bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
3274 TemplateArgumentListInfo &Result,
3275 const MultiLevelTemplateArgumentList &TemplateArgs) {
3276 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
3279 return Instantiator.TransformTemplateArguments(Args, NumArgs, Result);
3282 static const Decl *getCanonicalParmVarDecl(const Decl *D) {
3283 // When storing ParmVarDecls in the local instantiation scope, we always
3284 // want to use the ParmVarDecl from the canonical function declaration,
3285 // since the map is then valid for any redeclaration or definition of that
3287 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
3288 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
3289 unsigned i = PV->getFunctionScopeIndex();
3290 // This parameter might be from a freestanding function type within the
3291 // function and isn't necessarily referring to one of FD's parameters.
3292 if (i < FD->getNumParams() && FD->getParamDecl(i) == PV)
3293 return FD->getCanonicalDecl()->getParamDecl(i);
3300 llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
3301 LocalInstantiationScope::findInstantiationOf(const Decl *D) {
3302 D = getCanonicalParmVarDecl(D);
3303 for (LocalInstantiationScope *Current = this; Current;
3304 Current = Current->Outer) {
3306 // Check if we found something within this scope.
3307 const Decl *CheckD = D;
3309 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
3310 if (Found != Current->LocalDecls.end())
3311 return &Found->second;
3313 // If this is a tag declaration, it's possible that we need to look for
3314 // a previous declaration.
3315 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
3316 CheckD = Tag->getPreviousDecl();
3321 // If we aren't combined with our outer scope, we're done.
3322 if (!Current->CombineWithOuterScope)
3326 // If we're performing a partial substitution during template argument
3327 // deduction, we may not have values for template parameters yet.
3328 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
3329 isa<TemplateTemplateParmDecl>(D))
3332 // Local types referenced prior to definition may require instantiation.
3333 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
3334 if (RD->isLocalClass())
3337 // Enumeration types referenced prior to definition may appear as a result of
3339 if (isa<EnumDecl>(D))
3342 // If we didn't find the decl, then we either have a sema bug, or we have a
3343 // forward reference to a label declaration. Return null to indicate that
3344 // we have an uninstantiated label.
3345 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
3349 void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
3350 D = getCanonicalParmVarDecl(D);
3351 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
3352 if (Stored.isNull()) {
3354 // It should not be present in any surrounding scope either.
3355 LocalInstantiationScope *Current = this;
3356 while (Current->CombineWithOuterScope && Current->Outer) {
3357 Current = Current->Outer;
3358 assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
3359 "Instantiated local in inner and outer scopes");
3363 } else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>()) {
3364 Pack->push_back(cast<VarDecl>(Inst));
3366 assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
3370 void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
3372 D = getCanonicalParmVarDecl(D);
3373 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
3374 Pack->push_back(Inst);
3377 void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
3379 // This should be the first time we've been told about this decl.
3380 for (LocalInstantiationScope *Current = this;
3381 Current && Current->CombineWithOuterScope; Current = Current->Outer)
3382 assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
3383 "Creating local pack after instantiation of local");
3386 D = getCanonicalParmVarDecl(D);
3387 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
3388 DeclArgumentPack *Pack = new DeclArgumentPack;
3390 ArgumentPacks.push_back(Pack);
3393 void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
3394 const TemplateArgument *ExplicitArgs,
3395 unsigned NumExplicitArgs) {
3396 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
3397 "Already have a partially-substituted pack");
3398 assert((!PartiallySubstitutedPack
3399 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
3400 "Wrong number of arguments in partially-substituted pack");
3401 PartiallySubstitutedPack = Pack;
3402 ArgsInPartiallySubstitutedPack = ExplicitArgs;
3403 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
3406 NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
3407 const TemplateArgument **ExplicitArgs,
3408 unsigned *NumExplicitArgs) const {
3410 *ExplicitArgs = nullptr;
3411 if (NumExplicitArgs)
3412 *NumExplicitArgs = 0;
3414 for (const LocalInstantiationScope *Current = this; Current;
3415 Current = Current->Outer) {
3416 if (Current->PartiallySubstitutedPack) {
3418 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
3419 if (NumExplicitArgs)
3420 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
3422 return Current->PartiallySubstitutedPack;
3425 if (!Current->CombineWithOuterScope)