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/Sema/DeclSpec.h"
16 #include "clang/Sema/Initialization.h"
17 #include "clang/Sema/Lookup.h"
18 #include "clang/Sema/Template.h"
19 #include "clang/Sema/TemplateDeduction.h"
20 #include "clang/AST/ASTConsumer.h"
21 #include "clang/AST/ASTContext.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/DeclTemplate.h"
24 #include "clang/Basic/LangOptions.h"
26 using namespace clang;
29 //===----------------------------------------------------------------------===/
30 // Template Instantiation Support
31 //===----------------------------------------------------------------------===/
33 /// \brief Retrieve the template argument list(s) that should be used to
34 /// instantiate the definition of the given declaration.
36 /// \param D the declaration for which we are computing template instantiation
39 /// \param Innermost if non-NULL, the innermost template argument list.
41 /// \param RelativeToPrimary true if we should get the template
42 /// arguments relative to the primary template, even when we're
43 /// dealing with a specialization. This is only relevant for function
44 /// template specializations.
46 /// \param Pattern If non-NULL, indicates the pattern from which we will be
47 /// instantiating the definition of the given declaration, \p D. This is
48 /// used to determine the proper set of template instantiation arguments for
49 /// friend function template specializations.
50 MultiLevelTemplateArgumentList
51 Sema::getTemplateInstantiationArgs(NamedDecl *D,
52 const TemplateArgumentList *Innermost,
53 bool RelativeToPrimary,
54 const FunctionDecl *Pattern) {
55 // Accumulate the set of template argument lists in this structure.
56 MultiLevelTemplateArgumentList Result;
59 Result.addOuterTemplateArguments(Innermost);
61 DeclContext *Ctx = dyn_cast<DeclContext>(D);
63 Ctx = D->getDeclContext();
65 assert((!D->isTemplateParameter() || !Ctx->isTranslationUnit()) &&
66 "Template parameter doesn't have its context yet!");
69 while (!Ctx->isFileContext()) {
70 // Add template arguments from a class template instantiation.
71 if (ClassTemplateSpecializationDecl *Spec
72 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx)) {
73 // We're done when we hit an explicit specialization.
74 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
75 !isa<ClassTemplatePartialSpecializationDecl>(Spec))
78 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
80 // If this class template specialization was instantiated from a
81 // specialized member that is a class template, we're done.
82 assert(Spec->getSpecializedTemplate() && "No class template?");
83 if (Spec->getSpecializedTemplate()->isMemberSpecialization())
86 // Add template arguments from a function template specialization.
87 else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) {
88 if (!RelativeToPrimary &&
89 Function->getTemplateSpecializationKind()
90 == TSK_ExplicitSpecialization)
93 if (const TemplateArgumentList *TemplateArgs
94 = Function->getTemplateSpecializationArgs()) {
95 // Add the template arguments for this specialization.
96 Result.addOuterTemplateArguments(TemplateArgs);
98 // If this function was instantiated from a specialized member that is
99 // a function template, we're done.
100 assert(Function->getPrimaryTemplate() && "No function template?");
101 if (Function->getPrimaryTemplate()->isMemberSpecialization())
103 } else if (FunctionTemplateDecl *FunTmpl
104 = Function->getDescribedFunctionTemplate()) {
105 // Add the "injected" template arguments.
106 std::pair<const TemplateArgument *, unsigned>
107 Injected = FunTmpl->getInjectedTemplateArgs();
108 Result.addOuterTemplateArguments(Injected.first, Injected.second);
111 // If this is a friend declaration and it declares an entity at
112 // namespace scope, take arguments from its lexical parent
113 // instead of its semantic parent, unless of course the pattern we're
114 // instantiating actually comes from the file's context!
115 if (Function->getFriendObjectKind() &&
116 Function->getDeclContext()->isFileContext() &&
117 (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
118 Ctx = Function->getLexicalDeclContext();
119 RelativeToPrimary = false;
122 } else if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Ctx)) {
123 if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
124 QualType T = ClassTemplate->getInjectedClassNameSpecialization();
125 const TemplateSpecializationType *TST
126 = cast<TemplateSpecializationType>(Context.getCanonicalType(T));
127 Result.addOuterTemplateArguments(TST->getArgs(), TST->getNumArgs());
128 if (ClassTemplate->isMemberSpecialization())
133 Ctx = Ctx->getParent();
134 RelativeToPrimary = false;
140 bool Sema::ActiveTemplateInstantiation::isInstantiationRecord() const {
142 case TemplateInstantiation:
143 case DefaultTemplateArgumentInstantiation:
144 case DefaultFunctionArgumentInstantiation:
147 case ExplicitTemplateArgumentSubstitution:
148 case DeducedTemplateArgumentSubstitution:
149 case PriorTemplateArgumentSubstitution:
150 case DefaultTemplateArgumentChecking:
157 Sema::InstantiatingTemplate::
158 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
160 SourceRange InstantiationRange)
162 SavedInNonInstantiationSFINAEContext(
163 SemaRef.InNonInstantiationSFINAEContext)
165 Invalid = CheckInstantiationDepth(PointOfInstantiation,
168 ActiveTemplateInstantiation Inst;
169 Inst.Kind = ActiveTemplateInstantiation::TemplateInstantiation;
170 Inst.PointOfInstantiation = PointOfInstantiation;
171 Inst.Entity = reinterpret_cast<uintptr_t>(Entity);
172 Inst.TemplateArgs = 0;
173 Inst.NumTemplateArgs = 0;
174 Inst.InstantiationRange = InstantiationRange;
175 SemaRef.InNonInstantiationSFINAEContext = false;
176 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
180 Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
181 SourceLocation PointOfInstantiation,
182 TemplateDecl *Template,
183 const TemplateArgument *TemplateArgs,
184 unsigned NumTemplateArgs,
185 SourceRange InstantiationRange)
187 SavedInNonInstantiationSFINAEContext(
188 SemaRef.InNonInstantiationSFINAEContext)
190 Invalid = CheckInstantiationDepth(PointOfInstantiation,
193 ActiveTemplateInstantiation Inst;
195 = ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation;
196 Inst.PointOfInstantiation = PointOfInstantiation;
197 Inst.Entity = reinterpret_cast<uintptr_t>(Template);
198 Inst.TemplateArgs = TemplateArgs;
199 Inst.NumTemplateArgs = NumTemplateArgs;
200 Inst.InstantiationRange = InstantiationRange;
201 SemaRef.InNonInstantiationSFINAEContext = false;
202 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
206 Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
207 SourceLocation PointOfInstantiation,
208 FunctionTemplateDecl *FunctionTemplate,
209 const TemplateArgument *TemplateArgs,
210 unsigned NumTemplateArgs,
211 ActiveTemplateInstantiation::InstantiationKind Kind,
212 sema::TemplateDeductionInfo &DeductionInfo,
213 SourceRange InstantiationRange)
215 SavedInNonInstantiationSFINAEContext(
216 SemaRef.InNonInstantiationSFINAEContext)
218 Invalid = CheckInstantiationDepth(PointOfInstantiation,
221 ActiveTemplateInstantiation Inst;
223 Inst.PointOfInstantiation = PointOfInstantiation;
224 Inst.Entity = reinterpret_cast<uintptr_t>(FunctionTemplate);
225 Inst.TemplateArgs = TemplateArgs;
226 Inst.NumTemplateArgs = NumTemplateArgs;
227 Inst.DeductionInfo = &DeductionInfo;
228 Inst.InstantiationRange = InstantiationRange;
229 SemaRef.InNonInstantiationSFINAEContext = false;
230 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
232 if (!Inst.isInstantiationRecord())
233 ++SemaRef.NonInstantiationEntries;
237 Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
238 SourceLocation PointOfInstantiation,
239 ClassTemplatePartialSpecializationDecl *PartialSpec,
240 const TemplateArgument *TemplateArgs,
241 unsigned NumTemplateArgs,
242 sema::TemplateDeductionInfo &DeductionInfo,
243 SourceRange InstantiationRange)
245 SavedInNonInstantiationSFINAEContext(
246 SemaRef.InNonInstantiationSFINAEContext)
250 ActiveTemplateInstantiation Inst;
251 Inst.Kind = ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution;
252 Inst.PointOfInstantiation = PointOfInstantiation;
253 Inst.Entity = reinterpret_cast<uintptr_t>(PartialSpec);
254 Inst.TemplateArgs = TemplateArgs;
255 Inst.NumTemplateArgs = NumTemplateArgs;
256 Inst.DeductionInfo = &DeductionInfo;
257 Inst.InstantiationRange = InstantiationRange;
258 SemaRef.InNonInstantiationSFINAEContext = false;
259 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
261 assert(!Inst.isInstantiationRecord());
262 ++SemaRef.NonInstantiationEntries;
265 Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
266 SourceLocation PointOfInstantiation,
268 const TemplateArgument *TemplateArgs,
269 unsigned NumTemplateArgs,
270 SourceRange InstantiationRange)
272 SavedInNonInstantiationSFINAEContext(
273 SemaRef.InNonInstantiationSFINAEContext)
275 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
278 ActiveTemplateInstantiation Inst;
280 = ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
281 Inst.PointOfInstantiation = PointOfInstantiation;
282 Inst.Entity = reinterpret_cast<uintptr_t>(Param);
283 Inst.TemplateArgs = TemplateArgs;
284 Inst.NumTemplateArgs = NumTemplateArgs;
285 Inst.InstantiationRange = InstantiationRange;
286 SemaRef.InNonInstantiationSFINAEContext = false;
287 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
291 Sema::InstantiatingTemplate::
292 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
294 NonTypeTemplateParmDecl *Param,
295 const TemplateArgument *TemplateArgs,
296 unsigned NumTemplateArgs,
297 SourceRange InstantiationRange)
299 SavedInNonInstantiationSFINAEContext(
300 SemaRef.InNonInstantiationSFINAEContext)
304 ActiveTemplateInstantiation Inst;
305 Inst.Kind = ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution;
306 Inst.PointOfInstantiation = PointOfInstantiation;
307 Inst.Template = Template;
308 Inst.Entity = reinterpret_cast<uintptr_t>(Param);
309 Inst.TemplateArgs = TemplateArgs;
310 Inst.NumTemplateArgs = NumTemplateArgs;
311 Inst.InstantiationRange = InstantiationRange;
312 SemaRef.InNonInstantiationSFINAEContext = false;
313 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
315 assert(!Inst.isInstantiationRecord());
316 ++SemaRef.NonInstantiationEntries;
319 Sema::InstantiatingTemplate::
320 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
322 TemplateTemplateParmDecl *Param,
323 const TemplateArgument *TemplateArgs,
324 unsigned NumTemplateArgs,
325 SourceRange InstantiationRange)
327 SavedInNonInstantiationSFINAEContext(
328 SemaRef.InNonInstantiationSFINAEContext)
331 ActiveTemplateInstantiation Inst;
332 Inst.Kind = ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution;
333 Inst.PointOfInstantiation = PointOfInstantiation;
334 Inst.Template = Template;
335 Inst.Entity = reinterpret_cast<uintptr_t>(Param);
336 Inst.TemplateArgs = TemplateArgs;
337 Inst.NumTemplateArgs = NumTemplateArgs;
338 Inst.InstantiationRange = InstantiationRange;
339 SemaRef.InNonInstantiationSFINAEContext = false;
340 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
342 assert(!Inst.isInstantiationRecord());
343 ++SemaRef.NonInstantiationEntries;
346 Sema::InstantiatingTemplate::
347 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
348 TemplateDecl *Template,
350 const TemplateArgument *TemplateArgs,
351 unsigned NumTemplateArgs,
352 SourceRange InstantiationRange)
354 SavedInNonInstantiationSFINAEContext(
355 SemaRef.InNonInstantiationSFINAEContext)
359 ActiveTemplateInstantiation Inst;
360 Inst.Kind = ActiveTemplateInstantiation::DefaultTemplateArgumentChecking;
361 Inst.PointOfInstantiation = PointOfInstantiation;
362 Inst.Template = Template;
363 Inst.Entity = reinterpret_cast<uintptr_t>(Param);
364 Inst.TemplateArgs = TemplateArgs;
365 Inst.NumTemplateArgs = NumTemplateArgs;
366 Inst.InstantiationRange = InstantiationRange;
367 SemaRef.InNonInstantiationSFINAEContext = false;
368 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
370 assert(!Inst.isInstantiationRecord());
371 ++SemaRef.NonInstantiationEntries;
374 void Sema::InstantiatingTemplate::Clear() {
376 if (!SemaRef.ActiveTemplateInstantiations.back().isInstantiationRecord()) {
377 assert(SemaRef.NonInstantiationEntries > 0);
378 --SemaRef.NonInstantiationEntries;
380 SemaRef.InNonInstantiationSFINAEContext
381 = SavedInNonInstantiationSFINAEContext;
382 SemaRef.ActiveTemplateInstantiations.pop_back();
387 bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
388 SourceLocation PointOfInstantiation,
389 SourceRange InstantiationRange) {
390 assert(SemaRef.NonInstantiationEntries <=
391 SemaRef.ActiveTemplateInstantiations.size());
392 if ((SemaRef.ActiveTemplateInstantiations.size() -
393 SemaRef.NonInstantiationEntries)
394 <= SemaRef.getLangOptions().InstantiationDepth)
397 SemaRef.Diag(PointOfInstantiation,
398 diag::err_template_recursion_depth_exceeded)
399 << SemaRef.getLangOptions().InstantiationDepth
400 << InstantiationRange;
401 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
402 << SemaRef.getLangOptions().InstantiationDepth;
406 /// \brief Prints the current instantiation stack through a series of
408 void Sema::PrintInstantiationStack() {
409 // Determine which template instantiations to skip, if any.
410 unsigned SkipStart = ActiveTemplateInstantiations.size(), SkipEnd = SkipStart;
411 unsigned Limit = Diags.getTemplateBacktraceLimit();
412 if (Limit && Limit < ActiveTemplateInstantiations.size()) {
413 SkipStart = Limit / 2 + Limit % 2;
414 SkipEnd = ActiveTemplateInstantiations.size() - Limit / 2;
417 // FIXME: In all of these cases, we need to show the template arguments
418 unsigned InstantiationIdx = 0;
419 for (llvm::SmallVector<ActiveTemplateInstantiation, 16>::reverse_iterator
420 Active = ActiveTemplateInstantiations.rbegin(),
421 ActiveEnd = ActiveTemplateInstantiations.rend();
423 ++Active, ++InstantiationIdx) {
424 // Skip this instantiation?
425 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
426 if (InstantiationIdx == SkipStart) {
427 // Note that we're skipping instantiations.
428 Diags.Report(Active->PointOfInstantiation,
429 diag::note_instantiation_contexts_suppressed)
430 << unsigned(ActiveTemplateInstantiations.size() - Limit);
435 switch (Active->Kind) {
436 case ActiveTemplateInstantiation::TemplateInstantiation: {
437 Decl *D = reinterpret_cast<Decl *>(Active->Entity);
438 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
439 unsigned DiagID = diag::note_template_member_class_here;
440 if (isa<ClassTemplateSpecializationDecl>(Record))
441 DiagID = diag::note_template_class_instantiation_here;
442 Diags.Report(Active->PointOfInstantiation, DiagID)
443 << Context.getTypeDeclType(Record)
444 << Active->InstantiationRange;
445 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
447 if (Function->getPrimaryTemplate())
448 DiagID = diag::note_function_template_spec_here;
450 DiagID = diag::note_template_member_function_here;
451 Diags.Report(Active->PointOfInstantiation, DiagID)
453 << Active->InstantiationRange;
454 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
455 Diags.Report(Active->PointOfInstantiation,
456 diag::note_template_static_data_member_def_here)
458 << Active->InstantiationRange;
460 Diags.Report(Active->PointOfInstantiation,
461 diag::note_template_type_alias_instantiation_here)
462 << cast<TypeAliasTemplateDecl>(D)
463 << Active->InstantiationRange;
468 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation: {
469 TemplateDecl *Template = cast<TemplateDecl>((Decl *)Active->Entity);
470 std::string TemplateArgsStr
471 = TemplateSpecializationType::PrintTemplateArgumentList(
472 Active->TemplateArgs,
473 Active->NumTemplateArgs,
474 Context.PrintingPolicy);
475 Diags.Report(Active->PointOfInstantiation,
476 diag::note_default_arg_instantiation_here)
477 << (Template->getNameAsString() + TemplateArgsStr)
478 << Active->InstantiationRange;
482 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution: {
483 FunctionTemplateDecl *FnTmpl
484 = cast<FunctionTemplateDecl>((Decl *)Active->Entity);
485 Diags.Report(Active->PointOfInstantiation,
486 diag::note_explicit_template_arg_substitution_here)
488 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
489 Active->TemplateArgs,
490 Active->NumTemplateArgs)
491 << Active->InstantiationRange;
495 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
496 if (ClassTemplatePartialSpecializationDecl *PartialSpec
497 = dyn_cast<ClassTemplatePartialSpecializationDecl>(
498 (Decl *)Active->Entity)) {
499 Diags.Report(Active->PointOfInstantiation,
500 diag::note_partial_spec_deduct_instantiation_here)
501 << Context.getTypeDeclType(PartialSpec)
502 << getTemplateArgumentBindingsText(
503 PartialSpec->getTemplateParameters(),
504 Active->TemplateArgs,
505 Active->NumTemplateArgs)
506 << Active->InstantiationRange;
508 FunctionTemplateDecl *FnTmpl
509 = cast<FunctionTemplateDecl>((Decl *)Active->Entity);
510 Diags.Report(Active->PointOfInstantiation,
511 diag::note_function_template_deduction_instantiation_here)
513 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
514 Active->TemplateArgs,
515 Active->NumTemplateArgs)
516 << Active->InstantiationRange;
520 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation: {
521 ParmVarDecl *Param = cast<ParmVarDecl>((Decl *)Active->Entity);
522 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
524 std::string TemplateArgsStr
525 = TemplateSpecializationType::PrintTemplateArgumentList(
526 Active->TemplateArgs,
527 Active->NumTemplateArgs,
528 Context.PrintingPolicy);
529 Diags.Report(Active->PointOfInstantiation,
530 diag::note_default_function_arg_instantiation_here)
531 << (FD->getNameAsString() + TemplateArgsStr)
532 << Active->InstantiationRange;
536 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution: {
537 NamedDecl *Parm = cast<NamedDecl>((Decl *)Active->Entity);
539 if (!Parm->getName().empty())
540 Name = std::string(" '") + Parm->getName().str() + "'";
542 TemplateParameterList *TemplateParams = 0;
543 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
544 TemplateParams = Template->getTemplateParameters();
547 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
548 ->getTemplateParameters();
549 Diags.Report(Active->PointOfInstantiation,
550 diag::note_prior_template_arg_substitution)
551 << isa<TemplateTemplateParmDecl>(Parm)
553 << getTemplateArgumentBindingsText(TemplateParams,
554 Active->TemplateArgs,
555 Active->NumTemplateArgs)
556 << Active->InstantiationRange;
560 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking: {
561 TemplateParameterList *TemplateParams = 0;
562 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
563 TemplateParams = Template->getTemplateParameters();
566 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
567 ->getTemplateParameters();
569 Diags.Report(Active->PointOfInstantiation,
570 diag::note_template_default_arg_checking)
571 << getTemplateArgumentBindingsText(TemplateParams,
572 Active->TemplateArgs,
573 Active->NumTemplateArgs)
574 << Active->InstantiationRange;
581 llvm::Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
582 using llvm::SmallVector;
583 if (InNonInstantiationSFINAEContext)
584 return llvm::Optional<TemplateDeductionInfo *>(0);
586 for (SmallVector<ActiveTemplateInstantiation, 16>::const_reverse_iterator
587 Active = ActiveTemplateInstantiations.rbegin(),
588 ActiveEnd = ActiveTemplateInstantiations.rend();
592 switch(Active->Kind) {
593 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation:
594 case ActiveTemplateInstantiation::TemplateInstantiation:
595 // This is a template instantiation, so there is no SFINAE.
596 return llvm::Optional<TemplateDeductionInfo *>();
598 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation:
599 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution:
600 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking:
601 // A default template argument instantiation and substitution into
602 // template parameters with arguments for prior parameters may or may
603 // not be a SFINAE context; look further up the stack.
606 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution:
607 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
608 // We're either substitution explicitly-specified template arguments
609 // or deduced template arguments, so SFINAE applies.
610 assert(Active->DeductionInfo && "Missing deduction info pointer");
611 return Active->DeductionInfo;
615 return llvm::Optional<TemplateDeductionInfo *>();
618 /// \brief Retrieve the depth and index of a parameter pack.
619 static std::pair<unsigned, unsigned>
620 getDepthAndIndex(NamedDecl *ND) {
621 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
622 return std::make_pair(TTP->getDepth(), TTP->getIndex());
624 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
625 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
627 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
628 return std::make_pair(TTP->getDepth(), TTP->getIndex());
631 //===----------------------------------------------------------------------===/
632 // Template Instantiation for Types
633 //===----------------------------------------------------------------------===/
635 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
636 const MultiLevelTemplateArgumentList &TemplateArgs;
638 DeclarationName Entity;
641 typedef TreeTransform<TemplateInstantiator> inherited;
643 TemplateInstantiator(Sema &SemaRef,
644 const MultiLevelTemplateArgumentList &TemplateArgs,
646 DeclarationName Entity)
647 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
650 /// \brief Determine whether the given type \p T has already been
653 /// For the purposes of template instantiation, a type has already been
654 /// transformed if it is NULL or if it is not dependent.
655 bool AlreadyTransformed(QualType T);
657 /// \brief Returns the location of the entity being instantiated, if known.
658 SourceLocation getBaseLocation() { return Loc; }
660 /// \brief Returns the name of the entity being instantiated, if any.
661 DeclarationName getBaseEntity() { return Entity; }
663 /// \brief Sets the "base" location and entity when that
664 /// information is known based on another transformation.
665 void setBase(SourceLocation Loc, DeclarationName Entity) {
667 this->Entity = Entity;
670 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
671 SourceRange PatternRange,
672 const UnexpandedParameterPack *Unexpanded,
673 unsigned NumUnexpanded,
675 bool &RetainExpansion,
676 llvm::Optional<unsigned> &NumExpansions) {
677 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
678 PatternRange, Unexpanded,
686 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
687 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
690 TemplateArgument ForgetPartiallySubstitutedPack() {
691 TemplateArgument Result;
692 if (NamedDecl *PartialPack
693 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
694 MultiLevelTemplateArgumentList &TemplateArgs
695 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
696 unsigned Depth, Index;
697 llvm::tie(Depth, Index) = getDepthAndIndex(PartialPack);
698 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
699 Result = TemplateArgs(Depth, Index);
700 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
707 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
711 if (NamedDecl *PartialPack
712 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
713 MultiLevelTemplateArgumentList &TemplateArgs
714 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
715 unsigned Depth, Index;
716 llvm::tie(Depth, Index) = getDepthAndIndex(PartialPack);
717 TemplateArgs.setArgument(Depth, Index, Arg);
721 /// \brief Transform the given declaration by instantiating a reference to
722 /// this declaration.
723 Decl *TransformDecl(SourceLocation Loc, Decl *D);
725 /// \brief Transform the definition of the given declaration by
726 /// instantiating it.
727 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
729 /// \bried Transform the first qualifier within a scope by instantiating the
731 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
733 /// \brief Rebuild the exception declaration and register the declaration
734 /// as an instantiated local.
735 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
736 TypeSourceInfo *Declarator,
737 SourceLocation StartLoc,
738 SourceLocation NameLoc,
739 IdentifierInfo *Name);
741 /// \brief Rebuild the Objective-C exception declaration and register the
742 /// declaration as an instantiated local.
743 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
744 TypeSourceInfo *TSInfo, QualType T);
746 /// \brief Check for tag mismatches when instantiating an
748 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
749 ElaboratedTypeKeyword Keyword,
750 NestedNameSpecifierLoc QualifierLoc,
753 TemplateName TransformTemplateName(CXXScopeSpec &SS,
755 SourceLocation NameLoc,
756 QualType ObjectType = QualType(),
757 NamedDecl *FirstQualifierInScope = 0);
759 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
760 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
761 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
762 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
763 NonTypeTemplateParmDecl *D);
764 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
765 SubstNonTypeTemplateParmPackExpr *E);
767 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
768 FunctionProtoTypeLoc TL);
769 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
771 llvm::Optional<unsigned> NumExpansions);
773 /// \brief Transforms a template type parameter type by performing
774 /// substitution of the corresponding template type argument.
775 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
776 TemplateTypeParmTypeLoc TL);
778 /// \brief Transforms an already-substituted template type parameter pack
779 /// into either itself (if we aren't substituting into its pack expansion)
780 /// or the appropriate substituted argument.
781 QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
782 SubstTemplateTypeParmPackTypeLoc TL);
784 ExprResult TransformCallExpr(CallExpr *CE) {
785 getSema().CallsUndergoingInstantiation.push_back(CE);
787 TreeTransform<TemplateInstantiator>::TransformCallExpr(CE);
788 getSema().CallsUndergoingInstantiation.pop_back();
794 bool TemplateInstantiator::AlreadyTransformed(QualType T) {
798 if (T->isDependentType() || T->isVariablyModifiedType())
801 getSema().MarkDeclarationsReferencedInType(Loc, T);
805 Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
809 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
810 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
811 // If the corresponding template argument is NULL or non-existent, it's
812 // because we are performing instantiation from explicitly-specified
813 // template arguments in a function template, but there were some
814 // arguments left unspecified.
815 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
819 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
821 if (TTP->isParameterPack()) {
822 assert(Arg.getKind() == TemplateArgument::Pack &&
823 "Missing argument pack");
825 assert(getSema().ArgumentPackSubstitutionIndex >= 0);
826 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
827 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
830 TemplateName Template = Arg.getAsTemplate();
831 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
832 "Wrong kind of template template argument");
833 return Template.getAsTemplateDecl();
836 // Fall through to find the instantiated declaration for this template
837 // template parameter.
840 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
843 Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
844 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
848 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
853 TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
854 SourceLocation Loc) {
855 // If the first part of the nested-name-specifier was a template type
856 // parameter, instantiate that type parameter down to a tag type.
857 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
858 const TemplateTypeParmType *TTP
859 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
861 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
862 // FIXME: This needs testing w/ member access expressions.
863 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
865 if (TTP->isParameterPack()) {
866 assert(Arg.getKind() == TemplateArgument::Pack &&
867 "Missing argument pack");
869 if (getSema().ArgumentPackSubstitutionIndex == -1)
872 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
873 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
876 QualType T = Arg.getAsType();
878 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
880 if (const TagType *Tag = T->getAs<TagType>())
881 return Tag->getDecl();
883 // The resulting type is not a tag; complain.
884 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
889 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
893 TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
894 TypeSourceInfo *Declarator,
895 SourceLocation StartLoc,
896 SourceLocation NameLoc,
897 IdentifierInfo *Name) {
898 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
899 StartLoc, NameLoc, Name);
901 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
905 VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
906 TypeSourceInfo *TSInfo,
908 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
910 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
915 TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
916 ElaboratedTypeKeyword Keyword,
917 NestedNameSpecifierLoc QualifierLoc,
919 if (const TagType *TT = T->getAs<TagType>()) {
920 TagDecl* TD = TT->getDecl();
922 SourceLocation TagLocation = KeywordLoc;
924 // FIXME: type might be anonymous.
925 IdentifierInfo *Id = TD->getIdentifier();
927 // TODO: should we even warn on struct/class mismatches for this? Seems
928 // like it's likely to produce a lot of spurious errors.
929 if (Keyword != ETK_None && Keyword != ETK_Typename) {
930 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
931 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
933 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
935 << FixItHint::CreateReplacement(SourceRange(TagLocation),
937 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
942 return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(KeywordLoc,
948 TemplateName TemplateInstantiator::TransformTemplateName(CXXScopeSpec &SS,
950 SourceLocation NameLoc,
952 NamedDecl *FirstQualifierInScope) {
953 if (TemplateTemplateParmDecl *TTP
954 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
955 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
956 // If the corresponding template argument is NULL or non-existent, it's
957 // because we are performing instantiation from explicitly-specified
958 // template arguments in a function template, but there were some
959 // arguments left unspecified.
960 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
964 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
966 if (TTP->isParameterPack()) {
967 assert(Arg.getKind() == TemplateArgument::Pack &&
968 "Missing argument pack");
970 if (getSema().ArgumentPackSubstitutionIndex == -1) {
971 // We have the template argument pack to substitute, but we're not
972 // actually expanding the enclosing pack expansion yet. So, just
973 // keep the entire argument pack.
974 return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg);
977 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
978 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
981 TemplateName Template = Arg.getAsTemplate();
982 assert(!Template.isNull() && "Null template template argument");
984 // We don't ever want to substitute for a qualified template name, since
985 // the qualifier is handled separately. So, look through the qualified
986 // template name to its underlying declaration.
987 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
988 Template = TemplateName(QTN->getTemplateDecl());
994 if (SubstTemplateTemplateParmPackStorage *SubstPack
995 = Name.getAsSubstTemplateTemplateParmPack()) {
996 if (getSema().ArgumentPackSubstitutionIndex == -1)
999 const TemplateArgument &ArgPack = SubstPack->getArgumentPack();
1000 assert(getSema().ArgumentPackSubstitutionIndex < (int)ArgPack.pack_size() &&
1001 "Pack substitution index out-of-range");
1002 return ArgPack.pack_begin()[getSema().ArgumentPackSubstitutionIndex]
1006 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
1007 FirstQualifierInScope);
1011 TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
1012 if (!E->isTypeDependent())
1013 return SemaRef.Owned(E);
1015 FunctionDecl *currentDecl = getSema().getCurFunctionDecl();
1016 assert(currentDecl && "Must have current function declaration when "
1019 PredefinedExpr::IdentType IT = E->getIdentType();
1021 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
1023 llvm::APInt LengthI(32, Length + 1);
1024 QualType ResTy = getSema().Context.CharTy.withConst();
1025 ResTy = getSema().Context.getConstantArrayType(ResTy, LengthI,
1026 ArrayType::Normal, 0);
1027 PredefinedExpr *PE =
1028 new (getSema().Context) PredefinedExpr(E->getLocation(), ResTy, IT);
1029 return getSema().Owned(PE);
1033 TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
1034 NonTypeTemplateParmDecl *NTTP) {
1035 // If the corresponding template argument is NULL or non-existent, it's
1036 // because we are performing instantiation from explicitly-specified
1037 // template arguments in a function template, but there were some
1038 // arguments left unspecified.
1039 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
1040 NTTP->getPosition()))
1041 return SemaRef.Owned(E);
1043 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
1044 if (NTTP->isParameterPack()) {
1045 assert(Arg.getKind() == TemplateArgument::Pack &&
1046 "Missing argument pack");
1048 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1049 // We have an argument pack, but we can't select a particular argument
1050 // out of it yet. Therefore, we'll build an expression to hold on to that
1052 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1054 NTTP->getDeclName());
1055 if (TargetType.isNull())
1058 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(TargetType,
1064 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
1065 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
1068 // The template argument itself might be an expression, in which
1069 // case we just return that expression.
1070 if (Arg.getKind() == TemplateArgument::Expression)
1071 return SemaRef.Owned(Arg.getAsExpr());
1073 if (Arg.getKind() == TemplateArgument::Declaration) {
1074 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
1076 // Find the instantiation of the template argument. This is
1077 // required for nested templates.
1078 VD = cast_or_null<ValueDecl>(
1079 getSema().FindInstantiatedDecl(E->getLocation(),
1084 // Derive the type we want the substituted decl to have. This had
1085 // better be non-dependent, or these checks will have serious problems.
1086 QualType TargetType;
1087 if (NTTP->isExpandedParameterPack())
1088 TargetType = NTTP->getExpansionType(
1089 getSema().ArgumentPackSubstitutionIndex);
1090 else if (NTTP->isParameterPack() &&
1091 isa<PackExpansionType>(NTTP->getType())) {
1092 TargetType = SemaRef.SubstType(
1093 cast<PackExpansionType>(NTTP->getType())->getPattern(),
1094 TemplateArgs, E->getLocation(),
1095 NTTP->getDeclName());
1097 TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1098 E->getLocation(), NTTP->getDeclName());
1099 assert(!TargetType.isNull() && "type substitution failed for param type");
1100 assert(!TargetType->isDependentType() && "param type still dependent");
1101 return SemaRef.BuildExpressionFromDeclTemplateArgument(Arg,
1106 return SemaRef.BuildExpressionFromIntegralTemplateArgument(Arg,
1107 E->getSourceRange().getBegin());
1111 TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
1112 SubstNonTypeTemplateParmPackExpr *E) {
1113 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1114 // We aren't expanding the parameter pack, so just return ourselves.
1115 return getSema().Owned(E);
1118 const TemplateArgument &ArgPack = E->getArgumentPack();
1119 unsigned Index = (unsigned)getSema().ArgumentPackSubstitutionIndex;
1120 assert(Index < ArgPack.pack_size() && "Substitution index out-of-range");
1122 const TemplateArgument &Arg = ArgPack.pack_begin()[Index];
1123 if (Arg.getKind() == TemplateArgument::Expression)
1124 return SemaRef.Owned(Arg.getAsExpr());
1126 if (Arg.getKind() == TemplateArgument::Declaration) {
1127 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
1129 // Find the instantiation of the template argument. This is
1130 // required for nested templates.
1131 VD = cast_or_null<ValueDecl>(
1132 getSema().FindInstantiatedDecl(E->getParameterPackLocation(),
1138 NonTypeTemplateParmDecl *NTTP = E->getParameterPack();
1139 if (NTTP->isExpandedParameterPack())
1140 T = NTTP->getExpansionType(getSema().ArgumentPackSubstitutionIndex);
1141 else if (const PackExpansionType *Expansion
1142 = dyn_cast<PackExpansionType>(NTTP->getType()))
1143 T = SemaRef.SubstType(Expansion->getPattern(), TemplateArgs,
1144 E->getParameterPackLocation(), NTTP->getDeclName());
1147 return SemaRef.BuildExpressionFromDeclTemplateArgument(Arg, T,
1148 E->getParameterPackLocation());
1151 return SemaRef.BuildExpressionFromIntegralTemplateArgument(Arg,
1152 E->getParameterPackLocation());
1156 TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
1157 NamedDecl *D = E->getDecl();
1158 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
1159 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
1160 return TransformTemplateParmRefExpr(E, NTTP);
1162 // We have a non-type template parameter that isn't fully substituted;
1163 // FindInstantiatedDecl will find it in the local instantiation scope.
1166 return TreeTransform<TemplateInstantiator>::TransformDeclRefExpr(E);
1169 ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
1170 CXXDefaultArgExpr *E) {
1171 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
1172 getDescribedFunctionTemplate() &&
1173 "Default arg expressions are never formed in dependent cases.");
1174 return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
1175 cast<FunctionDecl>(E->getParam()->getDeclContext()),
1179 QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
1180 FunctionProtoTypeLoc TL) {
1181 // We need a local instantiation scope for this function prototype.
1182 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1183 return inherited::TransformFunctionProtoType(TLB, TL);
1187 TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
1188 int indexAdjustment,
1189 llvm::Optional<unsigned> NumExpansions) {
1190 return SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment,
1195 TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1196 TemplateTypeParmTypeLoc TL) {
1197 const TemplateTypeParmType *T = TL.getTypePtr();
1198 if (T->getDepth() < TemplateArgs.getNumLevels()) {
1199 // Replace the template type parameter with its corresponding
1200 // template argument.
1202 // If the corresponding template argument is NULL or doesn't exist, it's
1203 // because we are performing instantiation from explicitly-specified
1204 // template arguments in a function template class, but there were some
1205 // arguments left unspecified.
1206 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
1207 TemplateTypeParmTypeLoc NewTL
1208 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
1209 NewTL.setNameLoc(TL.getNameLoc());
1210 return TL.getType();
1213 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
1215 if (T->isParameterPack()) {
1216 assert(Arg.getKind() == TemplateArgument::Pack &&
1217 "Missing argument pack");
1219 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1220 // We have the template argument pack, but we're not expanding the
1221 // enclosing pack expansion yet. Just save the template argument
1222 // pack for later substitution.
1224 = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg);
1225 SubstTemplateTypeParmPackTypeLoc NewTL
1226 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
1227 NewTL.setNameLoc(TL.getNameLoc());
1231 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
1232 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
1235 assert(Arg.getKind() == TemplateArgument::Type &&
1236 "Template argument kind mismatch");
1238 QualType Replacement = Arg.getAsType();
1240 // TODO: only do this uniquing once, at the start of instantiation.
1242 = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
1243 SubstTemplateTypeParmTypeLoc NewTL
1244 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1245 NewTL.setNameLoc(TL.getNameLoc());
1249 // The template type parameter comes from an inner template (e.g.,
1250 // the template parameter list of a member template inside the
1251 // template we are instantiating). Create a new template type
1252 // parameter with the template "level" reduced by one.
1253 TemplateTypeParmDecl *NewTTPDecl = 0;
1254 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
1255 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
1256 TransformDecl(TL.getNameLoc(), OldTTPDecl));
1259 = getSema().Context.getTemplateTypeParmType(T->getDepth()
1260 - TemplateArgs.getNumLevels(),
1262 T->isParameterPack(),
1264 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
1265 NewTL.setNameLoc(TL.getNameLoc());
1270 TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
1271 TypeLocBuilder &TLB,
1272 SubstTemplateTypeParmPackTypeLoc TL) {
1273 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1274 // We aren't expanding the parameter pack, so just return ourselves.
1275 SubstTemplateTypeParmPackTypeLoc NewTL
1276 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(TL.getType());
1277 NewTL.setNameLoc(TL.getNameLoc());
1278 return TL.getType();
1281 const TemplateArgument &ArgPack = TL.getTypePtr()->getArgumentPack();
1282 unsigned Index = (unsigned)getSema().ArgumentPackSubstitutionIndex;
1283 assert(Index < ArgPack.pack_size() && "Substitution index out-of-range");
1285 QualType Result = ArgPack.pack_begin()[Index].getAsType();
1286 Result = getSema().Context.getSubstTemplateTypeParmType(
1287 TL.getTypePtr()->getReplacedParameter(),
1289 SubstTemplateTypeParmTypeLoc NewTL
1290 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1291 NewTL.setNameLoc(TL.getNameLoc());
1295 /// \brief Perform substitution on the type T with a given set of template
1298 /// This routine substitutes the given template arguments into the
1299 /// type T and produces the instantiated type.
1301 /// \param T the type into which the template arguments will be
1302 /// substituted. If this type is not dependent, it will be returned
1305 /// \param TemplateArgs the template arguments that will be
1306 /// substituted for the top-level template parameters within T.
1308 /// \param Loc the location in the source code where this substitution
1309 /// is being performed. It will typically be the location of the
1310 /// declarator (if we're instantiating the type of some declaration)
1311 /// or the location of the type in the source code (if, e.g., we're
1312 /// instantiating the type of a cast expression).
1314 /// \param Entity the name of the entity associated with a declaration
1315 /// being instantiated (if any). May be empty to indicate that there
1316 /// is no such entity (if, e.g., this is a type that occurs as part of
1317 /// a cast expression) or that the entity has no name (e.g., an
1318 /// unnamed function parameter).
1320 /// \returns If the instantiation succeeds, the instantiated
1321 /// type. Otherwise, produces diagnostics and returns a NULL type.
1322 TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
1323 const MultiLevelTemplateArgumentList &Args,
1325 DeclarationName Entity) {
1326 assert(!ActiveTemplateInstantiations.empty() &&
1327 "Cannot perform an instantiation without some context on the "
1328 "instantiation stack");
1330 if (!T->getType()->isDependentType() &&
1331 !T->getType()->isVariablyModifiedType())
1334 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1335 return Instantiator.TransformType(T);
1338 TypeSourceInfo *Sema::SubstType(TypeLoc TL,
1339 const MultiLevelTemplateArgumentList &Args,
1341 DeclarationName Entity) {
1342 assert(!ActiveTemplateInstantiations.empty() &&
1343 "Cannot perform an instantiation without some context on the "
1344 "instantiation stack");
1346 if (TL.getType().isNull())
1349 if (!TL.getType()->isDependentType() &&
1350 !TL.getType()->isVariablyModifiedType()) {
1351 // FIXME: Make a copy of the TypeLoc data here, so that we can
1352 // return a new TypeSourceInfo. Inefficient!
1354 TLB.pushFullCopy(TL);
1355 return TLB.getTypeSourceInfo(Context, TL.getType());
1358 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1360 TLB.reserve(TL.getFullDataSize());
1361 QualType Result = Instantiator.TransformType(TLB, TL);
1362 if (Result.isNull())
1365 return TLB.getTypeSourceInfo(Context, Result);
1368 /// Deprecated form of the above.
1369 QualType Sema::SubstType(QualType T,
1370 const MultiLevelTemplateArgumentList &TemplateArgs,
1371 SourceLocation Loc, DeclarationName Entity) {
1372 assert(!ActiveTemplateInstantiations.empty() &&
1373 "Cannot perform an instantiation without some context on the "
1374 "instantiation stack");
1376 // If T is not a dependent type or a variably-modified type, there
1377 // is nothing to do.
1378 if (!T->isDependentType() && !T->isVariablyModifiedType())
1381 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
1382 return Instantiator.TransformType(T);
1385 static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
1386 if (T->getType()->isDependentType() || T->getType()->isVariablyModifiedType())
1389 TypeLoc TL = T->getTypeLoc().IgnoreParens();
1390 if (!isa<FunctionProtoTypeLoc>(TL))
1393 FunctionProtoTypeLoc FP = cast<FunctionProtoTypeLoc>(TL);
1394 for (unsigned I = 0, E = FP.getNumArgs(); I != E; ++I) {
1395 ParmVarDecl *P = FP.getArg(I);
1397 // The parameter's type as written might be dependent even if the
1398 // decayed type was not dependent.
1399 if (TypeSourceInfo *TSInfo = P->getTypeSourceInfo())
1400 if (TSInfo->getType()->isDependentType())
1403 // TODO: currently we always rebuild expressions. When we
1404 // properly get lazier about this, we should use the same
1405 // logic to avoid rebuilding prototypes here.
1406 if (P->hasDefaultArg())
1413 /// A form of SubstType intended specifically for instantiating the
1414 /// type of a FunctionDecl. Its purpose is solely to force the
1415 /// instantiation of default-argument expressions.
1416 TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
1417 const MultiLevelTemplateArgumentList &Args,
1419 DeclarationName Entity) {
1420 assert(!ActiveTemplateInstantiations.empty() &&
1421 "Cannot perform an instantiation without some context on the "
1422 "instantiation stack");
1424 if (!NeedsInstantiationAsFunctionType(T))
1427 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1431 TypeLoc TL = T->getTypeLoc();
1432 TLB.reserve(TL.getFullDataSize());
1434 QualType Result = Instantiator.TransformType(TLB, TL);
1435 if (Result.isNull())
1438 return TLB.getTypeSourceInfo(Context, Result);
1441 ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm,
1442 const MultiLevelTemplateArgumentList &TemplateArgs,
1443 int indexAdjustment,
1444 llvm::Optional<unsigned> NumExpansions) {
1445 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
1446 TypeSourceInfo *NewDI = 0;
1448 TypeLoc OldTL = OldDI->getTypeLoc();
1449 if (isa<PackExpansionTypeLoc>(OldTL)) {
1450 PackExpansionTypeLoc ExpansionTL = cast<PackExpansionTypeLoc>(OldTL);
1452 // We have a function parameter pack. Substitute into the pattern of the
1454 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
1455 OldParm->getLocation(), OldParm->getDeclName());
1459 if (NewDI->getType()->containsUnexpandedParameterPack()) {
1460 // We still have unexpanded parameter packs, which means that
1461 // our function parameter is still a function parameter pack.
1462 // Therefore, make its type a pack expansion type.
1463 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
1467 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
1468 OldParm->getDeclName());
1474 if (NewDI->getType()->isVoidType()) {
1475 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
1479 ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
1480 OldParm->getInnerLocStart(),
1481 OldParm->getLocation(),
1482 OldParm->getIdentifier(),
1483 NewDI->getType(), NewDI,
1484 OldParm->getStorageClass(),
1485 OldParm->getStorageClassAsWritten());
1489 // Mark the (new) default argument as uninstantiated (if any).
1490 if (OldParm->hasUninstantiatedDefaultArg()) {
1491 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
1492 NewParm->setUninstantiatedDefaultArg(Arg);
1493 } else if (OldParm->hasUnparsedDefaultArg()) {
1494 NewParm->setUnparsedDefaultArg();
1495 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
1496 } else if (Expr *Arg = OldParm->getDefaultArg())
1497 NewParm->setUninstantiatedDefaultArg(Arg);
1499 NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
1501 // FIXME: When OldParm is a parameter pack and NewParm is not a parameter
1502 // pack, we actually have a set of instantiated locations. Maintain this set!
1503 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
1504 // Add the new parameter to
1505 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
1507 // Introduce an Old -> New mapping
1508 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
1511 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
1512 // can be anything, is this right ?
1513 NewParm->setDeclContext(CurContext);
1515 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
1516 OldParm->getFunctionScopeIndex() + indexAdjustment);
1521 /// \brief Substitute the given template arguments into the given set of
1522 /// parameters, producing the set of parameter types that would be generated
1523 /// from such a substitution.
1524 bool Sema::SubstParmTypes(SourceLocation Loc,
1525 ParmVarDecl **Params, unsigned NumParams,
1526 const MultiLevelTemplateArgumentList &TemplateArgs,
1527 llvm::SmallVectorImpl<QualType> &ParamTypes,
1528 llvm::SmallVectorImpl<ParmVarDecl *> *OutParams) {
1529 assert(!ActiveTemplateInstantiations.empty() &&
1530 "Cannot perform an instantiation without some context on the "
1531 "instantiation stack");
1533 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
1535 return Instantiator.TransformFunctionTypeParams(Loc, Params, NumParams, 0,
1536 ParamTypes, OutParams);
1539 /// \brief Perform substitution on the base class specifiers of the
1540 /// given class template specialization.
1542 /// Produces a diagnostic and returns true on error, returns false and
1543 /// attaches the instantiated base classes to the class template
1544 /// specialization if successful.
1546 Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
1547 CXXRecordDecl *Pattern,
1548 const MultiLevelTemplateArgumentList &TemplateArgs) {
1549 bool Invalid = false;
1550 llvm::SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
1551 for (ClassTemplateSpecializationDecl::base_class_iterator
1552 Base = Pattern->bases_begin(), BaseEnd = Pattern->bases_end();
1553 Base != BaseEnd; ++Base) {
1554 if (!Base->getType()->isDependentType()) {
1555 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(*Base));
1559 SourceLocation EllipsisLoc;
1560 TypeSourceInfo *BaseTypeLoc;
1561 if (Base->isPackExpansion()) {
1562 // This is a pack expansion. See whether we should expand it now, or
1563 // wait until later.
1564 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1565 collectUnexpandedParameterPacks(Base->getTypeSourceInfo()->getTypeLoc(),
1567 bool ShouldExpand = false;
1568 bool RetainExpansion = false;
1569 llvm::Optional<unsigned> NumExpansions;
1570 if (CheckParameterPacksForExpansion(Base->getEllipsisLoc(),
1571 Base->getSourceRange(),
1572 Unexpanded.data(), Unexpanded.size(),
1573 TemplateArgs, ShouldExpand,
1580 // If we should expand this pack expansion now, do so.
1582 for (unsigned I = 0; I != *NumExpansions; ++I) {
1583 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
1585 TypeSourceInfo *BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
1587 Base->getSourceRange().getBegin(),
1594 if (CXXBaseSpecifier *InstantiatedBase
1595 = CheckBaseSpecifier(Instantiation,
1596 Base->getSourceRange(),
1598 Base->getAccessSpecifierAsWritten(),
1601 InstantiatedBases.push_back(InstantiatedBase);
1609 // The resulting base specifier will (still) be a pack expansion.
1610 EllipsisLoc = Base->getEllipsisLoc();
1611 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
1612 BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
1614 Base->getSourceRange().getBegin(),
1617 BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
1619 Base->getSourceRange().getBegin(),
1628 if (CXXBaseSpecifier *InstantiatedBase
1629 = CheckBaseSpecifier(Instantiation,
1630 Base->getSourceRange(),
1632 Base->getAccessSpecifierAsWritten(),
1635 InstantiatedBases.push_back(InstantiatedBase);
1641 AttachBaseSpecifiers(Instantiation, InstantiatedBases.data(),
1642 InstantiatedBases.size()))
1648 /// \brief Instantiate the definition of a class from a given pattern.
1650 /// \param PointOfInstantiation The point of instantiation within the
1653 /// \param Instantiation is the declaration whose definition is being
1654 /// instantiated. This will be either a class template specialization
1655 /// or a member class of a class template specialization.
1657 /// \param Pattern is the pattern from which the instantiation
1658 /// occurs. This will be either the declaration of a class template or
1659 /// the declaration of a member class of a class template.
1661 /// \param TemplateArgs The template arguments to be substituted into
1664 /// \param TSK the kind of implicit or explicit instantiation to perform.
1666 /// \param Complain whether to complain if the class cannot be instantiated due
1667 /// to the lack of a definition.
1669 /// \returns true if an error occurred, false otherwise.
1671 Sema::InstantiateClass(SourceLocation PointOfInstantiation,
1672 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
1673 const MultiLevelTemplateArgumentList &TemplateArgs,
1674 TemplateSpecializationKind TSK,
1676 bool Invalid = false;
1678 CXXRecordDecl *PatternDef
1679 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
1680 if (!PatternDef || PatternDef->isBeingDefined()) {
1681 if (!Complain || (PatternDef && PatternDef->isInvalidDecl())) {
1683 } else if (PatternDef) {
1684 assert(PatternDef->isBeingDefined());
1685 Diag(PointOfInstantiation,
1686 diag::err_template_instantiate_within_definition)
1687 << (TSK != TSK_ImplicitInstantiation)
1688 << Context.getTypeDeclType(Instantiation);
1689 // Not much point in noting the template declaration here, since
1690 // we're lexically inside it.
1691 Instantiation->setInvalidDecl();
1692 } else if (Pattern == Instantiation->getInstantiatedFromMemberClass()) {
1693 Diag(PointOfInstantiation,
1694 diag::err_implicit_instantiate_member_undefined)
1695 << Context.getTypeDeclType(Instantiation);
1696 Diag(Pattern->getLocation(), diag::note_member_of_template_here);
1698 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
1699 << (TSK != TSK_ImplicitInstantiation)
1700 << Context.getTypeDeclType(Instantiation);
1701 Diag(Pattern->getLocation(), diag::note_template_decl_here);
1705 Pattern = PatternDef;
1707 // \brief Record the point of instantiation.
1708 if (MemberSpecializationInfo *MSInfo
1709 = Instantiation->getMemberSpecializationInfo()) {
1710 MSInfo->setTemplateSpecializationKind(TSK);
1711 MSInfo->setPointOfInstantiation(PointOfInstantiation);
1712 } else if (ClassTemplateSpecializationDecl *Spec
1713 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
1714 Spec->setTemplateSpecializationKind(TSK);
1715 Spec->setPointOfInstantiation(PointOfInstantiation);
1718 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
1722 // Enter the scope of this instantiation. We don't use
1723 // PushDeclContext because we don't have a scope.
1724 ContextRAII SavedContext(*this, Instantiation);
1725 EnterExpressionEvaluationContext EvalContext(*this,
1726 Sema::PotentiallyEvaluated);
1728 // If this is an instantiation of a local class, merge this local
1729 // instantiation scope with the enclosing scope. Otherwise, every
1730 // instantiation of a class has its own local instantiation scope.
1731 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
1732 LocalInstantiationScope Scope(*this, MergeWithParentScope);
1734 // Pull attributes from the pattern onto the instantiation.
1735 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
1737 // Start the definition of this instantiation.
1738 Instantiation->startDefinition();
1740 Instantiation->setTagKind(Pattern->getTagKind());
1742 // Do substitution on the base class specifiers.
1743 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
1746 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
1747 llvm::SmallVector<Decl*, 4> Fields;
1748 llvm::SmallVector<std::pair<FieldDecl*, FieldDecl*>, 4>
1749 FieldsWithMemberInitializers;
1750 for (RecordDecl::decl_iterator Member = Pattern->decls_begin(),
1751 MemberEnd = Pattern->decls_end();
1752 Member != MemberEnd; ++Member) {
1753 // Don't instantiate members not belonging in this semantic context.
1756 // template <int i> class A {
1760 // 'class B' has the template as lexical context but semantically it is
1761 // introduced in namespace scope.
1762 if ((*Member)->getDeclContext() != Pattern)
1765 if ((*Member)->isInvalidDecl()) {
1770 Decl *NewMember = Instantiator.Visit(*Member);
1772 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
1773 Fields.push_back(Field);
1774 FieldDecl *OldField = cast<FieldDecl>(*Member);
1775 if (OldField->getInClassInitializer())
1776 FieldsWithMemberInitializers.push_back(std::make_pair(OldField,
1778 } else if (NewMember->isInvalidDecl())
1781 // FIXME: Eventually, a NULL return will mean that one of the
1782 // instantiations was a semantic disaster, and we'll want to set Invalid =
1783 // true. For now, we expect to skip some members that we can't yet handle.
1787 // Finish checking fields.
1788 ActOnFields(0, Instantiation->getLocation(), Instantiation,
1789 Fields.data(), Fields.size(), SourceLocation(), SourceLocation(),
1791 CheckCompletedCXXClass(Instantiation);
1793 // Attach any in-class member initializers now the class is complete.
1794 for (unsigned I = 0, N = FieldsWithMemberInitializers.size(); I != N; ++I) {
1795 FieldDecl *OldField = FieldsWithMemberInitializers[I].first;
1796 FieldDecl *NewField = FieldsWithMemberInitializers[I].second;
1797 Expr *OldInit = OldField->getInClassInitializer();
1798 ExprResult NewInit = SubstExpr(OldInit, TemplateArgs);
1800 // If the initialization is no longer dependent, check it now.
1801 if ((OldField->getType()->isDependentType() || OldInit->isTypeDependent())
1802 && !NewField->getType()->isDependentType()
1803 && !NewInit.get()->isTypeDependent()) {
1804 // FIXME: handle list-initialization
1805 SourceLocation EqualLoc = NewField->getLocation();
1806 NewInit = PerformCopyInitialization(
1807 InitializedEntity::InitializeMember(NewField), EqualLoc,
1810 if (!NewInit.isInvalid()) {
1811 CheckImplicitConversions(NewInit.get(), EqualLoc);
1813 // C++0x [class.base.init]p7:
1814 // The initialization of each base and member constitutes a
1816 NewInit = MaybeCreateExprWithCleanups(NewInit);
1820 if (NewInit.isInvalid())
1821 NewField->setInvalidDecl();
1823 NewField->setInClassInitializer(NewInit.release());
1826 if (!FieldsWithMemberInitializers.empty())
1827 ActOnFinishDelayedMemberInitializers(Instantiation);
1829 if (Instantiation->isInvalidDecl())
1832 // Instantiate any out-of-line class template partial
1833 // specializations now.
1834 for (TemplateDeclInstantiator::delayed_partial_spec_iterator
1835 P = Instantiator.delayed_partial_spec_begin(),
1836 PEnd = Instantiator.delayed_partial_spec_end();
1838 if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
1847 // Exit the scope of this instantiation.
1851 Consumer.HandleTagDeclDefinition(Instantiation);
1853 // Always emit the vtable for an explicit instantiation definition
1854 // of a polymorphic class template specialization.
1855 if (TSK == TSK_ExplicitInstantiationDefinition)
1856 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
1863 /// \brief A partial specialization whose template arguments have matched
1864 /// a given template-id.
1865 struct PartialSpecMatchResult {
1866 ClassTemplatePartialSpecializationDecl *Partial;
1867 TemplateArgumentList *Args;
1872 Sema::InstantiateClassTemplateSpecialization(
1873 SourceLocation PointOfInstantiation,
1874 ClassTemplateSpecializationDecl *ClassTemplateSpec,
1875 TemplateSpecializationKind TSK,
1877 // Perform the actual instantiation on the canonical declaration.
1878 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
1879 ClassTemplateSpec->getCanonicalDecl());
1881 // Check whether we have already instantiated or specialized this class
1882 // template specialization.
1883 if (ClassTemplateSpec->getSpecializationKind() != TSK_Undeclared) {
1884 if (ClassTemplateSpec->getSpecializationKind() ==
1885 TSK_ExplicitInstantiationDeclaration &&
1886 TSK == TSK_ExplicitInstantiationDefinition) {
1887 // An explicit instantiation definition follows an explicit instantiation
1888 // declaration (C++0x [temp.explicit]p10); go ahead and perform the
1889 // explicit instantiation.
1890 ClassTemplateSpec->setSpecializationKind(TSK);
1892 // If this is an explicit instantiation definition, mark the
1894 if (TSK == TSK_ExplicitInstantiationDefinition)
1895 MarkVTableUsed(PointOfInstantiation, ClassTemplateSpec, true);
1900 // We can only instantiate something that hasn't already been
1901 // instantiated or specialized. Fail without any diagnostics: our
1902 // caller will provide an error message.
1906 if (ClassTemplateSpec->isInvalidDecl())
1909 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
1910 CXXRecordDecl *Pattern = 0;
1912 // C++ [temp.class.spec.match]p1:
1913 // When a class template is used in a context that requires an
1914 // instantiation of the class, it is necessary to determine
1915 // whether the instantiation is to be generated using the primary
1916 // template or one of the partial specializations. This is done by
1917 // matching the template arguments of the class template
1918 // specialization with the template argument lists of the partial
1920 typedef PartialSpecMatchResult MatchResult;
1921 llvm::SmallVector<MatchResult, 4> Matched;
1922 llvm::SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1923 Template->getPartialSpecializations(PartialSpecs);
1924 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
1925 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
1926 TemplateDeductionInfo Info(Context, PointOfInstantiation);
1927 if (TemplateDeductionResult Result
1928 = DeduceTemplateArguments(Partial,
1929 ClassTemplateSpec->getTemplateArgs(),
1931 // FIXME: Store the failed-deduction information for use in
1932 // diagnostics, later.
1935 Matched.push_back(PartialSpecMatchResult());
1936 Matched.back().Partial = Partial;
1937 Matched.back().Args = Info.take();
1941 // If we're dealing with a member template where the template parameters
1942 // have been instantiated, this provides the original template parameters
1943 // from which the member template's parameters were instantiated.
1944 llvm::SmallVector<const NamedDecl *, 4> InstantiatedTemplateParameters;
1946 if (Matched.size() >= 1) {
1947 llvm::SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
1948 if (Matched.size() == 1) {
1949 // -- If exactly one matching specialization is found, the
1950 // instantiation is generated from that specialization.
1951 // We don't need to do anything for this.
1953 // -- If more than one matching specialization is found, the
1954 // partial order rules (14.5.4.2) are used to determine
1955 // whether one of the specializations is more specialized
1956 // than the others. If none of the specializations is more
1957 // specialized than all of the other matching
1958 // specializations, then the use of the class template is
1959 // ambiguous and the program is ill-formed.
1960 for (llvm::SmallVector<MatchResult, 4>::iterator P = Best + 1,
1961 PEnd = Matched.end();
1963 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
1964 PointOfInstantiation)
1969 // Determine if the best partial specialization is more specialized than
1971 bool Ambiguous = false;
1972 for (llvm::SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
1973 PEnd = Matched.end();
1976 getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
1977 PointOfInstantiation)
1985 // Partial ordering did not produce a clear winner. Complain.
1986 ClassTemplateSpec->setInvalidDecl();
1987 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
1988 << ClassTemplateSpec;
1990 // Print the matching partial specializations.
1991 for (llvm::SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
1992 PEnd = Matched.end();
1994 Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
1995 << getTemplateArgumentBindingsText(
1996 P->Partial->getTemplateParameters(),
2003 // Instantiate using the best class template partial specialization.
2004 ClassTemplatePartialSpecializationDecl *OrigPartialSpec = Best->Partial;
2005 while (OrigPartialSpec->getInstantiatedFromMember()) {
2006 // If we've found an explicit specialization of this class template,
2007 // stop here and use that as the pattern.
2008 if (OrigPartialSpec->isMemberSpecialization())
2011 OrigPartialSpec = OrigPartialSpec->getInstantiatedFromMember();
2014 Pattern = OrigPartialSpec;
2015 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
2017 // -- If no matches are found, the instantiation is generated
2018 // from the primary template.
2019 ClassTemplateDecl *OrigTemplate = Template;
2020 while (OrigTemplate->getInstantiatedFromMemberTemplate()) {
2021 // If we've found an explicit specialization of this class template,
2022 // stop here and use that as the pattern.
2023 if (OrigTemplate->isMemberSpecialization())
2026 OrigTemplate = OrigTemplate->getInstantiatedFromMemberTemplate();
2029 Pattern = OrigTemplate->getTemplatedDecl();
2032 bool Result = InstantiateClass(PointOfInstantiation, ClassTemplateSpec,
2034 getTemplateInstantiationArgs(ClassTemplateSpec),
2041 /// \brief Instantiates the definitions of all of the member
2042 /// of the given class, which is an instantiation of a class template
2043 /// or a member class of a template.
2045 Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
2046 CXXRecordDecl *Instantiation,
2047 const MultiLevelTemplateArgumentList &TemplateArgs,
2048 TemplateSpecializationKind TSK) {
2049 for (DeclContext::decl_iterator D = Instantiation->decls_begin(),
2050 DEnd = Instantiation->decls_end();
2052 bool SuppressNew = false;
2053 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(*D)) {
2054 if (FunctionDecl *Pattern
2055 = Function->getInstantiatedFromMemberFunction()) {
2056 MemberSpecializationInfo *MSInfo
2057 = Function->getMemberSpecializationInfo();
2058 assert(MSInfo && "No member specialization information?");
2059 if (MSInfo->getTemplateSpecializationKind()
2060 == TSK_ExplicitSpecialization)
2063 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2065 MSInfo->getTemplateSpecializationKind(),
2066 MSInfo->getPointOfInstantiation(),
2071 if (Function->isDefined())
2074 if (TSK == TSK_ExplicitInstantiationDefinition) {
2075 // C++0x [temp.explicit]p8:
2076 // An explicit instantiation definition that names a class template
2077 // specialization explicitly instantiates the class template
2078 // specialization and is only an explicit instantiation definition
2079 // of members whose definition is visible at the point of
2081 if (!Pattern->isDefined())
2084 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2086 InstantiateFunctionDefinition(PointOfInstantiation, Function);
2088 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2091 } else if (VarDecl *Var = dyn_cast<VarDecl>(*D)) {
2092 if (Var->isStaticDataMember()) {
2093 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
2094 assert(MSInfo && "No member specialization information?");
2095 if (MSInfo->getTemplateSpecializationKind()
2096 == TSK_ExplicitSpecialization)
2099 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2101 MSInfo->getTemplateSpecializationKind(),
2102 MSInfo->getPointOfInstantiation(),
2107 if (TSK == TSK_ExplicitInstantiationDefinition) {
2108 // C++0x [temp.explicit]p8:
2109 // An explicit instantiation definition that names a class template
2110 // specialization explicitly instantiates the class template
2111 // specialization and is only an explicit instantiation definition
2112 // of members whose definition is visible at the point of
2114 if (!Var->getInstantiatedFromStaticDataMember()
2115 ->getOutOfLineDefinition())
2118 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2119 InstantiateStaticDataMemberDefinition(PointOfInstantiation, Var);
2121 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2124 } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(*D)) {
2125 // Always skip the injected-class-name, along with any
2126 // redeclarations of nested classes, since both would cause us
2127 // to try to instantiate the members of a class twice.
2128 if (Record->isInjectedClassName() || Record->getPreviousDeclaration())
2131 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
2132 assert(MSInfo && "No member specialization information?");
2134 if (MSInfo->getTemplateSpecializationKind()
2135 == TSK_ExplicitSpecialization)
2138 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2140 MSInfo->getTemplateSpecializationKind(),
2141 MSInfo->getPointOfInstantiation(),
2146 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2147 assert(Pattern && "Missing instantiated-from-template information");
2149 if (!Record->getDefinition()) {
2150 if (!Pattern->getDefinition()) {
2151 // C++0x [temp.explicit]p8:
2152 // An explicit instantiation definition that names a class template
2153 // specialization explicitly instantiates the class template
2154 // specialization and is only an explicit instantiation definition
2155 // of members whose definition is visible at the point of
2157 if (TSK == TSK_ExplicitInstantiationDeclaration) {
2158 MSInfo->setTemplateSpecializationKind(TSK);
2159 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2165 InstantiateClass(PointOfInstantiation, Record, Pattern,
2169 if (TSK == TSK_ExplicitInstantiationDefinition &&
2170 Record->getTemplateSpecializationKind() ==
2171 TSK_ExplicitInstantiationDeclaration) {
2172 Record->setTemplateSpecializationKind(TSK);
2173 MarkVTableUsed(PointOfInstantiation, Record, true);
2177 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
2179 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
2185 /// \brief Instantiate the definitions of all of the members of the
2186 /// given class template specialization, which was named as part of an
2187 /// explicit instantiation.
2189 Sema::InstantiateClassTemplateSpecializationMembers(
2190 SourceLocation PointOfInstantiation,
2191 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2192 TemplateSpecializationKind TSK) {
2193 // C++0x [temp.explicit]p7:
2194 // An explicit instantiation that names a class template
2195 // specialization is an explicit instantion of the same kind
2196 // (declaration or definition) of each of its members (not
2197 // including members inherited from base classes) that has not
2198 // been previously explicitly specialized in the translation unit
2199 // containing the explicit instantiation, except as described
2201 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
2202 getTemplateInstantiationArgs(ClassTemplateSpec),
2207 Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
2211 TemplateInstantiator Instantiator(*this, TemplateArgs,
2214 return Instantiator.TransformStmt(S);
2218 Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
2222 TemplateInstantiator Instantiator(*this, TemplateArgs,
2225 return Instantiator.TransformExpr(E);
2228 bool Sema::SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall,
2229 const MultiLevelTemplateArgumentList &TemplateArgs,
2230 llvm::SmallVectorImpl<Expr *> &Outputs) {
2234 TemplateInstantiator Instantiator(*this, TemplateArgs,
2237 return Instantiator.TransformExprs(Exprs, NumExprs, IsCall, Outputs);
2240 NestedNameSpecifierLoc
2241 Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
2242 const MultiLevelTemplateArgumentList &TemplateArgs) {
2244 return NestedNameSpecifierLoc();
2246 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
2248 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
2251 /// \brief Do template substitution on declaration name info.
2253 Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
2254 const MultiLevelTemplateArgumentList &TemplateArgs) {
2255 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
2256 NameInfo.getName());
2257 return Instantiator.TransformDeclarationNameInfo(NameInfo);
2261 Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,
2262 TemplateName Name, SourceLocation Loc,
2263 const MultiLevelTemplateArgumentList &TemplateArgs) {
2264 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
2267 SS.Adopt(QualifierLoc);
2268 return Instantiator.TransformTemplateName(SS, Name, Loc);
2271 bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
2272 TemplateArgumentListInfo &Result,
2273 const MultiLevelTemplateArgumentList &TemplateArgs) {
2274 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
2277 return Instantiator.TransformTemplateArguments(Args, NumArgs, Result);
2280 llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
2281 LocalInstantiationScope::findInstantiationOf(const Decl *D) {
2282 for (LocalInstantiationScope *Current = this; Current;
2283 Current = Current->Outer) {
2285 // Check if we found something within this scope.
2286 const Decl *CheckD = D;
2288 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
2289 if (Found != Current->LocalDecls.end())
2290 return &Found->second;
2292 // If this is a tag declaration, it's possible that we need to look for
2293 // a previous declaration.
2294 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
2295 CheckD = Tag->getPreviousDeclaration();
2300 // If we aren't combined with our outer scope, we're done.
2301 if (!Current->CombineWithOuterScope)
2305 // If we didn't find the decl, then we either have a sema bug, or we have a
2306 // forward reference to a label declaration. Return null to indicate that
2307 // we have an uninstantiated label.
2308 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
2312 void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
2313 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
2314 if (Stored.isNull())
2316 else if (Stored.is<Decl *>()) {
2317 assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
2320 LocalDecls[D].get<DeclArgumentPack *>()->push_back(Inst);
2323 void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
2325 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
2326 Pack->push_back(Inst);
2329 void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
2330 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
2331 assert(Stored.isNull() && "Already instantiated this local");
2332 DeclArgumentPack *Pack = new DeclArgumentPack;
2334 ArgumentPacks.push_back(Pack);
2337 void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
2338 const TemplateArgument *ExplicitArgs,
2339 unsigned NumExplicitArgs) {
2340 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
2341 "Already have a partially-substituted pack");
2342 assert((!PartiallySubstitutedPack
2343 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
2344 "Wrong number of arguments in partially-substituted pack");
2345 PartiallySubstitutedPack = Pack;
2346 ArgsInPartiallySubstitutedPack = ExplicitArgs;
2347 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
2350 NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
2351 const TemplateArgument **ExplicitArgs,
2352 unsigned *NumExplicitArgs) const {
2355 if (NumExplicitArgs)
2356 *NumExplicitArgs = 0;
2358 for (const LocalInstantiationScope *Current = this; Current;
2359 Current = Current->Outer) {
2360 if (Current->PartiallySubstitutedPack) {
2362 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
2363 if (NumExplicitArgs)
2364 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
2366 return Current->PartiallySubstitutedPack;
2369 if (!Current->CombineWithOuterScope)