1 //===--- SemaTemplateInstantiateDecl.cpp - C++ Template Decl 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 for declarations.
11 //===----------------------------------------------------------------------===/
12 #include "clang/Sema/SemaInternal.h"
13 #include "clang/AST/ASTConsumer.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/DeclTemplate.h"
16 #include "clang/AST/DeclVisitor.h"
17 #include "clang/AST/DependentDiagnostic.h"
18 #include "clang/AST/Expr.h"
19 #include "clang/AST/ExprCXX.h"
20 #include "clang/AST/TypeLoc.h"
21 #include "clang/Lex/Preprocessor.h"
22 #include "clang/Sema/Lookup.h"
23 #include "clang/Sema/PrettyDeclStackTrace.h"
24 #include "clang/Sema/Template.h"
26 using namespace clang;
28 bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
29 DeclaratorDecl *NewDecl) {
30 if (!OldDecl->getQualifierLoc())
33 NestedNameSpecifierLoc NewQualifierLoc
34 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
40 NewDecl->setQualifierInfo(NewQualifierLoc);
44 bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
46 if (!OldDecl->getQualifierLoc())
49 NestedNameSpecifierLoc NewQualifierLoc
50 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
56 NewDecl->setQualifierInfo(NewQualifierLoc);
60 // Include attribute instantiation code.
61 #include "clang/Sema/AttrTemplateInstantiate.inc"
63 static void instantiateDependentAlignedAttr(
64 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
65 const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion) {
66 if (Aligned->isAlignmentExpr()) {
67 // The alignment expression is a constant expression.
68 EnterExpressionEvaluationContext Unevaluated(S, Sema::ConstantEvaluated);
69 ExprResult Result = S.SubstExpr(Aligned->getAlignmentExpr(), TemplateArgs);
70 if (!Result.isInvalid())
71 S.AddAlignedAttr(Aligned->getLocation(), New, Result.takeAs<Expr>(),
72 Aligned->getSpellingListIndex(), IsPackExpansion);
74 TypeSourceInfo *Result = S.SubstType(Aligned->getAlignmentType(),
75 TemplateArgs, Aligned->getLocation(),
78 S.AddAlignedAttr(Aligned->getLocation(), New, Result,
79 Aligned->getSpellingListIndex(), IsPackExpansion);
83 static void instantiateDependentAlignedAttr(
84 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
85 const AlignedAttr *Aligned, Decl *New) {
86 if (!Aligned->isPackExpansion()) {
87 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
91 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
92 if (Aligned->isAlignmentExpr())
93 S.collectUnexpandedParameterPacks(Aligned->getAlignmentExpr(),
96 S.collectUnexpandedParameterPacks(Aligned->getAlignmentType()->getTypeLoc(),
98 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
100 // Determine whether we can expand this attribute pack yet.
101 bool Expand = true, RetainExpansion = false;
102 Optional<unsigned> NumExpansions;
103 // FIXME: Use the actual location of the ellipsis.
104 SourceLocation EllipsisLoc = Aligned->getLocation();
105 if (S.CheckParameterPacksForExpansion(EllipsisLoc, Aligned->getRange(),
106 Unexpanded, TemplateArgs, Expand,
107 RetainExpansion, NumExpansions))
111 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, -1);
112 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, true);
114 for (unsigned I = 0; I != *NumExpansions; ++I) {
115 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, I);
116 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
121 void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
122 const Decl *Tmpl, Decl *New,
123 LateInstantiatedAttrVec *LateAttrs,
124 LocalInstantiationScope *OuterMostScope) {
125 for (AttrVec::const_iterator i = Tmpl->attr_begin(), e = Tmpl->attr_end();
127 const Attr *TmplAttr = *i;
129 // FIXME: This should be generalized to more than just the AlignedAttr.
130 const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr);
131 if (Aligned && Aligned->isAlignmentDependent()) {
132 instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New);
136 assert(!TmplAttr->isPackExpansion());
137 if (TmplAttr->isLateParsed() && LateAttrs) {
138 // Late parsed attributes must be instantiated and attached after the
139 // enclosing class has been instantiated. See Sema::InstantiateClass.
140 LocalInstantiationScope *Saved = 0;
141 if (CurrentInstantiationScope)
142 Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
143 LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
145 Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
146 *this, TemplateArgs);
148 New->addAttr(NewAttr);
154 TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
155 llvm_unreachable("Translation units cannot be instantiated");
159 TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
160 LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
162 Owner->addDecl(Inst);
167 TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
168 llvm_unreachable("Namespaces cannot be instantiated");
172 TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
173 NamespaceAliasDecl *Inst
174 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
175 D->getNamespaceLoc(),
178 D->getQualifierLoc(),
179 D->getTargetNameLoc(),
181 Owner->addDecl(Inst);
185 Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
187 bool Invalid = false;
188 TypeSourceInfo *DI = D->getTypeSourceInfo();
189 if (DI->getType()->isInstantiationDependentType() ||
190 DI->getType()->isVariablyModifiedType()) {
191 DI = SemaRef.SubstType(DI, TemplateArgs,
192 D->getLocation(), D->getDeclName());
195 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
198 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
201 // HACK: g++ has a bug where it gets the value kind of ?: wrong.
202 // libstdc++ relies upon this bug in its implementation of common_type.
203 // If we happen to be processing that implementation, fake up the g++ ?:
204 // semantics. See LWG issue 2141 for more information on the bug.
205 const DecltypeType *DT = DI->getType()->getAs<DecltypeType>();
206 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
207 if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) &&
208 DT->isReferenceType() &&
209 RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() &&
210 RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") &&
211 D->getIdentifier() && D->getIdentifier()->isStr("type") &&
212 SemaRef.getSourceManager().isInSystemHeader(D->getLocStart()))
213 // Fold it to the (non-reference) type which g++ would have produced.
214 DI = SemaRef.Context.getTrivialTypeSourceInfo(
215 DI->getType().getNonReferenceType());
217 // Create the new typedef
218 TypedefNameDecl *Typedef;
220 Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
221 D->getLocation(), D->getIdentifier(), DI);
223 Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
224 D->getLocation(), D->getIdentifier(), DI);
226 Typedef->setInvalidDecl();
228 // If the old typedef was the name for linkage purposes of an anonymous
229 // tag decl, re-establish that relationship for the new typedef.
230 if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
231 TagDecl *oldTag = oldTagType->getDecl();
232 if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) {
233 TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
234 assert(!newTag->hasNameForLinkage());
235 newTag->setTypedefNameForAnonDecl(Typedef);
239 if (TypedefNameDecl *Prev = D->getPreviousDecl()) {
240 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
245 TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
247 // If the typedef types are not identical, reject them.
248 SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
250 Typedef->setPreviousDeclaration(InstPrevTypedef);
253 SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
255 Typedef->setAccess(D->getAccess());
260 Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
261 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
262 Owner->addDecl(Typedef);
266 Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
267 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
268 Owner->addDecl(Typedef);
273 TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
274 // Create a local instantiation scope for this type alias template, which
275 // will contain the instantiations of the template parameters.
276 LocalInstantiationScope Scope(SemaRef);
278 TemplateParameterList *TempParams = D->getTemplateParameters();
279 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
283 TypeAliasDecl *Pattern = D->getTemplatedDecl();
285 TypeAliasTemplateDecl *PrevAliasTemplate = 0;
286 if (Pattern->getPreviousDecl()) {
287 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
288 if (!Found.empty()) {
289 PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front());
293 TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
294 InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
298 TypeAliasTemplateDecl *Inst
299 = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
300 D->getDeclName(), InstParams, AliasInst);
301 if (PrevAliasTemplate)
302 Inst->setPreviousDeclaration(PrevAliasTemplate);
304 Inst->setAccess(D->getAccess());
306 if (!PrevAliasTemplate)
307 Inst->setInstantiatedFromMemberTemplate(D);
309 Owner->addDecl(Inst);
314 Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
315 // If this is the variable for an anonymous struct or union,
316 // instantiate the anonymous struct/union type first.
317 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
318 if (RecordTy->getDecl()->isAnonymousStructOrUnion())
319 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
322 // Do substitution on the type of the declaration
323 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
325 D->getTypeSpecStartLoc(),
330 if (DI->getType()->isFunctionType()) {
331 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
332 << D->isStaticDataMember() << DI->getType();
336 // Build the instantiated declaration
337 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
338 D->getInnerLocStart(),
339 D->getLocation(), D->getIdentifier(),
341 D->getStorageClass());
342 Var->setTSCSpec(D->getTSCSpec());
343 Var->setInitStyle(D->getInitStyle());
344 Var->setCXXForRangeDecl(D->isCXXForRangeDecl());
345 Var->setConstexpr(D->isConstexpr());
347 // Substitute the nested name specifier, if any.
348 if (SubstQualifier(D, Var))
351 // If we are instantiating a static data member defined
352 // out-of-line, the instantiation will have the same lexical
353 // context (which will be a namespace scope) as the template.
354 if (D->isOutOfLine())
355 Var->setLexicalDeclContext(D->getLexicalDeclContext());
357 Var->setAccess(D->getAccess());
359 if (!D->isStaticDataMember()) {
360 Var->setUsed(D->isUsed(false));
361 Var->setReferenced(D->isReferenced());
364 SemaRef.InstantiateAttrs(TemplateArgs, D, Var, LateAttrs, StartingScope);
367 SemaRef.CheckAlignasUnderalignment(Var);
369 // FIXME: In theory, we could have a previous declaration for variables that
370 // are not static data members.
371 // FIXME: having to fake up a LookupResult is dumb.
372 LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(),
373 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
374 if (D->isStaticDataMember())
375 SemaRef.LookupQualifiedName(Previous, Owner, false);
377 // In ARC, infer 'retaining' for variables of retainable type.
378 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
379 SemaRef.inferObjCARCLifetime(Var))
380 Var->setInvalidDecl();
382 SemaRef.CheckVariableDeclaration(Var, Previous);
384 if (D->isOutOfLine()) {
385 D->getLexicalDeclContext()->addDecl(Var);
386 Owner->makeDeclVisibleInContext(Var);
389 if (Owner->isFunctionOrMethod())
390 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Var);
393 // Link instantiations of static data members back to the template from
394 // which they were instantiated.
395 if (Var->isStaticDataMember())
396 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D,
397 TSK_ImplicitInstantiation);
399 if (Var->getAnyInitializer()) {
400 // We already have an initializer in the class.
401 } else if (D->getInit()) {
402 if (Var->isStaticDataMember() && !D->isOutOfLine())
403 SemaRef.PushExpressionEvaluationContext(Sema::ConstantEvaluated, D);
405 SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated, D);
407 // Instantiate the initializer.
408 ExprResult Init = SemaRef.SubstInitializer(D->getInit(), TemplateArgs,
409 D->getInitStyle() == VarDecl::CallInit);
410 if (!Init.isInvalid()) {
411 bool TypeMayContainAuto = true;
413 bool DirectInit = D->isDirectInit();
414 SemaRef.AddInitializerToDecl(Var, Init.take(), DirectInit,
417 SemaRef.ActOnUninitializedDecl(Var, TypeMayContainAuto);
419 // FIXME: Not too happy about invalidating the declaration
420 // because of a bogus initializer.
421 Var->setInvalidDecl();
424 SemaRef.PopExpressionEvaluationContext();
425 } else if ((!Var->isStaticDataMember() || Var->isOutOfLine()) &&
426 !Var->isCXXForRangeDecl())
427 SemaRef.ActOnUninitializedDecl(Var, false);
429 // Diagnose unused local variables with dependent types, where the diagnostic
430 // will have been deferred.
431 if (!Var->isInvalidDecl() && Owner->isFunctionOrMethod() && !Var->isUsed() &&
432 D->getType()->isDependentType())
433 SemaRef.DiagnoseUnusedDecl(Var);
438 Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
440 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
441 D->getAccessSpecifierLoc(), D->getColonLoc());
442 Owner->addHiddenDecl(AD);
446 Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
447 bool Invalid = false;
448 TypeSourceInfo *DI = D->getTypeSourceInfo();
449 if (DI->getType()->isInstantiationDependentType() ||
450 DI->getType()->isVariablyModifiedType()) {
451 DI = SemaRef.SubstType(DI, TemplateArgs,
452 D->getLocation(), D->getDeclName());
454 DI = D->getTypeSourceInfo();
456 } else if (DI->getType()->isFunctionType()) {
457 // C++ [temp.arg.type]p3:
458 // If a declaration acquires a function type through a type
459 // dependent on a template-parameter and this causes a
460 // declaration that does not use the syntactic form of a
461 // function declarator to have function type, the program is
463 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
468 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
471 Expr *BitWidth = D->getBitWidth();
475 // The bit-width expression is a constant expression.
476 EnterExpressionEvaluationContext Unevaluated(SemaRef,
477 Sema::ConstantEvaluated);
479 ExprResult InstantiatedBitWidth
480 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
481 if (InstantiatedBitWidth.isInvalid()) {
485 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
488 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
490 cast<RecordDecl>(Owner),
494 D->getInClassInitStyle(),
495 D->getInnerLocStart(),
499 cast<Decl>(Owner)->setInvalidDecl();
503 SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
505 if (Field->hasAttrs())
506 SemaRef.CheckAlignasUnderalignment(Field);
509 Field->setInvalidDecl();
511 if (!Field->getDeclName()) {
512 // Keep track of where this decl came from.
513 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
515 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
516 if (Parent->isAnonymousStructOrUnion() &&
517 Parent->getRedeclContext()->isFunctionOrMethod())
518 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
521 Field->setImplicit(D->isImplicit());
522 Field->setAccess(D->getAccess());
523 Owner->addDecl(Field);
528 Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) {
529 bool Invalid = false;
530 TypeSourceInfo *DI = D->getTypeSourceInfo();
532 if (DI->getType()->isVariablyModifiedType()) {
533 SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified)
536 } else if (DI->getType()->isInstantiationDependentType()) {
537 DI = SemaRef.SubstType(DI, TemplateArgs,
538 D->getLocation(), D->getDeclName());
540 DI = D->getTypeSourceInfo();
542 } else if (DI->getType()->isFunctionType()) {
543 // C++ [temp.arg.type]p3:
544 // If a declaration acquires a function type through a type
545 // dependent on a template-parameter and this causes a
546 // declaration that does not use the syntactic form of a
547 // function declarator to have function type, the program is
549 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
554 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
557 MSPropertyDecl *Property = new (SemaRef.Context)
558 MSPropertyDecl(Owner, D->getLocation(),
559 D->getDeclName(), DI->getType(), DI,
561 D->getGetterId(), D->getSetterId());
563 SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs,
567 Property->setInvalidDecl();
569 Property->setAccess(D->getAccess());
570 Owner->addDecl(Property);
575 Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
576 NamedDecl **NamedChain =
577 new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
580 for (IndirectFieldDecl::chain_iterator PI =
581 D->chain_begin(), PE = D->chain_end();
583 NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), *PI,
588 NamedChain[i++] = Next;
591 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
592 IndirectFieldDecl* IndirectField
593 = IndirectFieldDecl::Create(SemaRef.Context, Owner, D->getLocation(),
594 D->getIdentifier(), T,
595 NamedChain, D->getChainingSize());
598 IndirectField->setImplicit(D->isImplicit());
599 IndirectField->setAccess(D->getAccess());
600 Owner->addDecl(IndirectField);
601 return IndirectField;
604 Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
605 // Handle friend type expressions by simply substituting template
606 // parameters into the pattern type and checking the result.
607 if (TypeSourceInfo *Ty = D->getFriendType()) {
608 TypeSourceInfo *InstTy;
609 // If this is an unsupported friend, don't bother substituting template
610 // arguments into it. The actual type referred to won't be used by any
611 // parts of Clang, and may not be valid for instantiating. Just use the
612 // same info for the instantiated friend.
613 if (D->isUnsupportedFriend()) {
616 InstTy = SemaRef.SubstType(Ty, TemplateArgs,
617 D->getLocation(), DeclarationName());
622 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getLocStart(),
623 D->getFriendLoc(), InstTy);
627 FD->setAccess(AS_public);
628 FD->setUnsupportedFriend(D->isUnsupportedFriend());
633 NamedDecl *ND = D->getFriendDecl();
634 assert(ND && "friend decl must be a decl or a type!");
636 // All of the Visit implementations for the various potential friend
637 // declarations have to be carefully written to work for friend
638 // objects, with the most important detail being that the target
639 // decl should almost certainly not be placed in Owner.
640 Decl *NewND = Visit(ND);
641 if (!NewND) return 0;
644 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
645 cast<NamedDecl>(NewND), D->getFriendLoc());
646 FD->setAccess(AS_public);
647 FD->setUnsupportedFriend(D->isUnsupportedFriend());
652 Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
653 Expr *AssertExpr = D->getAssertExpr();
655 // The expression in a static assertion is a constant expression.
656 EnterExpressionEvaluationContext Unevaluated(SemaRef,
657 Sema::ConstantEvaluated);
659 ExprResult InstantiatedAssertExpr
660 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
661 if (InstantiatedAssertExpr.isInvalid())
664 return SemaRef.BuildStaticAssertDeclaration(D->getLocation(),
665 InstantiatedAssertExpr.get(),
671 Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
672 EnumDecl *PrevDecl = 0;
673 if (D->getPreviousDecl()) {
674 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
675 D->getPreviousDecl(),
678 PrevDecl = cast<EnumDecl>(Prev);
681 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
682 D->getLocation(), D->getIdentifier(),
683 PrevDecl, D->isScoped(),
684 D->isScopedUsingClassTag(), D->isFixed());
686 if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
687 // If we have type source information for the underlying type, it means it
688 // has been explicitly set by the user. Perform substitution on it before
690 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
691 TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
693 if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
694 Enum->setIntegerType(SemaRef.Context.IntTy);
696 Enum->setIntegerTypeSourceInfo(NewTI);
698 assert(!D->getIntegerType()->isDependentType()
699 && "Dependent type without type source info");
700 Enum->setIntegerType(D->getIntegerType());
704 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
706 Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
707 Enum->setAccess(D->getAccess());
708 if (SubstQualifier(D, Enum)) return 0;
709 Owner->addDecl(Enum);
711 EnumDecl *Def = D->getDefinition();
712 if (Def && Def != D) {
713 // If this is an out-of-line definition of an enum member template, check
714 // that the underlying types match in the instantiation of both
716 if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
717 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
718 QualType DefnUnderlying =
719 SemaRef.SubstType(TI->getType(), TemplateArgs,
720 UnderlyingLoc, DeclarationName());
721 SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
722 DefnUnderlying, Enum);
726 if (D->getDeclContext()->isFunctionOrMethod())
727 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
729 // C++11 [temp.inst]p1: The implicit instantiation of a class template
730 // specialization causes the implicit instantiation of the declarations, but
731 // not the definitions of scoped member enumerations.
732 // FIXME: There appears to be no wording for what happens for an enum defined
733 // within a block scope, but we treat that much like a member template. Only
734 // instantiate the definition when visiting the definition in that case, since
735 // we will visit all redeclarations.
736 if (!Enum->isScoped() && Def &&
737 (!D->getDeclContext()->isFunctionOrMethod() || D->isCompleteDefinition()))
738 InstantiateEnumDefinition(Enum, Def);
743 void TemplateDeclInstantiator::InstantiateEnumDefinition(
744 EnumDecl *Enum, EnumDecl *Pattern) {
745 Enum->startDefinition();
747 // Update the location to refer to the definition.
748 Enum->setLocation(Pattern->getLocation());
750 SmallVector<Decl*, 4> Enumerators;
752 EnumConstantDecl *LastEnumConst = 0;
753 for (EnumDecl::enumerator_iterator EC = Pattern->enumerator_begin(),
754 ECEnd = Pattern->enumerator_end();
756 // The specified value for the enumerator.
757 ExprResult Value = SemaRef.Owned((Expr *)0);
758 if (Expr *UninstValue = EC->getInitExpr()) {
759 // The enumerator's value expression is a constant expression.
760 EnterExpressionEvaluationContext Unevaluated(SemaRef,
761 Sema::ConstantEvaluated);
763 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
766 // Drop the initial value and continue.
767 bool isInvalid = false;
768 if (Value.isInvalid()) {
769 Value = SemaRef.Owned((Expr *)0);
773 EnumConstantDecl *EnumConst
774 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
775 EC->getLocation(), EC->getIdentifier(),
780 EnumConst->setInvalidDecl();
781 Enum->setInvalidDecl();
785 SemaRef.InstantiateAttrs(TemplateArgs, *EC, EnumConst);
787 EnumConst->setAccess(Enum->getAccess());
788 Enum->addDecl(EnumConst);
789 Enumerators.push_back(EnumConst);
790 LastEnumConst = EnumConst;
792 if (Pattern->getDeclContext()->isFunctionOrMethod() &&
794 // If the enumeration is within a function or method, record the enum
795 // constant as a local.
796 SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst);
801 // FIXME: Fixup LBraceLoc
802 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(),
803 Enum->getRBraceLoc(), Enum,
808 Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
809 llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
812 Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
813 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
815 // Create a local instantiation scope for this class template, which
816 // will contain the instantiations of the template parameters.
817 LocalInstantiationScope Scope(SemaRef);
818 TemplateParameterList *TempParams = D->getTemplateParameters();
819 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
823 CXXRecordDecl *Pattern = D->getTemplatedDecl();
825 // Instantiate the qualifier. We have to do this first in case
826 // we're a friend declaration, because if we are then we need to put
827 // the new declaration in the appropriate context.
828 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
830 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
836 CXXRecordDecl *PrevDecl = 0;
837 ClassTemplateDecl *PrevClassTemplate = 0;
839 if (!isFriend && Pattern->getPreviousDecl()) {
840 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
841 if (!Found.empty()) {
842 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
843 if (PrevClassTemplate)
844 PrevDecl = PrevClassTemplate->getTemplatedDecl();
848 // If this isn't a friend, then it's a member template, in which
849 // case we just want to build the instantiation in the
850 // specialization. If it is a friend, we want to build it in
851 // the appropriate context.
852 DeclContext *DC = Owner;
856 SS.Adopt(QualifierLoc);
857 DC = SemaRef.computeDeclContext(SS);
860 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
861 Pattern->getDeclContext(),
865 // Look for a previous declaration of the template in the owning
867 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
868 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
869 SemaRef.LookupQualifiedName(R, DC);
871 if (R.isSingleResult()) {
872 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
873 if (PrevClassTemplate)
874 PrevDecl = PrevClassTemplate->getTemplatedDecl();
877 if (!PrevClassTemplate && QualifierLoc) {
878 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
879 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
880 << QualifierLoc.getSourceRange();
884 bool AdoptedPreviousTemplateParams = false;
885 if (PrevClassTemplate) {
886 bool Complain = true;
888 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
889 // template for struct std::tr1::__detail::_Map_base, where the
890 // template parameters of the friend declaration don't match the
891 // template parameters of the original declaration. In this one
892 // case, we don't complain about the ill-formed friend
894 if (isFriend && Pattern->getIdentifier() &&
895 Pattern->getIdentifier()->isStr("_Map_base") &&
897 cast<NamespaceDecl>(DC)->getIdentifier() &&
898 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
899 DeclContext *DCParent = DC->getParent();
900 if (DCParent->isNamespace() &&
901 cast<NamespaceDecl>(DCParent)->getIdentifier() &&
902 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
903 DeclContext *DCParent2 = DCParent->getParent();
904 if (DCParent2->isNamespace() &&
905 cast<NamespaceDecl>(DCParent2)->getIdentifier() &&
906 cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") &&
907 DCParent2->getParent()->isTranslationUnit())
912 TemplateParameterList *PrevParams
913 = PrevClassTemplate->getTemplateParameters();
915 // Make sure the parameter lists match.
916 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
918 Sema::TPL_TemplateMatch)) {
922 AdoptedPreviousTemplateParams = true;
923 InstParams = PrevParams;
926 // Do some additional validation, then merge default arguments
927 // from the existing declarations.
928 if (!AdoptedPreviousTemplateParams &&
929 SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
930 Sema::TPC_ClassTemplate))
935 CXXRecordDecl *RecordInst
936 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
937 Pattern->getLocStart(), Pattern->getLocation(),
938 Pattern->getIdentifier(), PrevDecl,
939 /*DelayTypeCreation=*/true);
942 RecordInst->setQualifierInfo(QualifierLoc);
944 ClassTemplateDecl *Inst
945 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
946 D->getIdentifier(), InstParams, RecordInst,
948 RecordInst->setDescribedClassTemplate(Inst);
951 if (PrevClassTemplate)
952 Inst->setAccess(PrevClassTemplate->getAccess());
954 Inst->setAccess(D->getAccess());
956 Inst->setObjectOfFriendDecl(PrevClassTemplate != 0);
957 // TODO: do we want to track the instantiation progeny of this
958 // friend target decl?
960 Inst->setAccess(D->getAccess());
961 if (!PrevClassTemplate)
962 Inst->setInstantiatedFromMemberTemplate(D);
965 // Trigger creation of the type for the instantiation.
966 SemaRef.Context.getInjectedClassNameType(RecordInst,
967 Inst->getInjectedClassNameSpecialization());
969 // Finish handling of friends.
971 DC->makeDeclVisibleInContext(Inst);
972 Inst->setLexicalDeclContext(Owner);
973 RecordInst->setLexicalDeclContext(Owner);
977 if (D->isOutOfLine()) {
978 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
979 RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
982 Owner->addDecl(Inst);
984 if (!PrevClassTemplate) {
985 // Queue up any out-of-line partial specializations of this member
986 // class template; the client will force their instantiation once
987 // the enclosing class has been instantiated.
988 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
989 D->getPartialSpecializations(PartialSpecs);
990 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
991 if (PartialSpecs[I]->isOutOfLine())
992 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
999 TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
1000 ClassTemplatePartialSpecializationDecl *D) {
1001 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
1003 // Lookup the already-instantiated declaration in the instantiation
1004 // of the class template and return that.
1005 DeclContext::lookup_result Found
1006 = Owner->lookup(ClassTemplate->getDeclName());
1010 ClassTemplateDecl *InstClassTemplate
1011 = dyn_cast<ClassTemplateDecl>(Found.front());
1012 if (!InstClassTemplate)
1015 if (ClassTemplatePartialSpecializationDecl *Result
1016 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
1019 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
1023 TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
1024 // Create a local instantiation scope for this function template, which
1025 // will contain the instantiations of the template parameters and then get
1026 // merged with the local instantiation scope for the function template
1028 LocalInstantiationScope Scope(SemaRef);
1030 TemplateParameterList *TempParams = D->getTemplateParameters();
1031 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1035 FunctionDecl *Instantiated = 0;
1036 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
1037 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
1040 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
1041 D->getTemplatedDecl(),
1047 // Link the instantiated function template declaration to the function
1048 // template from which it was instantiated.
1049 FunctionTemplateDecl *InstTemplate
1050 = Instantiated->getDescribedFunctionTemplate();
1051 InstTemplate->setAccess(D->getAccess());
1052 assert(InstTemplate &&
1053 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
1055 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
1057 // Link the instantiation back to the pattern *unless* this is a
1058 // non-definition friend declaration.
1059 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
1060 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
1061 InstTemplate->setInstantiatedFromMemberTemplate(D);
1063 // Make declarations visible in the appropriate context.
1065 Owner->addDecl(InstTemplate);
1066 } else if (InstTemplate->getDeclContext()->isRecord() &&
1067 !D->getPreviousDecl()) {
1068 SemaRef.CheckFriendAccess(InstTemplate);
1071 return InstTemplate;
1074 Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
1075 CXXRecordDecl *PrevDecl = 0;
1076 if (D->isInjectedClassName())
1077 PrevDecl = cast<CXXRecordDecl>(Owner);
1078 else if (D->getPreviousDecl()) {
1079 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
1080 D->getPreviousDecl(),
1082 if (!Prev) return 0;
1083 PrevDecl = cast<CXXRecordDecl>(Prev);
1086 CXXRecordDecl *Record
1087 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
1088 D->getLocStart(), D->getLocation(),
1089 D->getIdentifier(), PrevDecl);
1091 // Substitute the nested name specifier, if any.
1092 if (SubstQualifier(D, Record))
1095 Record->setImplicit(D->isImplicit());
1096 // FIXME: Check against AS_none is an ugly hack to work around the issue that
1097 // the tag decls introduced by friend class declarations don't have an access
1098 // specifier. Remove once this area of the code gets sorted out.
1099 if (D->getAccess() != AS_none)
1100 Record->setAccess(D->getAccess());
1101 if (!D->isInjectedClassName())
1102 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
1104 // If the original function was part of a friend declaration,
1105 // inherit its namespace state.
1106 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
1107 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
1109 // Make sure that anonymous structs and unions are recorded.
1110 if (D->isAnonymousStructOrUnion()) {
1111 Record->setAnonymousStructOrUnion(true);
1112 if (Record->getDeclContext()->getRedeclContext()->isFunctionOrMethod())
1113 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
1116 Owner->addDecl(Record);
1120 /// \brief Adjust the given function type for an instantiation of the
1121 /// given declaration, to cope with modifications to the function's type that
1122 /// aren't reflected in the type-source information.
1124 /// \param D The declaration we're instantiating.
1125 /// \param TInfo The already-instantiated type.
1126 static QualType adjustFunctionTypeForInstantiation(ASTContext &Context,
1128 TypeSourceInfo *TInfo) {
1129 const FunctionProtoType *OrigFunc
1130 = D->getType()->castAs<FunctionProtoType>();
1131 const FunctionProtoType *NewFunc
1132 = TInfo->getType()->castAs<FunctionProtoType>();
1133 if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
1134 return TInfo->getType();
1136 FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
1137 NewEPI.ExtInfo = OrigFunc->getExtInfo();
1138 return Context.getFunctionType(NewFunc->getResultType(),
1139 ArrayRef<QualType>(NewFunc->arg_type_begin(),
1140 NewFunc->getNumArgs()),
1144 /// Normal class members are of more specific types and therefore
1145 /// don't make it here. This function serves two purposes:
1146 /// 1) instantiating function templates
1147 /// 2) substituting friend declarations
1148 /// FIXME: preserve function definitions in case #2
1149 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
1150 TemplateParameterList *TemplateParams) {
1151 // Check whether there is already a function template specialization for
1152 // this declaration.
1153 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1154 if (FunctionTemplate && !TemplateParams) {
1155 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
1157 void *InsertPos = 0;
1158 FunctionDecl *SpecFunc
1159 = FunctionTemplate->findSpecialization(Innermost.begin(), Innermost.size(),
1162 // If we already have a function template specialization, return it.
1168 if (FunctionTemplate)
1169 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1171 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1173 bool MergeWithParentScope = (TemplateParams != 0) ||
1174 Owner->isFunctionOrMethod() ||
1175 !(isa<Decl>(Owner) &&
1176 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1177 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
1179 SmallVector<ParmVarDecl *, 4> Params;
1180 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
1183 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
1185 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1187 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1193 // If we're instantiating a local function declaration, put the result
1194 // in the owner; otherwise we need to find the instantiated context.
1196 if (D->getDeclContext()->isFunctionOrMethod())
1198 else if (isFriend && QualifierLoc) {
1200 SS.Adopt(QualifierLoc);
1201 DC = SemaRef.computeDeclContext(SS);
1204 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
1208 FunctionDecl *Function =
1209 FunctionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
1210 D->getNameInfo(), T, TInfo,
1211 D->getCanonicalDecl()->getStorageClass(),
1212 D->isInlineSpecified(), D->hasWrittenPrototype(),
1216 Function->setImplicitlyInline();
1219 Function->setQualifierInfo(QualifierLoc);
1221 DeclContext *LexicalDC = Owner;
1222 if (!isFriend && D->isOutOfLine()) {
1223 assert(D->getDeclContext()->isFileContext());
1224 LexicalDC = D->getDeclContext();
1227 Function->setLexicalDeclContext(LexicalDC);
1229 // Attach the parameters
1230 if (isa<FunctionProtoType>(Function->getType().IgnoreParens())) {
1231 // Adopt the already-instantiated parameters into our own context.
1232 for (unsigned P = 0; P < Params.size(); ++P)
1234 Params[P]->setOwningFunction(Function);
1236 // Since we were instantiated via a typedef of a function type, create
1238 const FunctionProtoType *Proto
1239 = Function->getType()->getAs<FunctionProtoType>();
1240 assert(Proto && "No function prototype in template instantiation?");
1241 for (FunctionProtoType::arg_type_iterator AI = Proto->arg_type_begin(),
1242 AE = Proto->arg_type_end(); AI != AE; ++AI) {
1244 = SemaRef.BuildParmVarDeclForTypedef(Function, Function->getLocation(),
1246 Param->setScopeInfo(0, Params.size());
1247 Params.push_back(Param);
1250 Function->setParams(Params);
1252 SourceLocation InstantiateAtPOI;
1253 if (TemplateParams) {
1254 // Our resulting instantiation is actually a function template, since we
1255 // are substituting only the outer template parameters. For example, given
1257 // template<typename T>
1259 // template<typename U> friend void f(T, U);
1264 // We are instantiating the friend function template "f" within X<int>,
1265 // which means substituting int for T, but leaving "f" as a friend function
1267 // Build the function template itself.
1268 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
1269 Function->getLocation(),
1270 Function->getDeclName(),
1271 TemplateParams, Function);
1272 Function->setDescribedFunctionTemplate(FunctionTemplate);
1274 FunctionTemplate->setLexicalDeclContext(LexicalDC);
1276 if (isFriend && D->isThisDeclarationADefinition()) {
1277 // TODO: should we remember this connection regardless of whether
1278 // the friend declaration provided a body?
1279 FunctionTemplate->setInstantiatedFromMemberTemplate(
1280 D->getDescribedFunctionTemplate());
1282 } else if (FunctionTemplate) {
1283 // Record this function template specialization.
1284 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
1285 Function->setFunctionTemplateSpecialization(FunctionTemplate,
1286 TemplateArgumentList::CreateCopy(SemaRef.Context,
1290 } else if (isFriend) {
1291 // Note, we need this connection even if the friend doesn't have a body.
1292 // Its body may exist but not have been attached yet due to deferred
1294 // FIXME: It might be cleaner to set this when attaching the body to the
1295 // friend function declaration, however that would require finding all the
1296 // instantiations and modifying them.
1297 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
1300 if (InitFunctionInstantiation(Function, D))
1301 Function->setInvalidDecl();
1303 bool isExplicitSpecialization = false;
1305 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
1306 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
1308 if (DependentFunctionTemplateSpecializationInfo *Info
1309 = D->getDependentSpecializationInfo()) {
1310 assert(isFriend && "non-friend has dependent specialization info?");
1312 // This needs to be set now for future sanity.
1313 Function->setObjectOfFriendDecl(/*HasPrevious*/ true);
1315 // Instantiate the explicit template arguments.
1316 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1317 Info->getRAngleLoc());
1318 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1319 ExplicitArgs, TemplateArgs))
1322 // Map the candidate templates to their instantiations.
1323 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1324 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1325 Info->getTemplate(I),
1327 if (!Temp) return 0;
1329 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1332 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1335 Function->setInvalidDecl();
1337 isExplicitSpecialization = true;
1339 } else if (TemplateParams || !FunctionTemplate) {
1340 // Look only into the namespace where the friend would be declared to
1341 // find a previous declaration. This is the innermost enclosing namespace,
1342 // as described in ActOnFriendFunctionDecl.
1343 SemaRef.LookupQualifiedName(Previous, DC);
1345 // In C++, the previous declaration we find might be a tag type
1346 // (class or enum). In this case, the new declaration will hide the
1347 // tag type. Note that this does does not apply if we're declaring a
1348 // typedef (C++ [dcl.typedef]p4).
1349 if (Previous.isSingleTagDecl())
1353 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
1354 isExplicitSpecialization);
1356 NamedDecl *PrincipalDecl = (TemplateParams
1357 ? cast<NamedDecl>(FunctionTemplate)
1360 // If the original function was part of a friend declaration,
1361 // inherit its namespace state and add it to the owner.
1363 NamedDecl *PrevDecl;
1365 PrevDecl = FunctionTemplate->getPreviousDecl();
1367 PrevDecl = Function->getPreviousDecl();
1369 PrincipalDecl->setObjectOfFriendDecl(PrevDecl != 0);
1370 DC->makeDeclVisibleInContext(PrincipalDecl);
1372 bool queuedInstantiation = false;
1374 // C++98 [temp.friend]p5: When a function is defined in a friend function
1375 // declaration in a class template, the function is defined at each
1376 // instantiation of the class template. The function is defined even if it
1378 // C++11 [temp.friend]p4: When a function is defined in a friend function
1379 // declaration in a class template, the function is instantiated when the
1380 // function is odr-used.
1382 // If -Wc++98-compat is enabled, we go through the motions of checking for a
1383 // redefinition, but don't instantiate the function.
1384 if ((!SemaRef.getLangOpts().CPlusPlus11 ||
1385 SemaRef.Diags.getDiagnosticLevel(
1386 diag::warn_cxx98_compat_friend_redefinition,
1387 Function->getLocation())
1388 != DiagnosticsEngine::Ignored) &&
1389 D->isThisDeclarationADefinition()) {
1390 // Check for a function body.
1391 const FunctionDecl *Definition = 0;
1392 if (Function->isDefined(Definition) &&
1393 Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
1394 SemaRef.Diag(Function->getLocation(),
1395 SemaRef.getLangOpts().CPlusPlus11 ?
1396 diag::warn_cxx98_compat_friend_redefinition :
1397 diag::err_redefinition) << Function->getDeclName();
1398 SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
1399 if (!SemaRef.getLangOpts().CPlusPlus11)
1400 Function->setInvalidDecl();
1402 // Check for redefinitions due to other instantiations of this or
1403 // a similar friend function.
1404 else for (FunctionDecl::redecl_iterator R = Function->redecls_begin(),
1405 REnd = Function->redecls_end();
1409 switch (R->getFriendObjectKind()) {
1410 case Decl::FOK_None:
1411 if (!SemaRef.getLangOpts().CPlusPlus11 &&
1412 !queuedInstantiation && R->isUsed(false)) {
1413 if (MemberSpecializationInfo *MSInfo
1414 = Function->getMemberSpecializationInfo()) {
1415 if (MSInfo->getPointOfInstantiation().isInvalid()) {
1416 SourceLocation Loc = R->getLocation(); // FIXME
1417 MSInfo->setPointOfInstantiation(Loc);
1418 SemaRef.PendingLocalImplicitInstantiations.push_back(
1419 std::make_pair(Function, Loc));
1420 queuedInstantiation = true;
1426 if (const FunctionDecl *RPattern
1427 = R->getTemplateInstantiationPattern())
1428 if (RPattern->isDefined(RPattern)) {
1429 SemaRef.Diag(Function->getLocation(),
1430 SemaRef.getLangOpts().CPlusPlus11 ?
1431 diag::warn_cxx98_compat_friend_redefinition :
1432 diag::err_redefinition)
1433 << Function->getDeclName();
1434 SemaRef.Diag(R->getLocation(), diag::note_previous_definition);
1435 if (!SemaRef.getLangOpts().CPlusPlus11)
1436 Function->setInvalidDecl();
1444 if (Function->isOverloadedOperator() && !DC->isRecord() &&
1445 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1446 PrincipalDecl->setNonMemberOperator();
1448 assert(!D->isDefaulted() && "only methods should be defaulted");
1453 TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
1454 TemplateParameterList *TemplateParams,
1455 bool IsClassScopeSpecialization) {
1456 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1457 if (FunctionTemplate && !TemplateParams) {
1458 // We are creating a function template specialization from a function
1459 // template. Check whether there is already a function template
1460 // specialization for this particular set of template arguments.
1461 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
1463 void *InsertPos = 0;
1464 FunctionDecl *SpecFunc
1465 = FunctionTemplate->findSpecialization(Innermost.begin(),
1469 // If we already have a function template specialization, return it.
1475 if (FunctionTemplate)
1476 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1478 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1480 bool MergeWithParentScope = (TemplateParams != 0) ||
1481 !(isa<Decl>(Owner) &&
1482 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1483 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
1485 // Instantiate enclosing template arguments for friends.
1486 SmallVector<TemplateParameterList *, 4> TempParamLists;
1487 unsigned NumTempParamLists = 0;
1488 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
1489 TempParamLists.set_size(NumTempParamLists);
1490 for (unsigned I = 0; I != NumTempParamLists; ++I) {
1491 TemplateParameterList *TempParams = D->getTemplateParameterList(I);
1492 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1495 TempParamLists[I] = InstParams;
1499 SmallVector<ParmVarDecl *, 4> Params;
1500 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
1503 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
1505 // \brief If the type of this function, after ignoring parentheses,
1506 // is not *directly* a function type, then we're instantiating a function
1507 // that was declared via a typedef, e.g.,
1509 // typedef int functype(int, int);
1512 // In this case, we'll just go instantiate the ParmVarDecls that we
1513 // synthesized in the method declaration.
1514 if (!isa<FunctionProtoType>(T.IgnoreParens())) {
1515 assert(!Params.size() && "Instantiating type could not yield parameters");
1516 SmallVector<QualType, 4> ParamTypes;
1517 if (SemaRef.SubstParmTypes(D->getLocation(), D->param_begin(),
1518 D->getNumParams(), TemplateArgs, ParamTypes,
1523 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1525 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1531 DeclContext *DC = Owner;
1535 SS.Adopt(QualifierLoc);
1536 DC = SemaRef.computeDeclContext(SS);
1538 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
1541 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1542 D->getDeclContext(),
1548 // Build the instantiated method declaration.
1549 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1550 CXXMethodDecl *Method = 0;
1552 SourceLocation StartLoc = D->getInnerLocStart();
1553 DeclarationNameInfo NameInfo
1554 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
1555 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
1556 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
1557 StartLoc, NameInfo, T, TInfo,
1558 Constructor->isExplicit(),
1559 Constructor->isInlineSpecified(),
1560 false, Constructor->isConstexpr());
1562 // Claim that the instantiation of a constructor or constructor template
1563 // inherits the same constructor that the template does.
1564 if (CXXConstructorDecl *Inh = const_cast<CXXConstructorDecl *>(
1565 Constructor->getInheritedConstructor())) {
1566 // If we're instantiating a specialization of a function template, our
1567 // "inherited constructor" will actually itself be a function template.
1568 // Instantiate a declaration of it, too.
1569 if (FunctionTemplate) {
1570 assert(!TemplateParams && Inh->getDescribedFunctionTemplate() &&
1571 !Inh->getParent()->isDependentContext() &&
1572 "inheriting constructor template in dependent context?");
1573 Sema::InstantiatingTemplate Inst(SemaRef, Constructor->getLocation(),
1577 Sema::ContextRAII SavedContext(SemaRef, Inh->getDeclContext());
1578 LocalInstantiationScope LocalScope(SemaRef);
1580 // Use the same template arguments that we deduced for the inheriting
1581 // constructor. There's no way they could be deduced differently.
1582 MultiLevelTemplateArgumentList InheritedArgs;
1583 InheritedArgs.addOuterTemplateArguments(TemplateArgs.getInnermost());
1584 Inh = cast_or_null<CXXConstructorDecl>(
1585 SemaRef.SubstDecl(Inh, Inh->getDeclContext(), InheritedArgs));
1589 cast<CXXConstructorDecl>(Method)->setInheritedConstructor(Inh);
1591 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
1592 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
1593 StartLoc, NameInfo, T, TInfo,
1594 Destructor->isInlineSpecified(),
1596 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
1597 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
1598 StartLoc, NameInfo, T, TInfo,
1599 Conversion->isInlineSpecified(),
1600 Conversion->isExplicit(),
1601 Conversion->isConstexpr(),
1602 Conversion->getLocEnd());
1604 StorageClass SC = D->isStatic() ? SC_Static : SC_None;
1605 Method = CXXMethodDecl::Create(SemaRef.Context, Record,
1606 StartLoc, NameInfo, T, TInfo,
1607 SC, D->isInlineSpecified(),
1608 D->isConstexpr(), D->getLocEnd());
1612 Method->setImplicitlyInline();
1615 Method->setQualifierInfo(QualifierLoc);
1617 if (TemplateParams) {
1618 // Our resulting instantiation is actually a function template, since we
1619 // are substituting only the outer template parameters. For example, given
1621 // template<typename T>
1623 // template<typename U> void f(T, U);
1628 // We are instantiating the member template "f" within X<int>, which means
1629 // substituting int for T, but leaving "f" as a member function template.
1630 // Build the function template itself.
1631 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1632 Method->getLocation(),
1633 Method->getDeclName(),
1634 TemplateParams, Method);
1636 FunctionTemplate->setLexicalDeclContext(Owner);
1637 FunctionTemplate->setObjectOfFriendDecl(true);
1638 } else if (D->isOutOfLine())
1639 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
1640 Method->setDescribedFunctionTemplate(FunctionTemplate);
1641 } else if (FunctionTemplate) {
1642 // Record this function template specialization.
1643 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
1644 Method->setFunctionTemplateSpecialization(FunctionTemplate,
1645 TemplateArgumentList::CreateCopy(SemaRef.Context,
1649 } else if (!isFriend) {
1650 // Record that this is an instantiation of a member function.
1651 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
1654 // If we are instantiating a member function defined
1655 // out-of-line, the instantiation will have the same lexical
1656 // context (which will be a namespace scope) as the template.
1658 if (NumTempParamLists)
1659 Method->setTemplateParameterListsInfo(SemaRef.Context,
1661 TempParamLists.data());
1663 Method->setLexicalDeclContext(Owner);
1664 Method->setObjectOfFriendDecl(true);
1665 } else if (D->isOutOfLine())
1666 Method->setLexicalDeclContext(D->getLexicalDeclContext());
1668 // Attach the parameters
1669 for (unsigned P = 0; P < Params.size(); ++P)
1670 Params[P]->setOwningFunction(Method);
1671 Method->setParams(Params);
1673 if (InitMethodInstantiation(Method, D))
1674 Method->setInvalidDecl();
1676 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
1677 Sema::ForRedeclaration);
1679 if (!FunctionTemplate || TemplateParams || isFriend) {
1680 SemaRef.LookupQualifiedName(Previous, Record);
1682 // In C++, the previous declaration we find might be a tag type
1683 // (class or enum). In this case, the new declaration will hide the
1684 // tag type. Note that this does does not apply if we're declaring a
1685 // typedef (C++ [dcl.typedef]p4).
1686 if (Previous.isSingleTagDecl())
1690 if (!IsClassScopeSpecialization)
1691 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false);
1694 SemaRef.CheckPureMethod(Method, SourceRange());
1696 // Propagate access. For a non-friend declaration, the access is
1697 // whatever we're propagating from. For a friend, it should be the
1698 // previous declaration we just found.
1699 if (isFriend && Method->getPreviousDecl())
1700 Method->setAccess(Method->getPreviousDecl()->getAccess());
1702 Method->setAccess(D->getAccess());
1703 if (FunctionTemplate)
1704 FunctionTemplate->setAccess(Method->getAccess());
1706 SemaRef.CheckOverrideControl(Method);
1708 // If a function is defined as defaulted or deleted, mark it as such now.
1709 if (D->isExplicitlyDefaulted())
1710 SemaRef.SetDeclDefaulted(Method, Method->getLocation());
1711 if (D->isDeletedAsWritten())
1712 SemaRef.SetDeclDeleted(Method, Method->getLocation());
1714 // If there's a function template, let our caller handle it.
1715 if (FunctionTemplate) {
1718 // Don't hide a (potentially) valid declaration with an invalid one.
1719 } else if (Method->isInvalidDecl() && !Previous.empty()) {
1722 // Otherwise, check access to friends and make them visible.
1723 } else if (isFriend) {
1724 // We only need to re-check access for methods which we didn't
1725 // manage to match during parsing.
1726 if (!D->getPreviousDecl())
1727 SemaRef.CheckFriendAccess(Method);
1729 Record->makeDeclVisibleInContext(Method);
1731 // Otherwise, add the declaration. We don't need to do this for
1732 // class-scope specializations because we'll have matched them with
1733 // the appropriate template.
1734 } else if (!IsClassScopeSpecialization) {
1735 Owner->addDecl(Method);
1741 Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
1742 return VisitCXXMethodDecl(D);
1745 Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
1746 return VisitCXXMethodDecl(D);
1749 Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
1750 return VisitCXXMethodDecl(D);
1753 ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
1754 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0, None,
1755 /*ExpectParameterPack=*/ false);
1758 Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1759 TemplateTypeParmDecl *D) {
1760 // TODO: don't always clone when decls are refcounted.
1761 assert(D->getTypeForDecl()->isTemplateTypeParmType());
1763 TemplateTypeParmDecl *Inst =
1764 TemplateTypeParmDecl::Create(SemaRef.Context, Owner,
1765 D->getLocStart(), D->getLocation(),
1766 D->getDepth() - TemplateArgs.getNumLevels(),
1767 D->getIndex(), D->getIdentifier(),
1768 D->wasDeclaredWithTypename(),
1769 D->isParameterPack());
1770 Inst->setAccess(AS_public);
1772 if (D->hasDefaultArgument())
1773 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
1775 // Introduce this template parameter's instantiation into the instantiation
1777 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1782 Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1783 NonTypeTemplateParmDecl *D) {
1784 // Substitute into the type of the non-type template parameter.
1785 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
1786 SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
1787 SmallVector<QualType, 4> ExpandedParameterPackTypes;
1788 bool IsExpandedParameterPack = false;
1791 bool Invalid = false;
1793 if (D->isExpandedParameterPack()) {
1794 // The non-type template parameter pack is an already-expanded pack
1795 // expansion of types. Substitute into each of the expanded types.
1796 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
1797 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
1798 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
1799 TypeSourceInfo *NewDI =SemaRef.SubstType(D->getExpansionTypeSourceInfo(I),
1806 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1807 QualType NewT =SemaRef.CheckNonTypeTemplateParameterType(NewDI->getType(),
1811 ExpandedParameterPackTypes.push_back(NewT);
1814 IsExpandedParameterPack = true;
1815 DI = D->getTypeSourceInfo();
1817 } else if (D->isPackExpansion()) {
1818 // The non-type template parameter pack's type is a pack expansion of types.
1819 // Determine whether we need to expand this parameter pack into separate
1821 PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>();
1822 TypeLoc Pattern = Expansion.getPatternLoc();
1823 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1824 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
1826 // Determine whether the set of unexpanded parameter packs can and should
1829 bool RetainExpansion = false;
1830 Optional<unsigned> OrigNumExpansions
1831 = Expansion.getTypePtr()->getNumExpansions();
1832 Optional<unsigned> NumExpansions = OrigNumExpansions;
1833 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
1834 Pattern.getSourceRange(),
1837 Expand, RetainExpansion,
1842 for (unsigned I = 0; I != *NumExpansions; ++I) {
1843 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
1844 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
1850 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1851 QualType NewT = SemaRef.CheckNonTypeTemplateParameterType(
1856 ExpandedParameterPackTypes.push_back(NewT);
1859 // Note that we have an expanded parameter pack. The "type" of this
1860 // expanded parameter pack is the original expansion type, but callers
1861 // will end up using the expanded parameter pack types for type-checking.
1862 IsExpandedParameterPack = true;
1863 DI = D->getTypeSourceInfo();
1866 // We cannot fully expand the pack expansion now, so substitute into the
1867 // pattern and create a new pack expansion type.
1868 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
1869 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
1875 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
1883 // Simple case: substitution into a parameter that is not a parameter pack.
1884 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
1885 D->getLocation(), D->getDeclName());
1889 // Check that this type is acceptable for a non-type template parameter.
1890 T = SemaRef.CheckNonTypeTemplateParameterType(DI->getType(),
1893 T = SemaRef.Context.IntTy;
1898 NonTypeTemplateParmDecl *Param;
1899 if (IsExpandedParameterPack)
1900 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
1901 D->getInnerLocStart(),
1903 D->getDepth() - TemplateArgs.getNumLevels(),
1905 D->getIdentifier(), T,
1907 ExpandedParameterPackTypes.data(),
1908 ExpandedParameterPackTypes.size(),
1909 ExpandedParameterPackTypesAsWritten.data());
1911 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
1912 D->getInnerLocStart(),
1914 D->getDepth() - TemplateArgs.getNumLevels(),
1916 D->getIdentifier(), T,
1917 D->isParameterPack(), DI);
1919 Param->setAccess(AS_public);
1921 Param->setInvalidDecl();
1923 Param->setDefaultArgument(D->getDefaultArgument(), false);
1925 // Introduce this template parameter's instantiation into the instantiation
1927 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1931 static void collectUnexpandedParameterPacks(
1933 TemplateParameterList *Params,
1934 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
1935 for (TemplateParameterList::const_iterator I = Params->begin(),
1936 E = Params->end(); I != E; ++I) {
1937 if ((*I)->isTemplateParameterPack())
1939 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*I))
1940 S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
1942 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(*I))
1943 collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
1949 TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1950 TemplateTemplateParmDecl *D) {
1951 // Instantiate the template parameter list of the template template parameter.
1952 TemplateParameterList *TempParams = D->getTemplateParameters();
1953 TemplateParameterList *InstParams;
1954 SmallVector<TemplateParameterList*, 8> ExpandedParams;
1956 bool IsExpandedParameterPack = false;
1958 if (D->isExpandedParameterPack()) {
1959 // The template template parameter pack is an already-expanded pack
1960 // expansion of template parameters. Substitute into each of the expanded
1962 ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
1963 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
1965 LocalInstantiationScope Scope(SemaRef);
1966 TemplateParameterList *Expansion =
1967 SubstTemplateParams(D->getExpansionTemplateParameters(I));
1970 ExpandedParams.push_back(Expansion);
1973 IsExpandedParameterPack = true;
1974 InstParams = TempParams;
1975 } else if (D->isPackExpansion()) {
1976 // The template template parameter pack expands to a pack of template
1977 // template parameters. Determine whether we need to expand this parameter
1978 // pack into separate parameters.
1979 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1980 collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(),
1983 // Determine whether the set of unexpanded parameter packs can and should
1986 bool RetainExpansion = false;
1987 Optional<unsigned> NumExpansions;
1988 if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(),
1989 TempParams->getSourceRange(),
1992 Expand, RetainExpansion,
1997 for (unsigned I = 0; I != *NumExpansions; ++I) {
1998 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
1999 LocalInstantiationScope Scope(SemaRef);
2000 TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
2003 ExpandedParams.push_back(Expansion);
2006 // Note that we have an expanded parameter pack. The "type" of this
2007 // expanded parameter pack is the original expansion type, but callers
2008 // will end up using the expanded parameter pack types for type-checking.
2009 IsExpandedParameterPack = true;
2010 InstParams = TempParams;
2012 // We cannot fully expand the pack expansion now, so just substitute
2013 // into the pattern.
2014 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2016 LocalInstantiationScope Scope(SemaRef);
2017 InstParams = SubstTemplateParams(TempParams);
2022 // Perform the actual substitution of template parameters within a new,
2023 // local instantiation scope.
2024 LocalInstantiationScope Scope(SemaRef);
2025 InstParams = SubstTemplateParams(TempParams);
2030 // Build the template template parameter.
2031 TemplateTemplateParmDecl *Param;
2032 if (IsExpandedParameterPack)
2033 Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
2035 D->getDepth() - TemplateArgs.getNumLevels(),
2037 D->getIdentifier(), InstParams,
2040 Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
2042 D->getDepth() - TemplateArgs.getNumLevels(),
2044 D->isParameterPack(),
2045 D->getIdentifier(), InstParams);
2046 Param->setDefaultArgument(D->getDefaultArgument(), false);
2047 Param->setAccess(AS_public);
2049 // Introduce this template parameter's instantiation into the instantiation
2051 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
2056 Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
2057 // Using directives are never dependent (and never contain any types or
2058 // expressions), so they require no explicit instantiation work.
2060 UsingDirectiveDecl *Inst
2061 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
2062 D->getNamespaceKeyLocation(),
2063 D->getQualifierLoc(),
2064 D->getIdentLocation(),
2065 D->getNominatedNamespace(),
2066 D->getCommonAncestor());
2068 // Add the using directive to its declaration context
2069 // only if this is not a function or method.
2070 if (!Owner->isFunctionOrMethod())
2071 Owner->addDecl(Inst);
2076 Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
2078 // The nested name specifier may be dependent, for example
2079 // template <typename T> struct t {
2080 // struct s1 { T f1(); };
2081 // struct s2 : s1 { using s1::f1; };
2083 // template struct t<int>;
2084 // Here, in using s1::f1, s1 refers to t<T>::s1;
2085 // we need to substitute for t<int>::s1.
2086 NestedNameSpecifierLoc QualifierLoc
2087 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
2092 // The name info is non-dependent, so no transformation
2094 DeclarationNameInfo NameInfo = D->getNameInfo();
2096 // We only need to do redeclaration lookups if we're in a class
2097 // scope (in fact, it's not really even possible in non-class
2099 bool CheckRedeclaration = Owner->isRecord();
2101 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
2102 Sema::ForRedeclaration);
2104 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
2105 D->getUsingLocation(),
2111 SS.Adopt(QualifierLoc);
2112 if (CheckRedeclaration) {
2113 Prev.setHideTags(false);
2114 SemaRef.LookupQualifiedName(Prev, Owner);
2116 // Check for invalid redeclarations.
2117 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
2118 D->isTypeName(), SS,
2119 D->getLocation(), Prev))
2120 NewUD->setInvalidDecl();
2124 if (!NewUD->isInvalidDecl() &&
2125 SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
2127 NewUD->setInvalidDecl();
2129 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
2130 NewUD->setAccess(D->getAccess());
2131 Owner->addDecl(NewUD);
2133 // Don't process the shadow decls for an invalid decl.
2134 if (NewUD->isInvalidDecl())
2137 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
2138 if (SemaRef.CheckInheritingConstructorUsingDecl(NewUD))
2139 NewUD->setInvalidDecl();
2143 bool isFunctionScope = Owner->isFunctionOrMethod();
2145 // Process the shadow decls.
2146 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
2148 UsingShadowDecl *Shadow = *I;
2149 NamedDecl *InstTarget =
2150 cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
2151 Shadow->getLocation(),
2152 Shadow->getTargetDecl(),
2157 if (CheckRedeclaration &&
2158 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
2161 UsingShadowDecl *InstShadow
2162 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
2163 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
2165 if (isFunctionScope)
2166 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
2172 Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
2173 // Ignore these; we handle them in bulk when processing the UsingDecl.
2177 Decl * TemplateDeclInstantiator
2178 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
2179 NestedNameSpecifierLoc QualifierLoc
2180 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
2186 SS.Adopt(QualifierLoc);
2188 // Since NameInfo refers to a typename, it cannot be a C++ special name.
2189 // Hence, no transformation is required for it.
2190 DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation());
2192 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
2193 D->getUsingLoc(), SS, NameInfo, 0,
2194 /*instantiation*/ true,
2195 /*typename*/ true, D->getTypenameLoc());
2197 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
2202 Decl * TemplateDeclInstantiator
2203 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
2204 NestedNameSpecifierLoc QualifierLoc
2205 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), TemplateArgs);
2210 SS.Adopt(QualifierLoc);
2212 DeclarationNameInfo NameInfo
2213 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2216 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
2217 D->getUsingLoc(), SS, NameInfo, 0,
2218 /*instantiation*/ true,
2219 /*typename*/ false, SourceLocation());
2221 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
2227 Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
2228 ClassScopeFunctionSpecializationDecl *Decl) {
2229 CXXMethodDecl *OldFD = Decl->getSpecialization();
2230 CXXMethodDecl *NewFD = cast<CXXMethodDecl>(VisitCXXMethodDecl(OldFD,
2233 LookupResult Previous(SemaRef, NewFD->getNameInfo(), Sema::LookupOrdinaryName,
2234 Sema::ForRedeclaration);
2236 TemplateArgumentListInfo TemplateArgs;
2237 TemplateArgumentListInfo* TemplateArgsPtr = 0;
2238 if (Decl->hasExplicitTemplateArgs()) {
2239 TemplateArgs = Decl->templateArgs();
2240 TemplateArgsPtr = &TemplateArgs;
2243 SemaRef.LookupQualifiedName(Previous, SemaRef.CurContext);
2244 if (SemaRef.CheckFunctionTemplateSpecialization(NewFD, TemplateArgsPtr,
2246 NewFD->setInvalidDecl();
2250 // Associate the specialization with the pattern.
2251 FunctionDecl *Specialization = cast<FunctionDecl>(Previous.getFoundDecl());
2252 assert(Specialization && "Class scope Specialization is null");
2253 SemaRef.Context.setClassScopeSpecializationPattern(Specialization, OldFD);
2258 Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
2259 OMPThreadPrivateDecl *D) {
2260 SmallVector<DeclRefExpr *, 5> Vars;
2261 for (ArrayRef<DeclRefExpr *>::iterator I = D->varlist_begin(),
2262 E = D->varlist_end();
2264 Expr *Var = SemaRef.SubstExpr(*I, TemplateArgs).take();
2265 assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
2266 Vars.push_back(cast<DeclRefExpr>(Var));
2269 OMPThreadPrivateDecl *TD =
2270 SemaRef.CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
2275 Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
2276 const MultiLevelTemplateArgumentList &TemplateArgs) {
2277 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
2278 if (D->isInvalidDecl())
2281 return Instantiator.Visit(D);
2284 /// \brief Instantiates a nested template parameter list in the current
2285 /// instantiation context.
2287 /// \param L The parameter list to instantiate
2289 /// \returns NULL if there was an error
2290 TemplateParameterList *
2291 TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
2292 // Get errors for all the parameters before bailing out.
2293 bool Invalid = false;
2295 unsigned N = L->size();
2296 typedef SmallVector<NamedDecl *, 8> ParamVector;
2299 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
2301 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
2302 Params.push_back(D);
2303 Invalid = Invalid || !D || D->isInvalidDecl();
2306 // Clean up if we had an error.
2310 TemplateParameterList *InstL
2311 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
2312 L->getLAngleLoc(), &Params.front(), N,
2317 /// \brief Instantiate the declaration of a class template partial
2320 /// \param ClassTemplate the (instantiated) class template that is partially
2321 // specialized by the instantiation of \p PartialSpec.
2323 /// \param PartialSpec the (uninstantiated) class template partial
2324 /// specialization that we are instantiating.
2326 /// \returns The instantiated partial specialization, if successful; otherwise,
2327 /// NULL to indicate an error.
2328 ClassTemplatePartialSpecializationDecl *
2329 TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
2330 ClassTemplateDecl *ClassTemplate,
2331 ClassTemplatePartialSpecializationDecl *PartialSpec) {
2332 // Create a local instantiation scope for this class template partial
2333 // specialization, which will contain the instantiations of the template
2335 LocalInstantiationScope Scope(SemaRef);
2337 // Substitute into the template parameters of the class template partial
2339 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
2340 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2344 // Substitute into the template arguments of the class template partial
2346 TemplateArgumentListInfo InstTemplateArgs; // no angle locations
2347 if (SemaRef.Subst(PartialSpec->getTemplateArgsAsWritten(),
2348 PartialSpec->getNumTemplateArgsAsWritten(),
2349 InstTemplateArgs, TemplateArgs))
2352 // Check that the template argument list is well-formed for this
2354 SmallVector<TemplateArgument, 4> Converted;
2355 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
2356 PartialSpec->getLocation(),
2362 // Figure out where to insert this class template partial specialization
2363 // in the member template's set of class template partial specializations.
2364 void *InsertPos = 0;
2365 ClassTemplateSpecializationDecl *PrevDecl
2366 = ClassTemplate->findPartialSpecialization(Converted.data(),
2367 Converted.size(), InsertPos);
2369 // Build the canonical type that describes the converted template
2370 // arguments of the class template partial specialization.
2372 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
2376 // Build the fully-sugared type for this class template
2377 // specialization as the user wrote in the specialization
2378 // itself. This means that we'll pretty-print the type retrieved
2379 // from the specialization's declaration the way that the user
2380 // actually wrote the specialization, rather than formatting the
2381 // name based on the "canonical" representation used to store the
2382 // template arguments in the specialization.
2383 TypeSourceInfo *WrittenTy
2384 = SemaRef.Context.getTemplateSpecializationTypeInfo(
2385 TemplateName(ClassTemplate),
2386 PartialSpec->getLocation(),
2391 // We've already seen a partial specialization with the same template
2392 // parameters and template arguments. This can happen, for example, when
2393 // substituting the outer template arguments ends up causing two
2394 // class template partial specializations of a member class template
2395 // to have identical forms, e.g.,
2397 // template<typename T, typename U>
2399 // template<typename X, typename Y> struct Inner;
2400 // template<typename Y> struct Inner<T, Y>;
2401 // template<typename Y> struct Inner<U, Y>;
2404 // Outer<int, int> outer; // error: the partial specializations of Inner
2405 // // have the same signature.
2406 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
2407 << WrittenTy->getType();
2408 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
2409 << SemaRef.Context.getTypeDeclType(PrevDecl);
2414 // Create the class template partial specialization declaration.
2415 ClassTemplatePartialSpecializationDecl *InstPartialSpec
2416 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
2417 PartialSpec->getTagKind(),
2419 PartialSpec->getLocStart(),
2420 PartialSpec->getLocation(),
2428 ClassTemplate->getNextPartialSpecSequenceNumber());
2429 // Substitute the nested name specifier, if any.
2430 if (SubstQualifier(PartialSpec, InstPartialSpec))
2433 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
2434 InstPartialSpec->setTypeAsWritten(WrittenTy);
2436 // Add this partial specialization to the set of class template partial
2438 ClassTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/0);
2439 return InstPartialSpec;
2443 TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
2444 SmallVectorImpl<ParmVarDecl *> &Params) {
2445 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
2446 assert(OldTInfo && "substituting function without type source info");
2447 assert(Params.empty() && "parameter vector is non-empty at start");
2449 CXXRecordDecl *ThisContext = 0;
2450 unsigned ThisTypeQuals = 0;
2451 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
2452 ThisContext = Method->getParent();
2453 ThisTypeQuals = Method->getTypeQualifiers();
2456 TypeSourceInfo *NewTInfo
2457 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
2458 D->getTypeSpecStartLoc(),
2460 ThisContext, ThisTypeQuals);
2464 if (NewTInfo != OldTInfo) {
2465 // Get parameters from the new type info.
2466 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
2467 if (FunctionProtoTypeLoc OldProtoLoc =
2468 OldTL.getAs<FunctionProtoTypeLoc>()) {
2469 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
2470 FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
2471 unsigned NewIdx = 0;
2472 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumArgs();
2473 OldIdx != NumOldParams; ++OldIdx) {
2474 ParmVarDecl *OldParam = OldProtoLoc.getArg(OldIdx);
2475 LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
2477 Optional<unsigned> NumArgumentsInExpansion;
2478 if (OldParam->isParameterPack())
2479 NumArgumentsInExpansion =
2480 SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
2482 if (!NumArgumentsInExpansion) {
2483 // Simple case: normal parameter, or a parameter pack that's
2484 // instantiated to a (still-dependent) parameter pack.
2485 ParmVarDecl *NewParam = NewProtoLoc.getArg(NewIdx++);
2486 Params.push_back(NewParam);
2487 Scope->InstantiatedLocal(OldParam, NewParam);
2489 // Parameter pack expansion: make the instantiation an argument pack.
2490 Scope->MakeInstantiatedLocalArgPack(OldParam);
2491 for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
2492 ParmVarDecl *NewParam = NewProtoLoc.getArg(NewIdx++);
2493 Params.push_back(NewParam);
2494 Scope->InstantiatedLocalPackArg(OldParam, NewParam);
2500 // The function type itself was not dependent and therefore no
2501 // substitution occurred. However, we still need to instantiate
2502 // the function parameters themselves.
2503 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
2504 if (FunctionProtoTypeLoc OldProtoLoc =
2505 OldTL.getAs<FunctionProtoTypeLoc>()) {
2506 for (unsigned i = 0, i_end = OldProtoLoc.getNumArgs(); i != i_end; ++i) {
2507 ParmVarDecl *Parm = VisitParmVarDecl(OldProtoLoc.getArg(i));
2510 Params.push_back(Parm);
2517 /// Introduce the instantiated function parameters into the local
2518 /// instantiation scope, and set the parameter names to those used
2519 /// in the template.
2520 static void addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function,
2521 const FunctionDecl *PatternDecl,
2522 LocalInstantiationScope &Scope,
2523 const MultiLevelTemplateArgumentList &TemplateArgs) {
2524 unsigned FParamIdx = 0;
2525 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
2526 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
2527 if (!PatternParam->isParameterPack()) {
2528 // Simple case: not a parameter pack.
2529 assert(FParamIdx < Function->getNumParams());
2530 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
2531 FunctionParam->setDeclName(PatternParam->getDeclName());
2532 Scope.InstantiatedLocal(PatternParam, FunctionParam);
2537 // Expand the parameter pack.
2538 Scope.MakeInstantiatedLocalArgPack(PatternParam);
2539 Optional<unsigned> NumArgumentsInExpansion
2540 = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
2541 assert(NumArgumentsInExpansion &&
2542 "should only be called when all template arguments are known");
2543 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
2544 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
2545 FunctionParam->setDeclName(PatternParam->getDeclName());
2546 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
2552 static void InstantiateExceptionSpec(Sema &SemaRef, FunctionDecl *New,
2553 const FunctionProtoType *Proto,
2554 const MultiLevelTemplateArgumentList &TemplateArgs) {
2555 assert(Proto->getExceptionSpecType() != EST_Uninstantiated);
2557 // C++11 [expr.prim.general]p3:
2558 // If a declaration declares a member function or member function
2559 // template of a class X, the expression this is a prvalue of type
2560 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
2561 // and the end of the function-definition, member-declarator, or
2563 CXXRecordDecl *ThisContext = 0;
2564 unsigned ThisTypeQuals = 0;
2565 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(New)) {
2566 ThisContext = Method->getParent();
2567 ThisTypeQuals = Method->getTypeQualifiers();
2569 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals,
2570 SemaRef.getLangOpts().CPlusPlus11);
2572 // The function has an exception specification or a "noreturn"
2573 // attribute. Substitute into each of the exception types.
2574 SmallVector<QualType, 4> Exceptions;
2575 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
2576 // FIXME: Poor location information!
2577 if (const PackExpansionType *PackExpansion
2578 = Proto->getExceptionType(I)->getAs<PackExpansionType>()) {
2579 // We have a pack expansion. Instantiate it.
2580 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2581 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
2583 assert(!Unexpanded.empty() &&
2584 "Pack expansion without parameter packs?");
2586 bool Expand = false;
2587 bool RetainExpansion = false;
2588 Optional<unsigned> NumExpansions
2589 = PackExpansion->getNumExpansions();
2590 if (SemaRef.CheckParameterPacksForExpansion(New->getLocation(),
2600 // We can't expand this pack expansion into separate arguments yet;
2601 // just substitute into the pattern and create a new pack expansion
2603 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2604 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2606 New->getLocation(), New->getDeclName());
2610 T = SemaRef.Context.getPackExpansionType(T, NumExpansions);
2611 Exceptions.push_back(T);
2615 // Substitute into the pack expansion pattern for each template
2616 bool Invalid = false;
2617 for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
2618 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, ArgIdx);
2620 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2622 New->getLocation(), New->getDeclName());
2628 Exceptions.push_back(T);
2638 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
2639 New->getLocation(), New->getDeclName());
2641 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
2644 Exceptions.push_back(T);
2646 Expr *NoexceptExpr = 0;
2647 if (Expr *OldNoexceptExpr = Proto->getNoexceptExpr()) {
2648 EnterExpressionEvaluationContext Unevaluated(SemaRef,
2649 Sema::ConstantEvaluated);
2650 ExprResult E = SemaRef.SubstExpr(OldNoexceptExpr, TemplateArgs);
2652 E = SemaRef.CheckBooleanCondition(E.get(), E.get()->getLocStart());
2655 NoexceptExpr = E.take();
2656 if (!NoexceptExpr->isTypeDependent() &&
2657 !NoexceptExpr->isValueDependent())
2659 = SemaRef.VerifyIntegerConstantExpression(NoexceptExpr,
2660 0, diag::err_noexcept_needs_constant_expression,
2661 /*AllowFold*/ false).take();
2665 // Rebuild the function type
2666 const FunctionProtoType *NewProto
2667 = New->getType()->getAs<FunctionProtoType>();
2668 assert(NewProto && "Template instantiation without function prototype?");
2670 FunctionProtoType::ExtProtoInfo EPI = NewProto->getExtProtoInfo();
2671 EPI.ExceptionSpecType = Proto->getExceptionSpecType();
2672 EPI.NumExceptions = Exceptions.size();
2673 EPI.Exceptions = Exceptions.data();
2674 EPI.NoexceptExpr = NoexceptExpr;
2676 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
2677 ArrayRef<QualType>(NewProto->arg_type_begin(),
2678 NewProto->getNumArgs()),
2682 void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
2683 FunctionDecl *Decl) {
2684 const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
2685 if (Proto->getExceptionSpecType() != EST_Uninstantiated)
2688 InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
2689 InstantiatingTemplate::ExceptionSpecification());
2691 // We hit the instantiation depth limit. Clear the exception specification
2692 // so that our callers don't have to cope with EST_Uninstantiated.
2693 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
2694 EPI.ExceptionSpecType = EST_None;
2695 Decl->setType(Context.getFunctionType(Proto->getResultType(),
2696 ArrayRef<QualType>(Proto->arg_type_begin(),
2697 Proto->getNumArgs()),
2702 // Enter the scope of this instantiation. We don't use
2703 // PushDeclContext because we don't have a scope.
2704 Sema::ContextRAII savedContext(*this, Decl);
2705 LocalInstantiationScope Scope(*this);
2707 MultiLevelTemplateArgumentList TemplateArgs =
2708 getTemplateInstantiationArgs(Decl, 0, /*RelativeToPrimary*/true);
2710 FunctionDecl *Template = Proto->getExceptionSpecTemplate();
2711 addInstantiatedParametersToScope(*this, Decl, Template, Scope, TemplateArgs);
2713 ::InstantiateExceptionSpec(*this, Decl,
2714 Template->getType()->castAs<FunctionProtoType>(),
2718 /// \brief Initializes the common fields of an instantiation function
2719 /// declaration (New) from the corresponding fields of its template (Tmpl).
2721 /// \returns true if there was an error
2723 TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
2724 FunctionDecl *Tmpl) {
2725 if (Tmpl->isDeleted())
2726 New->setDeletedAsWritten();
2728 // If we are performing substituting explicitly-specified template arguments
2729 // or deduced template arguments into a function template and we reach this
2730 // point, we are now past the point where SFINAE applies and have committed
2731 // to keeping the new function template specialization. We therefore
2732 // convert the active template instantiation for the function template
2733 // into a template instantiation for this specific function template
2734 // specialization, which is not a SFINAE context, so that we diagnose any
2735 // further errors in the declaration itself.
2736 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
2737 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
2738 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
2739 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
2740 if (FunctionTemplateDecl *FunTmpl
2741 = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) {
2742 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
2743 "Deduction from the wrong function template?");
2745 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
2746 ActiveInst.Entity = New;
2750 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
2751 assert(Proto && "Function template without prototype?");
2753 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
2754 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
2756 // DR1330: In C++11, defer instantiation of a non-trivial
2757 // exception specification.
2758 if (SemaRef.getLangOpts().CPlusPlus11 &&
2759 EPI.ExceptionSpecType != EST_None &&
2760 EPI.ExceptionSpecType != EST_DynamicNone &&
2761 EPI.ExceptionSpecType != EST_BasicNoexcept) {
2762 FunctionDecl *ExceptionSpecTemplate = Tmpl;
2763 if (EPI.ExceptionSpecType == EST_Uninstantiated)
2764 ExceptionSpecTemplate = EPI.ExceptionSpecTemplate;
2765 ExceptionSpecificationType NewEST = EST_Uninstantiated;
2766 if (EPI.ExceptionSpecType == EST_Unevaluated)
2767 NewEST = EST_Unevaluated;
2769 // Mark the function has having an uninstantiated exception specification.
2770 const FunctionProtoType *NewProto
2771 = New->getType()->getAs<FunctionProtoType>();
2772 assert(NewProto && "Template instantiation without function prototype?");
2773 EPI = NewProto->getExtProtoInfo();
2774 EPI.ExceptionSpecType = NewEST;
2775 EPI.ExceptionSpecDecl = New;
2776 EPI.ExceptionSpecTemplate = ExceptionSpecTemplate;
2777 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
2778 ArrayRef<QualType>(NewProto->arg_type_begin(),
2779 NewProto->getNumArgs()),
2782 ::InstantiateExceptionSpec(SemaRef, New, Proto, TemplateArgs);
2786 // Get the definition. Leaves the variable unchanged if undefined.
2787 const FunctionDecl *Definition = Tmpl;
2788 Tmpl->isDefined(Definition);
2790 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
2791 LateAttrs, StartingScope);
2796 /// \brief Initializes common fields of an instantiated method
2797 /// declaration (New) from the corresponding fields of its template
2800 /// \returns true if there was an error
2802 TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
2803 CXXMethodDecl *Tmpl) {
2804 if (InitFunctionInstantiation(New, Tmpl))
2807 New->setAccess(Tmpl->getAccess());
2808 if (Tmpl->isVirtualAsWritten())
2809 New->setVirtualAsWritten(true);
2811 // FIXME: New needs a pointer to Tmpl
2815 /// \brief Instantiate the definition of the given function from its
2818 /// \param PointOfInstantiation the point at which the instantiation was
2819 /// required. Note that this is not precisely a "point of instantiation"
2820 /// for the function, but it's close.
2822 /// \param Function the already-instantiated declaration of a
2823 /// function template specialization or member function of a class template
2826 /// \param Recursive if true, recursively instantiates any functions that
2827 /// are required by this instantiation.
2829 /// \param DefinitionRequired if true, then we are performing an explicit
2830 /// instantiation where the body of the function is required. Complain if
2831 /// there is no such body.
2832 void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
2833 FunctionDecl *Function,
2835 bool DefinitionRequired) {
2836 if (Function->isInvalidDecl() || Function->isDefined())
2839 // Never instantiate an explicit specialization except if it is a class scope
2840 // explicit specialization.
2841 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
2842 !Function->getClassScopeSpecializationPattern())
2845 // Find the function body that we'll be substituting.
2846 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
2847 assert(PatternDecl && "instantiating a non-template");
2849 Stmt *Pattern = PatternDecl->getBody(PatternDecl);
2850 assert(PatternDecl && "template definition is not a template");
2852 // Try to find a defaulted definition
2853 PatternDecl->isDefined(PatternDecl);
2855 assert(PatternDecl && "template definition is not a template");
2857 // Postpone late parsed template instantiations.
2858 if (PatternDecl->isLateTemplateParsed() &&
2859 !LateTemplateParser) {
2860 PendingInstantiations.push_back(
2861 std::make_pair(Function, PointOfInstantiation));
2865 // Call the LateTemplateParser callback if there a need to late parse
2866 // a templated function definition.
2867 if (!Pattern && PatternDecl->isLateTemplateParsed() &&
2868 LateTemplateParser) {
2869 LateTemplateParser(OpaqueParser, PatternDecl);
2870 Pattern = PatternDecl->getBody(PatternDecl);
2873 if (!Pattern && !PatternDecl->isDefaulted()) {
2874 if (DefinitionRequired) {
2875 if (Function->getPrimaryTemplate())
2876 Diag(PointOfInstantiation,
2877 diag::err_explicit_instantiation_undefined_func_template)
2878 << Function->getPrimaryTemplate();
2880 Diag(PointOfInstantiation,
2881 diag::err_explicit_instantiation_undefined_member)
2882 << 1 << Function->getDeclName() << Function->getDeclContext();
2885 Diag(PatternDecl->getLocation(),
2886 diag::note_explicit_instantiation_here);
2887 Function->setInvalidDecl();
2888 } else if (Function->getTemplateSpecializationKind()
2889 == TSK_ExplicitInstantiationDefinition) {
2890 PendingInstantiations.push_back(
2891 std::make_pair(Function, PointOfInstantiation));
2897 // C++1y [temp.explicit]p10:
2898 // Except for inline functions, declarations with types deduced from their
2899 // initializer or return value, and class template specializations, other
2900 // explicit instantiation declarations have the effect of suppressing the
2901 // implicit instantiation of the entity to which they refer.
2902 if (Function->getTemplateSpecializationKind()
2903 == TSK_ExplicitInstantiationDeclaration &&
2904 !PatternDecl->isInlined() &&
2905 !PatternDecl->getResultType()->isUndeducedType())
2908 if (PatternDecl->isInlined())
2909 Function->setImplicitlyInline();
2911 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
2915 // Copy the inner loc start from the pattern.
2916 Function->setInnerLocStart(PatternDecl->getInnerLocStart());
2918 // If we're performing recursive template instantiation, create our own
2919 // queue of pending implicit instantiations that we will instantiate later,
2920 // while we're still within our own instantiation context.
2921 SmallVector<VTableUse, 16> SavedVTableUses;
2922 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
2924 VTableUses.swap(SavedVTableUses);
2925 PendingInstantiations.swap(SavedPendingInstantiations);
2928 EnterExpressionEvaluationContext EvalContext(*this,
2929 Sema::PotentiallyEvaluated);
2931 // Introduce a new scope where local variable instantiations will be
2932 // recorded, unless we're actually a member function within a local
2933 // class, in which case we need to merge our results with the parent
2934 // scope (of the enclosing function).
2935 bool MergeWithParentScope = false;
2936 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
2937 MergeWithParentScope = Rec->isLocalClass();
2939 LocalInstantiationScope Scope(*this, MergeWithParentScope);
2941 if (PatternDecl->isDefaulted())
2942 SetDeclDefaulted(Function, PatternDecl->getLocation());
2944 ActOnStartOfFunctionDef(0, Function);
2946 // Enter the scope of this instantiation. We don't use
2947 // PushDeclContext because we don't have a scope.
2948 Sema::ContextRAII savedContext(*this, Function);
2950 MultiLevelTemplateArgumentList TemplateArgs =
2951 getTemplateInstantiationArgs(Function, 0, false, PatternDecl);
2953 addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope,
2956 // If this is a constructor, instantiate the member initializers.
2957 if (const CXXConstructorDecl *Ctor =
2958 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
2959 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
2963 // Instantiate the function body.
2964 StmtResult Body = SubstStmt(Pattern, TemplateArgs);
2966 if (Body.isInvalid())
2967 Function->setInvalidDecl();
2969 ActOnFinishFunctionBody(Function, Body.get(),
2970 /*IsInstantiation=*/true);
2972 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
2977 DeclGroupRef DG(Function);
2978 Consumer.HandleTopLevelDecl(DG);
2980 // This class may have local implicit instantiations that need to be
2981 // instantiation within this scope.
2982 PerformPendingInstantiations(/*LocalOnly=*/true);
2986 // Define any pending vtables.
2987 DefineUsedVTables();
2989 // Instantiate any pending implicit instantiations found during the
2990 // instantiation of this template.
2991 PerformPendingInstantiations();
2993 // Restore the set of pending vtables.
2994 assert(VTableUses.empty() &&
2995 "VTableUses should be empty before it is discarded.");
2996 VTableUses.swap(SavedVTableUses);
2998 // Restore the set of pending implicit instantiations.
2999 assert(PendingInstantiations.empty() &&
3000 "PendingInstantiations should be empty before it is discarded.");
3001 PendingInstantiations.swap(SavedPendingInstantiations);
3005 /// \brief Instantiate the definition of the given variable from its
3008 /// \param PointOfInstantiation the point at which the instantiation was
3009 /// required. Note that this is not precisely a "point of instantiation"
3010 /// for the function, but it's close.
3012 /// \param Var the already-instantiated declaration of a static member
3013 /// variable of a class template specialization.
3015 /// \param Recursive if true, recursively instantiates any functions that
3016 /// are required by this instantiation.
3018 /// \param DefinitionRequired if true, then we are performing an explicit
3019 /// instantiation where an out-of-line definition of the member variable
3020 /// is required. Complain if there is no such definition.
3021 void Sema::InstantiateStaticDataMemberDefinition(
3022 SourceLocation PointOfInstantiation,
3025 bool DefinitionRequired) {
3026 if (Var->isInvalidDecl())
3029 // Find the out-of-line definition of this static data member.
3030 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
3031 assert(Def && "This data member was not instantiated from a template?");
3032 assert(Def->isStaticDataMember() && "Not a static data member?");
3033 Def = Def->getOutOfLineDefinition();
3036 // We did not find an out-of-line definition of this static data member,
3037 // so we won't perform any instantiation. Rather, we rely on the user to
3038 // instantiate this definition (or provide a specialization for it) in
3039 // another translation unit.
3040 if (DefinitionRequired) {
3041 Def = Var->getInstantiatedFromStaticDataMember();
3042 Diag(PointOfInstantiation,
3043 diag::err_explicit_instantiation_undefined_member)
3044 << 2 << Var->getDeclName() << Var->getDeclContext();
3045 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
3046 } else if (Var->getTemplateSpecializationKind()
3047 == TSK_ExplicitInstantiationDefinition) {
3048 PendingInstantiations.push_back(
3049 std::make_pair(Var, PointOfInstantiation));
3055 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
3057 // Never instantiate an explicit specialization.
3058 if (TSK == TSK_ExplicitSpecialization)
3061 // C++0x [temp.explicit]p9:
3062 // Except for inline functions, other explicit instantiation declarations
3063 // have the effect of suppressing the implicit instantiation of the entity
3064 // to which they refer.
3065 if (TSK == TSK_ExplicitInstantiationDeclaration)
3068 // Make sure to pass the instantiated variable to the consumer at the end.
3069 struct PassToConsumerRAII {
3070 ASTConsumer &Consumer;
3073 PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
3074 : Consumer(Consumer), Var(Var) { }
3076 ~PassToConsumerRAII() {
3077 Consumer.HandleCXXStaticMemberVarInstantiation(Var);
3079 } PassToConsumerRAII(Consumer, Var);
3081 // If we already have a definition, we're done.
3082 if (VarDecl *Def = Var->getDefinition()) {
3083 // We may be explicitly instantiating something we've already implicitly
3085 Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
3086 PointOfInstantiation);
3090 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
3094 // If we're performing recursive template instantiation, create our own
3095 // queue of pending implicit instantiations that we will instantiate later,
3096 // while we're still within our own instantiation context.
3097 SmallVector<VTableUse, 16> SavedVTableUses;
3098 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
3100 VTableUses.swap(SavedVTableUses);
3101 PendingInstantiations.swap(SavedPendingInstantiations);
3104 // Enter the scope of this instantiation. We don't use
3105 // PushDeclContext because we don't have a scope.
3106 ContextRAII previousContext(*this, Var->getDeclContext());
3107 LocalInstantiationScope Local(*this);
3109 VarDecl *OldVar = Var;
3110 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
3111 getTemplateInstantiationArgs(Var)));
3113 previousContext.pop();
3116 PassToConsumerRAII.Var = Var;
3117 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
3118 assert(MSInfo && "Missing member specialization information?");
3119 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
3120 MSInfo->getPointOfInstantiation());
3125 // Define any newly required vtables.
3126 DefineUsedVTables();
3128 // Instantiate any pending implicit instantiations found during the
3129 // instantiation of this template.
3130 PerformPendingInstantiations();
3132 // Restore the set of pending vtables.
3133 assert(VTableUses.empty() &&
3134 "VTableUses should be empty before it is discarded, "
3135 "while instantiating static data member.");
3136 VTableUses.swap(SavedVTableUses);
3138 // Restore the set of pending implicit instantiations.
3139 assert(PendingInstantiations.empty() &&
3140 "PendingInstantiations should be empty before it is discarded, "
3141 "while instantiating static data member.");
3142 PendingInstantiations.swap(SavedPendingInstantiations);
3147 Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
3148 const CXXConstructorDecl *Tmpl,
3149 const MultiLevelTemplateArgumentList &TemplateArgs) {
3151 SmallVector<CXXCtorInitializer*, 4> NewInits;
3152 bool AnyErrors = Tmpl->isInvalidDecl();
3154 // Instantiate all the initializers.
3155 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
3156 InitsEnd = Tmpl->init_end();
3157 Inits != InitsEnd; ++Inits) {
3158 CXXCtorInitializer *Init = *Inits;
3160 // Only instantiate written initializers, let Sema re-construct implicit
3162 if (!Init->isWritten())
3165 SourceLocation EllipsisLoc;
3167 if (Init->isPackExpansion()) {
3168 // This is a pack expansion. We should expand it now.
3169 TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
3170 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3171 collectUnexpandedParameterPacks(BaseTL, Unexpanded);
3172 bool ShouldExpand = false;
3173 bool RetainExpansion = false;
3174 Optional<unsigned> NumExpansions;
3175 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
3176 BaseTL.getSourceRange(),
3178 TemplateArgs, ShouldExpand,
3182 New->setInvalidDecl();
3185 assert(ShouldExpand && "Partial instantiation of base initializer?");
3187 // Loop over all of the arguments in the argument pack(s),
3188 for (unsigned I = 0; I != *NumExpansions; ++I) {
3189 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
3191 // Instantiate the initializer.
3192 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
3193 /*CXXDirectInit=*/true);
3194 if (TempInit.isInvalid()) {
3199 // Instantiate the base type.
3200 TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
3202 Init->getSourceLocation(),
3203 New->getDeclName());
3209 // Build the initializer.
3210 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
3211 BaseTInfo, TempInit.take(),
3214 if (NewInit.isInvalid()) {
3219 NewInits.push_back(NewInit.get());
3225 // Instantiate the initializer.
3226 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
3227 /*CXXDirectInit=*/true);
3228 if (TempInit.isInvalid()) {
3233 MemInitResult NewInit;
3234 if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
3235 TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
3237 Init->getSourceLocation(),
3238 New->getDeclName());
3241 New->setInvalidDecl();
3245 if (Init->isBaseInitializer())
3246 NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.take(),
3247 New->getParent(), EllipsisLoc);
3249 NewInit = BuildDelegatingInitializer(TInfo, TempInit.take(),
3250 cast<CXXRecordDecl>(CurContext->getParent()));
3251 } else if (Init->isMemberInitializer()) {
3252 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
3253 Init->getMemberLocation(),
3258 New->setInvalidDecl();
3262 NewInit = BuildMemberInitializer(Member, TempInit.take(),
3263 Init->getSourceLocation());
3264 } else if (Init->isIndirectMemberInitializer()) {
3265 IndirectFieldDecl *IndirectMember =
3266 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
3267 Init->getMemberLocation(),
3268 Init->getIndirectMember(), TemplateArgs));
3270 if (!IndirectMember) {
3272 New->setInvalidDecl();
3276 NewInit = BuildMemberInitializer(IndirectMember, TempInit.take(),
3277 Init->getSourceLocation());
3280 if (NewInit.isInvalid()) {
3282 New->setInvalidDecl();
3284 NewInits.push_back(NewInit.get());
3288 // Assign all the initializers to the new constructor.
3289 ActOnMemInitializers(New,
3290 /*FIXME: ColonLoc */
3296 // TODO: this could be templated if the various decl types used the
3297 // same method name.
3298 static bool isInstantiationOf(ClassTemplateDecl *Pattern,
3299 ClassTemplateDecl *Instance) {
3300 Pattern = Pattern->getCanonicalDecl();
3303 Instance = Instance->getCanonicalDecl();
3304 if (Pattern == Instance) return true;
3305 Instance = Instance->getInstantiatedFromMemberTemplate();
3311 static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
3312 FunctionTemplateDecl *Instance) {
3313 Pattern = Pattern->getCanonicalDecl();
3316 Instance = Instance->getCanonicalDecl();
3317 if (Pattern == Instance) return true;
3318 Instance = Instance->getInstantiatedFromMemberTemplate();
3325 isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
3326 ClassTemplatePartialSpecializationDecl *Instance) {
3328 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
3330 Instance = cast<ClassTemplatePartialSpecializationDecl>(
3331 Instance->getCanonicalDecl());
3332 if (Pattern == Instance)
3334 Instance = Instance->getInstantiatedFromMember();
3340 static bool isInstantiationOf(CXXRecordDecl *Pattern,
3341 CXXRecordDecl *Instance) {
3342 Pattern = Pattern->getCanonicalDecl();
3345 Instance = Instance->getCanonicalDecl();
3346 if (Pattern == Instance) return true;
3347 Instance = Instance->getInstantiatedFromMemberClass();
3353 static bool isInstantiationOf(FunctionDecl *Pattern,
3354 FunctionDecl *Instance) {
3355 Pattern = Pattern->getCanonicalDecl();
3358 Instance = Instance->getCanonicalDecl();
3359 if (Pattern == Instance) return true;
3360 Instance = Instance->getInstantiatedFromMemberFunction();
3366 static bool isInstantiationOf(EnumDecl *Pattern,
3367 EnumDecl *Instance) {
3368 Pattern = Pattern->getCanonicalDecl();
3371 Instance = Instance->getCanonicalDecl();
3372 if (Pattern == Instance) return true;
3373 Instance = Instance->getInstantiatedFromMemberEnum();
3379 static bool isInstantiationOf(UsingShadowDecl *Pattern,
3380 UsingShadowDecl *Instance,
3382 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
3385 static bool isInstantiationOf(UsingDecl *Pattern,
3386 UsingDecl *Instance,
3388 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
3391 static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
3392 UsingDecl *Instance,
3394 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
3397 static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
3398 UsingDecl *Instance,
3400 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
3403 static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
3404 VarDecl *Instance) {
3405 assert(Instance->isStaticDataMember());
3407 Pattern = Pattern->getCanonicalDecl();
3410 Instance = Instance->getCanonicalDecl();
3411 if (Pattern == Instance) return true;
3412 Instance = Instance->getInstantiatedFromStaticDataMember();
3418 // Other is the prospective instantiation
3419 // D is the prospective pattern
3420 static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
3421 if (D->getKind() != Other->getKind()) {
3422 if (UnresolvedUsingTypenameDecl *UUD
3423 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3424 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
3425 return isInstantiationOf(UUD, UD, Ctx);
3429 if (UnresolvedUsingValueDecl *UUD
3430 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
3431 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
3432 return isInstantiationOf(UUD, UD, Ctx);
3439 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
3440 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
3442 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
3443 return isInstantiationOf(cast<FunctionDecl>(D), Function);
3445 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
3446 return isInstantiationOf(cast<EnumDecl>(D), Enum);
3448 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
3449 if (Var->isStaticDataMember())
3450 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
3452 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
3453 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
3455 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
3456 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
3458 if (ClassTemplatePartialSpecializationDecl *PartialSpec
3459 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
3460 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
3463 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
3464 if (!Field->getDeclName()) {
3465 // This is an unnamed field.
3466 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
3471 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
3472 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
3474 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
3475 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
3477 return D->getDeclName() && isa<NamedDecl>(Other) &&
3478 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
3481 template<typename ForwardIterator>
3482 static NamedDecl *findInstantiationOf(ASTContext &Ctx,
3484 ForwardIterator first,
3485 ForwardIterator last) {
3486 for (; first != last; ++first)
3487 if (isInstantiationOf(Ctx, D, *first))
3488 return cast<NamedDecl>(*first);
3493 /// \brief Finds the instantiation of the given declaration context
3494 /// within the current instantiation.
3496 /// \returns NULL if there was an error
3497 DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
3498 const MultiLevelTemplateArgumentList &TemplateArgs) {
3499 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
3500 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
3501 return cast_or_null<DeclContext>(ID);
3505 /// \brief Find the instantiation of the given declaration within the
3506 /// current instantiation.
3508 /// This routine is intended to be used when \p D is a declaration
3509 /// referenced from within a template, that needs to mapped into the
3510 /// corresponding declaration within an instantiation. For example,
3514 /// template<typename T>
3517 /// KnownValue = sizeof(T)
3520 /// bool getKind() const { return KnownValue; }
3523 /// template struct X<int>;
3526 /// In the instantiation of X<int>::getKind(), we need to map the
3527 /// EnumConstantDecl for KnownValue (which refers to
3528 /// X<T>::\<Kind>\::KnownValue) to its instantiation
3529 /// (X<int>::\<Kind>\::KnownValue). InstantiateCurrentDeclRef() performs
3530 /// this mapping from within the instantiation of X<int>.
3531 NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
3532 const MultiLevelTemplateArgumentList &TemplateArgs) {
3533 DeclContext *ParentDC = D->getDeclContext();
3534 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
3535 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
3536 (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext()) ||
3537 (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) {
3538 // D is a local of some kind. Look into the map of local
3539 // declarations to their instantiations.
3540 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
3541 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
3542 = CurrentInstantiationScope->findInstantiationOf(D);
3545 if (Decl *FD = Found->dyn_cast<Decl *>())
3546 return cast<NamedDecl>(FD);
3548 int PackIdx = ArgumentPackSubstitutionIndex;
3549 assert(PackIdx != -1 && "found declaration pack but not pack expanding");
3550 return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
3553 // If we didn't find the decl, then we must have a label decl that hasn't
3554 // been found yet. Lazily instantiate it and return it now.
3555 assert(isa<LabelDecl>(D));
3557 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
3558 assert(Inst && "Failed to instantiate label??");
3560 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
3561 return cast<LabelDecl>(Inst);
3564 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
3565 if (!Record->isDependentContext())
3568 // Determine whether this record is the "templated" declaration describing
3569 // a class template or class template partial specialization.
3570 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
3572 ClassTemplate = ClassTemplate->getCanonicalDecl();
3573 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
3574 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
3575 ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
3577 // Walk the current context to find either the record or an instantiation of
3579 DeclContext *DC = CurContext;
3580 while (!DC->isFileContext()) {
3581 // If we're performing substitution while we're inside the template
3582 // definition, we'll find our own context. We're done.
3583 if (DC->Equals(Record))
3586 if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
3587 // Check whether we're in the process of instantiating a class template
3588 // specialization of the template we're mapping.
3589 if (ClassTemplateSpecializationDecl *InstSpec
3590 = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
3591 ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
3592 if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
3596 // Check whether we're in the process of instantiating a member class.
3597 if (isInstantiationOf(Record, InstRecord))
3602 // Move to the outer template scope.
3603 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
3604 if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){
3605 DC = FD->getLexicalDeclContext();
3610 DC = DC->getParent();
3613 // Fall through to deal with other dependent record types (e.g.,
3614 // anonymous unions in class templates).
3617 if (!ParentDC->isDependentContext())
3620 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
3624 if (ParentDC != D->getDeclContext()) {
3625 // We performed some kind of instantiation in the parent context,
3626 // so now we need to look into the instantiated parent context to
3627 // find the instantiation of the declaration D.
3629 // If our context used to be dependent, we may need to instantiate
3630 // it before performing lookup into that context.
3631 bool IsBeingInstantiated = false;
3632 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
3633 if (!Spec->isDependentContext()) {
3634 QualType T = Context.getTypeDeclType(Spec);
3635 const RecordType *Tag = T->getAs<RecordType>();
3636 assert(Tag && "type of non-dependent record is not a RecordType");
3637 if (Tag->isBeingDefined())
3638 IsBeingInstantiated = true;
3639 if (!Tag->isBeingDefined() &&
3640 RequireCompleteType(Loc, T, diag::err_incomplete_type))
3643 ParentDC = Tag->getDecl();
3647 NamedDecl *Result = 0;
3648 if (D->getDeclName()) {
3649 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
3650 Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
3652 // Since we don't have a name for the entity we're looking for,
3653 // our only option is to walk through all of the declarations to
3654 // find that name. This will occur in a few cases:
3656 // - anonymous struct/union within a template
3657 // - unnamed class/struct/union/enum within a template
3659 // FIXME: Find a better way to find these instantiations!
3660 Result = findInstantiationOf(Context, D,
3661 ParentDC->decls_begin(),
3662 ParentDC->decls_end());
3666 if (isa<UsingShadowDecl>(D)) {
3667 // UsingShadowDecls can instantiate to nothing because of using hiding.
3668 } else if (Diags.hasErrorOccurred()) {
3669 // We've already complained about something, so most likely this
3670 // declaration failed to instantiate. There's no point in complaining
3671 // further, since this is normal in invalid code.
3672 } else if (IsBeingInstantiated) {
3673 // The class in which this member exists is currently being
3674 // instantiated, and we haven't gotten around to instantiating this
3675 // member yet. This can happen when the code uses forward declarations
3676 // of member classes, and introduces ordering dependencies via
3677 // template instantiation.
3678 Diag(Loc, diag::err_member_not_yet_instantiated)
3680 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
3681 Diag(D->getLocation(), diag::note_non_instantiated_member_here);
3682 } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
3683 // This enumeration constant was found when the template was defined,
3684 // but can't be found in the instantiation. This can happen if an
3685 // unscoped enumeration member is explicitly specialized.
3686 EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
3687 EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
3689 assert(Spec->getTemplateSpecializationKind() ==
3690 TSK_ExplicitSpecialization);
3691 Diag(Loc, diag::err_enumerator_does_not_exist)
3693 << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
3694 Diag(Spec->getLocation(), diag::note_enum_specialized_here)
3695 << Context.getTypeDeclType(Spec);
3697 // We should have found something, but didn't.
3698 llvm_unreachable("Unable to find instantiation of declaration!");
3708 /// \brief Performs template instantiation for all implicit template
3709 /// instantiations we have seen until this point.
3710 void Sema::PerformPendingInstantiations(bool LocalOnly) {
3711 // Load pending instantiations from the external source.
3712 if (!LocalOnly && ExternalSource) {
3713 SmallVector<PendingImplicitInstantiation, 4> Pending;
3714 ExternalSource->ReadPendingInstantiations(Pending);
3715 PendingInstantiations.insert(PendingInstantiations.begin(),
3716 Pending.begin(), Pending.end());
3719 while (!PendingLocalImplicitInstantiations.empty() ||
3720 (!LocalOnly && !PendingInstantiations.empty())) {
3721 PendingImplicitInstantiation Inst;
3723 if (PendingLocalImplicitInstantiations.empty()) {
3724 Inst = PendingInstantiations.front();
3725 PendingInstantiations.pop_front();
3727 Inst = PendingLocalImplicitInstantiations.front();
3728 PendingLocalImplicitInstantiations.pop_front();
3731 // Instantiate function definitions
3732 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
3733 PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(),
3734 "instantiating function definition");
3735 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
3736 TSK_ExplicitInstantiationDefinition;
3737 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true,
3738 DefinitionRequired);
3742 // Instantiate static data member definitions.
3743 VarDecl *Var = cast<VarDecl>(Inst.first);
3744 assert(Var->isStaticDataMember() && "Not a static data member?");
3746 // Don't try to instantiate declarations if the most recent redeclaration
3748 if (Var->getMostRecentDecl()->isInvalidDecl())
3751 // Check if the most recent declaration has changed the specialization kind
3752 // and removed the need for implicit instantiation.
3753 switch (Var->getMostRecentDecl()->getTemplateSpecializationKind()) {
3754 case TSK_Undeclared:
3755 llvm_unreachable("Cannot instantitiate an undeclared specialization.");
3756 case TSK_ExplicitInstantiationDeclaration:
3757 case TSK_ExplicitSpecialization:
3758 continue; // No longer need to instantiate this type.
3759 case TSK_ExplicitInstantiationDefinition:
3760 // We only need an instantiation if the pending instantiation *is* the
3761 // explicit instantiation.
3762 if (Var != Var->getMostRecentDecl()) continue;
3763 case TSK_ImplicitInstantiation:
3767 PrettyDeclStackTraceEntry CrashInfo(*this, Var, Var->getLocation(),
3768 "instantiating static data member "
3771 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
3772 TSK_ExplicitInstantiationDefinition;
3773 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true,
3774 DefinitionRequired);
3778 void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
3779 const MultiLevelTemplateArgumentList &TemplateArgs) {
3780 for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(),
3781 E = Pattern->ddiag_end(); I != E; ++I) {
3782 DependentDiagnostic *DD = *I;
3784 switch (DD->getKind()) {
3785 case DependentDiagnostic::Access:
3786 HandleDependentAccessCheck(*DD, TemplateArgs);