1 //===------- SemaTemplateInstantiate.cpp - C++ Template Instantiation ------===/
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //===----------------------------------------------------------------------===/
9 // This file implements C++ template instantiation.
11 //===----------------------------------------------------------------------===/
13 #include "clang/Sema/SemaInternal.h"
14 #include "TreeTransform.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/DeclTemplate.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/Basic/LangOptions.h"
21 #include "clang/Sema/DeclSpec.h"
22 #include "clang/Sema/Initialization.h"
23 #include "clang/Sema/Lookup.h"
24 #include "clang/Sema/Template.h"
25 #include "clang/Sema/TemplateDeduction.h"
27 using namespace clang;
30 //===----------------------------------------------------------------------===/
31 // Template Instantiation Support
32 //===----------------------------------------------------------------------===/
34 /// \brief Retrieve the template argument list(s) that should be used to
35 /// instantiate the definition of the given declaration.
37 /// \param D the declaration for which we are computing template instantiation
40 /// \param Innermost if non-NULL, the innermost template argument list.
42 /// \param RelativeToPrimary true if we should get the template
43 /// arguments relative to the primary template, even when we're
44 /// dealing with a specialization. This is only relevant for function
45 /// template specializations.
47 /// \param Pattern If non-NULL, indicates the pattern from which we will be
48 /// instantiating the definition of the given declaration, \p D. This is
49 /// used to determine the proper set of template instantiation arguments for
50 /// friend function template specializations.
51 MultiLevelTemplateArgumentList
52 Sema::getTemplateInstantiationArgs(NamedDecl *D,
53 const TemplateArgumentList *Innermost,
54 bool RelativeToPrimary,
55 const FunctionDecl *Pattern) {
56 // Accumulate the set of template argument lists in this structure.
57 MultiLevelTemplateArgumentList Result;
60 Result.addOuterTemplateArguments(Innermost);
62 DeclContext *Ctx = dyn_cast<DeclContext>(D);
64 Ctx = D->getDeclContext();
66 // Add template arguments from a variable template instantiation.
67 if (VarTemplateSpecializationDecl *Spec =
68 dyn_cast<VarTemplateSpecializationDecl>(D)) {
69 // We're done when we hit an explicit specialization.
70 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
71 !isa<VarTemplatePartialSpecializationDecl>(Spec))
74 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
76 // If this variable template specialization was instantiated from a
77 // specialized member that is a variable template, we're done.
78 assert(Spec->getSpecializedTemplate() && "No variable template?");
79 llvm::PointerUnion<VarTemplateDecl*,
80 VarTemplatePartialSpecializationDecl*> Specialized
81 = Spec->getSpecializedTemplateOrPartial();
82 if (VarTemplatePartialSpecializationDecl *Partial =
83 Specialized.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
84 if (Partial->isMemberSpecialization())
87 VarTemplateDecl *Tmpl = Specialized.get<VarTemplateDecl *>();
88 if (Tmpl->isMemberSpecialization())
93 // If we have a template template parameter with translation unit context,
94 // then we're performing substitution into a default template argument of
95 // this template template parameter before we've constructed the template
96 // that will own this template template parameter. In this case, we
97 // use empty template parameter lists for all of the outer templates
98 // to avoid performing any substitutions.
99 if (Ctx->isTranslationUnit()) {
100 if (TemplateTemplateParmDecl *TTP
101 = dyn_cast<TemplateTemplateParmDecl>(D)) {
102 for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
103 Result.addOuterTemplateArguments(None);
109 while (!Ctx->isFileContext()) {
110 // Add template arguments from a class template instantiation.
111 if (ClassTemplateSpecializationDecl *Spec
112 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx)) {
113 // We're done when we hit an explicit specialization.
114 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
115 !isa<ClassTemplatePartialSpecializationDecl>(Spec))
118 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
120 // If this class template specialization was instantiated from a
121 // specialized member that is a class template, we're done.
122 assert(Spec->getSpecializedTemplate() && "No class template?");
123 if (Spec->getSpecializedTemplate()->isMemberSpecialization())
126 // Add template arguments from a function template specialization.
127 else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) {
128 if (!RelativeToPrimary &&
129 (Function->getTemplateSpecializationKind() ==
130 TSK_ExplicitSpecialization &&
131 !Function->getClassScopeSpecializationPattern()))
134 if (const TemplateArgumentList *TemplateArgs
135 = Function->getTemplateSpecializationArgs()) {
136 // Add the template arguments for this specialization.
137 Result.addOuterTemplateArguments(TemplateArgs);
139 // If this function was instantiated from a specialized member that is
140 // a function template, we're done.
141 assert(Function->getPrimaryTemplate() && "No function template?");
142 if (Function->getPrimaryTemplate()->isMemberSpecialization())
145 // If this function is a generic lambda specialization, we are done.
146 if (isGenericLambdaCallOperatorSpecialization(Function))
149 } else if (FunctionTemplateDecl *FunTmpl
150 = Function->getDescribedFunctionTemplate()) {
151 // Add the "injected" template arguments.
152 Result.addOuterTemplateArguments(FunTmpl->getInjectedTemplateArgs());
155 // If this is a friend declaration and it declares an entity at
156 // namespace scope, take arguments from its lexical parent
157 // instead of its semantic parent, unless of course the pattern we're
158 // instantiating actually comes from the file's context!
159 if (Function->getFriendObjectKind() &&
160 Function->getDeclContext()->isFileContext() &&
161 (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
162 Ctx = Function->getLexicalDeclContext();
163 RelativeToPrimary = false;
166 } else if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Ctx)) {
167 if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
168 QualType T = ClassTemplate->getInjectedClassNameSpecialization();
169 const TemplateSpecializationType *TST =
170 cast<TemplateSpecializationType>(Context.getCanonicalType(T));
171 Result.addOuterTemplateArguments(
172 llvm::makeArrayRef(TST->getArgs(), TST->getNumArgs()));
173 if (ClassTemplate->isMemberSpecialization())
178 Ctx = Ctx->getParent();
179 RelativeToPrimary = false;
185 bool Sema::ActiveTemplateInstantiation::isInstantiationRecord() const {
187 case TemplateInstantiation:
188 case ExceptionSpecInstantiation:
189 case DefaultTemplateArgumentInstantiation:
190 case DefaultFunctionArgumentInstantiation:
191 case ExplicitTemplateArgumentSubstitution:
192 case DeducedTemplateArgumentSubstitution:
193 case PriorTemplateArgumentSubstitution:
196 case DefaultTemplateArgumentChecking:
200 llvm_unreachable("Invalid InstantiationKind!");
203 Sema::InstantiatingTemplate::InstantiatingTemplate(
204 Sema &SemaRef, ActiveTemplateInstantiation::InstantiationKind Kind,
205 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
206 Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
207 sema::TemplateDeductionInfo *DeductionInfo)
208 : SemaRef(SemaRef), SavedInNonInstantiationSFINAEContext(
209 SemaRef.InNonInstantiationSFINAEContext) {
210 // Don't allow further instantiation if a fatal error has occcured. Any
211 // diagnostics we might have raised will not be visible.
212 if (SemaRef.Diags.hasFatalErrorOccurred()) {
216 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
218 ActiveTemplateInstantiation Inst;
220 Inst.PointOfInstantiation = PointOfInstantiation;
221 Inst.Entity = Entity;
222 Inst.Template = Template;
223 Inst.TemplateArgs = TemplateArgs.data();
224 Inst.NumTemplateArgs = TemplateArgs.size();
225 Inst.DeductionInfo = DeductionInfo;
226 Inst.InstantiationRange = InstantiationRange;
227 SemaRef.InNonInstantiationSFINAEContext = false;
228 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
229 if (!Inst.isInstantiationRecord())
230 ++SemaRef.NonInstantiationEntries;
234 Sema::InstantiatingTemplate::InstantiatingTemplate(
235 Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity,
236 SourceRange InstantiationRange)
237 : InstantiatingTemplate(SemaRef,
238 ActiveTemplateInstantiation::TemplateInstantiation,
239 PointOfInstantiation, InstantiationRange, Entity) {}
241 Sema::InstantiatingTemplate::InstantiatingTemplate(
242 Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity,
243 ExceptionSpecification, SourceRange InstantiationRange)
244 : InstantiatingTemplate(
245 SemaRef, ActiveTemplateInstantiation::ExceptionSpecInstantiation,
246 PointOfInstantiation, InstantiationRange, Entity) {}
248 Sema::InstantiatingTemplate::InstantiatingTemplate(
249 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template,
250 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
251 : InstantiatingTemplate(
253 ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation,
254 PointOfInstantiation, InstantiationRange, Template, nullptr,
257 Sema::InstantiatingTemplate::InstantiatingTemplate(
258 Sema &SemaRef, SourceLocation PointOfInstantiation,
259 FunctionTemplateDecl *FunctionTemplate,
260 ArrayRef<TemplateArgument> TemplateArgs,
261 ActiveTemplateInstantiation::InstantiationKind Kind,
262 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
263 : InstantiatingTemplate(SemaRef, Kind, PointOfInstantiation,
264 InstantiationRange, FunctionTemplate, nullptr,
265 TemplateArgs, &DeductionInfo) {}
267 Sema::InstantiatingTemplate::InstantiatingTemplate(
268 Sema &SemaRef, SourceLocation PointOfInstantiation,
269 ClassTemplatePartialSpecializationDecl *PartialSpec,
270 ArrayRef<TemplateArgument> TemplateArgs,
271 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
272 : InstantiatingTemplate(
274 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
275 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
276 TemplateArgs, &DeductionInfo) {}
278 Sema::InstantiatingTemplate::InstantiatingTemplate(
279 Sema &SemaRef, SourceLocation PointOfInstantiation,
280 VarTemplatePartialSpecializationDecl *PartialSpec,
281 ArrayRef<TemplateArgument> TemplateArgs,
282 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
283 : InstantiatingTemplate(
285 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
286 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
287 TemplateArgs, &DeductionInfo) {}
289 Sema::InstantiatingTemplate::InstantiatingTemplate(
290 Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param,
291 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
292 : InstantiatingTemplate(
294 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation,
295 PointOfInstantiation, InstantiationRange, Param, nullptr,
298 Sema::InstantiatingTemplate::InstantiatingTemplate(
299 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
300 NonTypeTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
301 SourceRange InstantiationRange)
302 : InstantiatingTemplate(
304 ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution,
305 PointOfInstantiation, InstantiationRange, Param, Template,
308 Sema::InstantiatingTemplate::InstantiatingTemplate(
309 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
310 TemplateTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
311 SourceRange InstantiationRange)
312 : InstantiatingTemplate(
314 ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution,
315 PointOfInstantiation, InstantiationRange, Param, Template,
318 Sema::InstantiatingTemplate::InstantiatingTemplate(
319 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template,
320 NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
321 SourceRange InstantiationRange)
322 : InstantiatingTemplate(
323 SemaRef, ActiveTemplateInstantiation::DefaultTemplateArgumentChecking,
324 PointOfInstantiation, InstantiationRange, Param, Template,
327 void Sema::InstantiatingTemplate::Clear() {
329 if (!SemaRef.ActiveTemplateInstantiations.back().isInstantiationRecord()) {
330 assert(SemaRef.NonInstantiationEntries > 0);
331 --SemaRef.NonInstantiationEntries;
333 SemaRef.InNonInstantiationSFINAEContext
334 = SavedInNonInstantiationSFINAEContext;
336 // Name lookup no longer looks in this template's defining module.
337 assert(SemaRef.ActiveTemplateInstantiations.size() >=
338 SemaRef.ActiveTemplateInstantiationLookupModules.size() &&
339 "forgot to remove a lookup module for a template instantiation");
340 if (SemaRef.ActiveTemplateInstantiations.size() ==
341 SemaRef.ActiveTemplateInstantiationLookupModules.size()) {
342 if (Module *M = SemaRef.ActiveTemplateInstantiationLookupModules.back())
343 SemaRef.LookupModulesCache.erase(M);
344 SemaRef.ActiveTemplateInstantiationLookupModules.pop_back();
347 SemaRef.ActiveTemplateInstantiations.pop_back();
352 bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
353 SourceLocation PointOfInstantiation,
354 SourceRange InstantiationRange) {
355 assert(SemaRef.NonInstantiationEntries <=
356 SemaRef.ActiveTemplateInstantiations.size());
357 if ((SemaRef.ActiveTemplateInstantiations.size() -
358 SemaRef.NonInstantiationEntries)
359 <= SemaRef.getLangOpts().InstantiationDepth)
362 SemaRef.Diag(PointOfInstantiation,
363 diag::err_template_recursion_depth_exceeded)
364 << SemaRef.getLangOpts().InstantiationDepth
365 << InstantiationRange;
366 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
367 << SemaRef.getLangOpts().InstantiationDepth;
371 /// \brief Prints the current instantiation stack through a series of
373 void Sema::PrintInstantiationStack() {
374 // Determine which template instantiations to skip, if any.
375 unsigned SkipStart = ActiveTemplateInstantiations.size(), SkipEnd = SkipStart;
376 unsigned Limit = Diags.getTemplateBacktraceLimit();
377 if (Limit && Limit < ActiveTemplateInstantiations.size()) {
378 SkipStart = Limit / 2 + Limit % 2;
379 SkipEnd = ActiveTemplateInstantiations.size() - Limit / 2;
382 // FIXME: In all of these cases, we need to show the template arguments
383 unsigned InstantiationIdx = 0;
384 for (SmallVectorImpl<ActiveTemplateInstantiation>::reverse_iterator
385 Active = ActiveTemplateInstantiations.rbegin(),
386 ActiveEnd = ActiveTemplateInstantiations.rend();
388 ++Active, ++InstantiationIdx) {
389 // Skip this instantiation?
390 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
391 if (InstantiationIdx == SkipStart) {
392 // Note that we're skipping instantiations.
393 Diags.Report(Active->PointOfInstantiation,
394 diag::note_instantiation_contexts_suppressed)
395 << unsigned(ActiveTemplateInstantiations.size() - Limit);
400 switch (Active->Kind) {
401 case ActiveTemplateInstantiation::TemplateInstantiation: {
402 Decl *D = Active->Entity;
403 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
404 unsigned DiagID = diag::note_template_member_class_here;
405 if (isa<ClassTemplateSpecializationDecl>(Record))
406 DiagID = diag::note_template_class_instantiation_here;
407 Diags.Report(Active->PointOfInstantiation, DiagID)
408 << Context.getTypeDeclType(Record)
409 << Active->InstantiationRange;
410 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
412 if (Function->getPrimaryTemplate())
413 DiagID = diag::note_function_template_spec_here;
415 DiagID = diag::note_template_member_function_here;
416 Diags.Report(Active->PointOfInstantiation, DiagID)
418 << Active->InstantiationRange;
419 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
420 Diags.Report(Active->PointOfInstantiation,
421 VD->isStaticDataMember()?
422 diag::note_template_static_data_member_def_here
423 : diag::note_template_variable_def_here)
425 << Active->InstantiationRange;
426 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
427 Diags.Report(Active->PointOfInstantiation,
428 diag::note_template_enum_def_here)
430 << Active->InstantiationRange;
431 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
432 Diags.Report(Active->PointOfInstantiation,
433 diag::note_template_nsdmi_here)
434 << FD << Active->InstantiationRange;
436 Diags.Report(Active->PointOfInstantiation,
437 diag::note_template_type_alias_instantiation_here)
438 << cast<TypeAliasTemplateDecl>(D)
439 << Active->InstantiationRange;
444 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation: {
445 TemplateDecl *Template = cast<TemplateDecl>(Active->Entity);
446 SmallVector<char, 128> TemplateArgsStr;
447 llvm::raw_svector_ostream OS(TemplateArgsStr);
448 Template->printName(OS);
449 TemplateSpecializationType::PrintTemplateArgumentList(OS,
450 Active->TemplateArgs,
451 Active->NumTemplateArgs,
452 getPrintingPolicy());
453 Diags.Report(Active->PointOfInstantiation,
454 diag::note_default_arg_instantiation_here)
456 << Active->InstantiationRange;
460 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution: {
461 FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
462 Diags.Report(Active->PointOfInstantiation,
463 diag::note_explicit_template_arg_substitution_here)
465 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
466 Active->TemplateArgs,
467 Active->NumTemplateArgs)
468 << Active->InstantiationRange;
472 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
473 if (ClassTemplatePartialSpecializationDecl *PartialSpec =
474 dyn_cast<ClassTemplatePartialSpecializationDecl>(Active->Entity)) {
475 Diags.Report(Active->PointOfInstantiation,
476 diag::note_partial_spec_deduct_instantiation_here)
477 << Context.getTypeDeclType(PartialSpec)
478 << getTemplateArgumentBindingsText(
479 PartialSpec->getTemplateParameters(),
480 Active->TemplateArgs,
481 Active->NumTemplateArgs)
482 << Active->InstantiationRange;
484 FunctionTemplateDecl *FnTmpl
485 = cast<FunctionTemplateDecl>(Active->Entity);
486 Diags.Report(Active->PointOfInstantiation,
487 diag::note_function_template_deduction_instantiation_here)
489 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
490 Active->TemplateArgs,
491 Active->NumTemplateArgs)
492 << Active->InstantiationRange;
496 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation: {
497 ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
498 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
500 SmallVector<char, 128> TemplateArgsStr;
501 llvm::raw_svector_ostream OS(TemplateArgsStr);
503 TemplateSpecializationType::PrintTemplateArgumentList(OS,
504 Active->TemplateArgs,
505 Active->NumTemplateArgs,
506 getPrintingPolicy());
507 Diags.Report(Active->PointOfInstantiation,
508 diag::note_default_function_arg_instantiation_here)
510 << Active->InstantiationRange;
514 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution: {
515 NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
517 if (!Parm->getName().empty())
518 Name = std::string(" '") + Parm->getName().str() + "'";
520 TemplateParameterList *TemplateParams = nullptr;
521 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
522 TemplateParams = Template->getTemplateParameters();
525 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
526 ->getTemplateParameters();
527 Diags.Report(Active->PointOfInstantiation,
528 diag::note_prior_template_arg_substitution)
529 << isa<TemplateTemplateParmDecl>(Parm)
531 << getTemplateArgumentBindingsText(TemplateParams,
532 Active->TemplateArgs,
533 Active->NumTemplateArgs)
534 << Active->InstantiationRange;
538 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking: {
539 TemplateParameterList *TemplateParams = nullptr;
540 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
541 TemplateParams = Template->getTemplateParameters();
544 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
545 ->getTemplateParameters();
547 Diags.Report(Active->PointOfInstantiation,
548 diag::note_template_default_arg_checking)
549 << getTemplateArgumentBindingsText(TemplateParams,
550 Active->TemplateArgs,
551 Active->NumTemplateArgs)
552 << Active->InstantiationRange;
556 case ActiveTemplateInstantiation::ExceptionSpecInstantiation:
557 Diags.Report(Active->PointOfInstantiation,
558 diag::note_template_exception_spec_instantiation_here)
559 << cast<FunctionDecl>(Active->Entity)
560 << Active->InstantiationRange;
566 Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
567 if (InNonInstantiationSFINAEContext)
568 return Optional<TemplateDeductionInfo *>(nullptr);
570 for (SmallVectorImpl<ActiveTemplateInstantiation>::const_reverse_iterator
571 Active = ActiveTemplateInstantiations.rbegin(),
572 ActiveEnd = ActiveTemplateInstantiations.rend();
576 switch(Active->Kind) {
577 case ActiveTemplateInstantiation::TemplateInstantiation:
578 // An instantiation of an alias template may or may not be a SFINAE
579 // context, depending on what else is on the stack.
580 if (isa<TypeAliasTemplateDecl>(Active->Entity))
583 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation:
584 case ActiveTemplateInstantiation::ExceptionSpecInstantiation:
585 // This is a template instantiation, so there is no SFINAE.
588 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation:
589 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution:
590 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking:
591 // A default template argument instantiation and substitution into
592 // template parameters with arguments for prior parameters may or may
593 // not be a SFINAE context; look further up the stack.
596 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution:
597 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
598 // We're either substitution explicitly-specified template arguments
599 // or deduced template arguments, so SFINAE applies.
600 assert(Active->DeductionInfo && "Missing deduction info pointer");
601 return Active->DeductionInfo;
608 /// \brief Retrieve the depth and index of a parameter pack.
609 static std::pair<unsigned, unsigned>
610 getDepthAndIndex(NamedDecl *ND) {
611 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
612 return std::make_pair(TTP->getDepth(), TTP->getIndex());
614 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
615 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
617 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
618 return std::make_pair(TTP->getDepth(), TTP->getIndex());
621 //===----------------------------------------------------------------------===/
622 // Template Instantiation for Types
623 //===----------------------------------------------------------------------===/
625 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
626 const MultiLevelTemplateArgumentList &TemplateArgs;
628 DeclarationName Entity;
631 typedef TreeTransform<TemplateInstantiator> inherited;
633 TemplateInstantiator(Sema &SemaRef,
634 const MultiLevelTemplateArgumentList &TemplateArgs,
636 DeclarationName Entity)
637 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
640 /// \brief Determine whether the given type \p T has already been
643 /// For the purposes of template instantiation, a type has already been
644 /// transformed if it is NULL or if it is not dependent.
645 bool AlreadyTransformed(QualType T);
647 /// \brief Returns the location of the entity being instantiated, if known.
648 SourceLocation getBaseLocation() { return Loc; }
650 /// \brief Returns the name of the entity being instantiated, if any.
651 DeclarationName getBaseEntity() { return Entity; }
653 /// \brief Sets the "base" location and entity when that
654 /// information is known based on another transformation.
655 void setBase(SourceLocation Loc, DeclarationName Entity) {
657 this->Entity = Entity;
660 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
661 SourceRange PatternRange,
662 ArrayRef<UnexpandedParameterPack> Unexpanded,
663 bool &ShouldExpand, bool &RetainExpansion,
664 Optional<unsigned> &NumExpansions) {
665 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
666 PatternRange, Unexpanded,
673 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
674 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
677 TemplateArgument ForgetPartiallySubstitutedPack() {
678 TemplateArgument Result;
679 if (NamedDecl *PartialPack
680 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
681 MultiLevelTemplateArgumentList &TemplateArgs
682 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
683 unsigned Depth, Index;
684 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
685 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
686 Result = TemplateArgs(Depth, Index);
687 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
694 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
698 if (NamedDecl *PartialPack
699 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
700 MultiLevelTemplateArgumentList &TemplateArgs
701 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
702 unsigned Depth, Index;
703 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
704 TemplateArgs.setArgument(Depth, Index, Arg);
708 /// \brief Transform the given declaration by instantiating a reference to
709 /// this declaration.
710 Decl *TransformDecl(SourceLocation Loc, Decl *D);
712 void transformAttrs(Decl *Old, Decl *New) {
713 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
716 void transformedLocalDecl(Decl *Old, Decl *New) {
717 // If we've instantiated the call operator of a lambda or the call
718 // operator template of a generic lambda, update the "instantiation of"
720 auto *NewMD = dyn_cast<CXXMethodDecl>(New);
721 if (NewMD && isLambdaCallOperator(NewMD)) {
722 auto *OldMD = dyn_cast<CXXMethodDecl>(Old);
723 if (auto *NewTD = NewMD->getDescribedFunctionTemplate())
724 NewTD->setInstantiatedFromMemberTemplate(
725 OldMD->getDescribedFunctionTemplate());
727 NewMD->setInstantiationOfMemberFunction(OldMD,
728 TSK_ImplicitInstantiation);
731 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);
734 /// \brief Transform the definition of the given declaration by
735 /// instantiating it.
736 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
738 /// \brief Transform the first qualifier within a scope by instantiating the
740 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
742 /// \brief Rebuild the exception declaration and register the declaration
743 /// as an instantiated local.
744 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
745 TypeSourceInfo *Declarator,
746 SourceLocation StartLoc,
747 SourceLocation NameLoc,
748 IdentifierInfo *Name);
750 /// \brief Rebuild the Objective-C exception declaration and register the
751 /// declaration as an instantiated local.
752 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
753 TypeSourceInfo *TSInfo, QualType T);
755 /// \brief Check for tag mismatches when instantiating an
757 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
758 ElaboratedTypeKeyword Keyword,
759 NestedNameSpecifierLoc QualifierLoc,
763 TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
764 SourceLocation NameLoc,
765 QualType ObjectType = QualType(),
766 NamedDecl *FirstQualifierInScope = nullptr);
768 const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
770 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
771 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
772 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
774 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
775 NonTypeTemplateParmDecl *D);
776 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
777 SubstNonTypeTemplateParmPackExpr *E);
779 /// \brief Rebuild a DeclRefExpr for a ParmVarDecl reference.
780 ExprResult RebuildParmVarDeclRefExpr(ParmVarDecl *PD, SourceLocation Loc);
782 /// \brief Transform a reference to a function parameter pack.
783 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E,
786 /// \brief Transform a FunctionParmPackExpr which was built when we couldn't
787 /// expand a function parameter pack reference which refers to an expanded
789 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
791 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
792 FunctionProtoTypeLoc TL) {
793 // Call the base version; it will forward to our overridden version below.
794 return inherited::TransformFunctionProtoType(TLB, TL);
797 template<typename Fn>
798 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
799 FunctionProtoTypeLoc TL,
800 CXXRecordDecl *ThisContext,
801 unsigned ThisTypeQuals,
802 Fn TransformExceptionSpec);
804 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
806 Optional<unsigned> NumExpansions,
807 bool ExpectParameterPack);
809 /// \brief Transforms a template type parameter type by performing
810 /// substitution of the corresponding template type argument.
811 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
812 TemplateTypeParmTypeLoc TL);
814 /// \brief Transforms an already-substituted template type parameter pack
815 /// into either itself (if we aren't substituting into its pack expansion)
816 /// or the appropriate substituted argument.
817 QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
818 SubstTemplateTypeParmPackTypeLoc TL);
820 ExprResult TransformCallExpr(CallExpr *CE) {
821 getSema().CallsUndergoingInstantiation.push_back(CE);
823 TreeTransform<TemplateInstantiator>::TransformCallExpr(CE);
824 getSema().CallsUndergoingInstantiation.pop_back();
828 ExprResult TransformLambdaExpr(LambdaExpr *E) {
829 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
830 return TreeTransform<TemplateInstantiator>::TransformLambdaExpr(E);
833 TemplateParameterList *TransformTemplateParameterList(
834 TemplateParameterList *OrigTPL) {
835 if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
837 DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
838 TemplateDeclInstantiator DeclInstantiator(getSema(),
839 /* DeclContext *Owner */ Owner, TemplateArgs);
840 return DeclInstantiator.SubstTemplateParams(OrigTPL);
843 ExprResult transformNonTypeTemplateParmRef(NonTypeTemplateParmDecl *parm,
845 TemplateArgument arg);
849 bool TemplateInstantiator::AlreadyTransformed(QualType T) {
853 if (T->isInstantiationDependentType() || T->isVariablyModifiedType())
856 getSema().MarkDeclarationsReferencedInType(Loc, T);
860 static TemplateArgument
861 getPackSubstitutedTemplateArgument(Sema &S, TemplateArgument Arg) {
862 assert(S.ArgumentPackSubstitutionIndex >= 0);
863 assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
864 Arg = Arg.pack_begin()[S.ArgumentPackSubstitutionIndex];
865 if (Arg.isPackExpansion())
866 Arg = Arg.getPackExpansionPattern();
870 Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
874 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
875 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
876 // If the corresponding template argument is NULL or non-existent, it's
877 // because we are performing instantiation from explicitly-specified
878 // template arguments in a function template, but there were some
879 // arguments left unspecified.
880 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
884 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
886 if (TTP->isParameterPack()) {
887 assert(Arg.getKind() == TemplateArgument::Pack &&
888 "Missing argument pack");
889 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
892 TemplateName Template = Arg.getAsTemplate();
893 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
894 "Wrong kind of template template argument");
895 return Template.getAsTemplateDecl();
898 // Fall through to find the instantiated declaration for this template
899 // template parameter.
902 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
905 Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
906 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
910 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
915 TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
916 SourceLocation Loc) {
917 // If the first part of the nested-name-specifier was a template type
918 // parameter, instantiate that type parameter down to a tag type.
919 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
920 const TemplateTypeParmType *TTP
921 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
923 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
924 // FIXME: This needs testing w/ member access expressions.
925 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
927 if (TTP->isParameterPack()) {
928 assert(Arg.getKind() == TemplateArgument::Pack &&
929 "Missing argument pack");
931 if (getSema().ArgumentPackSubstitutionIndex == -1)
934 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
937 QualType T = Arg.getAsType();
939 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
941 if (const TagType *Tag = T->getAs<TagType>())
942 return Tag->getDecl();
944 // The resulting type is not a tag; complain.
945 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
950 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
954 TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
955 TypeSourceInfo *Declarator,
956 SourceLocation StartLoc,
957 SourceLocation NameLoc,
958 IdentifierInfo *Name) {
959 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
960 StartLoc, NameLoc, Name);
962 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
966 VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
967 TypeSourceInfo *TSInfo,
969 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
971 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
976 TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
977 ElaboratedTypeKeyword Keyword,
978 NestedNameSpecifierLoc QualifierLoc,
980 if (const TagType *TT = T->getAs<TagType>()) {
981 TagDecl* TD = TT->getDecl();
983 SourceLocation TagLocation = KeywordLoc;
985 IdentifierInfo *Id = TD->getIdentifier();
987 // TODO: should we even warn on struct/class mismatches for this? Seems
988 // like it's likely to produce a lot of spurious errors.
989 if (Id && Keyword != ETK_None && Keyword != ETK_Typename) {
990 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
991 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
993 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
995 << FixItHint::CreateReplacement(SourceRange(TagLocation),
997 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
1002 return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(KeywordLoc,
1008 TemplateName TemplateInstantiator::TransformTemplateName(CXXScopeSpec &SS,
1010 SourceLocation NameLoc,
1011 QualType ObjectType,
1012 NamedDecl *FirstQualifierInScope) {
1013 if (TemplateTemplateParmDecl *TTP
1014 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
1015 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1016 // If the corresponding template argument is NULL or non-existent, it's
1017 // because we are performing instantiation from explicitly-specified
1018 // template arguments in a function template, but there were some
1019 // arguments left unspecified.
1020 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1021 TTP->getPosition()))
1024 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1026 if (TTP->isParameterPack()) {
1027 assert(Arg.getKind() == TemplateArgument::Pack &&
1028 "Missing argument pack");
1030 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1031 // We have the template argument pack to substitute, but we're not
1032 // actually expanding the enclosing pack expansion yet. So, just
1033 // keep the entire argument pack.
1034 return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg);
1037 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1040 TemplateName Template = Arg.getAsTemplate();
1041 assert(!Template.isNull() && "Null template template argument");
1043 // We don't ever want to substitute for a qualified template name, since
1044 // the qualifier is handled separately. So, look through the qualified
1045 // template name to its underlying declaration.
1046 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
1047 Template = TemplateName(QTN->getTemplateDecl());
1049 Template = getSema().Context.getSubstTemplateTemplateParm(TTP, Template);
1054 if (SubstTemplateTemplateParmPackStorage *SubstPack
1055 = Name.getAsSubstTemplateTemplateParmPack()) {
1056 if (getSema().ArgumentPackSubstitutionIndex == -1)
1059 TemplateArgument Arg = SubstPack->getArgumentPack();
1060 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1061 return Arg.getAsTemplate();
1064 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
1065 FirstQualifierInScope);
1069 TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
1070 if (!E->isTypeDependent())
1073 return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentType());
1077 TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
1078 NonTypeTemplateParmDecl *NTTP) {
1079 // If the corresponding template argument is NULL or non-existent, it's
1080 // because we are performing instantiation from explicitly-specified
1081 // template arguments in a function template, but there were some
1082 // arguments left unspecified.
1083 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
1084 NTTP->getPosition()))
1087 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
1088 if (NTTP->isParameterPack()) {
1089 assert(Arg.getKind() == TemplateArgument::Pack &&
1090 "Missing argument pack");
1092 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1093 // We have an argument pack, but we can't select a particular argument
1094 // out of it yet. Therefore, we'll build an expression to hold on to that
1096 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1098 NTTP->getDeclName());
1099 if (TargetType.isNull())
1102 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(TargetType,
1108 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1111 return transformNonTypeTemplateParmRef(NTTP, E->getLocation(), Arg);
1114 const LoopHintAttr *
1115 TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
1116 Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get();
1118 if (TransformedExpr == LH->getValue())
1121 // Generate error if there is a problem with the value.
1122 if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation()))
1125 // Create new LoopHintValueAttr with integral expression in place of the
1126 // non-type template parameter.
1127 return LoopHintAttr::CreateImplicit(
1128 getSema().Context, LH->getSemanticSpelling(), LH->getOption(),
1129 LH->getState(), TransformedExpr, LH->getRange());
1132 ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
1133 NonTypeTemplateParmDecl *parm,
1135 TemplateArgument arg) {
1139 // The template argument itself might be an expression, in which
1140 // case we just return that expression.
1141 if (arg.getKind() == TemplateArgument::Expression) {
1142 Expr *argExpr = arg.getAsExpr();
1144 type = argExpr->getType();
1146 } else if (arg.getKind() == TemplateArgument::Declaration ||
1147 arg.getKind() == TemplateArgument::NullPtr) {
1149 if (arg.getKind() == TemplateArgument::Declaration) {
1150 VD = cast<ValueDecl>(arg.getAsDecl());
1152 // Find the instantiation of the template argument. This is
1153 // required for nested templates.
1154 VD = cast_or_null<ValueDecl>(
1155 getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
1159 // Propagate NULL template argument.
1163 // Derive the type we want the substituted decl to have. This had
1164 // better be non-dependent, or these checks will have serious problems.
1165 if (parm->isExpandedParameterPack()) {
1166 type = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex);
1167 } else if (parm->isParameterPack() &&
1168 isa<PackExpansionType>(parm->getType())) {
1169 type = SemaRef.SubstType(
1170 cast<PackExpansionType>(parm->getType())->getPattern(),
1171 TemplateArgs, loc, parm->getDeclName());
1173 type = SemaRef.SubstType(parm->getType(), TemplateArgs,
1174 loc, parm->getDeclName());
1176 assert(!type.isNull() && "type substitution failed for param type");
1177 assert(!type->isDependentType() && "param type still dependent");
1178 result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, type, loc);
1180 if (!result.isInvalid()) type = result.get()->getType();
1182 result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc);
1184 // Note that this type can be different from the type of 'result',
1185 // e.g. if it's an enum type.
1186 type = arg.getIntegralType();
1188 if (result.isInvalid()) return ExprError();
1190 Expr *resultExpr = result.get();
1191 return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
1192 type, resultExpr->getValueKind(), loc, parm, resultExpr);
1196 TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
1197 SubstNonTypeTemplateParmPackExpr *E) {
1198 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1199 // We aren't expanding the parameter pack, so just return ourselves.
1203 TemplateArgument Arg = E->getArgumentPack();
1204 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1205 return transformNonTypeTemplateParmRef(E->getParameterPack(),
1206 E->getParameterPackLocation(),
1211 TemplateInstantiator::RebuildParmVarDeclRefExpr(ParmVarDecl *PD,
1212 SourceLocation Loc) {
1213 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
1214 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
1218 TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
1219 if (getSema().ArgumentPackSubstitutionIndex != -1) {
1220 // We can expand this parameter pack now.
1221 ParmVarDecl *D = E->getExpansion(getSema().ArgumentPackSubstitutionIndex);
1222 ValueDecl *VD = cast_or_null<ValueDecl>(TransformDecl(E->getExprLoc(), D));
1225 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(VD), E->getExprLoc());
1228 QualType T = TransformType(E->getType());
1232 // Transform each of the parameter expansions into the corresponding
1233 // parameters in the instantiation of the function decl.
1234 SmallVector<Decl *, 8> Parms;
1235 Parms.reserve(E->getNumExpansions());
1236 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
1239 cast_or_null<ParmVarDecl>(TransformDecl(E->getExprLoc(), *I));
1245 return FunctionParmPackExpr::Create(getSema().Context, T,
1246 E->getParameterPack(),
1247 E->getParameterPackLocation(), Parms);
1251 TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
1253 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
1254 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
1255 = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
1256 assert(Found && "no instantiation for parameter pack");
1258 Decl *TransformedDecl;
1259 if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
1260 // If this is a reference to a function parameter pack which we can
1261 // substitute but can't yet expand, build a FunctionParmPackExpr for it.
1262 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1263 QualType T = TransformType(E->getType());
1266 return FunctionParmPackExpr::Create(getSema().Context, T, PD,
1267 E->getExprLoc(), *Pack);
1270 TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
1272 TransformedDecl = Found->get<Decl*>();
1275 // We have either an unexpanded pack or a specific expansion.
1276 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(TransformedDecl),
1281 TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
1282 NamedDecl *D = E->getDecl();
1284 // Handle references to non-type template parameters and non-type template
1286 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
1287 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
1288 return TransformTemplateParmRefExpr(E, NTTP);
1290 // We have a non-type template parameter that isn't fully substituted;
1291 // FindInstantiatedDecl will find it in the local instantiation scope.
1294 // Handle references to function parameter packs.
1295 if (ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
1296 if (PD->isParameterPack())
1297 return TransformFunctionParmPackRefExpr(E, PD);
1299 return TreeTransform<TemplateInstantiator>::TransformDeclRefExpr(E);
1302 ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
1303 CXXDefaultArgExpr *E) {
1304 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
1305 getDescribedFunctionTemplate() &&
1306 "Default arg expressions are never formed in dependent cases.");
1307 return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
1308 cast<FunctionDecl>(E->getParam()->getDeclContext()),
1312 template<typename Fn>
1313 QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
1314 FunctionProtoTypeLoc TL,
1315 CXXRecordDecl *ThisContext,
1316 unsigned ThisTypeQuals,
1317 Fn TransformExceptionSpec) {
1318 // We need a local instantiation scope for this function prototype.
1319 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1320 return inherited::TransformFunctionProtoType(
1321 TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
1325 TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
1326 int indexAdjustment,
1327 Optional<unsigned> NumExpansions,
1328 bool ExpectParameterPack) {
1329 return SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment,
1330 NumExpansions, ExpectParameterPack);
1334 TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1335 TemplateTypeParmTypeLoc TL) {
1336 const TemplateTypeParmType *T = TL.getTypePtr();
1337 if (T->getDepth() < TemplateArgs.getNumLevels()) {
1338 // Replace the template type parameter with its corresponding
1339 // template argument.
1341 // If the corresponding template argument is NULL or doesn't exist, it's
1342 // because we are performing instantiation from explicitly-specified
1343 // template arguments in a function template class, but there were some
1344 // arguments left unspecified.
1345 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
1346 TemplateTypeParmTypeLoc NewTL
1347 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
1348 NewTL.setNameLoc(TL.getNameLoc());
1349 return TL.getType();
1352 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
1354 if (T->isParameterPack()) {
1355 assert(Arg.getKind() == TemplateArgument::Pack &&
1356 "Missing argument pack");
1358 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1359 // We have the template argument pack, but we're not expanding the
1360 // enclosing pack expansion yet. Just save the template argument
1361 // pack for later substitution.
1363 = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg);
1364 SubstTemplateTypeParmPackTypeLoc NewTL
1365 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
1366 NewTL.setNameLoc(TL.getNameLoc());
1370 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1373 assert(Arg.getKind() == TemplateArgument::Type &&
1374 "Template argument kind mismatch");
1376 QualType Replacement = Arg.getAsType();
1378 // TODO: only do this uniquing once, at the start of instantiation.
1380 = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
1381 SubstTemplateTypeParmTypeLoc NewTL
1382 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1383 NewTL.setNameLoc(TL.getNameLoc());
1387 // The template type parameter comes from an inner template (e.g.,
1388 // the template parameter list of a member template inside the
1389 // template we are instantiating). Create a new template type
1390 // parameter with the template "level" reduced by one.
1391 TemplateTypeParmDecl *NewTTPDecl = nullptr;
1392 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
1393 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
1394 TransformDecl(TL.getNameLoc(), OldTTPDecl));
1397 = getSema().Context.getTemplateTypeParmType(T->getDepth()
1398 - TemplateArgs.getNumLevels(),
1400 T->isParameterPack(),
1402 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
1403 NewTL.setNameLoc(TL.getNameLoc());
1408 TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
1409 TypeLocBuilder &TLB,
1410 SubstTemplateTypeParmPackTypeLoc TL) {
1411 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1412 // We aren't expanding the parameter pack, so just return ourselves.
1413 SubstTemplateTypeParmPackTypeLoc NewTL
1414 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(TL.getType());
1415 NewTL.setNameLoc(TL.getNameLoc());
1416 return TL.getType();
1419 TemplateArgument Arg = TL.getTypePtr()->getArgumentPack();
1420 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1421 QualType Result = Arg.getAsType();
1423 Result = getSema().Context.getSubstTemplateTypeParmType(
1424 TL.getTypePtr()->getReplacedParameter(),
1426 SubstTemplateTypeParmTypeLoc NewTL
1427 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1428 NewTL.setNameLoc(TL.getNameLoc());
1432 /// \brief Perform substitution on the type T with a given set of template
1435 /// This routine substitutes the given template arguments into the
1436 /// type T and produces the instantiated type.
1438 /// \param T the type into which the template arguments will be
1439 /// substituted. If this type is not dependent, it will be returned
1442 /// \param Args the template arguments that will be
1443 /// substituted for the top-level template parameters within T.
1445 /// \param Loc the location in the source code where this substitution
1446 /// is being performed. It will typically be the location of the
1447 /// declarator (if we're instantiating the type of some declaration)
1448 /// or the location of the type in the source code (if, e.g., we're
1449 /// instantiating the type of a cast expression).
1451 /// \param Entity the name of the entity associated with a declaration
1452 /// being instantiated (if any). May be empty to indicate that there
1453 /// is no such entity (if, e.g., this is a type that occurs as part of
1454 /// a cast expression) or that the entity has no name (e.g., an
1455 /// unnamed function parameter).
1457 /// \returns If the instantiation succeeds, the instantiated
1458 /// type. Otherwise, produces diagnostics and returns a NULL type.
1459 TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
1460 const MultiLevelTemplateArgumentList &Args,
1462 DeclarationName Entity) {
1463 assert(!ActiveTemplateInstantiations.empty() &&
1464 "Cannot perform an instantiation without some context on the "
1465 "instantiation stack");
1467 if (!T->getType()->isInstantiationDependentType() &&
1468 !T->getType()->isVariablyModifiedType())
1471 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1472 return Instantiator.TransformType(T);
1475 TypeSourceInfo *Sema::SubstType(TypeLoc TL,
1476 const MultiLevelTemplateArgumentList &Args,
1478 DeclarationName Entity) {
1479 assert(!ActiveTemplateInstantiations.empty() &&
1480 "Cannot perform an instantiation without some context on the "
1481 "instantiation stack");
1483 if (TL.getType().isNull())
1486 if (!TL.getType()->isInstantiationDependentType() &&
1487 !TL.getType()->isVariablyModifiedType()) {
1488 // FIXME: Make a copy of the TypeLoc data here, so that we can
1489 // return a new TypeSourceInfo. Inefficient!
1491 TLB.pushFullCopy(TL);
1492 return TLB.getTypeSourceInfo(Context, TL.getType());
1495 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1497 TLB.reserve(TL.getFullDataSize());
1498 QualType Result = Instantiator.TransformType(TLB, TL);
1499 if (Result.isNull())
1502 return TLB.getTypeSourceInfo(Context, Result);
1505 /// Deprecated form of the above.
1506 QualType Sema::SubstType(QualType T,
1507 const MultiLevelTemplateArgumentList &TemplateArgs,
1508 SourceLocation Loc, DeclarationName Entity) {
1509 assert(!ActiveTemplateInstantiations.empty() &&
1510 "Cannot perform an instantiation without some context on the "
1511 "instantiation stack");
1513 // If T is not a dependent type or a variably-modified type, there
1514 // is nothing to do.
1515 if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
1518 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
1519 return Instantiator.TransformType(T);
1522 static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
1523 if (T->getType()->isInstantiationDependentType() ||
1524 T->getType()->isVariablyModifiedType())
1527 TypeLoc TL = T->getTypeLoc().IgnoreParens();
1528 if (!TL.getAs<FunctionProtoTypeLoc>())
1531 FunctionProtoTypeLoc FP = TL.castAs<FunctionProtoTypeLoc>();
1532 for (unsigned I = 0, E = FP.getNumParams(); I != E; ++I) {
1533 ParmVarDecl *P = FP.getParam(I);
1535 // This must be synthesized from a typedef.
1538 // The parameter's type as written might be dependent even if the
1539 // decayed type was not dependent.
1540 if (TypeSourceInfo *TSInfo = P->getTypeSourceInfo())
1541 if (TSInfo->getType()->isInstantiationDependentType())
1544 // TODO: currently we always rebuild expressions. When we
1545 // properly get lazier about this, we should use the same
1546 // logic to avoid rebuilding prototypes here.
1547 if (P->hasDefaultArg())
1554 /// A form of SubstType intended specifically for instantiating the
1555 /// type of a FunctionDecl. Its purpose is solely to force the
1556 /// instantiation of default-argument expressions and to avoid
1557 /// instantiating an exception-specification.
1558 TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
1559 const MultiLevelTemplateArgumentList &Args,
1561 DeclarationName Entity,
1562 CXXRecordDecl *ThisContext,
1563 unsigned ThisTypeQuals) {
1564 assert(!ActiveTemplateInstantiations.empty() &&
1565 "Cannot perform an instantiation without some context on the "
1566 "instantiation stack");
1568 if (!NeedsInstantiationAsFunctionType(T))
1571 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1575 TypeLoc TL = T->getTypeLoc();
1576 TLB.reserve(TL.getFullDataSize());
1580 if (FunctionProtoTypeLoc Proto =
1581 TL.IgnoreParens().getAs<FunctionProtoTypeLoc>()) {
1582 // Instantiate the type, other than its exception specification. The
1583 // exception specification is instantiated in InitFunctionInstantiation
1584 // once we've built the FunctionDecl.
1585 // FIXME: Set the exception specification to EST_Uninstantiated here,
1586 // instead of rebuilding the function type again later.
1587 Result = Instantiator.TransformFunctionProtoType(
1588 TLB, Proto, ThisContext, ThisTypeQuals,
1589 [](FunctionProtoType::ExceptionSpecInfo &ESI,
1590 bool &Changed) { return false; });
1592 Result = Instantiator.TransformType(TLB, TL);
1594 if (Result.isNull())
1597 return TLB.getTypeSourceInfo(Context, Result);
1600 void Sema::SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
1601 const MultiLevelTemplateArgumentList &Args) {
1602 FunctionProtoType::ExceptionSpecInfo ESI =
1603 Proto->getExtProtoInfo().ExceptionSpec;
1604 assert(ESI.Type != EST_Uninstantiated);
1606 TemplateInstantiator Instantiator(*this, Args, New->getLocation(),
1607 New->getDeclName());
1609 SmallVector<QualType, 4> ExceptionStorage;
1610 bool Changed = false;
1611 if (Instantiator.TransformExceptionSpec(
1612 New->getTypeSourceInfo()->getTypeLoc().getLocEnd(), ESI,
1613 ExceptionStorage, Changed))
1614 // On error, recover by dropping the exception specification.
1615 ESI.Type = EST_None;
1617 UpdateExceptionSpec(New, ESI);
1620 ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm,
1621 const MultiLevelTemplateArgumentList &TemplateArgs,
1622 int indexAdjustment,
1623 Optional<unsigned> NumExpansions,
1624 bool ExpectParameterPack) {
1625 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
1626 TypeSourceInfo *NewDI = nullptr;
1628 TypeLoc OldTL = OldDI->getTypeLoc();
1629 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
1631 // We have a function parameter pack. Substitute into the pattern of the
1633 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
1634 OldParm->getLocation(), OldParm->getDeclName());
1638 if (NewDI->getType()->containsUnexpandedParameterPack()) {
1639 // We still have unexpanded parameter packs, which means that
1640 // our function parameter is still a function parameter pack.
1641 // Therefore, make its type a pack expansion type.
1642 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
1644 } else if (ExpectParameterPack) {
1645 // We expected to get a parameter pack but didn't (because the type
1646 // itself is not a pack expansion type), so complain. This can occur when
1647 // the substitution goes through an alias template that "loses" the
1649 Diag(OldParm->getLocation(),
1650 diag::err_function_parameter_pack_without_parameter_packs)
1651 << NewDI->getType();
1655 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
1656 OldParm->getDeclName());
1662 if (NewDI->getType()->isVoidType()) {
1663 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
1667 ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
1668 OldParm->getInnerLocStart(),
1669 OldParm->getLocation(),
1670 OldParm->getIdentifier(),
1671 NewDI->getType(), NewDI,
1672 OldParm->getStorageClass());
1676 // Mark the (new) default argument as uninstantiated (if any).
1677 if (OldParm->hasUninstantiatedDefaultArg()) {
1678 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
1679 NewParm->setUninstantiatedDefaultArg(Arg);
1680 } else if (OldParm->hasUnparsedDefaultArg()) {
1681 NewParm->setUnparsedDefaultArg();
1682 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
1683 } else if (Expr *Arg = OldParm->getDefaultArg())
1684 // FIXME: if we non-lazily instantiated non-dependent default args for
1685 // non-dependent parameter types we could remove a bunch of duplicate
1686 // conversion warnings for such arguments.
1687 NewParm->setUninstantiatedDefaultArg(Arg);
1689 NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
1691 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
1692 // Add the new parameter to the instantiated parameter pack.
1693 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
1695 // Introduce an Old -> New mapping
1696 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
1699 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
1700 // can be anything, is this right ?
1701 NewParm->setDeclContext(CurContext);
1703 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
1704 OldParm->getFunctionScopeIndex() + indexAdjustment);
1706 InstantiateAttrs(TemplateArgs, OldParm, NewParm);
1711 /// \brief Substitute the given template arguments into the given set of
1712 /// parameters, producing the set of parameter types that would be generated
1713 /// from such a substitution.
1714 bool Sema::SubstParmTypes(SourceLocation Loc,
1715 ParmVarDecl **Params, unsigned NumParams,
1716 const MultiLevelTemplateArgumentList &TemplateArgs,
1717 SmallVectorImpl<QualType> &ParamTypes,
1718 SmallVectorImpl<ParmVarDecl *> *OutParams) {
1719 assert(!ActiveTemplateInstantiations.empty() &&
1720 "Cannot perform an instantiation without some context on the "
1721 "instantiation stack");
1723 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
1725 return Instantiator.TransformFunctionTypeParams(Loc, Params, NumParams,
1726 nullptr, ParamTypes,
1730 /// \brief Perform substitution on the base class specifiers of the
1731 /// given class template specialization.
1733 /// Produces a diagnostic and returns true on error, returns false and
1734 /// attaches the instantiated base classes to the class template
1735 /// specialization if successful.
1737 Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
1738 CXXRecordDecl *Pattern,
1739 const MultiLevelTemplateArgumentList &TemplateArgs) {
1740 bool Invalid = false;
1741 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
1742 for (const auto &Base : Pattern->bases()) {
1743 if (!Base.getType()->isDependentType()) {
1744 if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
1745 if (RD->isInvalidDecl())
1746 Instantiation->setInvalidDecl();
1748 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
1752 SourceLocation EllipsisLoc;
1753 TypeSourceInfo *BaseTypeLoc;
1754 if (Base.isPackExpansion()) {
1755 // This is a pack expansion. See whether we should expand it now, or
1756 // wait until later.
1757 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1758 collectUnexpandedParameterPacks(Base.getTypeSourceInfo()->getTypeLoc(),
1760 bool ShouldExpand = false;
1761 bool RetainExpansion = false;
1762 Optional<unsigned> NumExpansions;
1763 if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(),
1764 Base.getSourceRange(),
1766 TemplateArgs, ShouldExpand,
1773 // If we should expand this pack expansion now, do so.
1775 for (unsigned I = 0; I != *NumExpansions; ++I) {
1776 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
1778 TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
1780 Base.getSourceRange().getBegin(),
1787 if (CXXBaseSpecifier *InstantiatedBase
1788 = CheckBaseSpecifier(Instantiation,
1789 Base.getSourceRange(),
1791 Base.getAccessSpecifierAsWritten(),
1794 InstantiatedBases.push_back(InstantiatedBase);
1802 // The resulting base specifier will (still) be a pack expansion.
1803 EllipsisLoc = Base.getEllipsisLoc();
1804 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
1805 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
1807 Base.getSourceRange().getBegin(),
1810 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
1812 Base.getSourceRange().getBegin(),
1821 if (CXXBaseSpecifier *InstantiatedBase
1822 = CheckBaseSpecifier(Instantiation,
1823 Base.getSourceRange(),
1825 Base.getAccessSpecifierAsWritten(),
1828 InstantiatedBases.push_back(InstantiatedBase);
1834 AttachBaseSpecifiers(Instantiation, InstantiatedBases.data(),
1835 InstantiatedBases.size()))
1841 // Defined via #include from SemaTemplateInstantiateDecl.cpp
1844 Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S,
1845 const MultiLevelTemplateArgumentList &TemplateArgs);
1849 /// Determine whether we would be unable to instantiate this template (because
1850 /// it either has no definition, or is in the process of being instantiated).
1851 static bool DiagnoseUninstantiableTemplate(Sema &S,
1852 SourceLocation PointOfInstantiation,
1853 TagDecl *Instantiation,
1854 bool InstantiatedFromMember,
1856 TagDecl *PatternDef,
1857 TemplateSpecializationKind TSK,
1858 bool Complain = true) {
1859 if (PatternDef && !PatternDef->isBeingDefined())
1862 if (!Complain || (PatternDef && PatternDef->isInvalidDecl())) {
1864 } else if (PatternDef) {
1865 assert(PatternDef->isBeingDefined());
1866 S.Diag(PointOfInstantiation,
1867 diag::err_template_instantiate_within_definition)
1868 << (TSK != TSK_ImplicitInstantiation)
1869 << S.Context.getTypeDeclType(Instantiation);
1870 // Not much point in noting the template declaration here, since
1871 // we're lexically inside it.
1872 Instantiation->setInvalidDecl();
1873 } else if (InstantiatedFromMember) {
1874 S.Diag(PointOfInstantiation,
1875 diag::err_implicit_instantiate_member_undefined)
1876 << S.Context.getTypeDeclType(Instantiation);
1877 S.Diag(Pattern->getLocation(), diag::note_member_declared_at);
1879 S.Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
1880 << (TSK != TSK_ImplicitInstantiation)
1881 << S.Context.getTypeDeclType(Instantiation);
1882 S.Diag(Pattern->getLocation(), diag::note_template_decl_here);
1885 // In general, Instantiation isn't marked invalid to get more than one
1886 // error for multiple undefined instantiations. But the code that does
1887 // explicit declaration -> explicit definition conversion can't handle
1888 // invalid declarations, so mark as invalid in that case.
1889 if (TSK == TSK_ExplicitInstantiationDeclaration)
1890 Instantiation->setInvalidDecl();
1894 /// \brief Instantiate the definition of a class from a given pattern.
1896 /// \param PointOfInstantiation The point of instantiation within the
1899 /// \param Instantiation is the declaration whose definition is being
1900 /// instantiated. This will be either a class template specialization
1901 /// or a member class of a class template specialization.
1903 /// \param Pattern is the pattern from which the instantiation
1904 /// occurs. This will be either the declaration of a class template or
1905 /// the declaration of a member class of a class template.
1907 /// \param TemplateArgs The template arguments to be substituted into
1910 /// \param TSK the kind of implicit or explicit instantiation to perform.
1912 /// \param Complain whether to complain if the class cannot be instantiated due
1913 /// to the lack of a definition.
1915 /// \returns true if an error occurred, false otherwise.
1917 Sema::InstantiateClass(SourceLocation PointOfInstantiation,
1918 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
1919 const MultiLevelTemplateArgumentList &TemplateArgs,
1920 TemplateSpecializationKind TSK,
1922 CXXRecordDecl *PatternDef
1923 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
1924 if (DiagnoseUninstantiableTemplate(*this, PointOfInstantiation, Instantiation,
1925 Instantiation->getInstantiatedFromMemberClass(),
1926 Pattern, PatternDef, TSK, Complain))
1928 Pattern = PatternDef;
1930 // \brief Record the point of instantiation.
1931 if (MemberSpecializationInfo *MSInfo
1932 = Instantiation->getMemberSpecializationInfo()) {
1933 MSInfo->setTemplateSpecializationKind(TSK);
1934 MSInfo->setPointOfInstantiation(PointOfInstantiation);
1935 } else if (ClassTemplateSpecializationDecl *Spec
1936 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
1937 Spec->setTemplateSpecializationKind(TSK);
1938 Spec->setPointOfInstantiation(PointOfInstantiation);
1941 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
1942 if (Inst.isInvalid())
1945 // Enter the scope of this instantiation. We don't use
1946 // PushDeclContext because we don't have a scope.
1947 ContextRAII SavedContext(*this, Instantiation);
1948 EnterExpressionEvaluationContext EvalContext(*this,
1949 Sema::PotentiallyEvaluated);
1951 // If this is an instantiation of a local class, merge this local
1952 // instantiation scope with the enclosing scope. Otherwise, every
1953 // instantiation of a class has its own local instantiation scope.
1954 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
1955 LocalInstantiationScope Scope(*this, MergeWithParentScope);
1957 // Pull attributes from the pattern onto the instantiation.
1958 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
1960 // Start the definition of this instantiation.
1961 Instantiation->startDefinition();
1963 // The instantiation is visible here, even if it was first declared in an
1964 // unimported module.
1965 Instantiation->setHidden(false);
1967 // FIXME: This loses the as-written tag kind for an explicit instantiation.
1968 Instantiation->setTagKind(Pattern->getTagKind());
1970 // Do substitution on the base class specifiers.
1971 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
1972 Instantiation->setInvalidDecl();
1974 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
1975 SmallVector<Decl*, 4> Fields;
1976 // Delay instantiation of late parsed attributes.
1977 LateInstantiatedAttrVec LateAttrs;
1978 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
1980 for (auto *Member : Pattern->decls()) {
1981 // Don't instantiate members not belonging in this semantic context.
1984 // template <int i> class A {
1988 // 'class B' has the template as lexical context but semantically it is
1989 // introduced in namespace scope.
1990 if (Member->getDeclContext() != Pattern)
1993 if (Member->isInvalidDecl()) {
1994 Instantiation->setInvalidDecl();
1998 Decl *NewMember = Instantiator.Visit(Member);
2000 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
2001 Fields.push_back(Field);
2002 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
2003 // C++11 [temp.inst]p1: The implicit instantiation of a class template
2004 // specialization causes the implicit instantiation of the definitions
2005 // of unscoped member enumerations.
2006 // Record a point of instantiation for this implicit instantiation.
2007 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
2008 Enum->isCompleteDefinition()) {
2009 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
2010 assert(MSInfo && "no spec info for member enum specialization");
2011 MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation);
2012 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2014 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
2015 if (SA->isFailed()) {
2016 // A static_assert failed. Bail out; instantiating this
2017 // class is probably not meaningful.
2018 Instantiation->setInvalidDecl();
2023 if (NewMember->isInvalidDecl())
2024 Instantiation->setInvalidDecl();
2026 // FIXME: Eventually, a NULL return will mean that one of the
2027 // instantiations was a semantic disaster, and we'll want to mark the
2028 // declaration invalid.
2029 // For now, we expect to skip some members that we can't yet handle.
2033 // Finish checking fields.
2034 ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
2035 SourceLocation(), SourceLocation(), nullptr);
2036 CheckCompletedCXXClass(Instantiation);
2038 // Default arguments are parsed, if not instantiated. We can go instantiate
2039 // default arg exprs for default constructors if necessary now.
2040 ActOnFinishCXXMemberDefaultArgs(Instantiation);
2042 // Instantiate late parsed attributes, and attach them to their decls.
2043 // See Sema::InstantiateAttrs
2044 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
2045 E = LateAttrs.end(); I != E; ++I) {
2046 assert(CurrentInstantiationScope == Instantiator.getStartingScope());
2047 CurrentInstantiationScope = I->Scope;
2049 // Allow 'this' within late-parsed attributes.
2050 NamedDecl *ND = dyn_cast<NamedDecl>(I->NewDecl);
2051 CXXRecordDecl *ThisContext =
2052 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
2053 CXXThisScopeRAII ThisScope(*this, ThisContext, /*TypeQuals*/0,
2054 ND && ND->isCXXInstanceMember());
2057 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
2058 I->NewDecl->addAttr(NewAttr);
2059 LocalInstantiationScope::deleteScopes(I->Scope,
2060 Instantiator.getStartingScope());
2062 Instantiator.disableLateAttributeInstantiation();
2065 ActOnFinishDelayedMemberInitializers(Instantiation);
2067 // FIXME: We should do something similar for explicit instantiations so they
2068 // end up in the right module.
2069 if (TSK == TSK_ImplicitInstantiation) {
2070 Instantiation->setLocation(Pattern->getLocation());
2071 Instantiation->setLocStart(Pattern->getInnerLocStart());
2072 Instantiation->setRBraceLoc(Pattern->getRBraceLoc());
2075 if (!Instantiation->isInvalidDecl()) {
2076 // Perform any dependent diagnostics from the pattern.
2077 PerformDependentDiagnostics(Pattern, TemplateArgs);
2079 // Instantiate any out-of-line class template partial
2080 // specializations now.
2081 for (TemplateDeclInstantiator::delayed_partial_spec_iterator
2082 P = Instantiator.delayed_partial_spec_begin(),
2083 PEnd = Instantiator.delayed_partial_spec_end();
2085 if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
2086 P->first, P->second)) {
2087 Instantiation->setInvalidDecl();
2092 // Instantiate any out-of-line variable template partial
2093 // specializations now.
2094 for (TemplateDeclInstantiator::delayed_var_partial_spec_iterator
2095 P = Instantiator.delayed_var_partial_spec_begin(),
2096 PEnd = Instantiator.delayed_var_partial_spec_end();
2098 if (!Instantiator.InstantiateVarTemplatePartialSpecialization(
2099 P->first, P->second)) {
2100 Instantiation->setInvalidDecl();
2106 // Exit the scope of this instantiation.
2109 if (!Instantiation->isInvalidDecl()) {
2110 Consumer.HandleTagDeclDefinition(Instantiation);
2112 // Always emit the vtable for an explicit instantiation definition
2113 // of a polymorphic class template specialization.
2114 if (TSK == TSK_ExplicitInstantiationDefinition)
2115 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
2118 return Instantiation->isInvalidDecl();
2121 /// \brief Instantiate the definition of an enum from a given pattern.
2123 /// \param PointOfInstantiation The point of instantiation within the
2125 /// \param Instantiation is the declaration whose definition is being
2126 /// instantiated. This will be a member enumeration of a class
2127 /// temploid specialization, or a local enumeration within a
2128 /// function temploid specialization.
2129 /// \param Pattern The templated declaration from which the instantiation
2131 /// \param TemplateArgs The template arguments to be substituted into
2133 /// \param TSK The kind of implicit or explicit instantiation to perform.
2135 /// \return \c true if an error occurred, \c false otherwise.
2136 bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
2137 EnumDecl *Instantiation, EnumDecl *Pattern,
2138 const MultiLevelTemplateArgumentList &TemplateArgs,
2139 TemplateSpecializationKind TSK) {
2140 EnumDecl *PatternDef = Pattern->getDefinition();
2141 if (DiagnoseUninstantiableTemplate(*this, PointOfInstantiation, Instantiation,
2142 Instantiation->getInstantiatedFromMemberEnum(),
2143 Pattern, PatternDef, TSK,/*Complain*/true))
2145 Pattern = PatternDef;
2147 // Record the point of instantiation.
2148 if (MemberSpecializationInfo *MSInfo
2149 = Instantiation->getMemberSpecializationInfo()) {
2150 MSInfo->setTemplateSpecializationKind(TSK);
2151 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2154 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2155 if (Inst.isInvalid())
2158 // The instantiation is visible here, even if it was first declared in an
2159 // unimported module.
2160 Instantiation->setHidden(false);
2162 // Enter the scope of this instantiation. We don't use
2163 // PushDeclContext because we don't have a scope.
2164 ContextRAII SavedContext(*this, Instantiation);
2165 EnterExpressionEvaluationContext EvalContext(*this,
2166 Sema::PotentiallyEvaluated);
2168 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
2170 // Pull attributes from the pattern onto the instantiation.
2171 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2173 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2174 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
2176 // Exit the scope of this instantiation.
2179 return Instantiation->isInvalidDecl();
2183 /// \brief Instantiate the definition of a field from the given pattern.
2185 /// \param PointOfInstantiation The point of instantiation within the
2187 /// \param Instantiation is the declaration whose definition is being
2188 /// instantiated. This will be a class of a class temploid
2189 /// specialization, or a local enumeration within a function temploid
2191 /// \param Pattern The templated declaration from which the instantiation
2193 /// \param TemplateArgs The template arguments to be substituted into
2196 /// \return \c true if an error occurred, \c false otherwise.
2197 bool Sema::InstantiateInClassInitializer(
2198 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
2199 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
2200 // If there is no initializer, we don't need to do anything.
2201 if (!Pattern->hasInClassInitializer())
2204 assert(Instantiation->getInClassInitStyle() ==
2205 Pattern->getInClassInitStyle() &&
2206 "pattern and instantiation disagree about init style");
2208 // Error out if we haven't parsed the initializer of the pattern yet because
2209 // we are waiting for the closing brace of the outer class.
2210 Expr *OldInit = Pattern->getInClassInitializer();
2212 RecordDecl *PatternRD = Pattern->getParent();
2213 RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext();
2214 if (OutermostClass == PatternRD) {
2215 Diag(Pattern->getLocEnd(), diag::err_in_class_initializer_not_yet_parsed)
2216 << PatternRD << Pattern;
2218 Diag(Pattern->getLocEnd(),
2219 diag::err_in_class_initializer_not_yet_parsed_outer_class)
2220 << PatternRD << OutermostClass << Pattern;
2222 Instantiation->setInvalidDecl();
2226 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2227 if (Inst.isInvalid())
2230 // Enter the scope of this instantiation. We don't use PushDeclContext because
2231 // we don't have a scope.
2232 ContextRAII SavedContext(*this, Instantiation->getParent());
2233 EnterExpressionEvaluationContext EvalContext(*this,
2234 Sema::PotentiallyEvaluated);
2236 LocalInstantiationScope Scope(*this, true);
2238 // Instantiate the initializer.
2239 ActOnStartCXXInClassMemberInitializer();
2240 CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), /*TypeQuals=*/0);
2242 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
2243 /*CXXDirectInit=*/false);
2244 Expr *Init = NewInit.get();
2245 assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class");
2246 ActOnFinishCXXInClassMemberInitializer(
2247 Instantiation, Init ? Init->getLocStart() : SourceLocation(), Init);
2249 // Exit the scope of this instantiation.
2252 // Return true if the in-class initializer is still missing.
2253 return !Instantiation->getInClassInitializer();
2257 /// \brief A partial specialization whose template arguments have matched
2258 /// a given template-id.
2259 struct PartialSpecMatchResult {
2260 ClassTemplatePartialSpecializationDecl *Partial;
2261 TemplateArgumentList *Args;
2265 bool Sema::InstantiateClassTemplateSpecialization(
2266 SourceLocation PointOfInstantiation,
2267 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2268 TemplateSpecializationKind TSK, bool Complain) {
2269 // Perform the actual instantiation on the canonical declaration.
2270 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
2271 ClassTemplateSpec->getCanonicalDecl());
2273 // Check whether we have already instantiated or specialized this class
2274 // template specialization.
2275 if (ClassTemplateSpec->getSpecializationKind() != TSK_Undeclared) {
2276 if (ClassTemplateSpec->getSpecializationKind() ==
2277 TSK_ExplicitInstantiationDeclaration &&
2278 TSK == TSK_ExplicitInstantiationDefinition) {
2279 // An explicit instantiation definition follows an explicit instantiation
2280 // declaration (C++0x [temp.explicit]p10); go ahead and perform the
2281 // explicit instantiation.
2282 ClassTemplateSpec->setSpecializationKind(TSK);
2284 // If this is an explicit instantiation definition, mark the
2286 if (TSK == TSK_ExplicitInstantiationDefinition &&
2287 !ClassTemplateSpec->isInvalidDecl())
2288 MarkVTableUsed(PointOfInstantiation, ClassTemplateSpec, true);
2293 // We can only instantiate something that hasn't already been
2294 // instantiated or specialized. Fail without any diagnostics: our
2295 // caller will provide an error message.
2299 if (ClassTemplateSpec->isInvalidDecl())
2302 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
2303 CXXRecordDecl *Pattern = nullptr;
2305 // C++ [temp.class.spec.match]p1:
2306 // When a class template is used in a context that requires an
2307 // instantiation of the class, it is necessary to determine
2308 // whether the instantiation is to be generated using the primary
2309 // template or one of the partial specializations. This is done by
2310 // matching the template arguments of the class template
2311 // specialization with the template argument lists of the partial
2313 typedef PartialSpecMatchResult MatchResult;
2314 SmallVector<MatchResult, 4> Matched;
2315 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2316 Template->getPartialSpecializations(PartialSpecs);
2317 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
2318 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2319 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
2320 TemplateDeductionInfo Info(FailedCandidates.getLocation());
2321 if (TemplateDeductionResult Result
2322 = DeduceTemplateArguments(Partial,
2323 ClassTemplateSpec->getTemplateArgs(),
2325 // Store the failed-deduction information for use in diagnostics, later.
2326 // TODO: Actually use the failed-deduction info?
2327 FailedCandidates.addCandidate()
2328 .set(Partial, MakeDeductionFailureInfo(Context, Result, Info));
2331 Matched.push_back(PartialSpecMatchResult());
2332 Matched.back().Partial = Partial;
2333 Matched.back().Args = Info.take();
2337 // If we're dealing with a member template where the template parameters
2338 // have been instantiated, this provides the original template parameters
2339 // from which the member template's parameters were instantiated.
2341 if (Matched.size() >= 1) {
2342 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
2343 if (Matched.size() == 1) {
2344 // -- If exactly one matching specialization is found, the
2345 // instantiation is generated from that specialization.
2346 // We don't need to do anything for this.
2348 // -- If more than one matching specialization is found, the
2349 // partial order rules (14.5.4.2) are used to determine
2350 // whether one of the specializations is more specialized
2351 // than the others. If none of the specializations is more
2352 // specialized than all of the other matching
2353 // specializations, then the use of the class template is
2354 // ambiguous and the program is ill-formed.
2355 for (SmallVectorImpl<MatchResult>::iterator P = Best + 1,
2356 PEnd = Matched.end();
2358 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
2359 PointOfInstantiation)
2364 // Determine if the best partial specialization is more specialized than
2366 bool Ambiguous = false;
2367 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2368 PEnd = Matched.end();
2371 getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
2372 PointOfInstantiation)
2380 // Partial ordering did not produce a clear winner. Complain.
2381 ClassTemplateSpec->setInvalidDecl();
2382 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2383 << ClassTemplateSpec;
2385 // Print the matching partial specializations.
2386 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2387 PEnd = Matched.end();
2389 Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2390 << getTemplateArgumentBindingsText(
2391 P->Partial->getTemplateParameters(),
2398 // Instantiate using the best class template partial specialization.
2399 ClassTemplatePartialSpecializationDecl *OrigPartialSpec = Best->Partial;
2400 while (OrigPartialSpec->getInstantiatedFromMember()) {
2401 // If we've found an explicit specialization of this class template,
2402 // stop here and use that as the pattern.
2403 if (OrigPartialSpec->isMemberSpecialization())
2406 OrigPartialSpec = OrigPartialSpec->getInstantiatedFromMember();
2409 Pattern = OrigPartialSpec;
2410 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
2412 // -- If no matches are found, the instantiation is generated
2413 // from the primary template.
2414 ClassTemplateDecl *OrigTemplate = Template;
2415 while (OrigTemplate->getInstantiatedFromMemberTemplate()) {
2416 // If we've found an explicit specialization of this class template,
2417 // stop here and use that as the pattern.
2418 if (OrigTemplate->isMemberSpecialization())
2421 OrigTemplate = OrigTemplate->getInstantiatedFromMemberTemplate();
2424 Pattern = OrigTemplate->getTemplatedDecl();
2427 bool Result = InstantiateClass(PointOfInstantiation, ClassTemplateSpec,
2429 getTemplateInstantiationArgs(ClassTemplateSpec),
2436 /// \brief Instantiates the definitions of all of the member
2437 /// of the given class, which is an instantiation of a class template
2438 /// or a member class of a template.
2440 Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
2441 CXXRecordDecl *Instantiation,
2442 const MultiLevelTemplateArgumentList &TemplateArgs,
2443 TemplateSpecializationKind TSK) {
2444 // FIXME: We need to notify the ASTMutationListener that we did all of these
2445 // things, in case we have an explicit instantiation definition in a PCM, a
2446 // module, or preamble, and the declaration is in an imported AST.
2448 (TSK == TSK_ExplicitInstantiationDefinition ||
2449 TSK == TSK_ExplicitInstantiationDeclaration ||
2450 (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&
2451 "Unexpected template specialization kind!");
2452 for (auto *D : Instantiation->decls()) {
2453 bool SuppressNew = false;
2454 if (auto *Function = dyn_cast<FunctionDecl>(D)) {
2455 if (FunctionDecl *Pattern
2456 = Function->getInstantiatedFromMemberFunction()) {
2457 MemberSpecializationInfo *MSInfo
2458 = Function->getMemberSpecializationInfo();
2459 assert(MSInfo && "No member specialization information?");
2460 if (MSInfo->getTemplateSpecializationKind()
2461 == TSK_ExplicitSpecialization)
2464 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2466 MSInfo->getTemplateSpecializationKind(),
2467 MSInfo->getPointOfInstantiation(),
2472 // C++11 [temp.explicit]p8:
2473 // An explicit instantiation definition that names a class template
2474 // specialization explicitly instantiates the class template
2475 // specialization and is only an explicit instantiation definition
2476 // of members whose definition is visible at the point of
2478 if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())
2481 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2483 if (Function->isDefined()) {
2484 // Let the ASTConsumer know that this function has been explicitly
2485 // instantiated now, and its linkage might have changed.
2486 Consumer.HandleTopLevelDecl(DeclGroupRef(Function));
2487 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
2488 InstantiateFunctionDefinition(PointOfInstantiation, Function);
2489 } else if (TSK == TSK_ImplicitInstantiation) {
2490 PendingLocalImplicitInstantiations.push_back(
2491 std::make_pair(Function, PointOfInstantiation));
2494 } else if (auto *Var = dyn_cast<VarDecl>(D)) {
2495 if (isa<VarTemplateSpecializationDecl>(Var))
2498 if (Var->isStaticDataMember()) {
2499 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
2500 assert(MSInfo && "No member specialization information?");
2501 if (MSInfo->getTemplateSpecializationKind()
2502 == TSK_ExplicitSpecialization)
2505 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2507 MSInfo->getTemplateSpecializationKind(),
2508 MSInfo->getPointOfInstantiation(),
2513 if (TSK == TSK_ExplicitInstantiationDefinition) {
2514 // C++0x [temp.explicit]p8:
2515 // An explicit instantiation definition that names a class template
2516 // specialization explicitly instantiates the class template
2517 // specialization and is only an explicit instantiation definition
2518 // of members whose definition is visible at the point of
2520 if (!Var->getInstantiatedFromStaticDataMember()
2521 ->getOutOfLineDefinition())
2524 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2525 InstantiateStaticDataMemberDefinition(PointOfInstantiation, Var);
2527 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2530 } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
2531 // Always skip the injected-class-name, along with any
2532 // redeclarations of nested classes, since both would cause us
2533 // to try to instantiate the members of a class twice.
2534 // Skip closure types; they'll get instantiated when we instantiate
2535 // the corresponding lambda-expression.
2536 if (Record->isInjectedClassName() || Record->getPreviousDecl() ||
2540 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
2541 assert(MSInfo && "No member specialization information?");
2543 if (MSInfo->getTemplateSpecializationKind()
2544 == TSK_ExplicitSpecialization)
2547 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2549 MSInfo->getTemplateSpecializationKind(),
2550 MSInfo->getPointOfInstantiation(),
2555 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2556 assert(Pattern && "Missing instantiated-from-template information");
2558 if (!Record->getDefinition()) {
2559 if (!Pattern->getDefinition()) {
2560 // C++0x [temp.explicit]p8:
2561 // An explicit instantiation definition that names a class template
2562 // specialization explicitly instantiates the class template
2563 // specialization and is only an explicit instantiation definition
2564 // of members whose definition is visible at the point of
2566 if (TSK == TSK_ExplicitInstantiationDeclaration) {
2567 MSInfo->setTemplateSpecializationKind(TSK);
2568 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2574 InstantiateClass(PointOfInstantiation, Record, Pattern,
2578 if (TSK == TSK_ExplicitInstantiationDefinition &&
2579 Record->getTemplateSpecializationKind() ==
2580 TSK_ExplicitInstantiationDeclaration) {
2581 Record->setTemplateSpecializationKind(TSK);
2582 MarkVTableUsed(PointOfInstantiation, Record, true);
2586 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
2588 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
2590 } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
2591 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
2592 assert(MSInfo && "No member specialization information?");
2594 if (MSInfo->getTemplateSpecializationKind()
2595 == TSK_ExplicitSpecialization)
2598 if (CheckSpecializationInstantiationRedecl(
2599 PointOfInstantiation, TSK, Enum,
2600 MSInfo->getTemplateSpecializationKind(),
2601 MSInfo->getPointOfInstantiation(), SuppressNew) ||
2605 if (Enum->getDefinition())
2608 EnumDecl *Pattern = Enum->getInstantiatedFromMemberEnum();
2609 assert(Pattern && "Missing instantiated-from-template information");
2611 if (TSK == TSK_ExplicitInstantiationDefinition) {
2612 if (!Pattern->getDefinition())
2615 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
2617 MSInfo->setTemplateSpecializationKind(TSK);
2618 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2620 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
2621 // No need to instantiate in-class initializers during explicit
2623 if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) {
2624 CXXRecordDecl *ClassPattern =
2625 Instantiation->getTemplateInstantiationPattern();
2626 DeclContext::lookup_result Lookup =
2627 ClassPattern->lookup(Field->getDeclName());
2628 assert(Lookup.size() == 1);
2629 FieldDecl *Pattern = cast<FieldDecl>(Lookup[0]);
2630 InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern,
2637 /// \brief Instantiate the definitions of all of the members of the
2638 /// given class template specialization, which was named as part of an
2639 /// explicit instantiation.
2641 Sema::InstantiateClassTemplateSpecializationMembers(
2642 SourceLocation PointOfInstantiation,
2643 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2644 TemplateSpecializationKind TSK) {
2645 // C++0x [temp.explicit]p7:
2646 // An explicit instantiation that names a class template
2647 // specialization is an explicit instantion of the same kind
2648 // (declaration or definition) of each of its members (not
2649 // including members inherited from base classes) that has not
2650 // been previously explicitly specialized in the translation unit
2651 // containing the explicit instantiation, except as described
2653 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
2654 getTemplateInstantiationArgs(ClassTemplateSpec),
2659 Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
2663 TemplateInstantiator Instantiator(*this, TemplateArgs,
2666 return Instantiator.TransformStmt(S);
2670 Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
2674 TemplateInstantiator Instantiator(*this, TemplateArgs,
2677 return Instantiator.TransformExpr(E);
2680 ExprResult Sema::SubstInitializer(Expr *Init,
2681 const MultiLevelTemplateArgumentList &TemplateArgs,
2682 bool CXXDirectInit) {
2683 TemplateInstantiator Instantiator(*this, TemplateArgs,
2686 return Instantiator.TransformInitializer(Init, CXXDirectInit);
2689 bool Sema::SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall,
2690 const MultiLevelTemplateArgumentList &TemplateArgs,
2691 SmallVectorImpl<Expr *> &Outputs) {
2695 TemplateInstantiator Instantiator(*this, TemplateArgs,
2698 return Instantiator.TransformExprs(Exprs, NumExprs, IsCall, Outputs);
2701 NestedNameSpecifierLoc
2702 Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
2703 const MultiLevelTemplateArgumentList &TemplateArgs) {
2705 return NestedNameSpecifierLoc();
2707 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
2709 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
2712 /// \brief Do template substitution on declaration name info.
2714 Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
2715 const MultiLevelTemplateArgumentList &TemplateArgs) {
2716 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
2717 NameInfo.getName());
2718 return Instantiator.TransformDeclarationNameInfo(NameInfo);
2722 Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,
2723 TemplateName Name, SourceLocation Loc,
2724 const MultiLevelTemplateArgumentList &TemplateArgs) {
2725 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
2728 SS.Adopt(QualifierLoc);
2729 return Instantiator.TransformTemplateName(SS, Name, Loc);
2732 bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
2733 TemplateArgumentListInfo &Result,
2734 const MultiLevelTemplateArgumentList &TemplateArgs) {
2735 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
2738 return Instantiator.TransformTemplateArguments(Args, NumArgs, Result);
2741 static const Decl *getCanonicalParmVarDecl(const Decl *D) {
2742 // When storing ParmVarDecls in the local instantiation scope, we always
2743 // want to use the ParmVarDecl from the canonical function declaration,
2744 // since the map is then valid for any redeclaration or definition of that
2746 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
2747 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
2748 unsigned i = PV->getFunctionScopeIndex();
2749 // This parameter might be from a freestanding function type within the
2750 // function and isn't necessarily referring to one of FD's parameters.
2751 if (FD->getParamDecl(i) == PV)
2752 return FD->getCanonicalDecl()->getParamDecl(i);
2759 llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
2760 LocalInstantiationScope::findInstantiationOf(const Decl *D) {
2761 D = getCanonicalParmVarDecl(D);
2762 for (LocalInstantiationScope *Current = this; Current;
2763 Current = Current->Outer) {
2765 // Check if we found something within this scope.
2766 const Decl *CheckD = D;
2768 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
2769 if (Found != Current->LocalDecls.end())
2770 return &Found->second;
2772 // If this is a tag declaration, it's possible that we need to look for
2773 // a previous declaration.
2774 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
2775 CheckD = Tag->getPreviousDecl();
2780 // If we aren't combined with our outer scope, we're done.
2781 if (!Current->CombineWithOuterScope)
2785 // If we're performing a partial substitution during template argument
2786 // deduction, we may not have values for template parameters yet.
2787 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
2788 isa<TemplateTemplateParmDecl>(D))
2791 // Local types referenced prior to definition may require instantiation.
2792 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
2793 if (RD->isLocalClass())
2796 // Enumeration types referenced prior to definition may appear as a result of
2798 if (isa<EnumDecl>(D))
2801 // If we didn't find the decl, then we either have a sema bug, or we have a
2802 // forward reference to a label declaration. Return null to indicate that
2803 // we have an uninstantiated label.
2804 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
2808 void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
2809 D = getCanonicalParmVarDecl(D);
2810 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
2811 if (Stored.isNull()) {
2813 // It should not be present in any surrounding scope either.
2814 LocalInstantiationScope *Current = this;
2815 while (Current->CombineWithOuterScope && Current->Outer) {
2816 Current = Current->Outer;
2817 assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
2818 "Instantiated local in inner and outer scopes");
2822 } else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>()) {
2823 Pack->push_back(Inst);
2825 assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
2829 void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
2831 D = getCanonicalParmVarDecl(D);
2832 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
2833 Pack->push_back(Inst);
2836 void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
2838 // This should be the first time we've been told about this decl.
2839 for (LocalInstantiationScope *Current = this;
2840 Current && Current->CombineWithOuterScope; Current = Current->Outer)
2841 assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
2842 "Creating local pack after instantiation of local");
2845 D = getCanonicalParmVarDecl(D);
2846 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
2847 DeclArgumentPack *Pack = new DeclArgumentPack;
2849 ArgumentPacks.push_back(Pack);
2852 void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
2853 const TemplateArgument *ExplicitArgs,
2854 unsigned NumExplicitArgs) {
2855 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
2856 "Already have a partially-substituted pack");
2857 assert((!PartiallySubstitutedPack
2858 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
2859 "Wrong number of arguments in partially-substituted pack");
2860 PartiallySubstitutedPack = Pack;
2861 ArgsInPartiallySubstitutedPack = ExplicitArgs;
2862 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
2865 NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
2866 const TemplateArgument **ExplicitArgs,
2867 unsigned *NumExplicitArgs) const {
2869 *ExplicitArgs = nullptr;
2870 if (NumExplicitArgs)
2871 *NumExplicitArgs = 0;
2873 for (const LocalInstantiationScope *Current = this; Current;
2874 Current = Current->Outer) {
2875 if (Current->PartiallySubstitutedPack) {
2877 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
2878 if (NumExplicitArgs)
2879 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
2881 return Current->PartiallySubstitutedPack;
2884 if (!Current->CombineWithOuterScope)