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/Lookup.h"
17 #include "clang/Sema/Template.h"
18 #include "clang/Sema/TemplateDeduction.h"
19 #include "clang/AST/ASTConsumer.h"
20 #include "clang/AST/ASTContext.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/Basic/LangOptions.h"
25 using namespace clang;
28 //===----------------------------------------------------------------------===/
29 // Template Instantiation Support
30 //===----------------------------------------------------------------------===/
32 /// \brief Retrieve the template argument list(s) that should be used to
33 /// instantiate the definition of the given declaration.
35 /// \param D the declaration for which we are computing template instantiation
38 /// \param Innermost if non-NULL, the innermost template argument list.
40 /// \param RelativeToPrimary true if we should get the template
41 /// arguments relative to the primary template, even when we're
42 /// dealing with a specialization. This is only relevant for function
43 /// template specializations.
45 /// \param Pattern If non-NULL, indicates the pattern from which we will be
46 /// instantiating the definition of the given declaration, \p D. This is
47 /// used to determine the proper set of template instantiation arguments for
48 /// friend function template specializations.
49 MultiLevelTemplateArgumentList
50 Sema::getTemplateInstantiationArgs(NamedDecl *D,
51 const TemplateArgumentList *Innermost,
52 bool RelativeToPrimary,
53 const FunctionDecl *Pattern) {
54 // Accumulate the set of template argument lists in this structure.
55 MultiLevelTemplateArgumentList Result;
58 Result.addOuterTemplateArguments(Innermost);
60 DeclContext *Ctx = dyn_cast<DeclContext>(D);
62 Ctx = D->getDeclContext();
64 while (!Ctx->isFileContext()) {
65 // Add template arguments from a class template instantiation.
66 if (ClassTemplateSpecializationDecl *Spec
67 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx)) {
68 // We're done when we hit an explicit specialization.
69 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
70 !isa<ClassTemplatePartialSpecializationDecl>(Spec))
73 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
75 // If this class template specialization was instantiated from a
76 // specialized member that is a class template, we're done.
77 assert(Spec->getSpecializedTemplate() && "No class template?");
78 if (Spec->getSpecializedTemplate()->isMemberSpecialization())
81 // Add template arguments from a function template specialization.
82 else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) {
83 if (!RelativeToPrimary &&
84 Function->getTemplateSpecializationKind()
85 == TSK_ExplicitSpecialization)
88 if (const TemplateArgumentList *TemplateArgs
89 = Function->getTemplateSpecializationArgs()) {
90 // Add the template arguments for this specialization.
91 Result.addOuterTemplateArguments(TemplateArgs);
93 // If this function was instantiated from a specialized member that is
94 // a function template, we're done.
95 assert(Function->getPrimaryTemplate() && "No function template?");
96 if (Function->getPrimaryTemplate()->isMemberSpecialization())
98 } else if (FunctionTemplateDecl *FunTmpl
99 = Function->getDescribedFunctionTemplate()) {
100 // Add the "injected" template arguments.
101 std::pair<const TemplateArgument *, unsigned>
102 Injected = FunTmpl->getInjectedTemplateArgs();
103 Result.addOuterTemplateArguments(Injected.first, Injected.second);
106 // If this is a friend declaration and it declares an entity at
107 // namespace scope, take arguments from its lexical parent
108 // instead of its semantic parent, unless of course the pattern we're
109 // instantiating actually comes from the file's context!
110 if (Function->getFriendObjectKind() &&
111 Function->getDeclContext()->isFileContext() &&
112 (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
113 Ctx = Function->getLexicalDeclContext();
114 RelativeToPrimary = false;
117 } else if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Ctx)) {
118 if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
119 QualType T = ClassTemplate->getInjectedClassNameSpecialization();
120 const TemplateSpecializationType *TST
121 = cast<TemplateSpecializationType>(Context.getCanonicalType(T));
122 Result.addOuterTemplateArguments(TST->getArgs(), TST->getNumArgs());
123 if (ClassTemplate->isMemberSpecialization())
128 Ctx = Ctx->getParent();
129 RelativeToPrimary = false;
135 bool Sema::ActiveTemplateInstantiation::isInstantiationRecord() const {
137 case TemplateInstantiation:
138 case DefaultTemplateArgumentInstantiation:
139 case DefaultFunctionArgumentInstantiation:
142 case ExplicitTemplateArgumentSubstitution:
143 case DeducedTemplateArgumentSubstitution:
144 case PriorTemplateArgumentSubstitution:
145 case DefaultTemplateArgumentChecking:
152 Sema::InstantiatingTemplate::
153 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
155 SourceRange InstantiationRange)
157 SavedInNonInstantiationSFINAEContext(
158 SemaRef.InNonInstantiationSFINAEContext)
160 Invalid = CheckInstantiationDepth(PointOfInstantiation,
163 ActiveTemplateInstantiation Inst;
164 Inst.Kind = ActiveTemplateInstantiation::TemplateInstantiation;
165 Inst.PointOfInstantiation = PointOfInstantiation;
166 Inst.Entity = reinterpret_cast<uintptr_t>(Entity);
167 Inst.TemplateArgs = 0;
168 Inst.NumTemplateArgs = 0;
169 Inst.InstantiationRange = InstantiationRange;
170 SemaRef.InNonInstantiationSFINAEContext = false;
171 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
175 Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
176 SourceLocation PointOfInstantiation,
177 TemplateDecl *Template,
178 const TemplateArgument *TemplateArgs,
179 unsigned NumTemplateArgs,
180 SourceRange InstantiationRange)
182 SavedInNonInstantiationSFINAEContext(
183 SemaRef.InNonInstantiationSFINAEContext)
185 Invalid = CheckInstantiationDepth(PointOfInstantiation,
188 ActiveTemplateInstantiation Inst;
190 = ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation;
191 Inst.PointOfInstantiation = PointOfInstantiation;
192 Inst.Entity = reinterpret_cast<uintptr_t>(Template);
193 Inst.TemplateArgs = TemplateArgs;
194 Inst.NumTemplateArgs = NumTemplateArgs;
195 Inst.InstantiationRange = InstantiationRange;
196 SemaRef.InNonInstantiationSFINAEContext = false;
197 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
201 Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
202 SourceLocation PointOfInstantiation,
203 FunctionTemplateDecl *FunctionTemplate,
204 const TemplateArgument *TemplateArgs,
205 unsigned NumTemplateArgs,
206 ActiveTemplateInstantiation::InstantiationKind Kind,
207 sema::TemplateDeductionInfo &DeductionInfo,
208 SourceRange InstantiationRange)
210 SavedInNonInstantiationSFINAEContext(
211 SemaRef.InNonInstantiationSFINAEContext)
213 Invalid = CheckInstantiationDepth(PointOfInstantiation,
216 ActiveTemplateInstantiation Inst;
218 Inst.PointOfInstantiation = PointOfInstantiation;
219 Inst.Entity = reinterpret_cast<uintptr_t>(FunctionTemplate);
220 Inst.TemplateArgs = TemplateArgs;
221 Inst.NumTemplateArgs = NumTemplateArgs;
222 Inst.DeductionInfo = &DeductionInfo;
223 Inst.InstantiationRange = InstantiationRange;
224 SemaRef.InNonInstantiationSFINAEContext = false;
225 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
227 if (!Inst.isInstantiationRecord())
228 ++SemaRef.NonInstantiationEntries;
232 Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
233 SourceLocation PointOfInstantiation,
234 ClassTemplatePartialSpecializationDecl *PartialSpec,
235 const TemplateArgument *TemplateArgs,
236 unsigned NumTemplateArgs,
237 sema::TemplateDeductionInfo &DeductionInfo,
238 SourceRange InstantiationRange)
240 SavedInNonInstantiationSFINAEContext(
241 SemaRef.InNonInstantiationSFINAEContext)
245 ActiveTemplateInstantiation Inst;
246 Inst.Kind = ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution;
247 Inst.PointOfInstantiation = PointOfInstantiation;
248 Inst.Entity = reinterpret_cast<uintptr_t>(PartialSpec);
249 Inst.TemplateArgs = TemplateArgs;
250 Inst.NumTemplateArgs = NumTemplateArgs;
251 Inst.DeductionInfo = &DeductionInfo;
252 Inst.InstantiationRange = InstantiationRange;
253 SemaRef.InNonInstantiationSFINAEContext = false;
254 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
256 assert(!Inst.isInstantiationRecord());
257 ++SemaRef.NonInstantiationEntries;
260 Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
261 SourceLocation PointOfInstantiation,
263 const TemplateArgument *TemplateArgs,
264 unsigned NumTemplateArgs,
265 SourceRange InstantiationRange)
267 SavedInNonInstantiationSFINAEContext(
268 SemaRef.InNonInstantiationSFINAEContext)
270 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
273 ActiveTemplateInstantiation Inst;
275 = ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
276 Inst.PointOfInstantiation = PointOfInstantiation;
277 Inst.Entity = reinterpret_cast<uintptr_t>(Param);
278 Inst.TemplateArgs = TemplateArgs;
279 Inst.NumTemplateArgs = NumTemplateArgs;
280 Inst.InstantiationRange = InstantiationRange;
281 SemaRef.InNonInstantiationSFINAEContext = false;
282 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
286 Sema::InstantiatingTemplate::
287 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
289 NonTypeTemplateParmDecl *Param,
290 const TemplateArgument *TemplateArgs,
291 unsigned NumTemplateArgs,
292 SourceRange InstantiationRange)
294 SavedInNonInstantiationSFINAEContext(
295 SemaRef.InNonInstantiationSFINAEContext)
299 ActiveTemplateInstantiation Inst;
300 Inst.Kind = ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution;
301 Inst.PointOfInstantiation = PointOfInstantiation;
302 Inst.Template = Template;
303 Inst.Entity = reinterpret_cast<uintptr_t>(Param);
304 Inst.TemplateArgs = TemplateArgs;
305 Inst.NumTemplateArgs = NumTemplateArgs;
306 Inst.InstantiationRange = InstantiationRange;
307 SemaRef.InNonInstantiationSFINAEContext = false;
308 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
310 assert(!Inst.isInstantiationRecord());
311 ++SemaRef.NonInstantiationEntries;
314 Sema::InstantiatingTemplate::
315 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
317 TemplateTemplateParmDecl *Param,
318 const TemplateArgument *TemplateArgs,
319 unsigned NumTemplateArgs,
320 SourceRange InstantiationRange)
322 SavedInNonInstantiationSFINAEContext(
323 SemaRef.InNonInstantiationSFINAEContext)
326 ActiveTemplateInstantiation Inst;
327 Inst.Kind = ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution;
328 Inst.PointOfInstantiation = PointOfInstantiation;
329 Inst.Template = Template;
330 Inst.Entity = reinterpret_cast<uintptr_t>(Param);
331 Inst.TemplateArgs = TemplateArgs;
332 Inst.NumTemplateArgs = NumTemplateArgs;
333 Inst.InstantiationRange = InstantiationRange;
334 SemaRef.InNonInstantiationSFINAEContext = false;
335 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
337 assert(!Inst.isInstantiationRecord());
338 ++SemaRef.NonInstantiationEntries;
341 Sema::InstantiatingTemplate::
342 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
343 TemplateDecl *Template,
345 const TemplateArgument *TemplateArgs,
346 unsigned NumTemplateArgs,
347 SourceRange InstantiationRange)
349 SavedInNonInstantiationSFINAEContext(
350 SemaRef.InNonInstantiationSFINAEContext)
354 ActiveTemplateInstantiation Inst;
355 Inst.Kind = ActiveTemplateInstantiation::DefaultTemplateArgumentChecking;
356 Inst.PointOfInstantiation = PointOfInstantiation;
357 Inst.Template = Template;
358 Inst.Entity = reinterpret_cast<uintptr_t>(Param);
359 Inst.TemplateArgs = TemplateArgs;
360 Inst.NumTemplateArgs = NumTemplateArgs;
361 Inst.InstantiationRange = InstantiationRange;
362 SemaRef.InNonInstantiationSFINAEContext = false;
363 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
365 assert(!Inst.isInstantiationRecord());
366 ++SemaRef.NonInstantiationEntries;
369 void Sema::InstantiatingTemplate::Clear() {
371 if (!SemaRef.ActiveTemplateInstantiations.back().isInstantiationRecord()) {
372 assert(SemaRef.NonInstantiationEntries > 0);
373 --SemaRef.NonInstantiationEntries;
375 SemaRef.InNonInstantiationSFINAEContext
376 = SavedInNonInstantiationSFINAEContext;
377 SemaRef.ActiveTemplateInstantiations.pop_back();
382 bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
383 SourceLocation PointOfInstantiation,
384 SourceRange InstantiationRange) {
385 assert(SemaRef.NonInstantiationEntries <=
386 SemaRef.ActiveTemplateInstantiations.size());
387 if ((SemaRef.ActiveTemplateInstantiations.size() -
388 SemaRef.NonInstantiationEntries)
389 <= SemaRef.getLangOptions().InstantiationDepth)
392 SemaRef.Diag(PointOfInstantiation,
393 diag::err_template_recursion_depth_exceeded)
394 << SemaRef.getLangOptions().InstantiationDepth
395 << InstantiationRange;
396 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
397 << SemaRef.getLangOptions().InstantiationDepth;
401 /// \brief Prints the current instantiation stack through a series of
403 void Sema::PrintInstantiationStack() {
404 // Determine which template instantiations to skip, if any.
405 unsigned SkipStart = ActiveTemplateInstantiations.size(), SkipEnd = SkipStart;
406 unsigned Limit = Diags.getTemplateBacktraceLimit();
407 if (Limit && Limit < ActiveTemplateInstantiations.size()) {
408 SkipStart = Limit / 2 + Limit % 2;
409 SkipEnd = ActiveTemplateInstantiations.size() - Limit / 2;
412 // FIXME: In all of these cases, we need to show the template arguments
413 unsigned InstantiationIdx = 0;
414 for (llvm::SmallVector<ActiveTemplateInstantiation, 16>::reverse_iterator
415 Active = ActiveTemplateInstantiations.rbegin(),
416 ActiveEnd = ActiveTemplateInstantiations.rend();
418 ++Active, ++InstantiationIdx) {
419 // Skip this instantiation?
420 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
421 if (InstantiationIdx == SkipStart) {
422 // Note that we're skipping instantiations.
423 Diags.Report(Active->PointOfInstantiation,
424 diag::note_instantiation_contexts_suppressed)
425 << unsigned(ActiveTemplateInstantiations.size() - Limit);
430 switch (Active->Kind) {
431 case ActiveTemplateInstantiation::TemplateInstantiation: {
432 Decl *D = reinterpret_cast<Decl *>(Active->Entity);
433 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
434 unsigned DiagID = diag::note_template_member_class_here;
435 if (isa<ClassTemplateSpecializationDecl>(Record))
436 DiagID = diag::note_template_class_instantiation_here;
437 Diags.Report(Active->PointOfInstantiation, DiagID)
438 << Context.getTypeDeclType(Record)
439 << Active->InstantiationRange;
440 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
442 if (Function->getPrimaryTemplate())
443 DiagID = diag::note_function_template_spec_here;
445 DiagID = diag::note_template_member_function_here;
446 Diags.Report(Active->PointOfInstantiation, DiagID)
448 << Active->InstantiationRange;
450 Diags.Report(Active->PointOfInstantiation,
451 diag::note_template_static_data_member_def_here)
453 << Active->InstantiationRange;
458 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation: {
459 TemplateDecl *Template = cast<TemplateDecl>((Decl *)Active->Entity);
460 std::string TemplateArgsStr
461 = TemplateSpecializationType::PrintTemplateArgumentList(
462 Active->TemplateArgs,
463 Active->NumTemplateArgs,
464 Context.PrintingPolicy);
465 Diags.Report(Active->PointOfInstantiation,
466 diag::note_default_arg_instantiation_here)
467 << (Template->getNameAsString() + TemplateArgsStr)
468 << Active->InstantiationRange;
472 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution: {
473 FunctionTemplateDecl *FnTmpl
474 = cast<FunctionTemplateDecl>((Decl *)Active->Entity);
475 Diags.Report(Active->PointOfInstantiation,
476 diag::note_explicit_template_arg_substitution_here)
478 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
479 Active->TemplateArgs,
480 Active->NumTemplateArgs)
481 << Active->InstantiationRange;
485 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
486 if (ClassTemplatePartialSpecializationDecl *PartialSpec
487 = dyn_cast<ClassTemplatePartialSpecializationDecl>(
488 (Decl *)Active->Entity)) {
489 Diags.Report(Active->PointOfInstantiation,
490 diag::note_partial_spec_deduct_instantiation_here)
491 << Context.getTypeDeclType(PartialSpec)
492 << getTemplateArgumentBindingsText(
493 PartialSpec->getTemplateParameters(),
494 Active->TemplateArgs,
495 Active->NumTemplateArgs)
496 << Active->InstantiationRange;
498 FunctionTemplateDecl *FnTmpl
499 = cast<FunctionTemplateDecl>((Decl *)Active->Entity);
500 Diags.Report(Active->PointOfInstantiation,
501 diag::note_function_template_deduction_instantiation_here)
503 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
504 Active->TemplateArgs,
505 Active->NumTemplateArgs)
506 << Active->InstantiationRange;
510 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation: {
511 ParmVarDecl *Param = cast<ParmVarDecl>((Decl *)Active->Entity);
512 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
514 std::string TemplateArgsStr
515 = TemplateSpecializationType::PrintTemplateArgumentList(
516 Active->TemplateArgs,
517 Active->NumTemplateArgs,
518 Context.PrintingPolicy);
519 Diags.Report(Active->PointOfInstantiation,
520 diag::note_default_function_arg_instantiation_here)
521 << (FD->getNameAsString() + TemplateArgsStr)
522 << Active->InstantiationRange;
526 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution: {
527 NamedDecl *Parm = cast<NamedDecl>((Decl *)Active->Entity);
529 if (!Parm->getName().empty())
530 Name = std::string(" '") + Parm->getName().str() + "'";
532 TemplateParameterList *TemplateParams = 0;
533 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
534 TemplateParams = Template->getTemplateParameters();
537 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
538 ->getTemplateParameters();
539 Diags.Report(Active->PointOfInstantiation,
540 diag::note_prior_template_arg_substitution)
541 << isa<TemplateTemplateParmDecl>(Parm)
543 << getTemplateArgumentBindingsText(TemplateParams,
544 Active->TemplateArgs,
545 Active->NumTemplateArgs)
546 << Active->InstantiationRange;
550 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking: {
551 TemplateParameterList *TemplateParams = 0;
552 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
553 TemplateParams = Template->getTemplateParameters();
556 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
557 ->getTemplateParameters();
559 Diags.Report(Active->PointOfInstantiation,
560 diag::note_template_default_arg_checking)
561 << getTemplateArgumentBindingsText(TemplateParams,
562 Active->TemplateArgs,
563 Active->NumTemplateArgs)
564 << Active->InstantiationRange;
571 llvm::Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
572 using llvm::SmallVector;
573 if (InNonInstantiationSFINAEContext)
574 return llvm::Optional<TemplateDeductionInfo *>(0);
576 for (SmallVector<ActiveTemplateInstantiation, 16>::const_reverse_iterator
577 Active = ActiveTemplateInstantiations.rbegin(),
578 ActiveEnd = ActiveTemplateInstantiations.rend();
582 switch(Active->Kind) {
583 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation:
584 case ActiveTemplateInstantiation::TemplateInstantiation:
585 // This is a template instantiation, so there is no SFINAE.
586 return llvm::Optional<TemplateDeductionInfo *>();
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;
605 return llvm::Optional<TemplateDeductionInfo *>();
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 const UnexpandedParameterPack *Unexpanded,
663 unsigned NumUnexpanded,
665 bool &RetainExpansion,
666 llvm::Optional<unsigned> &NumExpansions) {
667 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
668 PatternRange, Unexpanded,
676 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
677 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
680 TemplateArgument ForgetPartiallySubstitutedPack() {
681 TemplateArgument Result;
682 if (NamedDecl *PartialPack
683 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
684 MultiLevelTemplateArgumentList &TemplateArgs
685 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
686 unsigned Depth, Index;
687 llvm::tie(Depth, Index) = getDepthAndIndex(PartialPack);
688 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
689 Result = TemplateArgs(Depth, Index);
690 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
697 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
701 if (NamedDecl *PartialPack
702 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
703 MultiLevelTemplateArgumentList &TemplateArgs
704 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
705 unsigned Depth, Index;
706 llvm::tie(Depth, Index) = getDepthAndIndex(PartialPack);
707 TemplateArgs.setArgument(Depth, Index, Arg);
711 /// \brief Transform the given declaration by instantiating a reference to
712 /// this declaration.
713 Decl *TransformDecl(SourceLocation Loc, Decl *D);
715 /// \brief Transform the definition of the given declaration by
716 /// instantiating it.
717 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
719 /// \bried Transform the first qualifier within a scope by instantiating the
721 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
723 /// \brief Rebuild the exception declaration and register the declaration
724 /// as an instantiated local.
725 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
726 TypeSourceInfo *Declarator,
727 SourceLocation StartLoc,
728 SourceLocation NameLoc,
729 IdentifierInfo *Name);
731 /// \brief Rebuild the Objective-C exception declaration and register the
732 /// declaration as an instantiated local.
733 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
734 TypeSourceInfo *TSInfo, QualType T);
736 /// \brief Check for tag mismatches when instantiating an
738 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
739 ElaboratedTypeKeyword Keyword,
740 NestedNameSpecifierLoc QualifierLoc,
743 TemplateName TransformTemplateName(CXXScopeSpec &SS,
745 SourceLocation NameLoc,
746 QualType ObjectType = QualType(),
747 NamedDecl *FirstQualifierInScope = 0);
749 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
750 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
751 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
752 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
753 NonTypeTemplateParmDecl *D);
754 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
755 SubstNonTypeTemplateParmPackExpr *E);
757 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
758 FunctionProtoTypeLoc TL);
759 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
761 llvm::Optional<unsigned> NumExpansions);
763 /// \brief Transforms a template type parameter type by performing
764 /// substitution of the corresponding template type argument.
765 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
766 TemplateTypeParmTypeLoc TL);
768 /// \brief Transforms an already-substituted template type parameter pack
769 /// into either itself (if we aren't substituting into its pack expansion)
770 /// or the appropriate substituted argument.
771 QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
772 SubstTemplateTypeParmPackTypeLoc TL);
774 ExprResult TransformCallExpr(CallExpr *CE) {
775 getSema().CallsUndergoingInstantiation.push_back(CE);
777 TreeTransform<TemplateInstantiator>::TransformCallExpr(CE);
778 getSema().CallsUndergoingInstantiation.pop_back();
784 bool TemplateInstantiator::AlreadyTransformed(QualType T) {
788 if (T->isDependentType() || T->isVariablyModifiedType())
791 getSema().MarkDeclarationsReferencedInType(Loc, T);
795 Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
799 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
800 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
801 // If the corresponding template argument is NULL or non-existent, it's
802 // because we are performing instantiation from explicitly-specified
803 // template arguments in a function template, but there were some
804 // arguments left unspecified.
805 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
809 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
811 if (TTP->isParameterPack()) {
812 assert(Arg.getKind() == TemplateArgument::Pack &&
813 "Missing argument pack");
815 assert(getSema().ArgumentPackSubstitutionIndex >= 0);
816 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
817 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
820 TemplateName Template = Arg.getAsTemplate();
821 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
822 "Wrong kind of template template argument");
823 return Template.getAsTemplateDecl();
826 // Fall through to find the instantiated declaration for this template
827 // template parameter.
830 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
833 Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
834 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
838 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
843 TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
844 SourceLocation Loc) {
845 // If the first part of the nested-name-specifier was a template type
846 // parameter, instantiate that type parameter down to a tag type.
847 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
848 const TemplateTypeParmType *TTP
849 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
851 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
852 // FIXME: This needs testing w/ member access expressions.
853 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
855 if (TTP->isParameterPack()) {
856 assert(Arg.getKind() == TemplateArgument::Pack &&
857 "Missing argument pack");
859 if (getSema().ArgumentPackSubstitutionIndex == -1)
862 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
863 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
866 QualType T = Arg.getAsType();
868 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
870 if (const TagType *Tag = T->getAs<TagType>())
871 return Tag->getDecl();
873 // The resulting type is not a tag; complain.
874 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
879 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
883 TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
884 TypeSourceInfo *Declarator,
885 SourceLocation StartLoc,
886 SourceLocation NameLoc,
887 IdentifierInfo *Name) {
888 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
889 StartLoc, NameLoc, Name);
891 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
895 VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
896 TypeSourceInfo *TSInfo,
898 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
900 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
905 TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
906 ElaboratedTypeKeyword Keyword,
907 NestedNameSpecifierLoc QualifierLoc,
909 if (const TagType *TT = T->getAs<TagType>()) {
910 TagDecl* TD = TT->getDecl();
912 SourceLocation TagLocation = KeywordLoc;
914 // FIXME: type might be anonymous.
915 IdentifierInfo *Id = TD->getIdentifier();
917 // TODO: should we even warn on struct/class mismatches for this? Seems
918 // like it's likely to produce a lot of spurious errors.
919 if (Keyword != ETK_None && Keyword != ETK_Typename) {
920 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
921 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, TagLocation, *Id)) {
922 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
924 << FixItHint::CreateReplacement(SourceRange(TagLocation),
926 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
931 return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(KeywordLoc,
937 TemplateName TemplateInstantiator::TransformTemplateName(CXXScopeSpec &SS,
939 SourceLocation NameLoc,
941 NamedDecl *FirstQualifierInScope) {
942 if (TemplateTemplateParmDecl *TTP
943 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
944 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
945 // If the corresponding template argument is NULL or non-existent, it's
946 // because we are performing instantiation from explicitly-specified
947 // template arguments in a function template, but there were some
948 // arguments left unspecified.
949 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
953 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
955 if (TTP->isParameterPack()) {
956 assert(Arg.getKind() == TemplateArgument::Pack &&
957 "Missing argument pack");
959 if (getSema().ArgumentPackSubstitutionIndex == -1) {
960 // We have the template argument pack to substitute, but we're not
961 // actually expanding the enclosing pack expansion yet. So, just
962 // keep the entire argument pack.
963 return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg);
966 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
967 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
970 TemplateName Template = Arg.getAsTemplate();
971 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
972 "Wrong kind of template template argument");
974 // We don't ever want to substitute for a qualified template name, since
975 // the qualifier is handled separately. So, look through the qualified
976 // template name to its underlying declaration.
977 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
978 Template = TemplateName(QTN->getTemplateDecl());
984 if (SubstTemplateTemplateParmPackStorage *SubstPack
985 = Name.getAsSubstTemplateTemplateParmPack()) {
986 if (getSema().ArgumentPackSubstitutionIndex == -1)
989 const TemplateArgument &ArgPack = SubstPack->getArgumentPack();
990 assert(getSema().ArgumentPackSubstitutionIndex < (int)ArgPack.pack_size() &&
991 "Pack substitution index out-of-range");
992 return ArgPack.pack_begin()[getSema().ArgumentPackSubstitutionIndex]
996 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
997 FirstQualifierInScope);
1001 TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
1002 if (!E->isTypeDependent())
1003 return SemaRef.Owned(E);
1005 FunctionDecl *currentDecl = getSema().getCurFunctionDecl();
1006 assert(currentDecl && "Must have current function declaration when "
1009 PredefinedExpr::IdentType IT = E->getIdentType();
1011 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
1013 llvm::APInt LengthI(32, Length + 1);
1014 QualType ResTy = getSema().Context.CharTy.withConst();
1015 ResTy = getSema().Context.getConstantArrayType(ResTy, LengthI,
1016 ArrayType::Normal, 0);
1017 PredefinedExpr *PE =
1018 new (getSema().Context) PredefinedExpr(E->getLocation(), ResTy, IT);
1019 return getSema().Owned(PE);
1023 TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
1024 NonTypeTemplateParmDecl *NTTP) {
1025 // If the corresponding template argument is NULL or non-existent, it's
1026 // because we are performing instantiation from explicitly-specified
1027 // template arguments in a function template, but there were some
1028 // arguments left unspecified.
1029 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
1030 NTTP->getPosition()))
1031 return SemaRef.Owned(E);
1033 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
1034 if (NTTP->isParameterPack()) {
1035 assert(Arg.getKind() == TemplateArgument::Pack &&
1036 "Missing argument pack");
1038 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1039 // We have an argument pack, but we can't select a particular argument
1040 // out of it yet. Therefore, we'll build an expression to hold on to that
1042 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1044 NTTP->getDeclName());
1045 if (TargetType.isNull())
1048 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(TargetType,
1054 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
1055 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
1058 // The template argument itself might be an expression, in which
1059 // case we just return that expression.
1060 if (Arg.getKind() == TemplateArgument::Expression)
1061 return SemaRef.Owned(Arg.getAsExpr());
1063 if (Arg.getKind() == TemplateArgument::Declaration) {
1064 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
1066 // Find the instantiation of the template argument. This is
1067 // required for nested templates.
1068 VD = cast_or_null<ValueDecl>(
1069 getSema().FindInstantiatedDecl(E->getLocation(),
1074 // Derive the type we want the substituted decl to have. This had
1075 // better be non-dependent, or these checks will have serious problems.
1076 QualType TargetType;
1077 if (NTTP->isExpandedParameterPack())
1078 TargetType = NTTP->getExpansionType(
1079 getSema().ArgumentPackSubstitutionIndex);
1080 else if (NTTP->isParameterPack() &&
1081 isa<PackExpansionType>(NTTP->getType())) {
1082 TargetType = SemaRef.SubstType(
1083 cast<PackExpansionType>(NTTP->getType())->getPattern(),
1084 TemplateArgs, E->getLocation(),
1085 NTTP->getDeclName());
1087 TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1088 E->getLocation(), NTTP->getDeclName());
1089 assert(!TargetType.isNull() && "type substitution failed for param type");
1090 assert(!TargetType->isDependentType() && "param type still dependent");
1091 return SemaRef.BuildExpressionFromDeclTemplateArgument(Arg,
1096 return SemaRef.BuildExpressionFromIntegralTemplateArgument(Arg,
1097 E->getSourceRange().getBegin());
1101 TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
1102 SubstNonTypeTemplateParmPackExpr *E) {
1103 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1104 // We aren't expanding the parameter pack, so just return ourselves.
1105 return getSema().Owned(E);
1108 const TemplateArgument &ArgPack = E->getArgumentPack();
1109 unsigned Index = (unsigned)getSema().ArgumentPackSubstitutionIndex;
1110 assert(Index < ArgPack.pack_size() && "Substitution index out-of-range");
1112 const TemplateArgument &Arg = ArgPack.pack_begin()[Index];
1113 if (Arg.getKind() == TemplateArgument::Expression)
1114 return SemaRef.Owned(Arg.getAsExpr());
1116 if (Arg.getKind() == TemplateArgument::Declaration) {
1117 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
1119 // Find the instantiation of the template argument. This is
1120 // required for nested templates.
1121 VD = cast_or_null<ValueDecl>(
1122 getSema().FindInstantiatedDecl(E->getParameterPackLocation(),
1128 NonTypeTemplateParmDecl *NTTP = E->getParameterPack();
1129 if (NTTP->isExpandedParameterPack())
1130 T = NTTP->getExpansionType(getSema().ArgumentPackSubstitutionIndex);
1131 else if (const PackExpansionType *Expansion
1132 = dyn_cast<PackExpansionType>(NTTP->getType()))
1133 T = SemaRef.SubstType(Expansion->getPattern(), TemplateArgs,
1134 E->getParameterPackLocation(), NTTP->getDeclName());
1137 return SemaRef.BuildExpressionFromDeclTemplateArgument(Arg, T,
1138 E->getParameterPackLocation());
1141 return SemaRef.BuildExpressionFromIntegralTemplateArgument(Arg,
1142 E->getParameterPackLocation());
1146 TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
1147 NamedDecl *D = E->getDecl();
1148 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
1149 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
1150 return TransformTemplateParmRefExpr(E, NTTP);
1152 // We have a non-type template parameter that isn't fully substituted;
1153 // FindInstantiatedDecl will find it in the local instantiation scope.
1156 return TreeTransform<TemplateInstantiator>::TransformDeclRefExpr(E);
1159 ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
1160 CXXDefaultArgExpr *E) {
1161 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
1162 getDescribedFunctionTemplate() &&
1163 "Default arg expressions are never formed in dependent cases.");
1164 return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
1165 cast<FunctionDecl>(E->getParam()->getDeclContext()),
1169 QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
1170 FunctionProtoTypeLoc TL) {
1171 // We need a local instantiation scope for this function prototype.
1172 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1173 return inherited::TransformFunctionProtoType(TLB, TL);
1177 TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
1178 int indexAdjustment,
1179 llvm::Optional<unsigned> NumExpansions) {
1180 return SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment,
1185 TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1186 TemplateTypeParmTypeLoc TL) {
1187 const TemplateTypeParmType *T = TL.getTypePtr();
1188 if (T->getDepth() < TemplateArgs.getNumLevels()) {
1189 // Replace the template type parameter with its corresponding
1190 // template argument.
1192 // If the corresponding template argument is NULL or doesn't exist, it's
1193 // because we are performing instantiation from explicitly-specified
1194 // template arguments in a function template class, but there were some
1195 // arguments left unspecified.
1196 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
1197 TemplateTypeParmTypeLoc NewTL
1198 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
1199 NewTL.setNameLoc(TL.getNameLoc());
1200 return TL.getType();
1203 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
1205 if (T->isParameterPack()) {
1206 assert(Arg.getKind() == TemplateArgument::Pack &&
1207 "Missing argument pack");
1209 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1210 // We have the template argument pack, but we're not expanding the
1211 // enclosing pack expansion yet. Just save the template argument
1212 // pack for later substitution.
1214 = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg);
1215 SubstTemplateTypeParmPackTypeLoc NewTL
1216 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
1217 NewTL.setNameLoc(TL.getNameLoc());
1221 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
1222 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
1225 assert(Arg.getKind() == TemplateArgument::Type &&
1226 "Template argument kind mismatch");
1228 QualType Replacement = Arg.getAsType();
1230 // TODO: only do this uniquing once, at the start of instantiation.
1232 = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
1233 SubstTemplateTypeParmTypeLoc NewTL
1234 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1235 NewTL.setNameLoc(TL.getNameLoc());
1239 // The template type parameter comes from an inner template (e.g.,
1240 // the template parameter list of a member template inside the
1241 // template we are instantiating). Create a new template type
1242 // parameter with the template "level" reduced by one.
1243 TemplateTypeParmDecl *NewTTPDecl = 0;
1244 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
1245 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
1246 TransformDecl(TL.getNameLoc(), OldTTPDecl));
1249 = getSema().Context.getTemplateTypeParmType(T->getDepth()
1250 - TemplateArgs.getNumLevels(),
1252 T->isParameterPack(),
1254 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
1255 NewTL.setNameLoc(TL.getNameLoc());
1260 TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
1261 TypeLocBuilder &TLB,
1262 SubstTemplateTypeParmPackTypeLoc TL) {
1263 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1264 // We aren't expanding the parameter pack, so just return ourselves.
1265 SubstTemplateTypeParmPackTypeLoc NewTL
1266 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(TL.getType());
1267 NewTL.setNameLoc(TL.getNameLoc());
1268 return TL.getType();
1271 const TemplateArgument &ArgPack = TL.getTypePtr()->getArgumentPack();
1272 unsigned Index = (unsigned)getSema().ArgumentPackSubstitutionIndex;
1273 assert(Index < ArgPack.pack_size() && "Substitution index out-of-range");
1275 QualType Result = ArgPack.pack_begin()[Index].getAsType();
1276 Result = getSema().Context.getSubstTemplateTypeParmType(
1277 TL.getTypePtr()->getReplacedParameter(),
1279 SubstTemplateTypeParmTypeLoc NewTL
1280 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1281 NewTL.setNameLoc(TL.getNameLoc());
1285 /// \brief Perform substitution on the type T with a given set of template
1288 /// This routine substitutes the given template arguments into the
1289 /// type T and produces the instantiated type.
1291 /// \param T the type into which the template arguments will be
1292 /// substituted. If this type is not dependent, it will be returned
1295 /// \param TemplateArgs the template arguments that will be
1296 /// substituted for the top-level template parameters within T.
1298 /// \param Loc the location in the source code where this substitution
1299 /// is being performed. It will typically be the location of the
1300 /// declarator (if we're instantiating the type of some declaration)
1301 /// or the location of the type in the source code (if, e.g., we're
1302 /// instantiating the type of a cast expression).
1304 /// \param Entity the name of the entity associated with a declaration
1305 /// being instantiated (if any). May be empty to indicate that there
1306 /// is no such entity (if, e.g., this is a type that occurs as part of
1307 /// a cast expression) or that the entity has no name (e.g., an
1308 /// unnamed function parameter).
1310 /// \returns If the instantiation succeeds, the instantiated
1311 /// type. Otherwise, produces diagnostics and returns a NULL type.
1312 TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
1313 const MultiLevelTemplateArgumentList &Args,
1315 DeclarationName Entity) {
1316 assert(!ActiveTemplateInstantiations.empty() &&
1317 "Cannot perform an instantiation without some context on the "
1318 "instantiation stack");
1320 if (!T->getType()->isDependentType() &&
1321 !T->getType()->isVariablyModifiedType())
1324 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1325 return Instantiator.TransformType(T);
1328 TypeSourceInfo *Sema::SubstType(TypeLoc TL,
1329 const MultiLevelTemplateArgumentList &Args,
1331 DeclarationName Entity) {
1332 assert(!ActiveTemplateInstantiations.empty() &&
1333 "Cannot perform an instantiation without some context on the "
1334 "instantiation stack");
1336 if (TL.getType().isNull())
1339 if (!TL.getType()->isDependentType() &&
1340 !TL.getType()->isVariablyModifiedType()) {
1341 // FIXME: Make a copy of the TypeLoc data here, so that we can
1342 // return a new TypeSourceInfo. Inefficient!
1344 TLB.pushFullCopy(TL);
1345 return TLB.getTypeSourceInfo(Context, TL.getType());
1348 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1350 TLB.reserve(TL.getFullDataSize());
1351 QualType Result = Instantiator.TransformType(TLB, TL);
1352 if (Result.isNull())
1355 return TLB.getTypeSourceInfo(Context, Result);
1358 /// Deprecated form of the above.
1359 QualType Sema::SubstType(QualType T,
1360 const MultiLevelTemplateArgumentList &TemplateArgs,
1361 SourceLocation Loc, DeclarationName Entity) {
1362 assert(!ActiveTemplateInstantiations.empty() &&
1363 "Cannot perform an instantiation without some context on the "
1364 "instantiation stack");
1366 // If T is not a dependent type or a variably-modified type, there
1367 // is nothing to do.
1368 if (!T->isDependentType() && !T->isVariablyModifiedType())
1371 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
1372 return Instantiator.TransformType(T);
1375 static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
1376 if (T->getType()->isDependentType() || T->getType()->isVariablyModifiedType())
1379 TypeLoc TL = T->getTypeLoc().IgnoreParens();
1380 if (!isa<FunctionProtoTypeLoc>(TL))
1383 FunctionProtoTypeLoc FP = cast<FunctionProtoTypeLoc>(TL);
1384 for (unsigned I = 0, E = FP.getNumArgs(); I != E; ++I) {
1385 ParmVarDecl *P = FP.getArg(I);
1387 // TODO: currently we always rebuild expressions. When we
1388 // properly get lazier about this, we should use the same
1389 // logic to avoid rebuilding prototypes here.
1390 if (P->hasDefaultArg())
1397 /// A form of SubstType intended specifically for instantiating the
1398 /// type of a FunctionDecl. Its purpose is solely to force the
1399 /// instantiation of default-argument expressions.
1400 TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
1401 const MultiLevelTemplateArgumentList &Args,
1403 DeclarationName Entity) {
1404 assert(!ActiveTemplateInstantiations.empty() &&
1405 "Cannot perform an instantiation without some context on the "
1406 "instantiation stack");
1408 if (!NeedsInstantiationAsFunctionType(T))
1411 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1415 TypeLoc TL = T->getTypeLoc();
1416 TLB.reserve(TL.getFullDataSize());
1418 QualType Result = Instantiator.TransformType(TLB, TL);
1419 if (Result.isNull())
1422 return TLB.getTypeSourceInfo(Context, Result);
1425 ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm,
1426 const MultiLevelTemplateArgumentList &TemplateArgs,
1427 int indexAdjustment,
1428 llvm::Optional<unsigned> NumExpansions) {
1429 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
1430 TypeSourceInfo *NewDI = 0;
1432 TypeLoc OldTL = OldDI->getTypeLoc();
1433 if (isa<PackExpansionTypeLoc>(OldTL)) {
1434 PackExpansionTypeLoc ExpansionTL = cast<PackExpansionTypeLoc>(OldTL);
1436 // We have a function parameter pack. Substitute into the pattern of the
1438 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
1439 OldParm->getLocation(), OldParm->getDeclName());
1443 if (NewDI->getType()->containsUnexpandedParameterPack()) {
1444 // We still have unexpanded parameter packs, which means that
1445 // our function parameter is still a function parameter pack.
1446 // Therefore, make its type a pack expansion type.
1447 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
1451 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
1452 OldParm->getDeclName());
1458 if (NewDI->getType()->isVoidType()) {
1459 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
1463 ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
1464 OldParm->getInnerLocStart(),
1465 OldParm->getLocation(),
1466 OldParm->getIdentifier(),
1467 NewDI->getType(), NewDI,
1468 OldParm->getStorageClass(),
1469 OldParm->getStorageClassAsWritten());
1473 // Mark the (new) default argument as uninstantiated (if any).
1474 if (OldParm->hasUninstantiatedDefaultArg()) {
1475 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
1476 NewParm->setUninstantiatedDefaultArg(Arg);
1477 } else if (OldParm->hasUnparsedDefaultArg()) {
1478 NewParm->setUnparsedDefaultArg();
1479 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
1480 } else if (Expr *Arg = OldParm->getDefaultArg())
1481 NewParm->setUninstantiatedDefaultArg(Arg);
1483 NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
1485 // FIXME: When OldParm is a parameter pack and NewParm is not a parameter
1486 // pack, we actually have a set of instantiated locations. Maintain this set!
1487 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
1488 // Add the new parameter to
1489 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
1491 // Introduce an Old -> New mapping
1492 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
1495 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
1496 // can be anything, is this right ?
1497 NewParm->setDeclContext(CurContext);
1499 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
1500 OldParm->getFunctionScopeIndex() + indexAdjustment);
1505 /// \brief Substitute the given template arguments into the given set of
1506 /// parameters, producing the set of parameter types that would be generated
1507 /// from such a substitution.
1508 bool Sema::SubstParmTypes(SourceLocation Loc,
1509 ParmVarDecl **Params, unsigned NumParams,
1510 const MultiLevelTemplateArgumentList &TemplateArgs,
1511 llvm::SmallVectorImpl<QualType> &ParamTypes,
1512 llvm::SmallVectorImpl<ParmVarDecl *> *OutParams) {
1513 assert(!ActiveTemplateInstantiations.empty() &&
1514 "Cannot perform an instantiation without some context on the "
1515 "instantiation stack");
1517 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
1519 return Instantiator.TransformFunctionTypeParams(Loc, Params, NumParams, 0,
1520 ParamTypes, OutParams);
1523 /// \brief Perform substitution on the base class specifiers of the
1524 /// given class template specialization.
1526 /// Produces a diagnostic and returns true on error, returns false and
1527 /// attaches the instantiated base classes to the class template
1528 /// specialization if successful.
1530 Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
1531 CXXRecordDecl *Pattern,
1532 const MultiLevelTemplateArgumentList &TemplateArgs) {
1533 bool Invalid = false;
1534 llvm::SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
1535 for (ClassTemplateSpecializationDecl::base_class_iterator
1536 Base = Pattern->bases_begin(), BaseEnd = Pattern->bases_end();
1537 Base != BaseEnd; ++Base) {
1538 if (!Base->getType()->isDependentType()) {
1539 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(*Base));
1543 SourceLocation EllipsisLoc;
1544 TypeSourceInfo *BaseTypeLoc;
1545 if (Base->isPackExpansion()) {
1546 // This is a pack expansion. See whether we should expand it now, or
1547 // wait until later.
1548 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1549 collectUnexpandedParameterPacks(Base->getTypeSourceInfo()->getTypeLoc(),
1551 bool ShouldExpand = false;
1552 bool RetainExpansion = false;
1553 llvm::Optional<unsigned> NumExpansions;
1554 if (CheckParameterPacksForExpansion(Base->getEllipsisLoc(),
1555 Base->getSourceRange(),
1556 Unexpanded.data(), Unexpanded.size(),
1557 TemplateArgs, ShouldExpand,
1564 // If we should expand this pack expansion now, do so.
1566 for (unsigned I = 0; I != *NumExpansions; ++I) {
1567 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
1569 TypeSourceInfo *BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
1571 Base->getSourceRange().getBegin(),
1578 if (CXXBaseSpecifier *InstantiatedBase
1579 = CheckBaseSpecifier(Instantiation,
1580 Base->getSourceRange(),
1582 Base->getAccessSpecifierAsWritten(),
1585 InstantiatedBases.push_back(InstantiatedBase);
1593 // The resulting base specifier will (still) be a pack expansion.
1594 EllipsisLoc = Base->getEllipsisLoc();
1595 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
1596 BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
1598 Base->getSourceRange().getBegin(),
1601 BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
1603 Base->getSourceRange().getBegin(),
1612 if (CXXBaseSpecifier *InstantiatedBase
1613 = CheckBaseSpecifier(Instantiation,
1614 Base->getSourceRange(),
1616 Base->getAccessSpecifierAsWritten(),
1619 InstantiatedBases.push_back(InstantiatedBase);
1625 AttachBaseSpecifiers(Instantiation, InstantiatedBases.data(),
1626 InstantiatedBases.size()))
1632 /// \brief Instantiate the definition of a class from a given pattern.
1634 /// \param PointOfInstantiation The point of instantiation within the
1637 /// \param Instantiation is the declaration whose definition is being
1638 /// instantiated. This will be either a class template specialization
1639 /// or a member class of a class template specialization.
1641 /// \param Pattern is the pattern from which the instantiation
1642 /// occurs. This will be either the declaration of a class template or
1643 /// the declaration of a member class of a class template.
1645 /// \param TemplateArgs The template arguments to be substituted into
1648 /// \param TSK the kind of implicit or explicit instantiation to perform.
1650 /// \param Complain whether to complain if the class cannot be instantiated due
1651 /// to the lack of a definition.
1653 /// \returns true if an error occurred, false otherwise.
1655 Sema::InstantiateClass(SourceLocation PointOfInstantiation,
1656 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
1657 const MultiLevelTemplateArgumentList &TemplateArgs,
1658 TemplateSpecializationKind TSK,
1660 bool Invalid = false;
1662 CXXRecordDecl *PatternDef
1663 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
1664 if (!PatternDef || PatternDef->isBeingDefined()) {
1665 if (!Complain || (PatternDef && PatternDef->isInvalidDecl())) {
1667 } else if (PatternDef) {
1668 assert(PatternDef->isBeingDefined());
1669 Diag(PointOfInstantiation,
1670 diag::err_template_instantiate_within_definition)
1671 << (TSK != TSK_ImplicitInstantiation)
1672 << Context.getTypeDeclType(Instantiation);
1673 // Not much point in noting the template declaration here, since
1674 // we're lexically inside it.
1675 Instantiation->setInvalidDecl();
1676 } else if (Pattern == Instantiation->getInstantiatedFromMemberClass()) {
1677 Diag(PointOfInstantiation,
1678 diag::err_implicit_instantiate_member_undefined)
1679 << Context.getTypeDeclType(Instantiation);
1680 Diag(Pattern->getLocation(), diag::note_member_of_template_here);
1682 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
1683 << (TSK != TSK_ImplicitInstantiation)
1684 << Context.getTypeDeclType(Instantiation);
1685 Diag(Pattern->getLocation(), diag::note_template_decl_here);
1689 Pattern = PatternDef;
1691 // \brief Record the point of instantiation.
1692 if (MemberSpecializationInfo *MSInfo
1693 = Instantiation->getMemberSpecializationInfo()) {
1694 MSInfo->setTemplateSpecializationKind(TSK);
1695 MSInfo->setPointOfInstantiation(PointOfInstantiation);
1696 } else if (ClassTemplateSpecializationDecl *Spec
1697 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
1698 Spec->setTemplateSpecializationKind(TSK);
1699 Spec->setPointOfInstantiation(PointOfInstantiation);
1702 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
1706 // Enter the scope of this instantiation. We don't use
1707 // PushDeclContext because we don't have a scope.
1708 ContextRAII SavedContext(*this, Instantiation);
1709 EnterExpressionEvaluationContext EvalContext(*this,
1710 Sema::PotentiallyEvaluated);
1712 // If this is an instantiation of a local class, merge this local
1713 // instantiation scope with the enclosing scope. Otherwise, every
1714 // instantiation of a class has its own local instantiation scope.
1715 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
1716 LocalInstantiationScope Scope(*this, MergeWithParentScope);
1718 // Pull attributes from the pattern onto the instantiation.
1719 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
1721 // Start the definition of this instantiation.
1722 Instantiation->startDefinition();
1724 Instantiation->setTagKind(Pattern->getTagKind());
1726 // Do substitution on the base class specifiers.
1727 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
1730 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
1731 llvm::SmallVector<Decl*, 4> Fields;
1732 for (RecordDecl::decl_iterator Member = Pattern->decls_begin(),
1733 MemberEnd = Pattern->decls_end();
1734 Member != MemberEnd; ++Member) {
1735 // Don't instantiate members not belonging in this semantic context.
1738 // template <int i> class A {
1742 // 'class B' has the template as lexical context but semantically it is
1743 // introduced in namespace scope.
1744 if ((*Member)->getDeclContext() != Pattern)
1747 if ((*Member)->isInvalidDecl()) {
1752 Decl *NewMember = Instantiator.Visit(*Member);
1754 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember))
1755 Fields.push_back(Field);
1756 else if (NewMember->isInvalidDecl())
1759 // FIXME: Eventually, a NULL return will mean that one of the
1760 // instantiations was a semantic disaster, and we'll want to set Invalid =
1761 // true. For now, we expect to skip some members that we can't yet handle.
1765 // Finish checking fields.
1766 ActOnFields(0, Instantiation->getLocation(), Instantiation,
1767 Fields.data(), Fields.size(), SourceLocation(), SourceLocation(),
1769 CheckCompletedCXXClass(Instantiation);
1770 if (Instantiation->isInvalidDecl())
1773 // Instantiate any out-of-line class template partial
1774 // specializations now.
1775 for (TemplateDeclInstantiator::delayed_partial_spec_iterator
1776 P = Instantiator.delayed_partial_spec_begin(),
1777 PEnd = Instantiator.delayed_partial_spec_end();
1779 if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
1788 // Exit the scope of this instantiation.
1792 Consumer.HandleTagDeclDefinition(Instantiation);
1794 // Always emit the vtable for an explicit instantiation definition
1795 // of a polymorphic class template specialization.
1796 if (TSK == TSK_ExplicitInstantiationDefinition)
1797 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
1804 /// \brief A partial specialization whose template arguments have matched
1805 /// a given template-id.
1806 struct PartialSpecMatchResult {
1807 ClassTemplatePartialSpecializationDecl *Partial;
1808 TemplateArgumentList *Args;
1813 Sema::InstantiateClassTemplateSpecialization(
1814 SourceLocation PointOfInstantiation,
1815 ClassTemplateSpecializationDecl *ClassTemplateSpec,
1816 TemplateSpecializationKind TSK,
1818 // Perform the actual instantiation on the canonical declaration.
1819 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
1820 ClassTemplateSpec->getCanonicalDecl());
1822 // Check whether we have already instantiated or specialized this class
1823 // template specialization.
1824 if (ClassTemplateSpec->getSpecializationKind() != TSK_Undeclared) {
1825 if (ClassTemplateSpec->getSpecializationKind() ==
1826 TSK_ExplicitInstantiationDeclaration &&
1827 TSK == TSK_ExplicitInstantiationDefinition) {
1828 // An explicit instantiation definition follows an explicit instantiation
1829 // declaration (C++0x [temp.explicit]p10); go ahead and perform the
1830 // explicit instantiation.
1831 ClassTemplateSpec->setSpecializationKind(TSK);
1833 // If this is an explicit instantiation definition, mark the
1835 if (TSK == TSK_ExplicitInstantiationDefinition)
1836 MarkVTableUsed(PointOfInstantiation, ClassTemplateSpec, true);
1841 // We can only instantiate something that hasn't already been
1842 // instantiated or specialized. Fail without any diagnostics: our
1843 // caller will provide an error message.
1847 if (ClassTemplateSpec->isInvalidDecl())
1850 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
1851 CXXRecordDecl *Pattern = 0;
1853 // C++ [temp.class.spec.match]p1:
1854 // When a class template is used in a context that requires an
1855 // instantiation of the class, it is necessary to determine
1856 // whether the instantiation is to be generated using the primary
1857 // template or one of the partial specializations. This is done by
1858 // matching the template arguments of the class template
1859 // specialization with the template argument lists of the partial
1861 typedef PartialSpecMatchResult MatchResult;
1862 llvm::SmallVector<MatchResult, 4> Matched;
1863 llvm::SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1864 Template->getPartialSpecializations(PartialSpecs);
1865 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
1866 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
1867 TemplateDeductionInfo Info(Context, PointOfInstantiation);
1868 if (TemplateDeductionResult Result
1869 = DeduceTemplateArguments(Partial,
1870 ClassTemplateSpec->getTemplateArgs(),
1872 // FIXME: Store the failed-deduction information for use in
1873 // diagnostics, later.
1876 Matched.push_back(PartialSpecMatchResult());
1877 Matched.back().Partial = Partial;
1878 Matched.back().Args = Info.take();
1882 // If we're dealing with a member template where the template parameters
1883 // have been instantiated, this provides the original template parameters
1884 // from which the member template's parameters were instantiated.
1885 llvm::SmallVector<const NamedDecl *, 4> InstantiatedTemplateParameters;
1887 if (Matched.size() >= 1) {
1888 llvm::SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
1889 if (Matched.size() == 1) {
1890 // -- If exactly one matching specialization is found, the
1891 // instantiation is generated from that specialization.
1892 // We don't need to do anything for this.
1894 // -- If more than one matching specialization is found, the
1895 // partial order rules (14.5.4.2) are used to determine
1896 // whether one of the specializations is more specialized
1897 // than the others. If none of the specializations is more
1898 // specialized than all of the other matching
1899 // specializations, then the use of the class template is
1900 // ambiguous and the program is ill-formed.
1901 for (llvm::SmallVector<MatchResult, 4>::iterator P = Best + 1,
1902 PEnd = Matched.end();
1904 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
1905 PointOfInstantiation)
1910 // Determine if the best partial specialization is more specialized than
1912 bool Ambiguous = false;
1913 for (llvm::SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
1914 PEnd = Matched.end();
1917 getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
1918 PointOfInstantiation)
1926 // Partial ordering did not produce a clear winner. Complain.
1927 ClassTemplateSpec->setInvalidDecl();
1928 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
1929 << ClassTemplateSpec;
1931 // Print the matching partial specializations.
1932 for (llvm::SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
1933 PEnd = Matched.end();
1935 Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
1936 << getTemplateArgumentBindingsText(
1937 P->Partial->getTemplateParameters(),
1944 // Instantiate using the best class template partial specialization.
1945 ClassTemplatePartialSpecializationDecl *OrigPartialSpec = Best->Partial;
1946 while (OrigPartialSpec->getInstantiatedFromMember()) {
1947 // If we've found an explicit specialization of this class template,
1948 // stop here and use that as the pattern.
1949 if (OrigPartialSpec->isMemberSpecialization())
1952 OrigPartialSpec = OrigPartialSpec->getInstantiatedFromMember();
1955 Pattern = OrigPartialSpec;
1956 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
1958 // -- If no matches are found, the instantiation is generated
1959 // from the primary template.
1960 ClassTemplateDecl *OrigTemplate = Template;
1961 while (OrigTemplate->getInstantiatedFromMemberTemplate()) {
1962 // If we've found an explicit specialization of this class template,
1963 // stop here and use that as the pattern.
1964 if (OrigTemplate->isMemberSpecialization())
1967 OrigTemplate = OrigTemplate->getInstantiatedFromMemberTemplate();
1970 Pattern = OrigTemplate->getTemplatedDecl();
1973 bool Result = InstantiateClass(PointOfInstantiation, ClassTemplateSpec,
1975 getTemplateInstantiationArgs(ClassTemplateSpec),
1982 /// \brief Instantiates the definitions of all of the member
1983 /// of the given class, which is an instantiation of a class template
1984 /// or a member class of a template.
1986 Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
1987 CXXRecordDecl *Instantiation,
1988 const MultiLevelTemplateArgumentList &TemplateArgs,
1989 TemplateSpecializationKind TSK) {
1990 for (DeclContext::decl_iterator D = Instantiation->decls_begin(),
1991 DEnd = Instantiation->decls_end();
1993 bool SuppressNew = false;
1994 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(*D)) {
1995 if (FunctionDecl *Pattern
1996 = Function->getInstantiatedFromMemberFunction()) {
1997 MemberSpecializationInfo *MSInfo
1998 = Function->getMemberSpecializationInfo();
1999 assert(MSInfo && "No member specialization information?");
2000 if (MSInfo->getTemplateSpecializationKind()
2001 == TSK_ExplicitSpecialization)
2004 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2006 MSInfo->getTemplateSpecializationKind(),
2007 MSInfo->getPointOfInstantiation(),
2012 if (Function->hasBody())
2015 if (TSK == TSK_ExplicitInstantiationDefinition) {
2016 // C++0x [temp.explicit]p8:
2017 // An explicit instantiation definition that names a class template
2018 // specialization explicitly instantiates the class template
2019 // specialization and is only an explicit instantiation definition
2020 // of members whose definition is visible at the point of
2022 if (!Pattern->hasBody())
2025 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2027 InstantiateFunctionDefinition(PointOfInstantiation, Function);
2029 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2032 } else if (VarDecl *Var = dyn_cast<VarDecl>(*D)) {
2033 if (Var->isStaticDataMember()) {
2034 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
2035 assert(MSInfo && "No member specialization information?");
2036 if (MSInfo->getTemplateSpecializationKind()
2037 == TSK_ExplicitSpecialization)
2040 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2042 MSInfo->getTemplateSpecializationKind(),
2043 MSInfo->getPointOfInstantiation(),
2048 if (TSK == TSK_ExplicitInstantiationDefinition) {
2049 // C++0x [temp.explicit]p8:
2050 // An explicit instantiation definition that names a class template
2051 // specialization explicitly instantiates the class template
2052 // specialization and is only an explicit instantiation definition
2053 // of members whose definition is visible at the point of
2055 if (!Var->getInstantiatedFromStaticDataMember()
2056 ->getOutOfLineDefinition())
2059 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2060 InstantiateStaticDataMemberDefinition(PointOfInstantiation, Var);
2062 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2065 } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(*D)) {
2066 // Always skip the injected-class-name, along with any
2067 // redeclarations of nested classes, since both would cause us
2068 // to try to instantiate the members of a class twice.
2069 if (Record->isInjectedClassName() || Record->getPreviousDeclaration())
2072 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
2073 assert(MSInfo && "No member specialization information?");
2075 if (MSInfo->getTemplateSpecializationKind()
2076 == TSK_ExplicitSpecialization)
2079 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2081 MSInfo->getTemplateSpecializationKind(),
2082 MSInfo->getPointOfInstantiation(),
2087 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2088 assert(Pattern && "Missing instantiated-from-template information");
2090 if (!Record->getDefinition()) {
2091 if (!Pattern->getDefinition()) {
2092 // C++0x [temp.explicit]p8:
2093 // An explicit instantiation definition that names a class template
2094 // specialization explicitly instantiates the class template
2095 // specialization and is only an explicit instantiation definition
2096 // of members whose definition is visible at the point of
2098 if (TSK == TSK_ExplicitInstantiationDeclaration) {
2099 MSInfo->setTemplateSpecializationKind(TSK);
2100 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2106 InstantiateClass(PointOfInstantiation, Record, Pattern,
2110 if (TSK == TSK_ExplicitInstantiationDefinition &&
2111 Record->getTemplateSpecializationKind() ==
2112 TSK_ExplicitInstantiationDeclaration) {
2113 Record->setTemplateSpecializationKind(TSK);
2114 MarkVTableUsed(PointOfInstantiation, Record, true);
2118 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
2120 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
2126 /// \brief Instantiate the definitions of all of the members of the
2127 /// given class template specialization, which was named as part of an
2128 /// explicit instantiation.
2130 Sema::InstantiateClassTemplateSpecializationMembers(
2131 SourceLocation PointOfInstantiation,
2132 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2133 TemplateSpecializationKind TSK) {
2134 // C++0x [temp.explicit]p7:
2135 // An explicit instantiation that names a class template
2136 // specialization is an explicit instantion of the same kind
2137 // (declaration or definition) of each of its members (not
2138 // including members inherited from base classes) that has not
2139 // been previously explicitly specialized in the translation unit
2140 // containing the explicit instantiation, except as described
2142 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
2143 getTemplateInstantiationArgs(ClassTemplateSpec),
2148 Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
2152 TemplateInstantiator Instantiator(*this, TemplateArgs,
2155 return Instantiator.TransformStmt(S);
2159 Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
2163 TemplateInstantiator Instantiator(*this, TemplateArgs,
2166 return Instantiator.TransformExpr(E);
2169 bool Sema::SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall,
2170 const MultiLevelTemplateArgumentList &TemplateArgs,
2171 llvm::SmallVectorImpl<Expr *> &Outputs) {
2175 TemplateInstantiator Instantiator(*this, TemplateArgs,
2178 return Instantiator.TransformExprs(Exprs, NumExprs, IsCall, Outputs);
2181 NestedNameSpecifierLoc
2182 Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
2183 const MultiLevelTemplateArgumentList &TemplateArgs) {
2185 return NestedNameSpecifierLoc();
2187 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
2189 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
2192 /// \brief Do template substitution on declaration name info.
2194 Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
2195 const MultiLevelTemplateArgumentList &TemplateArgs) {
2196 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
2197 NameInfo.getName());
2198 return Instantiator.TransformDeclarationNameInfo(NameInfo);
2202 Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,
2203 TemplateName Name, SourceLocation Loc,
2204 const MultiLevelTemplateArgumentList &TemplateArgs) {
2205 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
2208 SS.Adopt(QualifierLoc);
2209 return Instantiator.TransformTemplateName(SS, Name, Loc);
2212 bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
2213 TemplateArgumentListInfo &Result,
2214 const MultiLevelTemplateArgumentList &TemplateArgs) {
2215 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
2218 return Instantiator.TransformTemplateArguments(Args, NumArgs, Result);
2221 llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
2222 LocalInstantiationScope::findInstantiationOf(const Decl *D) {
2223 for (LocalInstantiationScope *Current = this; Current;
2224 Current = Current->Outer) {
2226 // Check if we found something within this scope.
2227 const Decl *CheckD = D;
2229 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
2230 if (Found != Current->LocalDecls.end())
2231 return &Found->second;
2233 // If this is a tag declaration, it's possible that we need to look for
2234 // a previous declaration.
2235 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
2236 CheckD = Tag->getPreviousDeclaration();
2241 // If we aren't combined with our outer scope, we're done.
2242 if (!Current->CombineWithOuterScope)
2246 // If we didn't find the decl, then we either have a sema bug, or we have a
2247 // forward reference to a label declaration. Return null to indicate that
2248 // we have an uninstantiated label.
2249 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
2253 void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
2254 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
2255 if (Stored.isNull())
2257 else if (Stored.is<Decl *>()) {
2258 assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
2261 LocalDecls[D].get<DeclArgumentPack *>()->push_back(Inst);
2264 void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
2266 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
2267 Pack->push_back(Inst);
2270 void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
2271 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
2272 assert(Stored.isNull() && "Already instantiated this local");
2273 DeclArgumentPack *Pack = new DeclArgumentPack;
2275 ArgumentPacks.push_back(Pack);
2278 void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
2279 const TemplateArgument *ExplicitArgs,
2280 unsigned NumExplicitArgs) {
2281 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
2282 "Already have a partially-substituted pack");
2283 assert((!PartiallySubstitutedPack
2284 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
2285 "Wrong number of arguments in partially-substituted pack");
2286 PartiallySubstitutedPack = Pack;
2287 ArgsInPartiallySubstitutedPack = ExplicitArgs;
2288 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
2291 NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
2292 const TemplateArgument **ExplicitArgs,
2293 unsigned *NumExplicitArgs) const {
2296 if (NumExplicitArgs)
2297 *NumExplicitArgs = 0;
2299 for (const LocalInstantiationScope *Current = this; Current;
2300 Current = Current->Outer) {
2301 if (Current->PartiallySubstitutedPack) {
2303 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
2304 if (NumExplicitArgs)
2305 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
2307 return Current->PartiallySubstitutedPack;
2310 if (!Current->CombineWithOuterScope)