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/ASTMutationListener.h"
16 #include "clang/AST/DeclTemplate.h"
17 #include "clang/AST/DeclVisitor.h"
18 #include "clang/AST/DependentDiagnostic.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/AST/ExprCXX.h"
21 #include "clang/AST/TypeLoc.h"
22 #include "clang/Sema/Lookup.h"
23 #include "clang/Sema/PrettyDeclStackTrace.h"
24 #include "clang/Sema/Template.h"
26 using namespace clang;
28 static bool isDeclWithinFunction(const Decl *D) {
29 const DeclContext *DC = D->getDeclContext();
30 if (DC->isFunctionOrMethod())
34 return cast<CXXRecordDecl>(DC)->isLocalClass();
39 template<typename DeclT>
40 static bool SubstQualifier(Sema &SemaRef, const DeclT *OldDecl, DeclT *NewDecl,
41 const MultiLevelTemplateArgumentList &TemplateArgs) {
42 if (!OldDecl->getQualifierLoc())
45 assert((NewDecl->getFriendObjectKind() ||
46 !OldDecl->getLexicalDeclContext()->isDependentContext()) &&
47 "non-friend with qualified name defined in dependent context");
48 Sema::ContextRAII SavedContext(
50 const_cast<DeclContext *>(NewDecl->getFriendObjectKind()
51 ? NewDecl->getLexicalDeclContext()
52 : OldDecl->getLexicalDeclContext()));
54 NestedNameSpecifierLoc NewQualifierLoc
55 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
61 NewDecl->setQualifierInfo(NewQualifierLoc);
65 bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
66 DeclaratorDecl *NewDecl) {
67 return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
70 bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
72 return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
75 // Include attribute instantiation code.
76 #include "clang/Sema/AttrTemplateInstantiate.inc"
78 static void instantiateDependentAlignedAttr(
79 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
80 const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion) {
81 if (Aligned->isAlignmentExpr()) {
82 // The alignment expression is a constant expression.
83 EnterExpressionEvaluationContext Unevaluated(S, Sema::ConstantEvaluated);
84 ExprResult Result = S.SubstExpr(Aligned->getAlignmentExpr(), TemplateArgs);
85 if (!Result.isInvalid())
86 S.AddAlignedAttr(Aligned->getLocation(), New, Result.getAs<Expr>(),
87 Aligned->getSpellingListIndex(), IsPackExpansion);
89 TypeSourceInfo *Result = S.SubstType(Aligned->getAlignmentType(),
90 TemplateArgs, Aligned->getLocation(),
93 S.AddAlignedAttr(Aligned->getLocation(), New, Result,
94 Aligned->getSpellingListIndex(), IsPackExpansion);
98 static void instantiateDependentAlignedAttr(
99 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
100 const AlignedAttr *Aligned, Decl *New) {
101 if (!Aligned->isPackExpansion()) {
102 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
106 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
107 if (Aligned->isAlignmentExpr())
108 S.collectUnexpandedParameterPacks(Aligned->getAlignmentExpr(),
111 S.collectUnexpandedParameterPacks(Aligned->getAlignmentType()->getTypeLoc(),
113 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
115 // Determine whether we can expand this attribute pack yet.
116 bool Expand = true, RetainExpansion = false;
117 Optional<unsigned> NumExpansions;
118 // FIXME: Use the actual location of the ellipsis.
119 SourceLocation EllipsisLoc = Aligned->getLocation();
120 if (S.CheckParameterPacksForExpansion(EllipsisLoc, Aligned->getRange(),
121 Unexpanded, TemplateArgs, Expand,
122 RetainExpansion, NumExpansions))
126 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, -1);
127 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, true);
129 for (unsigned I = 0; I != *NumExpansions; ++I) {
130 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, I);
131 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
136 static void instantiateDependentAssumeAlignedAttr(
137 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
138 const AssumeAlignedAttr *Aligned, Decl *New) {
139 // The alignment expression is a constant expression.
140 EnterExpressionEvaluationContext Unevaluated(S, Sema::ConstantEvaluated);
142 Expr *E, *OE = nullptr;
143 ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
144 if (Result.isInvalid())
146 E = Result.getAs<Expr>();
148 if (Aligned->getOffset()) {
149 Result = S.SubstExpr(Aligned->getOffset(), TemplateArgs);
150 if (Result.isInvalid())
152 OE = Result.getAs<Expr>();
155 S.AddAssumeAlignedAttr(Aligned->getLocation(), New, E, OE,
156 Aligned->getSpellingListIndex());
159 static void instantiateDependentAlignValueAttr(
160 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
161 const AlignValueAttr *Aligned, Decl *New) {
162 // The alignment expression is a constant expression.
163 EnterExpressionEvaluationContext Unevaluated(S, Sema::ConstantEvaluated);
164 ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
165 if (!Result.isInvalid())
166 S.AddAlignValueAttr(Aligned->getLocation(), New, Result.getAs<Expr>(),
167 Aligned->getSpellingListIndex());
170 static void instantiateDependentEnableIfAttr(
171 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
172 const EnableIfAttr *A, const Decl *Tmpl, Decl *New) {
173 Expr *Cond = nullptr;
175 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
176 ExprResult Result = S.SubstExpr(A->getCond(), TemplateArgs);
177 if (Result.isInvalid())
179 Cond = Result.getAs<Expr>();
181 if (A->getCond()->isTypeDependent() && !Cond->isTypeDependent()) {
182 ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
183 if (Converted.isInvalid())
185 Cond = Converted.get();
188 SmallVector<PartialDiagnosticAt, 8> Diags;
189 if (A->getCond()->isValueDependent() && !Cond->isValueDependent() &&
190 !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(Tmpl),
192 S.Diag(A->getLocation(), diag::err_enable_if_never_constant_expr);
193 for (int I = 0, N = Diags.size(); I != N; ++I)
194 S.Diag(Diags[I].first, Diags[I].second);
198 EnableIfAttr *EIA = new (S.getASTContext())
199 EnableIfAttr(A->getLocation(), S.getASTContext(), Cond,
201 A->getSpellingListIndex());
205 void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
206 const Decl *Tmpl, Decl *New,
207 LateInstantiatedAttrVec *LateAttrs,
208 LocalInstantiationScope *OuterMostScope) {
209 for (const auto *TmplAttr : Tmpl->attrs()) {
210 // FIXME: This should be generalized to more than just the AlignedAttr.
211 const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr);
212 if (Aligned && Aligned->isAlignmentDependent()) {
213 instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New);
217 const AssumeAlignedAttr *AssumeAligned = dyn_cast<AssumeAlignedAttr>(TmplAttr);
219 instantiateDependentAssumeAlignedAttr(*this, TemplateArgs, AssumeAligned, New);
223 const AlignValueAttr *AlignValue = dyn_cast<AlignValueAttr>(TmplAttr);
225 instantiateDependentAlignValueAttr(*this, TemplateArgs, AlignValue, New);
229 const EnableIfAttr *EnableIf = dyn_cast<EnableIfAttr>(TmplAttr);
230 if (EnableIf && EnableIf->getCond()->isValueDependent()) {
231 instantiateDependentEnableIfAttr(*this, TemplateArgs, EnableIf, Tmpl,
236 // Existing DLL attribute on the instantiation takes precedence.
237 if (TmplAttr->getKind() == attr::DLLExport ||
238 TmplAttr->getKind() == attr::DLLImport) {
239 if (New->hasAttr<DLLExportAttr>() || New->hasAttr<DLLImportAttr>()) {
244 assert(!TmplAttr->isPackExpansion());
245 if (TmplAttr->isLateParsed() && LateAttrs) {
246 // Late parsed attributes must be instantiated and attached after the
247 // enclosing class has been instantiated. See Sema::InstantiateClass.
248 LocalInstantiationScope *Saved = nullptr;
249 if (CurrentInstantiationScope)
250 Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
251 LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
253 // Allow 'this' within late-parsed attributes.
254 NamedDecl *ND = dyn_cast<NamedDecl>(New);
255 CXXRecordDecl *ThisContext =
256 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
257 CXXThisScopeRAII ThisScope(*this, ThisContext, /*TypeQuals*/0,
258 ND && ND->isCXXInstanceMember());
260 Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
261 *this, TemplateArgs);
263 New->addAttr(NewAttr);
268 /// Get the previous declaration of a declaration for the purposes of template
269 /// instantiation. If this finds a previous declaration, then the previous
270 /// declaration of the instantiation of D should be an instantiation of the
271 /// result of this function.
272 template<typename DeclT>
273 static DeclT *getPreviousDeclForInstantiation(DeclT *D) {
274 DeclT *Result = D->getPreviousDecl();
276 // If the declaration is within a class, and the previous declaration was
277 // merged from a different definition of that class, then we don't have a
278 // previous declaration for the purpose of template instantiation.
279 if (Result && isa<CXXRecordDecl>(D->getDeclContext()) &&
280 D->getLexicalDeclContext() != Result->getLexicalDeclContext())
287 TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
288 llvm_unreachable("Translation units cannot be instantiated");
292 TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
293 LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
295 Owner->addDecl(Inst);
300 TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
301 llvm_unreachable("Namespaces cannot be instantiated");
305 TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
306 NamespaceAliasDecl *Inst
307 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
308 D->getNamespaceLoc(),
311 D->getQualifierLoc(),
312 D->getTargetNameLoc(),
314 Owner->addDecl(Inst);
318 Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
320 bool Invalid = false;
321 TypeSourceInfo *DI = D->getTypeSourceInfo();
322 if (DI->getType()->isInstantiationDependentType() ||
323 DI->getType()->isVariablyModifiedType()) {
324 DI = SemaRef.SubstType(DI, TemplateArgs,
325 D->getLocation(), D->getDeclName());
328 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
331 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
334 // HACK: g++ has a bug where it gets the value kind of ?: wrong.
335 // libstdc++ relies upon this bug in its implementation of common_type.
336 // If we happen to be processing that implementation, fake up the g++ ?:
337 // semantics. See LWG issue 2141 for more information on the bug.
338 const DecltypeType *DT = DI->getType()->getAs<DecltypeType>();
339 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
340 if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) &&
341 DT->isReferenceType() &&
342 RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() &&
343 RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") &&
344 D->getIdentifier() && D->getIdentifier()->isStr("type") &&
345 SemaRef.getSourceManager().isInSystemHeader(D->getLocStart()))
346 // Fold it to the (non-reference) type which g++ would have produced.
347 DI = SemaRef.Context.getTrivialTypeSourceInfo(
348 DI->getType().getNonReferenceType());
350 // Create the new typedef
351 TypedefNameDecl *Typedef;
353 Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
354 D->getLocation(), D->getIdentifier(), DI);
356 Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
357 D->getLocation(), D->getIdentifier(), DI);
359 Typedef->setInvalidDecl();
361 // If the old typedef was the name for linkage purposes of an anonymous
362 // tag decl, re-establish that relationship for the new typedef.
363 if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
364 TagDecl *oldTag = oldTagType->getDecl();
365 if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) {
366 TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
367 assert(!newTag->hasNameForLinkage());
368 newTag->setTypedefNameForAnonDecl(Typedef);
372 if (TypedefNameDecl *Prev = getPreviousDeclForInstantiation(D)) {
373 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
378 TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
380 // If the typedef types are not identical, reject them.
381 SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
383 Typedef->setPreviousDecl(InstPrevTypedef);
386 SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
388 Typedef->setAccess(D->getAccess());
393 Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
394 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
396 Owner->addDecl(Typedef);
400 Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
401 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
403 Owner->addDecl(Typedef);
408 TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
409 // Create a local instantiation scope for this type alias template, which
410 // will contain the instantiations of the template parameters.
411 LocalInstantiationScope Scope(SemaRef);
413 TemplateParameterList *TempParams = D->getTemplateParameters();
414 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
418 TypeAliasDecl *Pattern = D->getTemplatedDecl();
420 TypeAliasTemplateDecl *PrevAliasTemplate = nullptr;
421 if (getPreviousDeclForInstantiation<TypedefNameDecl>(Pattern)) {
422 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
423 if (!Found.empty()) {
424 PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front());
428 TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
429 InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
433 TypeAliasTemplateDecl *Inst
434 = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
435 D->getDeclName(), InstParams, AliasInst);
436 AliasInst->setDescribedAliasTemplate(Inst);
437 if (PrevAliasTemplate)
438 Inst->setPreviousDecl(PrevAliasTemplate);
440 Inst->setAccess(D->getAccess());
442 if (!PrevAliasTemplate)
443 Inst->setInstantiatedFromMemberTemplate(D);
445 Owner->addDecl(Inst);
450 Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
451 return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false);
454 Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D,
455 bool InstantiatingVarTemplate) {
457 // If this is the variable for an anonymous struct or union,
458 // instantiate the anonymous struct/union type first.
459 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
460 if (RecordTy->getDecl()->isAnonymousStructOrUnion())
461 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
464 // Do substitution on the type of the declaration
465 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
467 D->getTypeSpecStartLoc(),
472 if (DI->getType()->isFunctionType()) {
473 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
474 << D->isStaticDataMember() << DI->getType();
478 DeclContext *DC = Owner;
479 if (D->isLocalExternDecl())
480 SemaRef.adjustContextForLocalExternDecl(DC);
482 // Build the instantiated declaration.
483 VarDecl *Var = VarDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
484 D->getLocation(), D->getIdentifier(),
485 DI->getType(), DI, D->getStorageClass());
487 // In ARC, infer 'retaining' for variables of retainable type.
488 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
489 SemaRef.inferObjCARCLifetime(Var))
490 Var->setInvalidDecl();
492 // Substitute the nested name specifier, if any.
493 if (SubstQualifier(D, Var))
496 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
497 StartingScope, InstantiatingVarTemplate);
499 if (D->isNRVOVariable()) {
500 QualType ReturnType = cast<FunctionDecl>(DC)->getReturnType();
501 if (SemaRef.isCopyElisionCandidate(ReturnType, Var, false))
502 Var->setNRVOVariable(true);
505 Var->setImplicit(D->isImplicit());
510 Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
512 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
513 D->getAccessSpecifierLoc(), D->getColonLoc());
514 Owner->addHiddenDecl(AD);
518 Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
519 bool Invalid = false;
520 TypeSourceInfo *DI = D->getTypeSourceInfo();
521 if (DI->getType()->isInstantiationDependentType() ||
522 DI->getType()->isVariablyModifiedType()) {
523 DI = SemaRef.SubstType(DI, TemplateArgs,
524 D->getLocation(), D->getDeclName());
526 DI = D->getTypeSourceInfo();
528 } else if (DI->getType()->isFunctionType()) {
529 // C++ [temp.arg.type]p3:
530 // If a declaration acquires a function type through a type
531 // dependent on a template-parameter and this causes a
532 // declaration that does not use the syntactic form of a
533 // function declarator to have function type, the program is
535 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
540 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
543 Expr *BitWidth = D->getBitWidth();
547 // The bit-width expression is a constant expression.
548 EnterExpressionEvaluationContext Unevaluated(SemaRef,
549 Sema::ConstantEvaluated);
551 ExprResult InstantiatedBitWidth
552 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
553 if (InstantiatedBitWidth.isInvalid()) {
557 BitWidth = InstantiatedBitWidth.getAs<Expr>();
560 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
562 cast<RecordDecl>(Owner),
566 D->getInClassInitStyle(),
567 D->getInnerLocStart(),
571 cast<Decl>(Owner)->setInvalidDecl();
575 SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
577 if (Field->hasAttrs())
578 SemaRef.CheckAlignasUnderalignment(Field);
581 Field->setInvalidDecl();
583 if (!Field->getDeclName()) {
584 // Keep track of where this decl came from.
585 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
587 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
588 if (Parent->isAnonymousStructOrUnion() &&
589 Parent->getRedeclContext()->isFunctionOrMethod())
590 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
593 Field->setImplicit(D->isImplicit());
594 Field->setAccess(D->getAccess());
595 Owner->addDecl(Field);
600 Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) {
601 bool Invalid = false;
602 TypeSourceInfo *DI = D->getTypeSourceInfo();
604 if (DI->getType()->isVariablyModifiedType()) {
605 SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified)
608 } else if (DI->getType()->isInstantiationDependentType()) {
609 DI = SemaRef.SubstType(DI, TemplateArgs,
610 D->getLocation(), D->getDeclName());
612 DI = D->getTypeSourceInfo();
614 } else if (DI->getType()->isFunctionType()) {
615 // C++ [temp.arg.type]p3:
616 // If a declaration acquires a function type through a type
617 // dependent on a template-parameter and this causes a
618 // declaration that does not use the syntactic form of a
619 // function declarator to have function type, the program is
621 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
626 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
629 MSPropertyDecl *Property = MSPropertyDecl::Create(
630 SemaRef.Context, Owner, D->getLocation(), D->getDeclName(), DI->getType(),
631 DI, D->getLocStart(), D->getGetterId(), D->getSetterId());
633 SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs,
637 Property->setInvalidDecl();
639 Property->setAccess(D->getAccess());
640 Owner->addDecl(Property);
645 Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
646 NamedDecl **NamedChain =
647 new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
650 for (auto *PI : D->chain()) {
651 NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), PI,
656 NamedChain[i++] = Next;
659 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
660 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
661 SemaRef.Context, Owner, D->getLocation(), D->getIdentifier(), T,
662 NamedChain, D->getChainingSize());
664 for (const auto *Attr : D->attrs())
665 IndirectField->addAttr(Attr->clone(SemaRef.Context));
667 IndirectField->setImplicit(D->isImplicit());
668 IndirectField->setAccess(D->getAccess());
669 Owner->addDecl(IndirectField);
670 return IndirectField;
673 Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
674 // Handle friend type expressions by simply substituting template
675 // parameters into the pattern type and checking the result.
676 if (TypeSourceInfo *Ty = D->getFriendType()) {
677 TypeSourceInfo *InstTy;
678 // If this is an unsupported friend, don't bother substituting template
679 // arguments into it. The actual type referred to won't be used by any
680 // parts of Clang, and may not be valid for instantiating. Just use the
681 // same info for the instantiated friend.
682 if (D->isUnsupportedFriend()) {
685 InstTy = SemaRef.SubstType(Ty, TemplateArgs,
686 D->getLocation(), DeclarationName());
691 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getLocStart(),
692 D->getFriendLoc(), InstTy);
696 FD->setAccess(AS_public);
697 FD->setUnsupportedFriend(D->isUnsupportedFriend());
702 NamedDecl *ND = D->getFriendDecl();
703 assert(ND && "friend decl must be a decl or a type!");
705 // All of the Visit implementations for the various potential friend
706 // declarations have to be carefully written to work for friend
707 // objects, with the most important detail being that the target
708 // decl should almost certainly not be placed in Owner.
709 Decl *NewND = Visit(ND);
710 if (!NewND) return nullptr;
713 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
714 cast<NamedDecl>(NewND), D->getFriendLoc());
715 FD->setAccess(AS_public);
716 FD->setUnsupportedFriend(D->isUnsupportedFriend());
721 Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
722 Expr *AssertExpr = D->getAssertExpr();
724 // The expression in a static assertion is a constant expression.
725 EnterExpressionEvaluationContext Unevaluated(SemaRef,
726 Sema::ConstantEvaluated);
728 ExprResult InstantiatedAssertExpr
729 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
730 if (InstantiatedAssertExpr.isInvalid())
733 return SemaRef.BuildStaticAssertDeclaration(D->getLocation(),
734 InstantiatedAssertExpr.get(),
740 Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
741 EnumDecl *PrevDecl = nullptr;
742 if (EnumDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
743 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
746 if (!Prev) return nullptr;
747 PrevDecl = cast<EnumDecl>(Prev);
750 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
751 D->getLocation(), D->getIdentifier(),
752 PrevDecl, D->isScoped(),
753 D->isScopedUsingClassTag(), D->isFixed());
755 if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
756 // If we have type source information for the underlying type, it means it
757 // has been explicitly set by the user. Perform substitution on it before
759 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
760 TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
762 if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
763 Enum->setIntegerType(SemaRef.Context.IntTy);
765 Enum->setIntegerTypeSourceInfo(NewTI);
767 assert(!D->getIntegerType()->isDependentType()
768 && "Dependent type without type source info");
769 Enum->setIntegerType(D->getIntegerType());
773 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
775 Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
776 Enum->setAccess(D->getAccess());
777 // Forward the mangling number from the template to the instantiated decl.
778 SemaRef.Context.setManglingNumber(Enum, SemaRef.Context.getManglingNumber(D));
779 if (SubstQualifier(D, Enum)) return nullptr;
780 Owner->addDecl(Enum);
782 EnumDecl *Def = D->getDefinition();
783 if (Def && Def != D) {
784 // If this is an out-of-line definition of an enum member template, check
785 // that the underlying types match in the instantiation of both
787 if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
788 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
789 QualType DefnUnderlying =
790 SemaRef.SubstType(TI->getType(), TemplateArgs,
791 UnderlyingLoc, DeclarationName());
792 SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
793 DefnUnderlying, Enum);
797 // C++11 [temp.inst]p1: The implicit instantiation of a class template
798 // specialization causes the implicit instantiation of the declarations, but
799 // not the definitions of scoped member enumerations.
801 // DR1484 clarifies that enumeration definitions inside of a template
802 // declaration aren't considered entities that can be separately instantiated
803 // from the rest of the entity they are declared inside of.
804 if (isDeclWithinFunction(D) ? D == Def : Def && !Enum->isScoped()) {
805 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
806 InstantiateEnumDefinition(Enum, Def);
812 void TemplateDeclInstantiator::InstantiateEnumDefinition(
813 EnumDecl *Enum, EnumDecl *Pattern) {
814 Enum->startDefinition();
816 // Update the location to refer to the definition.
817 Enum->setLocation(Pattern->getLocation());
819 SmallVector<Decl*, 4> Enumerators;
821 EnumConstantDecl *LastEnumConst = nullptr;
822 for (auto *EC : Pattern->enumerators()) {
823 // The specified value for the enumerator.
824 ExprResult Value((Expr *)nullptr);
825 if (Expr *UninstValue = EC->getInitExpr()) {
826 // The enumerator's value expression is a constant expression.
827 EnterExpressionEvaluationContext Unevaluated(SemaRef,
828 Sema::ConstantEvaluated);
830 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
833 // Drop the initial value and continue.
834 bool isInvalid = false;
835 if (Value.isInvalid()) {
840 EnumConstantDecl *EnumConst
841 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
842 EC->getLocation(), EC->getIdentifier(),
847 EnumConst->setInvalidDecl();
848 Enum->setInvalidDecl();
852 SemaRef.InstantiateAttrs(TemplateArgs, EC, EnumConst);
854 EnumConst->setAccess(Enum->getAccess());
855 Enum->addDecl(EnumConst);
856 Enumerators.push_back(EnumConst);
857 LastEnumConst = EnumConst;
859 if (Pattern->getDeclContext()->isFunctionOrMethod() &&
861 // If the enumeration is within a function or method, record the enum
862 // constant as a local.
863 SemaRef.CurrentInstantiationScope->InstantiatedLocal(EC, EnumConst);
868 // FIXME: Fixup LBraceLoc
869 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(),
870 Enum->getRBraceLoc(), Enum,
875 Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
876 llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
879 Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
880 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
882 // Create a local instantiation scope for this class template, which
883 // will contain the instantiations of the template parameters.
884 LocalInstantiationScope Scope(SemaRef);
885 TemplateParameterList *TempParams = D->getTemplateParameters();
886 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
890 CXXRecordDecl *Pattern = D->getTemplatedDecl();
892 // Instantiate the qualifier. We have to do this first in case
893 // we're a friend declaration, because if we are then we need to put
894 // the new declaration in the appropriate context.
895 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
897 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
903 CXXRecordDecl *PrevDecl = nullptr;
904 ClassTemplateDecl *PrevClassTemplate = nullptr;
906 if (!isFriend && getPreviousDeclForInstantiation(Pattern)) {
907 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
908 if (!Found.empty()) {
909 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
910 if (PrevClassTemplate)
911 PrevDecl = PrevClassTemplate->getTemplatedDecl();
915 // If this isn't a friend, then it's a member template, in which
916 // case we just want to build the instantiation in the
917 // specialization. If it is a friend, we want to build it in
918 // the appropriate context.
919 DeclContext *DC = Owner;
923 SS.Adopt(QualifierLoc);
924 DC = SemaRef.computeDeclContext(SS);
925 if (!DC) return nullptr;
927 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
928 Pattern->getDeclContext(),
932 // Look for a previous declaration of the template in the owning
934 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
935 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
936 SemaRef.LookupQualifiedName(R, DC);
938 if (R.isSingleResult()) {
939 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
940 if (PrevClassTemplate)
941 PrevDecl = PrevClassTemplate->getTemplatedDecl();
944 if (!PrevClassTemplate && QualifierLoc) {
945 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
946 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
947 << QualifierLoc.getSourceRange();
951 bool AdoptedPreviousTemplateParams = false;
952 if (PrevClassTemplate) {
953 bool Complain = true;
955 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
956 // template for struct std::tr1::__detail::_Map_base, where the
957 // template parameters of the friend declaration don't match the
958 // template parameters of the original declaration. In this one
959 // case, we don't complain about the ill-formed friend
961 if (isFriend && Pattern->getIdentifier() &&
962 Pattern->getIdentifier()->isStr("_Map_base") &&
964 cast<NamespaceDecl>(DC)->getIdentifier() &&
965 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
966 DeclContext *DCParent = DC->getParent();
967 if (DCParent->isNamespace() &&
968 cast<NamespaceDecl>(DCParent)->getIdentifier() &&
969 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
970 if (cast<Decl>(DCParent)->isInStdNamespace())
975 TemplateParameterList *PrevParams
976 = PrevClassTemplate->getTemplateParameters();
978 // Make sure the parameter lists match.
979 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
981 Sema::TPL_TemplateMatch)) {
985 AdoptedPreviousTemplateParams = true;
986 InstParams = PrevParams;
989 // Do some additional validation, then merge default arguments
990 // from the existing declarations.
991 if (!AdoptedPreviousTemplateParams &&
992 SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
993 Sema::TPC_ClassTemplate))
998 CXXRecordDecl *RecordInst
999 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
1000 Pattern->getLocStart(), Pattern->getLocation(),
1001 Pattern->getIdentifier(), PrevDecl,
1002 /*DelayTypeCreation=*/true);
1005 RecordInst->setQualifierInfo(QualifierLoc);
1007 ClassTemplateDecl *Inst
1008 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
1009 D->getIdentifier(), InstParams, RecordInst,
1011 RecordInst->setDescribedClassTemplate(Inst);
1014 if (PrevClassTemplate)
1015 Inst->setAccess(PrevClassTemplate->getAccess());
1017 Inst->setAccess(D->getAccess());
1019 Inst->setObjectOfFriendDecl();
1020 // TODO: do we want to track the instantiation progeny of this
1021 // friend target decl?
1023 Inst->setAccess(D->getAccess());
1024 if (!PrevClassTemplate)
1025 Inst->setInstantiatedFromMemberTemplate(D);
1028 // Trigger creation of the type for the instantiation.
1029 SemaRef.Context.getInjectedClassNameType(RecordInst,
1030 Inst->getInjectedClassNameSpecialization());
1032 // Finish handling of friends.
1034 DC->makeDeclVisibleInContext(Inst);
1035 Inst->setLexicalDeclContext(Owner);
1036 RecordInst->setLexicalDeclContext(Owner);
1040 if (D->isOutOfLine()) {
1041 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1042 RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
1045 Owner->addDecl(Inst);
1047 if (!PrevClassTemplate) {
1048 // Queue up any out-of-line partial specializations of this member
1049 // class template; the client will force their instantiation once
1050 // the enclosing class has been instantiated.
1051 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1052 D->getPartialSpecializations(PartialSpecs);
1053 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
1054 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
1055 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
1062 TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
1063 ClassTemplatePartialSpecializationDecl *D) {
1064 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
1066 // Lookup the already-instantiated declaration in the instantiation
1067 // of the class template and return that.
1068 DeclContext::lookup_result Found
1069 = Owner->lookup(ClassTemplate->getDeclName());
1073 ClassTemplateDecl *InstClassTemplate
1074 = dyn_cast<ClassTemplateDecl>(Found.front());
1075 if (!InstClassTemplate)
1078 if (ClassTemplatePartialSpecializationDecl *Result
1079 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
1082 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
1085 Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) {
1086 assert(D->getTemplatedDecl()->isStaticDataMember() &&
1087 "Only static data member templates are allowed.");
1089 // Create a local instantiation scope for this variable template, which
1090 // will contain the instantiations of the template parameters.
1091 LocalInstantiationScope Scope(SemaRef);
1092 TemplateParameterList *TempParams = D->getTemplateParameters();
1093 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1097 VarDecl *Pattern = D->getTemplatedDecl();
1098 VarTemplateDecl *PrevVarTemplate = nullptr;
1100 if (getPreviousDeclForInstantiation(Pattern)) {
1101 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1103 PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1107 cast_or_null<VarDecl>(VisitVarDecl(Pattern,
1108 /*InstantiatingVarTemplate=*/true));
1110 DeclContext *DC = Owner;
1112 VarTemplateDecl *Inst = VarTemplateDecl::Create(
1113 SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams,
1115 VarInst->setDescribedVarTemplate(Inst);
1116 Inst->setPreviousDecl(PrevVarTemplate);
1118 Inst->setAccess(D->getAccess());
1119 if (!PrevVarTemplate)
1120 Inst->setInstantiatedFromMemberTemplate(D);
1122 if (D->isOutOfLine()) {
1123 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1124 VarInst->setLexicalDeclContext(D->getLexicalDeclContext());
1127 Owner->addDecl(Inst);
1129 if (!PrevVarTemplate) {
1130 // Queue up any out-of-line partial specializations of this member
1131 // variable template; the client will force their instantiation once
1132 // the enclosing class has been instantiated.
1133 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1134 D->getPartialSpecializations(PartialSpecs);
1135 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
1136 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
1137 OutOfLineVarPartialSpecs.push_back(
1138 std::make_pair(Inst, PartialSpecs[I]));
1144 Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl(
1145 VarTemplatePartialSpecializationDecl *D) {
1146 assert(D->isStaticDataMember() &&
1147 "Only static data member templates are allowed.");
1149 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
1151 // Lookup the already-instantiated declaration and return that.
1152 DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName());
1153 assert(!Found.empty() && "Instantiation found nothing?");
1155 VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1156 assert(InstVarTemplate && "Instantiation did not find a variable template?");
1158 if (VarTemplatePartialSpecializationDecl *Result =
1159 InstVarTemplate->findPartialSpecInstantiatedFromMember(D))
1162 return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D);
1166 TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
1167 // Create a local instantiation scope for this function template, which
1168 // will contain the instantiations of the template parameters and then get
1169 // merged with the local instantiation scope for the function template
1171 LocalInstantiationScope Scope(SemaRef);
1173 TemplateParameterList *TempParams = D->getTemplateParameters();
1174 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1178 FunctionDecl *Instantiated = nullptr;
1179 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
1180 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
1183 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
1184 D->getTemplatedDecl(),
1190 // Link the instantiated function template declaration to the function
1191 // template from which it was instantiated.
1192 FunctionTemplateDecl *InstTemplate
1193 = Instantiated->getDescribedFunctionTemplate();
1194 InstTemplate->setAccess(D->getAccess());
1195 assert(InstTemplate &&
1196 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
1198 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
1200 // Link the instantiation back to the pattern *unless* this is a
1201 // non-definition friend declaration.
1202 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
1203 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
1204 InstTemplate->setInstantiatedFromMemberTemplate(D);
1206 // Make declarations visible in the appropriate context.
1208 Owner->addDecl(InstTemplate);
1209 } else if (InstTemplate->getDeclContext()->isRecord() &&
1210 !getPreviousDeclForInstantiation(D)) {
1211 SemaRef.CheckFriendAccess(InstTemplate);
1214 return InstTemplate;
1217 Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
1218 CXXRecordDecl *PrevDecl = nullptr;
1219 if (D->isInjectedClassName())
1220 PrevDecl = cast<CXXRecordDecl>(Owner);
1221 else if (CXXRecordDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
1222 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
1225 if (!Prev) return nullptr;
1226 PrevDecl = cast<CXXRecordDecl>(Prev);
1229 CXXRecordDecl *Record
1230 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
1231 D->getLocStart(), D->getLocation(),
1232 D->getIdentifier(), PrevDecl);
1234 // Substitute the nested name specifier, if any.
1235 if (SubstQualifier(D, Record))
1238 Record->setImplicit(D->isImplicit());
1239 // FIXME: Check against AS_none is an ugly hack to work around the issue that
1240 // the tag decls introduced by friend class declarations don't have an access
1241 // specifier. Remove once this area of the code gets sorted out.
1242 if (D->getAccess() != AS_none)
1243 Record->setAccess(D->getAccess());
1244 if (!D->isInjectedClassName())
1245 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
1247 // If the original function was part of a friend declaration,
1248 // inherit its namespace state.
1249 if (D->getFriendObjectKind())
1250 Record->setObjectOfFriendDecl();
1252 // Make sure that anonymous structs and unions are recorded.
1253 if (D->isAnonymousStructOrUnion())
1254 Record->setAnonymousStructOrUnion(true);
1256 if (D->isLocalClass())
1257 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
1259 // Forward the mangling number from the template to the instantiated decl.
1260 SemaRef.Context.setManglingNumber(Record,
1261 SemaRef.Context.getManglingNumber(D));
1263 Owner->addDecl(Record);
1265 // DR1484 clarifies that the members of a local class are instantiated as part
1266 // of the instantiation of their enclosing entity.
1267 if (D->isCompleteDefinition() && D->isLocalClass()) {
1268 SemaRef.InstantiateClass(D->getLocation(), Record, D, TemplateArgs,
1269 TSK_ImplicitInstantiation,
1271 SemaRef.InstantiateClassMembers(D->getLocation(), Record, TemplateArgs,
1272 TSK_ImplicitInstantiation);
1275 SemaRef.DiagnoseUnusedNestedTypedefs(Record);
1280 /// \brief Adjust the given function type for an instantiation of the
1281 /// given declaration, to cope with modifications to the function's type that
1282 /// aren't reflected in the type-source information.
1284 /// \param D The declaration we're instantiating.
1285 /// \param TInfo The already-instantiated type.
1286 static QualType adjustFunctionTypeForInstantiation(ASTContext &Context,
1288 TypeSourceInfo *TInfo) {
1289 const FunctionProtoType *OrigFunc
1290 = D->getType()->castAs<FunctionProtoType>();
1291 const FunctionProtoType *NewFunc
1292 = TInfo->getType()->castAs<FunctionProtoType>();
1293 if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
1294 return TInfo->getType();
1296 FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
1297 NewEPI.ExtInfo = OrigFunc->getExtInfo();
1298 return Context.getFunctionType(NewFunc->getReturnType(),
1299 NewFunc->getParamTypes(), NewEPI);
1302 /// Normal class members are of more specific types and therefore
1303 /// don't make it here. This function serves two purposes:
1304 /// 1) instantiating function templates
1305 /// 2) substituting friend declarations
1306 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
1307 TemplateParameterList *TemplateParams) {
1308 // Check whether there is already a function template specialization for
1309 // this declaration.
1310 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1311 if (FunctionTemplate && !TemplateParams) {
1312 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
1314 void *InsertPos = nullptr;
1315 FunctionDecl *SpecFunc
1316 = FunctionTemplate->findSpecialization(Innermost, InsertPos);
1318 // If we already have a function template specialization, return it.
1324 if (FunctionTemplate)
1325 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1327 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1329 bool MergeWithParentScope = (TemplateParams != nullptr) ||
1330 Owner->isFunctionOrMethod() ||
1331 !(isa<Decl>(Owner) &&
1332 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1333 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
1335 SmallVector<ParmVarDecl *, 4> Params;
1336 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
1339 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
1341 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1343 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1349 // If we're instantiating a local function declaration, put the result
1350 // in the enclosing namespace; otherwise we need to find the instantiated
1353 if (D->isLocalExternDecl()) {
1355 SemaRef.adjustContextForLocalExternDecl(DC);
1356 } else if (isFriend && QualifierLoc) {
1358 SS.Adopt(QualifierLoc);
1359 DC = SemaRef.computeDeclContext(SS);
1360 if (!DC) return nullptr;
1362 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
1366 FunctionDecl *Function =
1367 FunctionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
1368 D->getNameInfo(), T, TInfo,
1369 D->getCanonicalDecl()->getStorageClass(),
1370 D->isInlineSpecified(), D->hasWrittenPrototype(),
1372 Function->setRangeEnd(D->getSourceRange().getEnd());
1375 Function->setImplicitlyInline();
1378 Function->setQualifierInfo(QualifierLoc);
1380 if (D->isLocalExternDecl())
1381 Function->setLocalExternDecl();
1383 DeclContext *LexicalDC = Owner;
1384 if (!isFriend && D->isOutOfLine() && !D->isLocalExternDecl()) {
1385 assert(D->getDeclContext()->isFileContext());
1386 LexicalDC = D->getDeclContext();
1389 Function->setLexicalDeclContext(LexicalDC);
1391 // Attach the parameters
1392 for (unsigned P = 0; P < Params.size(); ++P)
1394 Params[P]->setOwningFunction(Function);
1395 Function->setParams(Params);
1397 SourceLocation InstantiateAtPOI;
1398 if (TemplateParams) {
1399 // Our resulting instantiation is actually a function template, since we
1400 // are substituting only the outer template parameters. For example, given
1402 // template<typename T>
1404 // template<typename U> friend void f(T, U);
1409 // We are instantiating the friend function template "f" within X<int>,
1410 // which means substituting int for T, but leaving "f" as a friend function
1412 // Build the function template itself.
1413 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
1414 Function->getLocation(),
1415 Function->getDeclName(),
1416 TemplateParams, Function);
1417 Function->setDescribedFunctionTemplate(FunctionTemplate);
1419 FunctionTemplate->setLexicalDeclContext(LexicalDC);
1421 if (isFriend && D->isThisDeclarationADefinition()) {
1422 // TODO: should we remember this connection regardless of whether
1423 // the friend declaration provided a body?
1424 FunctionTemplate->setInstantiatedFromMemberTemplate(
1425 D->getDescribedFunctionTemplate());
1427 } else if (FunctionTemplate) {
1428 // Record this function template specialization.
1429 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
1430 Function->setFunctionTemplateSpecialization(FunctionTemplate,
1431 TemplateArgumentList::CreateCopy(SemaRef.Context,
1434 /*InsertPos=*/nullptr);
1435 } else if (isFriend) {
1436 // Note, we need this connection even if the friend doesn't have a body.
1437 // Its body may exist but not have been attached yet due to deferred
1439 // FIXME: It might be cleaner to set this when attaching the body to the
1440 // friend function declaration, however that would require finding all the
1441 // instantiations and modifying them.
1442 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
1445 if (InitFunctionInstantiation(Function, D))
1446 Function->setInvalidDecl();
1448 bool isExplicitSpecialization = false;
1450 LookupResult Previous(
1451 SemaRef, Function->getDeclName(), SourceLocation(),
1452 D->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
1453 : Sema::LookupOrdinaryName,
1454 Sema::ForRedeclaration);
1456 if (DependentFunctionTemplateSpecializationInfo *Info
1457 = D->getDependentSpecializationInfo()) {
1458 assert(isFriend && "non-friend has dependent specialization info?");
1460 // This needs to be set now for future sanity.
1461 Function->setObjectOfFriendDecl();
1463 // Instantiate the explicit template arguments.
1464 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1465 Info->getRAngleLoc());
1466 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1467 ExplicitArgs, TemplateArgs))
1470 // Map the candidate templates to their instantiations.
1471 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1472 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1473 Info->getTemplate(I),
1475 if (!Temp) return nullptr;
1477 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1480 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1483 Function->setInvalidDecl();
1485 isExplicitSpecialization = true;
1487 } else if (TemplateParams || !FunctionTemplate) {
1488 // Look only into the namespace where the friend would be declared to
1489 // find a previous declaration. This is the innermost enclosing namespace,
1490 // as described in ActOnFriendFunctionDecl.
1491 SemaRef.LookupQualifiedName(Previous, DC);
1493 // In C++, the previous declaration we find might be a tag type
1494 // (class or enum). In this case, the new declaration will hide the
1495 // tag type. Note that this does does not apply if we're declaring a
1496 // typedef (C++ [dcl.typedef]p4).
1497 if (Previous.isSingleTagDecl())
1501 SemaRef.CheckFunctionDeclaration(/*Scope*/ nullptr, Function, Previous,
1502 isExplicitSpecialization);
1504 NamedDecl *PrincipalDecl = (TemplateParams
1505 ? cast<NamedDecl>(FunctionTemplate)
1508 // If the original function was part of a friend declaration,
1509 // inherit its namespace state and add it to the owner.
1511 PrincipalDecl->setObjectOfFriendDecl();
1512 DC->makeDeclVisibleInContext(PrincipalDecl);
1514 bool QueuedInstantiation = false;
1516 // C++11 [temp.friend]p4 (DR329):
1517 // When a function is defined in a friend function declaration in a class
1518 // template, the function is instantiated when the function is odr-used.
1519 // The same restrictions on multiple declarations and definitions that
1520 // apply to non-template function declarations and definitions also apply
1521 // to these implicit definitions.
1522 if (D->isThisDeclarationADefinition()) {
1523 // Check for a function body.
1524 const FunctionDecl *Definition = nullptr;
1525 if (Function->isDefined(Definition) &&
1526 Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
1527 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1528 << Function->getDeclName();
1529 SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
1531 // Check for redefinitions due to other instantiations of this or
1532 // a similar friend function.
1533 else for (auto R : Function->redecls()) {
1537 // If some prior declaration of this function has been used, we need
1538 // to instantiate its definition.
1539 if (!QueuedInstantiation && R->isUsed(false)) {
1540 if (MemberSpecializationInfo *MSInfo =
1541 Function->getMemberSpecializationInfo()) {
1542 if (MSInfo->getPointOfInstantiation().isInvalid()) {
1543 SourceLocation Loc = R->getLocation(); // FIXME
1544 MSInfo->setPointOfInstantiation(Loc);
1545 SemaRef.PendingLocalImplicitInstantiations.push_back(
1546 std::make_pair(Function, Loc));
1547 QueuedInstantiation = true;
1552 // If some prior declaration of this function was a friend with an
1553 // uninstantiated definition, reject it.
1554 if (R->getFriendObjectKind()) {
1555 if (const FunctionDecl *RPattern =
1556 R->getTemplateInstantiationPattern()) {
1557 if (RPattern->isDefined(RPattern)) {
1558 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1559 << Function->getDeclName();
1560 SemaRef.Diag(R->getLocation(), diag::note_previous_definition);
1569 if (Function->isLocalExternDecl() && !Function->getPreviousDecl())
1570 DC->makeDeclVisibleInContext(PrincipalDecl);
1572 if (Function->isOverloadedOperator() && !DC->isRecord() &&
1573 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1574 PrincipalDecl->setNonMemberOperator();
1576 assert(!D->isDefaulted() && "only methods should be defaulted");
1581 TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
1582 TemplateParameterList *TemplateParams,
1583 bool IsClassScopeSpecialization) {
1584 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1585 if (FunctionTemplate && !TemplateParams) {
1586 // We are creating a function template specialization from a function
1587 // template. Check whether there is already a function template
1588 // specialization for this particular set of template arguments.
1589 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
1591 void *InsertPos = nullptr;
1592 FunctionDecl *SpecFunc
1593 = FunctionTemplate->findSpecialization(Innermost, InsertPos);
1595 // If we already have a function template specialization, return it.
1601 if (FunctionTemplate)
1602 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1604 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1606 bool MergeWithParentScope = (TemplateParams != nullptr) ||
1607 !(isa<Decl>(Owner) &&
1608 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1609 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
1611 // Instantiate enclosing template arguments for friends.
1612 SmallVector<TemplateParameterList *, 4> TempParamLists;
1613 unsigned NumTempParamLists = 0;
1614 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
1615 TempParamLists.set_size(NumTempParamLists);
1616 for (unsigned I = 0; I != NumTempParamLists; ++I) {
1617 TemplateParameterList *TempParams = D->getTemplateParameterList(I);
1618 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1621 TempParamLists[I] = InstParams;
1625 SmallVector<ParmVarDecl *, 4> Params;
1626 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
1629 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
1631 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1633 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1639 DeclContext *DC = Owner;
1643 SS.Adopt(QualifierLoc);
1644 DC = SemaRef.computeDeclContext(SS);
1646 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
1649 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1650 D->getDeclContext(),
1653 if (!DC) return nullptr;
1656 // Build the instantiated method declaration.
1657 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1658 CXXMethodDecl *Method = nullptr;
1660 SourceLocation StartLoc = D->getInnerLocStart();
1661 DeclarationNameInfo NameInfo
1662 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
1663 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
1664 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
1665 StartLoc, NameInfo, T, TInfo,
1666 Constructor->isExplicit(),
1667 Constructor->isInlineSpecified(),
1668 false, Constructor->isConstexpr());
1670 // Claim that the instantiation of a constructor or constructor template
1671 // inherits the same constructor that the template does.
1672 if (CXXConstructorDecl *Inh = const_cast<CXXConstructorDecl *>(
1673 Constructor->getInheritedConstructor())) {
1674 // If we're instantiating a specialization of a function template, our
1675 // "inherited constructor" will actually itself be a function template.
1676 // Instantiate a declaration of it, too.
1677 if (FunctionTemplate) {
1678 assert(!TemplateParams && Inh->getDescribedFunctionTemplate() &&
1679 !Inh->getParent()->isDependentContext() &&
1680 "inheriting constructor template in dependent context?");
1681 Sema::InstantiatingTemplate Inst(SemaRef, Constructor->getLocation(),
1683 if (Inst.isInvalid())
1685 Sema::ContextRAII SavedContext(SemaRef, Inh->getDeclContext());
1686 LocalInstantiationScope LocalScope(SemaRef);
1688 // Use the same template arguments that we deduced for the inheriting
1689 // constructor. There's no way they could be deduced differently.
1690 MultiLevelTemplateArgumentList InheritedArgs;
1691 InheritedArgs.addOuterTemplateArguments(TemplateArgs.getInnermost());
1692 Inh = cast_or_null<CXXConstructorDecl>(
1693 SemaRef.SubstDecl(Inh, Inh->getDeclContext(), InheritedArgs));
1697 cast<CXXConstructorDecl>(Method)->setInheritedConstructor(Inh);
1699 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
1700 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
1701 StartLoc, NameInfo, T, TInfo,
1702 Destructor->isInlineSpecified(),
1704 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
1705 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
1706 StartLoc, NameInfo, T, TInfo,
1707 Conversion->isInlineSpecified(),
1708 Conversion->isExplicit(),
1709 Conversion->isConstexpr(),
1710 Conversion->getLocEnd());
1712 StorageClass SC = D->isStatic() ? SC_Static : SC_None;
1713 Method = CXXMethodDecl::Create(SemaRef.Context, Record,
1714 StartLoc, NameInfo, T, TInfo,
1715 SC, D->isInlineSpecified(),
1716 D->isConstexpr(), D->getLocEnd());
1720 Method->setImplicitlyInline();
1723 Method->setQualifierInfo(QualifierLoc);
1725 if (TemplateParams) {
1726 // Our resulting instantiation is actually a function template, since we
1727 // are substituting only the outer template parameters. For example, given
1729 // template<typename T>
1731 // template<typename U> void f(T, U);
1736 // We are instantiating the member template "f" within X<int>, which means
1737 // substituting int for T, but leaving "f" as a member function template.
1738 // Build the function template itself.
1739 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1740 Method->getLocation(),
1741 Method->getDeclName(),
1742 TemplateParams, Method);
1744 FunctionTemplate->setLexicalDeclContext(Owner);
1745 FunctionTemplate->setObjectOfFriendDecl();
1746 } else if (D->isOutOfLine())
1747 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
1748 Method->setDescribedFunctionTemplate(FunctionTemplate);
1749 } else if (FunctionTemplate) {
1750 // Record this function template specialization.
1751 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
1752 Method->setFunctionTemplateSpecialization(FunctionTemplate,
1753 TemplateArgumentList::CreateCopy(SemaRef.Context,
1756 /*InsertPos=*/nullptr);
1757 } else if (!isFriend) {
1758 // Record that this is an instantiation of a member function.
1759 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
1762 // If we are instantiating a member function defined
1763 // out-of-line, the instantiation will have the same lexical
1764 // context (which will be a namespace scope) as the template.
1766 if (NumTempParamLists)
1767 Method->setTemplateParameterListsInfo(SemaRef.Context,
1769 TempParamLists.data());
1771 Method->setLexicalDeclContext(Owner);
1772 Method->setObjectOfFriendDecl();
1773 } else if (D->isOutOfLine())
1774 Method->setLexicalDeclContext(D->getLexicalDeclContext());
1776 // Attach the parameters
1777 for (unsigned P = 0; P < Params.size(); ++P)
1778 Params[P]->setOwningFunction(Method);
1779 Method->setParams(Params);
1781 if (InitMethodInstantiation(Method, D))
1782 Method->setInvalidDecl();
1784 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
1785 Sema::ForRedeclaration);
1787 if (!FunctionTemplate || TemplateParams || isFriend) {
1788 SemaRef.LookupQualifiedName(Previous, Record);
1790 // In C++, the previous declaration we find might be a tag type
1791 // (class or enum). In this case, the new declaration will hide the
1792 // tag type. Note that this does does not apply if we're declaring a
1793 // typedef (C++ [dcl.typedef]p4).
1794 if (Previous.isSingleTagDecl())
1798 if (!IsClassScopeSpecialization)
1799 SemaRef.CheckFunctionDeclaration(nullptr, Method, Previous, false);
1802 SemaRef.CheckPureMethod(Method, SourceRange());
1804 // Propagate access. For a non-friend declaration, the access is
1805 // whatever we're propagating from. For a friend, it should be the
1806 // previous declaration we just found.
1807 if (isFriend && Method->getPreviousDecl())
1808 Method->setAccess(Method->getPreviousDecl()->getAccess());
1810 Method->setAccess(D->getAccess());
1811 if (FunctionTemplate)
1812 FunctionTemplate->setAccess(Method->getAccess());
1814 SemaRef.CheckOverrideControl(Method);
1816 // If a function is defined as defaulted or deleted, mark it as such now.
1817 if (D->isExplicitlyDefaulted())
1818 SemaRef.SetDeclDefaulted(Method, Method->getLocation());
1819 if (D->isDeletedAsWritten())
1820 SemaRef.SetDeclDeleted(Method, Method->getLocation());
1822 // If there's a function template, let our caller handle it.
1823 if (FunctionTemplate) {
1826 // Don't hide a (potentially) valid declaration with an invalid one.
1827 } else if (Method->isInvalidDecl() && !Previous.empty()) {
1830 // Otherwise, check access to friends and make them visible.
1831 } else if (isFriend) {
1832 // We only need to re-check access for methods which we didn't
1833 // manage to match during parsing.
1834 if (!D->getPreviousDecl())
1835 SemaRef.CheckFriendAccess(Method);
1837 Record->makeDeclVisibleInContext(Method);
1839 // Otherwise, add the declaration. We don't need to do this for
1840 // class-scope specializations because we'll have matched them with
1841 // the appropriate template.
1842 } else if (!IsClassScopeSpecialization) {
1843 Owner->addDecl(Method);
1849 Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
1850 return VisitCXXMethodDecl(D);
1853 Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
1854 return VisitCXXMethodDecl(D);
1857 Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
1858 return VisitCXXMethodDecl(D);
1861 Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
1862 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0, None,
1863 /*ExpectParameterPack=*/ false);
1866 Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1867 TemplateTypeParmDecl *D) {
1868 // TODO: don't always clone when decls are refcounted.
1869 assert(D->getTypeForDecl()->isTemplateTypeParmType());
1871 TemplateTypeParmDecl *Inst =
1872 TemplateTypeParmDecl::Create(SemaRef.Context, Owner,
1873 D->getLocStart(), D->getLocation(),
1874 D->getDepth() - TemplateArgs.getNumLevels(),
1875 D->getIndex(), D->getIdentifier(),
1876 D->wasDeclaredWithTypename(),
1877 D->isParameterPack());
1878 Inst->setAccess(AS_public);
1880 if (D->hasDefaultArgument()) {
1881 TypeSourceInfo *InstantiatedDefaultArg =
1882 SemaRef.SubstType(D->getDefaultArgumentInfo(), TemplateArgs,
1883 D->getDefaultArgumentLoc(), D->getDeclName());
1884 if (InstantiatedDefaultArg)
1885 Inst->setDefaultArgument(InstantiatedDefaultArg, false);
1888 // Introduce this template parameter's instantiation into the instantiation
1890 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1895 Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1896 NonTypeTemplateParmDecl *D) {
1897 // Substitute into the type of the non-type template parameter.
1898 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
1899 SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
1900 SmallVector<QualType, 4> ExpandedParameterPackTypes;
1901 bool IsExpandedParameterPack = false;
1904 bool Invalid = false;
1906 if (D->isExpandedParameterPack()) {
1907 // The non-type template parameter pack is an already-expanded pack
1908 // expansion of types. Substitute into each of the expanded types.
1909 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
1910 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
1911 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
1912 TypeSourceInfo *NewDI =SemaRef.SubstType(D->getExpansionTypeSourceInfo(I),
1919 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1920 QualType NewT =SemaRef.CheckNonTypeTemplateParameterType(NewDI->getType(),
1924 ExpandedParameterPackTypes.push_back(NewT);
1927 IsExpandedParameterPack = true;
1928 DI = D->getTypeSourceInfo();
1930 } else if (D->isPackExpansion()) {
1931 // The non-type template parameter pack's type is a pack expansion of types.
1932 // Determine whether we need to expand this parameter pack into separate
1934 PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>();
1935 TypeLoc Pattern = Expansion.getPatternLoc();
1936 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1937 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
1939 // Determine whether the set of unexpanded parameter packs can and should
1942 bool RetainExpansion = false;
1943 Optional<unsigned> OrigNumExpansions
1944 = Expansion.getTypePtr()->getNumExpansions();
1945 Optional<unsigned> NumExpansions = OrigNumExpansions;
1946 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
1947 Pattern.getSourceRange(),
1950 Expand, RetainExpansion,
1955 for (unsigned I = 0; I != *NumExpansions; ++I) {
1956 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
1957 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
1963 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1964 QualType NewT = SemaRef.CheckNonTypeTemplateParameterType(
1969 ExpandedParameterPackTypes.push_back(NewT);
1972 // Note that we have an expanded parameter pack. The "type" of this
1973 // expanded parameter pack is the original expansion type, but callers
1974 // will end up using the expanded parameter pack types for type-checking.
1975 IsExpandedParameterPack = true;
1976 DI = D->getTypeSourceInfo();
1979 // We cannot fully expand the pack expansion now, so substitute into the
1980 // pattern and create a new pack expansion type.
1981 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
1982 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
1988 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
1996 // Simple case: substitution into a parameter that is not a parameter pack.
1997 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
1998 D->getLocation(), D->getDeclName());
2002 // Check that this type is acceptable for a non-type template parameter.
2003 T = SemaRef.CheckNonTypeTemplateParameterType(DI->getType(),
2006 T = SemaRef.Context.IntTy;
2011 NonTypeTemplateParmDecl *Param;
2012 if (IsExpandedParameterPack)
2013 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
2014 D->getInnerLocStart(),
2016 D->getDepth() - TemplateArgs.getNumLevels(),
2018 D->getIdentifier(), T,
2020 ExpandedParameterPackTypes.data(),
2021 ExpandedParameterPackTypes.size(),
2022 ExpandedParameterPackTypesAsWritten.data());
2024 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
2025 D->getInnerLocStart(),
2027 D->getDepth() - TemplateArgs.getNumLevels(),
2029 D->getIdentifier(), T,
2030 D->isParameterPack(), DI);
2032 Param->setAccess(AS_public);
2034 Param->setInvalidDecl();
2036 if (D->hasDefaultArgument()) {
2037 ExprResult Value = SemaRef.SubstExpr(D->getDefaultArgument(), TemplateArgs);
2038 if (!Value.isInvalid())
2039 Param->setDefaultArgument(Value.get(), false);
2042 // Introduce this template parameter's instantiation into the instantiation
2044 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
2048 static void collectUnexpandedParameterPacks(
2050 TemplateParameterList *Params,
2051 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
2052 for (TemplateParameterList::const_iterator I = Params->begin(),
2053 E = Params->end(); I != E; ++I) {
2054 if ((*I)->isTemplateParameterPack())
2056 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*I))
2057 S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
2059 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(*I))
2060 collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
2066 TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
2067 TemplateTemplateParmDecl *D) {
2068 // Instantiate the template parameter list of the template template parameter.
2069 TemplateParameterList *TempParams = D->getTemplateParameters();
2070 TemplateParameterList *InstParams;
2071 SmallVector<TemplateParameterList*, 8> ExpandedParams;
2073 bool IsExpandedParameterPack = false;
2075 if (D->isExpandedParameterPack()) {
2076 // The template template parameter pack is an already-expanded pack
2077 // expansion of template parameters. Substitute into each of the expanded
2079 ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
2080 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
2082 LocalInstantiationScope Scope(SemaRef);
2083 TemplateParameterList *Expansion =
2084 SubstTemplateParams(D->getExpansionTemplateParameters(I));
2087 ExpandedParams.push_back(Expansion);
2090 IsExpandedParameterPack = true;
2091 InstParams = TempParams;
2092 } else if (D->isPackExpansion()) {
2093 // The template template parameter pack expands to a pack of template
2094 // template parameters. Determine whether we need to expand this parameter
2095 // pack into separate parameters.
2096 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2097 collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(),
2100 // Determine whether the set of unexpanded parameter packs can and should
2103 bool RetainExpansion = false;
2104 Optional<unsigned> NumExpansions;
2105 if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(),
2106 TempParams->getSourceRange(),
2109 Expand, RetainExpansion,
2114 for (unsigned I = 0; I != *NumExpansions; ++I) {
2115 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2116 LocalInstantiationScope Scope(SemaRef);
2117 TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
2120 ExpandedParams.push_back(Expansion);
2123 // Note that we have an expanded parameter pack. The "type" of this
2124 // expanded parameter pack is the original expansion type, but callers
2125 // will end up using the expanded parameter pack types for type-checking.
2126 IsExpandedParameterPack = true;
2127 InstParams = TempParams;
2129 // We cannot fully expand the pack expansion now, so just substitute
2130 // into the pattern.
2131 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2133 LocalInstantiationScope Scope(SemaRef);
2134 InstParams = SubstTemplateParams(TempParams);
2139 // Perform the actual substitution of template parameters within a new,
2140 // local instantiation scope.
2141 LocalInstantiationScope Scope(SemaRef);
2142 InstParams = SubstTemplateParams(TempParams);
2147 // Build the template template parameter.
2148 TemplateTemplateParmDecl *Param;
2149 if (IsExpandedParameterPack)
2150 Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
2152 D->getDepth() - TemplateArgs.getNumLevels(),
2154 D->getIdentifier(), InstParams,
2157 Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
2159 D->getDepth() - TemplateArgs.getNumLevels(),
2161 D->isParameterPack(),
2162 D->getIdentifier(), InstParams);
2163 if (D->hasDefaultArgument()) {
2164 NestedNameSpecifierLoc QualifierLoc =
2165 D->getDefaultArgument().getTemplateQualifierLoc();
2167 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs);
2168 TemplateName TName = SemaRef.SubstTemplateName(
2169 QualifierLoc, D->getDefaultArgument().getArgument().getAsTemplate(),
2170 D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs);
2171 if (!TName.isNull())
2172 Param->setDefaultArgument(
2173 TemplateArgumentLoc(TemplateArgument(TName),
2174 D->getDefaultArgument().getTemplateQualifierLoc(),
2175 D->getDefaultArgument().getTemplateNameLoc()),
2178 Param->setAccess(AS_public);
2180 // Introduce this template parameter's instantiation into the instantiation
2182 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
2187 Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
2188 // Using directives are never dependent (and never contain any types or
2189 // expressions), so they require no explicit instantiation work.
2191 UsingDirectiveDecl *Inst
2192 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
2193 D->getNamespaceKeyLocation(),
2194 D->getQualifierLoc(),
2195 D->getIdentLocation(),
2196 D->getNominatedNamespace(),
2197 D->getCommonAncestor());
2199 // Add the using directive to its declaration context
2200 // only if this is not a function or method.
2201 if (!Owner->isFunctionOrMethod())
2202 Owner->addDecl(Inst);
2207 Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
2209 // The nested name specifier may be dependent, for example
2210 // template <typename T> struct t {
2211 // struct s1 { T f1(); };
2212 // struct s2 : s1 { using s1::f1; };
2214 // template struct t<int>;
2215 // Here, in using s1::f1, s1 refers to t<T>::s1;
2216 // we need to substitute for t<int>::s1.
2217 NestedNameSpecifierLoc QualifierLoc
2218 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
2223 // The name info is non-dependent, so no transformation
2225 DeclarationNameInfo NameInfo = D->getNameInfo();
2227 // We only need to do redeclaration lookups if we're in a class
2228 // scope (in fact, it's not really even possible in non-class
2230 bool CheckRedeclaration = Owner->isRecord();
2232 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
2233 Sema::ForRedeclaration);
2235 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
2242 SS.Adopt(QualifierLoc);
2243 if (CheckRedeclaration) {
2244 Prev.setHideTags(false);
2245 SemaRef.LookupQualifiedName(Prev, Owner);
2247 // Check for invalid redeclarations.
2248 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(),
2249 D->hasTypename(), SS,
2250 D->getLocation(), Prev))
2251 NewUD->setInvalidDecl();
2255 if (!NewUD->isInvalidDecl() &&
2256 SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), SS, NameInfo,
2258 NewUD->setInvalidDecl();
2260 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
2261 NewUD->setAccess(D->getAccess());
2262 Owner->addDecl(NewUD);
2264 // Don't process the shadow decls for an invalid decl.
2265 if (NewUD->isInvalidDecl())
2268 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
2269 SemaRef.CheckInheritingConstructorUsingDecl(NewUD);
2273 bool isFunctionScope = Owner->isFunctionOrMethod();
2275 // Process the shadow decls.
2276 for (auto *Shadow : D->shadows()) {
2277 NamedDecl *InstTarget =
2278 cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
2279 Shadow->getLocation(), Shadow->getTargetDecl(), TemplateArgs));
2283 UsingShadowDecl *PrevDecl = nullptr;
2284 if (CheckRedeclaration) {
2285 if (SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev, PrevDecl))
2287 } else if (UsingShadowDecl *OldPrev =
2288 getPreviousDeclForInstantiation(Shadow)) {
2289 PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl(
2290 Shadow->getLocation(), OldPrev, TemplateArgs));
2293 UsingShadowDecl *InstShadow =
2294 SemaRef.BuildUsingShadowDecl(/*Scope*/nullptr, NewUD, InstTarget,
2296 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
2298 if (isFunctionScope)
2299 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
2305 Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
2306 // Ignore these; we handle them in bulk when processing the UsingDecl.
2310 Decl * TemplateDeclInstantiator
2311 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
2312 NestedNameSpecifierLoc QualifierLoc
2313 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
2319 SS.Adopt(QualifierLoc);
2321 // Since NameInfo refers to a typename, it cannot be a C++ special name.
2322 // Hence, no transformation is required for it.
2323 DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation());
2325 SemaRef.BuildUsingDeclaration(/*Scope*/ nullptr, D->getAccess(),
2326 D->getUsingLoc(), SS, NameInfo, nullptr,
2327 /*instantiation*/ true,
2328 /*typename*/ true, D->getTypenameLoc());
2330 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
2335 Decl * TemplateDeclInstantiator
2336 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
2337 NestedNameSpecifierLoc QualifierLoc
2338 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), TemplateArgs);
2343 SS.Adopt(QualifierLoc);
2345 DeclarationNameInfo NameInfo
2346 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2349 SemaRef.BuildUsingDeclaration(/*Scope*/ nullptr, D->getAccess(),
2350 D->getUsingLoc(), SS, NameInfo, nullptr,
2351 /*instantiation*/ true,
2352 /*typename*/ false, SourceLocation());
2354 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
2360 Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
2361 ClassScopeFunctionSpecializationDecl *Decl) {
2362 CXXMethodDecl *OldFD = Decl->getSpecialization();
2363 CXXMethodDecl *NewFD =
2364 cast_or_null<CXXMethodDecl>(VisitCXXMethodDecl(OldFD, nullptr, true));
2368 LookupResult Previous(SemaRef, NewFD->getNameInfo(), Sema::LookupOrdinaryName,
2369 Sema::ForRedeclaration);
2371 TemplateArgumentListInfo TemplateArgs;
2372 TemplateArgumentListInfo *TemplateArgsPtr = nullptr;
2373 if (Decl->hasExplicitTemplateArgs()) {
2374 TemplateArgs = Decl->templateArgs();
2375 TemplateArgsPtr = &TemplateArgs;
2378 SemaRef.LookupQualifiedName(Previous, SemaRef.CurContext);
2379 if (SemaRef.CheckFunctionTemplateSpecialization(NewFD, TemplateArgsPtr,
2381 NewFD->setInvalidDecl();
2385 // Associate the specialization with the pattern.
2386 FunctionDecl *Specialization = cast<FunctionDecl>(Previous.getFoundDecl());
2387 assert(Specialization && "Class scope Specialization is null");
2388 SemaRef.Context.setClassScopeSpecializationPattern(Specialization, OldFD);
2393 Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
2394 OMPThreadPrivateDecl *D) {
2395 SmallVector<Expr *, 5> Vars;
2396 for (auto *I : D->varlists()) {
2397 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
2398 assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
2399 Vars.push_back(Var);
2402 OMPThreadPrivateDecl *TD =
2403 SemaRef.CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
2405 TD->setAccess(AS_public);
2411 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
2412 return VisitFunctionDecl(D, nullptr);
2415 Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
2416 return VisitCXXMethodDecl(D, nullptr);
2419 Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
2420 llvm_unreachable("There are only CXXRecordDecls in C++");
2424 TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
2425 ClassTemplateSpecializationDecl *D) {
2426 // As a MS extension, we permit class-scope explicit specialization
2427 // of member class templates.
2428 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
2429 assert(ClassTemplate->getDeclContext()->isRecord() &&
2430 D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
2431 "can only instantiate an explicit specialization "
2432 "for a member class template");
2434 // Lookup the already-instantiated declaration in the instantiation
2435 // of the class template. FIXME: Diagnose or assert if this fails?
2436 DeclContext::lookup_result Found
2437 = Owner->lookup(ClassTemplate->getDeclName());
2440 ClassTemplateDecl *InstClassTemplate
2441 = dyn_cast<ClassTemplateDecl>(Found.front());
2442 if (!InstClassTemplate)
2445 // Substitute into the template arguments of the class template explicit
2447 TemplateSpecializationTypeLoc Loc = D->getTypeAsWritten()->getTypeLoc().
2448 castAs<TemplateSpecializationTypeLoc>();
2449 TemplateArgumentListInfo InstTemplateArgs(Loc.getLAngleLoc(),
2450 Loc.getRAngleLoc());
2451 SmallVector<TemplateArgumentLoc, 4> ArgLocs;
2452 for (unsigned I = 0; I != Loc.getNumArgs(); ++I)
2453 ArgLocs.push_back(Loc.getArgLoc(I));
2454 if (SemaRef.Subst(ArgLocs.data(), ArgLocs.size(),
2455 InstTemplateArgs, TemplateArgs))
2458 // Check that the template argument list is well-formed for this
2460 SmallVector<TemplateArgument, 4> Converted;
2461 if (SemaRef.CheckTemplateArgumentList(InstClassTemplate,
2468 // Figure out where to insert this class template explicit specialization
2469 // in the member template's set of class template explicit specializations.
2470 void *InsertPos = nullptr;
2471 ClassTemplateSpecializationDecl *PrevDecl =
2472 InstClassTemplate->findSpecialization(Converted, InsertPos);
2474 // Check whether we've already seen a conflicting instantiation of this
2475 // declaration (for instance, if there was a prior implicit instantiation).
2478 SemaRef.CheckSpecializationInstantiationRedecl(D->getLocation(),
2479 D->getSpecializationKind(),
2481 PrevDecl->getSpecializationKind(),
2482 PrevDecl->getPointOfInstantiation(),
2486 // If PrevDecl was a definition and D is also a definition, diagnose.
2487 // This happens in cases like:
2489 // template<typename T, typename U>
2491 // template<typename X> struct Inner;
2492 // template<> struct Inner<T> {};
2493 // template<> struct Inner<U> {};
2496 // Outer<int, int> outer; // error: the explicit specializations of Inner
2497 // // have the same signature.
2498 if (PrevDecl && PrevDecl->getDefinition() &&
2499 D->isThisDeclarationADefinition()) {
2500 SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl;
2501 SemaRef.Diag(PrevDecl->getDefinition()->getLocation(),
2502 diag::note_previous_definition);
2506 // Create the class template partial specialization declaration.
2507 ClassTemplateSpecializationDecl *InstD
2508 = ClassTemplateSpecializationDecl::Create(SemaRef.Context,
2518 // Add this partial specialization to the set of class template partial
2521 InstClassTemplate->AddSpecialization(InstD, InsertPos);
2523 // Substitute the nested name specifier, if any.
2524 if (SubstQualifier(D, InstD))
2527 // Build the canonical type that describes the converted template
2528 // arguments of the class template explicit specialization.
2529 QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
2530 TemplateName(InstClassTemplate), Converted.data(), Converted.size(),
2531 SemaRef.Context.getRecordType(InstD));
2533 // Build the fully-sugared type for this class template
2534 // specialization as the user wrote in the specialization
2535 // itself. This means that we'll pretty-print the type retrieved
2536 // from the specialization's declaration the way that the user
2537 // actually wrote the specialization, rather than formatting the
2538 // name based on the "canonical" representation used to store the
2539 // template arguments in the specialization.
2540 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
2541 TemplateName(InstClassTemplate), D->getLocation(), InstTemplateArgs,
2544 InstD->setAccess(D->getAccess());
2545 InstD->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
2546 InstD->setSpecializationKind(D->getSpecializationKind());
2547 InstD->setTypeAsWritten(WrittenTy);
2548 InstD->setExternLoc(D->getExternLoc());
2549 InstD->setTemplateKeywordLoc(D->getTemplateKeywordLoc());
2551 Owner->addDecl(InstD);
2553 // Instantiate the members of the class-scope explicit specialization eagerly.
2554 // We don't have support for lazy instantiation of an explicit specialization
2555 // yet, and MSVC eagerly instantiates in this case.
2556 if (D->isThisDeclarationADefinition() &&
2557 SemaRef.InstantiateClass(D->getLocation(), InstD, D, TemplateArgs,
2558 TSK_ImplicitInstantiation,
2565 Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
2566 VarTemplateSpecializationDecl *D) {
2568 TemplateArgumentListInfo VarTemplateArgsInfo;
2569 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
2570 assert(VarTemplate &&
2571 "A template specialization without specialized template?");
2573 // Substitute the current template arguments.
2574 const TemplateArgumentListInfo &TemplateArgsInfo = D->getTemplateArgsInfo();
2575 VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo.getLAngleLoc());
2576 VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo.getRAngleLoc());
2578 if (SemaRef.Subst(TemplateArgsInfo.getArgumentArray(),
2579 TemplateArgsInfo.size(), VarTemplateArgsInfo, TemplateArgs))
2582 // Check that the template argument list is well-formed for this template.
2583 SmallVector<TemplateArgument, 4> Converted;
2584 if (SemaRef.CheckTemplateArgumentList(
2585 VarTemplate, VarTemplate->getLocStart(),
2586 const_cast<TemplateArgumentListInfo &>(VarTemplateArgsInfo), false,
2590 // Find the variable template specialization declaration that
2591 // corresponds to these arguments.
2592 void *InsertPos = nullptr;
2593 if (VarTemplateSpecializationDecl *VarSpec = VarTemplate->findSpecialization(
2594 Converted, InsertPos))
2595 // If we already have a variable template specialization, return it.
2598 return VisitVarTemplateSpecializationDecl(VarTemplate, D, InsertPos,
2599 VarTemplateArgsInfo, Converted);
2602 Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
2603 VarTemplateDecl *VarTemplate, VarDecl *D, void *InsertPos,
2604 const TemplateArgumentListInfo &TemplateArgsInfo,
2605 ArrayRef<TemplateArgument> Converted) {
2607 // If this is the variable for an anonymous struct or union,
2608 // instantiate the anonymous struct/union type first.
2609 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
2610 if (RecordTy->getDecl()->isAnonymousStructOrUnion())
2611 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
2614 // Do substitution on the type of the declaration
2615 TypeSourceInfo *DI =
2616 SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
2617 D->getTypeSpecStartLoc(), D->getDeclName());
2621 if (DI->getType()->isFunctionType()) {
2622 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
2623 << D->isStaticDataMember() << DI->getType();
2627 // Build the instantiated declaration
2628 VarTemplateSpecializationDecl *Var = VarTemplateSpecializationDecl::Create(
2629 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
2630 VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted.data(),
2632 Var->setTemplateArgsInfo(TemplateArgsInfo);
2634 VarTemplate->AddSpecialization(Var, InsertPos);
2636 // Substitute the nested name specifier, if any.
2637 if (SubstQualifier(D, Var))
2640 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs,
2641 Owner, StartingScope);
2646 Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
2647 llvm_unreachable("@defs is not supported in Objective-C++");
2650 Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
2651 // FIXME: We need to be able to instantiate FriendTemplateDecls.
2652 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
2653 DiagnosticsEngine::Error,
2654 "cannot instantiate %0 yet");
2655 SemaRef.Diag(D->getLocation(), DiagID)
2656 << D->getDeclKindName();
2661 Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) {
2662 llvm_unreachable("Unexpected decl");
2665 Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
2666 const MultiLevelTemplateArgumentList &TemplateArgs) {
2667 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
2668 if (D->isInvalidDecl())
2671 return Instantiator.Visit(D);
2674 /// \brief Instantiates a nested template parameter list in the current
2675 /// instantiation context.
2677 /// \param L The parameter list to instantiate
2679 /// \returns NULL if there was an error
2680 TemplateParameterList *
2681 TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
2682 // Get errors for all the parameters before bailing out.
2683 bool Invalid = false;
2685 unsigned N = L->size();
2686 typedef SmallVector<NamedDecl *, 8> ParamVector;
2689 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
2691 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
2692 Params.push_back(D);
2693 Invalid = Invalid || !D || D->isInvalidDecl();
2696 // Clean up if we had an error.
2700 TemplateParameterList *InstL
2701 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
2702 L->getLAngleLoc(), &Params.front(), N,
2707 /// \brief Instantiate the declaration of a class template partial
2710 /// \param ClassTemplate the (instantiated) class template that is partially
2711 // specialized by the instantiation of \p PartialSpec.
2713 /// \param PartialSpec the (uninstantiated) class template partial
2714 /// specialization that we are instantiating.
2716 /// \returns The instantiated partial specialization, if successful; otherwise,
2717 /// NULL to indicate an error.
2718 ClassTemplatePartialSpecializationDecl *
2719 TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
2720 ClassTemplateDecl *ClassTemplate,
2721 ClassTemplatePartialSpecializationDecl *PartialSpec) {
2722 // Create a local instantiation scope for this class template partial
2723 // specialization, which will contain the instantiations of the template
2725 LocalInstantiationScope Scope(SemaRef);
2727 // Substitute into the template parameters of the class template partial
2729 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
2730 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2734 // Substitute into the template arguments of the class template partial
2736 const ASTTemplateArgumentListInfo *TemplArgInfo
2737 = PartialSpec->getTemplateArgsAsWritten();
2738 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
2739 TemplArgInfo->RAngleLoc);
2740 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
2741 TemplArgInfo->NumTemplateArgs,
2742 InstTemplateArgs, TemplateArgs))
2745 // Check that the template argument list is well-formed for this
2747 SmallVector<TemplateArgument, 4> Converted;
2748 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
2749 PartialSpec->getLocation(),
2755 // Figure out where to insert this class template partial specialization
2756 // in the member template's set of class template partial specializations.
2757 void *InsertPos = nullptr;
2758 ClassTemplateSpecializationDecl *PrevDecl
2759 = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
2761 // Build the canonical type that describes the converted template
2762 // arguments of the class template partial specialization.
2764 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
2768 // Build the fully-sugared type for this class template
2769 // specialization as the user wrote in the specialization
2770 // itself. This means that we'll pretty-print the type retrieved
2771 // from the specialization's declaration the way that the user
2772 // actually wrote the specialization, rather than formatting the
2773 // name based on the "canonical" representation used to store the
2774 // template arguments in the specialization.
2775 TypeSourceInfo *WrittenTy
2776 = SemaRef.Context.getTemplateSpecializationTypeInfo(
2777 TemplateName(ClassTemplate),
2778 PartialSpec->getLocation(),
2783 // We've already seen a partial specialization with the same template
2784 // parameters and template arguments. This can happen, for example, when
2785 // substituting the outer template arguments ends up causing two
2786 // class template partial specializations of a member class template
2787 // to have identical forms, e.g.,
2789 // template<typename T, typename U>
2791 // template<typename X, typename Y> struct Inner;
2792 // template<typename Y> struct Inner<T, Y>;
2793 // template<typename Y> struct Inner<U, Y>;
2796 // Outer<int, int> outer; // error: the partial specializations of Inner
2797 // // have the same signature.
2798 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
2799 << WrittenTy->getType();
2800 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
2801 << SemaRef.Context.getTypeDeclType(PrevDecl);
2806 // Create the class template partial specialization declaration.
2807 ClassTemplatePartialSpecializationDecl *InstPartialSpec
2808 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
2809 PartialSpec->getTagKind(),
2811 PartialSpec->getLocStart(),
2812 PartialSpec->getLocation(),
2820 // Substitute the nested name specifier, if any.
2821 if (SubstQualifier(PartialSpec, InstPartialSpec))
2824 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
2825 InstPartialSpec->setTypeAsWritten(WrittenTy);
2827 // Add this partial specialization to the set of class template partial
2829 ClassTemplate->AddPartialSpecialization(InstPartialSpec,
2830 /*InsertPos=*/nullptr);
2831 return InstPartialSpec;
2834 /// \brief Instantiate the declaration of a variable template partial
2837 /// \param VarTemplate the (instantiated) variable template that is partially
2838 /// specialized by the instantiation of \p PartialSpec.
2840 /// \param PartialSpec the (uninstantiated) variable template partial
2841 /// specialization that we are instantiating.
2843 /// \returns The instantiated partial specialization, if successful; otherwise,
2844 /// NULL to indicate an error.
2845 VarTemplatePartialSpecializationDecl *
2846 TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization(
2847 VarTemplateDecl *VarTemplate,
2848 VarTemplatePartialSpecializationDecl *PartialSpec) {
2849 // Create a local instantiation scope for this variable template partial
2850 // specialization, which will contain the instantiations of the template
2852 LocalInstantiationScope Scope(SemaRef);
2854 // Substitute into the template parameters of the variable template partial
2856 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
2857 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2861 // Substitute into the template arguments of the variable template partial
2863 const ASTTemplateArgumentListInfo *TemplArgInfo
2864 = PartialSpec->getTemplateArgsAsWritten();
2865 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
2866 TemplArgInfo->RAngleLoc);
2867 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
2868 TemplArgInfo->NumTemplateArgs,
2869 InstTemplateArgs, TemplateArgs))
2872 // Check that the template argument list is well-formed for this
2874 SmallVector<TemplateArgument, 4> Converted;
2875 if (SemaRef.CheckTemplateArgumentList(VarTemplate, PartialSpec->getLocation(),
2876 InstTemplateArgs, false, Converted))
2879 // Figure out where to insert this variable template partial specialization
2880 // in the member template's set of variable template partial specializations.
2881 void *InsertPos = nullptr;
2882 VarTemplateSpecializationDecl *PrevDecl =
2883 VarTemplate->findPartialSpecialization(Converted, InsertPos);
2885 // Build the canonical type that describes the converted template
2886 // arguments of the variable template partial specialization.
2887 QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
2888 TemplateName(VarTemplate), Converted.data(), Converted.size());
2890 // Build the fully-sugared type for this variable template
2891 // specialization as the user wrote in the specialization
2892 // itself. This means that we'll pretty-print the type retrieved
2893 // from the specialization's declaration the way that the user
2894 // actually wrote the specialization, rather than formatting the
2895 // name based on the "canonical" representation used to store the
2896 // template arguments in the specialization.
2897 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
2898 TemplateName(VarTemplate), PartialSpec->getLocation(), InstTemplateArgs,
2902 // We've already seen a partial specialization with the same template
2903 // parameters and template arguments. This can happen, for example, when
2904 // substituting the outer template arguments ends up causing two
2905 // variable template partial specializations of a member variable template
2906 // to have identical forms, e.g.,
2908 // template<typename T, typename U>
2910 // template<typename X, typename Y> pair<X,Y> p;
2911 // template<typename Y> pair<T, Y> p;
2912 // template<typename Y> pair<U, Y> p;
2915 // Outer<int, int> outer; // error: the partial specializations of Inner
2916 // // have the same signature.
2917 SemaRef.Diag(PartialSpec->getLocation(),
2918 diag::err_var_partial_spec_redeclared)
2919 << WrittenTy->getType();
2920 SemaRef.Diag(PrevDecl->getLocation(),
2921 diag::note_var_prev_partial_spec_here);
2925 // Do substitution on the type of the declaration
2926 TypeSourceInfo *DI = SemaRef.SubstType(
2927 PartialSpec->getTypeSourceInfo(), TemplateArgs,
2928 PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName());
2932 if (DI->getType()->isFunctionType()) {
2933 SemaRef.Diag(PartialSpec->getLocation(),
2934 diag::err_variable_instantiates_to_function)
2935 << PartialSpec->isStaticDataMember() << DI->getType();
2939 // Create the variable template partial specialization declaration.
2940 VarTemplatePartialSpecializationDecl *InstPartialSpec =
2941 VarTemplatePartialSpecializationDecl::Create(
2942 SemaRef.Context, Owner, PartialSpec->getInnerLocStart(),
2943 PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(),
2944 DI, PartialSpec->getStorageClass(), Converted.data(),
2945 Converted.size(), InstTemplateArgs);
2947 // Substitute the nested name specifier, if any.
2948 if (SubstQualifier(PartialSpec, InstPartialSpec))
2951 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
2952 InstPartialSpec->setTypeAsWritten(WrittenTy);
2954 // Add this partial specialization to the set of variable template partial
2955 // specializations. The instantiation of the initializer is not necessary.
2956 VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/nullptr);
2958 SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs,
2959 LateAttrs, Owner, StartingScope);
2961 return InstPartialSpec;
2965 TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
2966 SmallVectorImpl<ParmVarDecl *> &Params) {
2967 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
2968 assert(OldTInfo && "substituting function without type source info");
2969 assert(Params.empty() && "parameter vector is non-empty at start");
2971 CXXRecordDecl *ThisContext = nullptr;
2972 unsigned ThisTypeQuals = 0;
2973 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
2974 ThisContext = cast<CXXRecordDecl>(Owner);
2975 ThisTypeQuals = Method->getTypeQualifiers();
2978 TypeSourceInfo *NewTInfo
2979 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
2980 D->getTypeSpecStartLoc(),
2982 ThisContext, ThisTypeQuals);
2986 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
2987 if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
2988 if (NewTInfo != OldTInfo) {
2989 // Get parameters from the new type info.
2990 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
2991 FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
2992 unsigned NewIdx = 0;
2993 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams();
2994 OldIdx != NumOldParams; ++OldIdx) {
2995 ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx);
2996 LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
2998 Optional<unsigned> NumArgumentsInExpansion;
2999 if (OldParam->isParameterPack())
3000 NumArgumentsInExpansion =
3001 SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
3003 if (!NumArgumentsInExpansion) {
3004 // Simple case: normal parameter, or a parameter pack that's
3005 // instantiated to a (still-dependent) parameter pack.
3006 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
3007 Params.push_back(NewParam);
3008 Scope->InstantiatedLocal(OldParam, NewParam);
3010 // Parameter pack expansion: make the instantiation an argument pack.
3011 Scope->MakeInstantiatedLocalArgPack(OldParam);
3012 for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
3013 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
3014 Params.push_back(NewParam);
3015 Scope->InstantiatedLocalPackArg(OldParam, NewParam);
3020 // The function type itself was not dependent and therefore no
3021 // substitution occurred. However, we still need to instantiate
3022 // the function parameters themselves.
3023 const FunctionProtoType *OldProto =
3024 cast<FunctionProtoType>(OldProtoLoc.getType());
3025 for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end;
3027 ParmVarDecl *OldParam = OldProtoLoc.getParam(i);
3029 Params.push_back(SemaRef.BuildParmVarDeclForTypedef(
3030 D, D->getLocation(), OldProto->getParamType(i)));
3035 cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam));
3038 Params.push_back(Parm);
3042 // If the type of this function, after ignoring parentheses, is not
3043 // *directly* a function type, then we're instantiating a function that
3044 // was declared via a typedef or with attributes, e.g.,
3046 // typedef int functype(int, int);
3048 // int __cdecl meth(int, int);
3050 // In this case, we'll just go instantiate the ParmVarDecls that we
3051 // synthesized in the method declaration.
3052 SmallVector<QualType, 4> ParamTypes;
3053 if (SemaRef.SubstParmTypes(D->getLocation(), D->param_begin(),
3054 D->getNumParams(), TemplateArgs, ParamTypes,
3062 /// Introduce the instantiated function parameters into the local
3063 /// instantiation scope, and set the parameter names to those used
3064 /// in the template.
3065 static bool addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function,
3066 const FunctionDecl *PatternDecl,
3067 LocalInstantiationScope &Scope,
3068 const MultiLevelTemplateArgumentList &TemplateArgs) {
3069 unsigned FParamIdx = 0;
3070 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
3071 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
3072 if (!PatternParam->isParameterPack()) {
3073 // Simple case: not a parameter pack.
3074 assert(FParamIdx < Function->getNumParams());
3075 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
3076 FunctionParam->setDeclName(PatternParam->getDeclName());
3077 // If the parameter's type is not dependent, update it to match the type
3078 // in the pattern. They can differ in top-level cv-qualifiers, and we want
3079 // the pattern's type here. If the type is dependent, they can't differ,
3080 // per core issue 1668. Substitute into the type from the pattern, in case
3081 // it's instantiation-dependent.
3082 // FIXME: Updating the type to work around this is at best fragile.
3083 if (!PatternDecl->getType()->isDependentType()) {
3084 QualType T = S.SubstType(PatternParam->getType(), TemplateArgs,
3085 FunctionParam->getLocation(),
3086 FunctionParam->getDeclName());
3089 FunctionParam->setType(T);
3092 Scope.InstantiatedLocal(PatternParam, FunctionParam);
3097 // Expand the parameter pack.
3098 Scope.MakeInstantiatedLocalArgPack(PatternParam);
3099 Optional<unsigned> NumArgumentsInExpansion
3100 = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
3101 assert(NumArgumentsInExpansion &&
3102 "should only be called when all template arguments are known");
3103 QualType PatternType =
3104 PatternParam->getType()->castAs<PackExpansionType>()->getPattern();
3105 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
3106 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
3107 FunctionParam->setDeclName(PatternParam->getDeclName());
3108 if (!PatternDecl->getType()->isDependentType()) {
3109 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, Arg);
3110 QualType T = S.SubstType(PatternType, TemplateArgs,
3111 FunctionParam->getLocation(),
3112 FunctionParam->getDeclName());
3115 FunctionParam->setType(T);
3118 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
3126 void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
3127 FunctionDecl *Decl) {
3128 const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
3129 if (Proto->getExceptionSpecType() != EST_Uninstantiated)
3132 InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
3133 InstantiatingTemplate::ExceptionSpecification());
3134 if (Inst.isInvalid()) {
3135 // We hit the instantiation depth limit. Clear the exception specification
3136 // so that our callers don't have to cope with EST_Uninstantiated.
3137 UpdateExceptionSpec(Decl, EST_None);
3141 // Enter the scope of this instantiation. We don't use
3142 // PushDeclContext because we don't have a scope.
3143 Sema::ContextRAII savedContext(*this, Decl);
3144 LocalInstantiationScope Scope(*this);
3146 MultiLevelTemplateArgumentList TemplateArgs =
3147 getTemplateInstantiationArgs(Decl, nullptr, /*RelativeToPrimary*/true);
3149 FunctionDecl *Template = Proto->getExceptionSpecTemplate();
3150 if (addInstantiatedParametersToScope(*this, Decl, Template, Scope,
3152 UpdateExceptionSpec(Decl, EST_None);
3156 SubstExceptionSpec(Decl, Template->getType()->castAs<FunctionProtoType>(),
3160 /// \brief Initializes the common fields of an instantiation function
3161 /// declaration (New) from the corresponding fields of its template (Tmpl).
3163 /// \returns true if there was an error
3165 TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
3166 FunctionDecl *Tmpl) {
3167 if (Tmpl->isDeleted())
3168 New->setDeletedAsWritten();
3170 // Forward the mangling number from the template to the instantiated decl.
3171 SemaRef.Context.setManglingNumber(New,
3172 SemaRef.Context.getManglingNumber(Tmpl));
3174 // If we are performing substituting explicitly-specified template arguments
3175 // or deduced template arguments into a function template and we reach this
3176 // point, we are now past the point where SFINAE applies and have committed
3177 // to keeping the new function template specialization. We therefore
3178 // convert the active template instantiation for the function template
3179 // into a template instantiation for this specific function template
3180 // specialization, which is not a SFINAE context, so that we diagnose any
3181 // further errors in the declaration itself.
3182 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
3183 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
3184 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
3185 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
3186 if (FunctionTemplateDecl *FunTmpl
3187 = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) {
3188 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
3189 "Deduction from the wrong function template?");
3191 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
3192 ActiveInst.Entity = New;
3196 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
3197 assert(Proto && "Function template without prototype?");
3199 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
3200 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3202 // DR1330: In C++11, defer instantiation of a non-trivial
3203 // exception specification.
3204 if (SemaRef.getLangOpts().CPlusPlus11 &&
3205 EPI.ExceptionSpec.Type != EST_None &&
3206 EPI.ExceptionSpec.Type != EST_DynamicNone &&
3207 EPI.ExceptionSpec.Type != EST_BasicNoexcept) {
3208 FunctionDecl *ExceptionSpecTemplate = Tmpl;
3209 if (EPI.ExceptionSpec.Type == EST_Uninstantiated)
3210 ExceptionSpecTemplate = EPI.ExceptionSpec.SourceTemplate;
3211 ExceptionSpecificationType NewEST = EST_Uninstantiated;
3212 if (EPI.ExceptionSpec.Type == EST_Unevaluated)
3213 NewEST = EST_Unevaluated;
3215 // Mark the function has having an uninstantiated exception specification.
3216 const FunctionProtoType *NewProto
3217 = New->getType()->getAs<FunctionProtoType>();
3218 assert(NewProto && "Template instantiation without function prototype?");
3219 EPI = NewProto->getExtProtoInfo();
3220 EPI.ExceptionSpec.Type = NewEST;
3221 EPI.ExceptionSpec.SourceDecl = New;
3222 EPI.ExceptionSpec.SourceTemplate = ExceptionSpecTemplate;
3223 New->setType(SemaRef.Context.getFunctionType(
3224 NewProto->getReturnType(), NewProto->getParamTypes(), EPI));
3226 SemaRef.SubstExceptionSpec(New, Proto, TemplateArgs);
3230 // Get the definition. Leaves the variable unchanged if undefined.
3231 const FunctionDecl *Definition = Tmpl;
3232 Tmpl->isDefined(Definition);
3234 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
3235 LateAttrs, StartingScope);
3240 /// \brief Initializes common fields of an instantiated method
3241 /// declaration (New) from the corresponding fields of its template
3244 /// \returns true if there was an error
3246 TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
3247 CXXMethodDecl *Tmpl) {
3248 if (InitFunctionInstantiation(New, Tmpl))
3251 New->setAccess(Tmpl->getAccess());
3252 if (Tmpl->isVirtualAsWritten())
3253 New->setVirtualAsWritten(true);
3255 // FIXME: New needs a pointer to Tmpl
3259 /// \brief Instantiate the definition of the given function from its
3262 /// \param PointOfInstantiation the point at which the instantiation was
3263 /// required. Note that this is not precisely a "point of instantiation"
3264 /// for the function, but it's close.
3266 /// \param Function the already-instantiated declaration of a
3267 /// function template specialization or member function of a class template
3270 /// \param Recursive if true, recursively instantiates any functions that
3271 /// are required by this instantiation.
3273 /// \param DefinitionRequired if true, then we are performing an explicit
3274 /// instantiation where the body of the function is required. Complain if
3275 /// there is no such body.
3276 void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
3277 FunctionDecl *Function,
3279 bool DefinitionRequired) {
3280 if (Function->isInvalidDecl() || Function->isDefined())
3283 // Never instantiate an explicit specialization except if it is a class scope
3284 // explicit specialization.
3285 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
3286 !Function->getClassScopeSpecializationPattern())
3289 // Find the function body that we'll be substituting.
3290 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
3291 assert(PatternDecl && "instantiating a non-template");
3293 Stmt *Pattern = PatternDecl->getBody(PatternDecl);
3294 assert(PatternDecl && "template definition is not a template");
3296 // Try to find a defaulted definition
3297 PatternDecl->isDefined(PatternDecl);
3299 assert(PatternDecl && "template definition is not a template");
3301 // Postpone late parsed template instantiations.
3302 if (PatternDecl->isLateTemplateParsed() &&
3303 !LateTemplateParser) {
3304 PendingInstantiations.push_back(
3305 std::make_pair(Function, PointOfInstantiation));
3309 // If we're performing recursive template instantiation, create our own
3310 // queue of pending implicit instantiations that we will instantiate later,
3311 // while we're still within our own instantiation context.
3312 // This has to happen before LateTemplateParser below is called, so that
3313 // it marks vtables used in late parsed templates as used.
3314 SavePendingLocalImplicitInstantiationsRAII
3315 SavedPendingLocalImplicitInstantiations(*this);
3316 std::unique_ptr<SavePendingInstantiationsAndVTableUsesRAII>
3317 SavePendingInstantiationsAndVTableUses;
3319 SavePendingInstantiationsAndVTableUses.reset(
3320 new SavePendingInstantiationsAndVTableUsesRAII(*this));
3323 // Call the LateTemplateParser callback if there is a need to late parse
3324 // a templated function definition.
3325 if (!Pattern && PatternDecl->isLateTemplateParsed() &&
3326 LateTemplateParser) {
3327 // FIXME: Optimize to allow individual templates to be deserialized.
3328 if (PatternDecl->isFromASTFile())
3329 ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap);
3331 LateParsedTemplate *LPT = LateParsedTemplateMap.lookup(PatternDecl);
3332 assert(LPT && "missing LateParsedTemplate");
3333 LateTemplateParser(OpaqueParser, *LPT);
3334 Pattern = PatternDecl->getBody(PatternDecl);
3337 if (!Pattern && !PatternDecl->isDefaulted()) {
3338 if (DefinitionRequired) {
3339 if (Function->getPrimaryTemplate())
3340 Diag(PointOfInstantiation,
3341 diag::err_explicit_instantiation_undefined_func_template)
3342 << Function->getPrimaryTemplate();
3344 Diag(PointOfInstantiation,
3345 diag::err_explicit_instantiation_undefined_member)
3346 << 1 << Function->getDeclName() << Function->getDeclContext();
3349 Diag(PatternDecl->getLocation(),
3350 diag::note_explicit_instantiation_here);
3351 Function->setInvalidDecl();
3352 } else if (Function->getTemplateSpecializationKind()
3353 == TSK_ExplicitInstantiationDefinition) {
3355 PendingInstantiations.push_back(
3356 std::make_pair(Function, PointOfInstantiation));
3362 // C++1y [temp.explicit]p10:
3363 // Except for inline functions, declarations with types deduced from their
3364 // initializer or return value, and class template specializations, other
3365 // explicit instantiation declarations have the effect of suppressing the
3366 // implicit instantiation of the entity to which they refer.
3367 if (Function->getTemplateSpecializationKind() ==
3368 TSK_ExplicitInstantiationDeclaration &&
3369 !PatternDecl->isInlined() &&
3370 !PatternDecl->getReturnType()->getContainedAutoType())
3373 if (PatternDecl->isInlined()) {
3374 // Function, and all later redeclarations of it (from imported modules,
3375 // for instance), are now implicitly inline.
3376 for (auto *D = Function->getMostRecentDecl(); /**/;
3377 D = D->getPreviousDecl()) {
3378 D->setImplicitlyInline();
3384 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
3385 if (Inst.isInvalid())
3388 // Copy the inner loc start from the pattern.
3389 Function->setInnerLocStart(PatternDecl->getInnerLocStart());
3391 EnterExpressionEvaluationContext EvalContext(*this,
3392 Sema::PotentiallyEvaluated);
3394 // Introduce a new scope where local variable instantiations will be
3395 // recorded, unless we're actually a member function within a local
3396 // class, in which case we need to merge our results with the parent
3397 // scope (of the enclosing function).
3398 bool MergeWithParentScope = false;
3399 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
3400 MergeWithParentScope = Rec->isLocalClass();
3402 LocalInstantiationScope Scope(*this, MergeWithParentScope);
3404 if (PatternDecl->isDefaulted())
3405 SetDeclDefaulted(Function, PatternDecl->getLocation());
3407 MultiLevelTemplateArgumentList TemplateArgs =
3408 getTemplateInstantiationArgs(Function, nullptr, false, PatternDecl);
3410 // Substitute into the qualifier; we can get a substitution failure here
3411 // through evil use of alias templates.
3412 // FIXME: Is CurContext correct for this? Should we go to the (instantiation
3413 // of the) lexical context of the pattern?
3414 SubstQualifier(*this, PatternDecl, Function, TemplateArgs);
3416 ActOnStartOfFunctionDef(nullptr, Function);
3418 // Enter the scope of this instantiation. We don't use
3419 // PushDeclContext because we don't have a scope.
3420 Sema::ContextRAII savedContext(*this, Function);
3422 if (addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope,
3426 // If this is a constructor, instantiate the member initializers.
3427 if (const CXXConstructorDecl *Ctor =
3428 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
3429 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
3433 // Instantiate the function body.
3434 StmtResult Body = SubstStmt(Pattern, TemplateArgs);
3436 if (Body.isInvalid())
3437 Function->setInvalidDecl();
3439 ActOnFinishFunctionBody(Function, Body.get(),
3440 /*IsInstantiation=*/true);
3442 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
3444 if (auto *Listener = getASTMutationListener())
3445 Listener->FunctionDefinitionInstantiated(Function);
3450 DeclGroupRef DG(Function);
3451 Consumer.HandleTopLevelDecl(DG);
3453 // This class may have local implicit instantiations that need to be
3454 // instantiation within this scope.
3455 PerformPendingInstantiations(/*LocalOnly=*/true);
3459 // Define any pending vtables.
3460 DefineUsedVTables();
3462 // Instantiate any pending implicit instantiations found during the
3463 // instantiation of this template.
3464 PerformPendingInstantiations();
3466 // Restore PendingInstantiations and VTableUses.
3467 SavePendingInstantiationsAndVTableUses.reset();
3471 VarTemplateSpecializationDecl *Sema::BuildVarTemplateInstantiation(
3472 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
3473 const TemplateArgumentList &TemplateArgList,
3474 const TemplateArgumentListInfo &TemplateArgsInfo,
3475 SmallVectorImpl<TemplateArgument> &Converted,
3476 SourceLocation PointOfInstantiation, void *InsertPos,
3477 LateInstantiatedAttrVec *LateAttrs,
3478 LocalInstantiationScope *StartingScope) {
3479 if (FromVar->isInvalidDecl())
3482 InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar);
3483 if (Inst.isInvalid())
3486 MultiLevelTemplateArgumentList TemplateArgLists;
3487 TemplateArgLists.addOuterTemplateArguments(&TemplateArgList);
3489 // Instantiate the first declaration of the variable template: for a partial
3490 // specialization of a static data member template, the first declaration may
3491 // or may not be the declaration in the class; if it's in the class, we want
3492 // to instantiate a member in the class (a declaration), and if it's outside,
3493 // we want to instantiate a definition.
3495 // If we're instantiating an explicitly-specialized member template or member
3496 // partial specialization, don't do this. The member specialization completely
3497 // replaces the original declaration in this case.
3498 bool IsMemberSpec = false;
3499 if (VarTemplatePartialSpecializationDecl *PartialSpec =
3500 dyn_cast<VarTemplatePartialSpecializationDecl>(FromVar))
3501 IsMemberSpec = PartialSpec->isMemberSpecialization();
3502 else if (VarTemplateDecl *FromTemplate = FromVar->getDescribedVarTemplate())
3503 IsMemberSpec = FromTemplate->isMemberSpecialization();
3505 FromVar = FromVar->getFirstDecl();
3507 MultiLevelTemplateArgumentList MultiLevelList(TemplateArgList);
3508 TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(),
3511 // TODO: Set LateAttrs and StartingScope ...
3513 return cast_or_null<VarTemplateSpecializationDecl>(
3514 Instantiator.VisitVarTemplateSpecializationDecl(
3515 VarTemplate, FromVar, InsertPos, TemplateArgsInfo, Converted));
3518 /// \brief Instantiates a variable template specialization by completing it
3519 /// with appropriate type information and initializer.
3520 VarTemplateSpecializationDecl *Sema::CompleteVarTemplateSpecializationDecl(
3521 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
3522 const MultiLevelTemplateArgumentList &TemplateArgs) {
3524 // Do substitution on the type of the declaration
3525 TypeSourceInfo *DI =
3526 SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs,
3527 PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName());
3531 // Update the type of this variable template specialization.
3532 VarSpec->setType(DI->getType());
3534 // Instantiate the initializer.
3535 InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs);
3540 /// BuildVariableInstantiation - Used after a new variable has been created.
3541 /// Sets basic variable data and decides whether to postpone the
3542 /// variable instantiation.
3543 void Sema::BuildVariableInstantiation(
3544 VarDecl *NewVar, VarDecl *OldVar,
3545 const MultiLevelTemplateArgumentList &TemplateArgs,
3546 LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner,
3547 LocalInstantiationScope *StartingScope,
3548 bool InstantiatingVarTemplate) {
3550 // If we are instantiating a local extern declaration, the
3551 // instantiation belongs lexically to the containing function.
3552 // If we are instantiating a static data member defined
3553 // out-of-line, the instantiation will have the same lexical
3554 // context (which will be a namespace scope) as the template.
3555 if (OldVar->isLocalExternDecl()) {
3556 NewVar->setLocalExternDecl();
3557 NewVar->setLexicalDeclContext(Owner);
3558 } else if (OldVar->isOutOfLine())
3559 NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext());
3560 NewVar->setTSCSpec(OldVar->getTSCSpec());
3561 NewVar->setInitStyle(OldVar->getInitStyle());
3562 NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl());
3563 NewVar->setConstexpr(OldVar->isConstexpr());
3564 NewVar->setInitCapture(OldVar->isInitCapture());
3565 NewVar->setPreviousDeclInSameBlockScope(
3566 OldVar->isPreviousDeclInSameBlockScope());
3567 NewVar->setAccess(OldVar->getAccess());
3569 if (!OldVar->isStaticDataMember()) {
3570 if (OldVar->isUsed(false))
3571 NewVar->setIsUsed();
3572 NewVar->setReferenced(OldVar->isReferenced());
3575 // See if the old variable had a type-specifier that defined an anonymous tag.
3576 // If it did, mark the new variable as being the declarator for the new
3578 if (const TagType *OldTagType = OldVar->getType()->getAs<TagType>()) {
3579 TagDecl *OldTag = OldTagType->getDecl();
3580 if (OldTag->getDeclaratorForAnonDecl() == OldVar) {
3581 TagDecl *NewTag = NewVar->getType()->castAs<TagType>()->getDecl();
3582 assert(!NewTag->hasNameForLinkage() &&
3583 !NewTag->hasDeclaratorForAnonDecl());
3584 NewTag->setDeclaratorForAnonDecl(NewVar);
3588 InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope);
3590 LookupResult Previous(
3591 *this, NewVar->getDeclName(), NewVar->getLocation(),
3592 NewVar->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
3593 : Sema::LookupOrdinaryName,
3594 Sema::ForRedeclaration);
3596 if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() &&
3597 (!OldVar->getPreviousDecl()->getDeclContext()->isDependentContext() ||
3598 OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) {
3599 // We have a previous declaration. Use that one, so we merge with the
3601 if (NamedDecl *NewPrev = FindInstantiatedDecl(
3602 NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs))
3603 Previous.addDecl(NewPrev);
3604 } else if (!isa<VarTemplateSpecializationDecl>(NewVar) &&
3605 OldVar->hasLinkage())
3606 LookupQualifiedName(Previous, NewVar->getDeclContext(), false);
3607 CheckVariableDeclaration(NewVar, Previous);
3609 if (!InstantiatingVarTemplate) {
3610 NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar);
3611 if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl())
3612 NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar);
3615 if (!OldVar->isOutOfLine()) {
3616 if (NewVar->getDeclContext()->isFunctionOrMethod())
3617 CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar);
3620 // Link instantiations of static data members back to the template from
3621 // which they were instantiated.
3622 if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate)
3623 NewVar->setInstantiationOfStaticDataMember(OldVar,
3624 TSK_ImplicitInstantiation);
3626 // Forward the mangling number from the template to the instantiated decl.
3627 Context.setManglingNumber(NewVar, Context.getManglingNumber(OldVar));
3628 Context.setStaticLocalNumber(NewVar, Context.getStaticLocalNumber(OldVar));
3630 // Delay instantiation of the initializer for variable templates until a
3631 // definition of the variable is needed. We need it right away if the type
3633 if ((!isa<VarTemplateSpecializationDecl>(NewVar) &&
3634 !InstantiatingVarTemplate) ||
3635 NewVar->getType()->isUndeducedType())
3636 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
3638 // Diagnose unused local variables with dependent types, where the diagnostic
3639 // will have been deferred.
3640 if (!NewVar->isInvalidDecl() &&
3641 NewVar->getDeclContext()->isFunctionOrMethod() &&
3642 OldVar->getType()->isDependentType())
3643 DiagnoseUnusedDecl(NewVar);
3646 /// \brief Instantiate the initializer of a variable.
3647 void Sema::InstantiateVariableInitializer(
3648 VarDecl *Var, VarDecl *OldVar,
3649 const MultiLevelTemplateArgumentList &TemplateArgs) {
3651 if (Var->getAnyInitializer())
3652 // We already have an initializer in the class.
3655 if (OldVar->getInit()) {
3656 if (Var->isStaticDataMember() && !OldVar->isOutOfLine())
3657 PushExpressionEvaluationContext(Sema::ConstantEvaluated, OldVar);
3659 PushExpressionEvaluationContext(Sema::PotentiallyEvaluated, OldVar);
3661 // Instantiate the initializer.
3663 SubstInitializer(OldVar->getInit(), TemplateArgs,
3664 OldVar->getInitStyle() == VarDecl::CallInit);
3665 if (!Init.isInvalid()) {
3666 bool TypeMayContainAuto = true;
3667 Expr *InitExpr = Init.get();
3669 if (Var->hasAttr<DLLImportAttr>() &&
3671 !InitExpr->isConstantInitializer(getASTContext(), false))) {
3672 // Do not dynamically initialize dllimport variables.
3673 } else if (InitExpr) {
3674 bool DirectInit = OldVar->isDirectInit();
3675 AddInitializerToDecl(Var, InitExpr, DirectInit, TypeMayContainAuto);
3677 ActOnUninitializedDecl(Var, TypeMayContainAuto);
3679 // FIXME: Not too happy about invalidating the declaration
3680 // because of a bogus initializer.
3681 Var->setInvalidDecl();
3684 PopExpressionEvaluationContext();
3685 } else if ((!Var->isStaticDataMember() || Var->isOutOfLine()) &&
3686 !Var->isCXXForRangeDecl())
3687 ActOnUninitializedDecl(Var, false);
3690 /// \brief Instantiate the definition of the given variable from its
3693 /// \param PointOfInstantiation the point at which the instantiation was
3694 /// required. Note that this is not precisely a "point of instantiation"
3695 /// for the function, but it's close.
3697 /// \param Var the already-instantiated declaration of a static member
3698 /// variable of a class template specialization.
3700 /// \param Recursive if true, recursively instantiates any functions that
3701 /// are required by this instantiation.
3703 /// \param DefinitionRequired if true, then we are performing an explicit
3704 /// instantiation where an out-of-line definition of the member variable
3705 /// is required. Complain if there is no such definition.
3706 void Sema::InstantiateStaticDataMemberDefinition(
3707 SourceLocation PointOfInstantiation,
3710 bool DefinitionRequired) {
3711 InstantiateVariableDefinition(PointOfInstantiation, Var, Recursive,
3712 DefinitionRequired);
3715 void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
3716 VarDecl *Var, bool Recursive,
3717 bool DefinitionRequired) {
3718 if (Var->isInvalidDecl())
3721 VarTemplateSpecializationDecl *VarSpec =
3722 dyn_cast<VarTemplateSpecializationDecl>(Var);
3723 VarDecl *PatternDecl = nullptr, *Def = nullptr;
3724 MultiLevelTemplateArgumentList TemplateArgs =
3725 getTemplateInstantiationArgs(Var);
3728 // If this is a variable template specialization, make sure that it is
3729 // non-dependent, then find its instantiation pattern.
3730 bool InstantiationDependent = false;
3731 assert(!TemplateSpecializationType::anyDependentTemplateArguments(
3732 VarSpec->getTemplateArgsInfo(), InstantiationDependent) &&
3733 "Only instantiate variable template specializations that are "
3734 "not type-dependent");
3735 (void)InstantiationDependent;
3737 // Find the variable initialization that we'll be substituting. If the
3738 // pattern was instantiated from a member template, look back further to
3739 // find the real pattern.
3740 assert(VarSpec->getSpecializedTemplate() &&
3741 "Specialization without specialized template?");
3742 llvm::PointerUnion<VarTemplateDecl *,
3743 VarTemplatePartialSpecializationDecl *> PatternPtr =
3744 VarSpec->getSpecializedTemplateOrPartial();
3745 if (PatternPtr.is<VarTemplatePartialSpecializationDecl *>()) {
3746 VarTemplatePartialSpecializationDecl *Tmpl =
3747 PatternPtr.get<VarTemplatePartialSpecializationDecl *>();
3748 while (VarTemplatePartialSpecializationDecl *From =
3749 Tmpl->getInstantiatedFromMember()) {
3750 if (Tmpl->isMemberSpecialization())
3757 VarTemplateDecl *Tmpl = PatternPtr.get<VarTemplateDecl *>();
3758 while (VarTemplateDecl *From =
3759 Tmpl->getInstantiatedFromMemberTemplate()) {
3760 if (Tmpl->isMemberSpecialization())
3765 PatternDecl = Tmpl->getTemplatedDecl();
3768 // If this is a static data member template, there might be an
3769 // uninstantiated initializer on the declaration. If so, instantiate
3771 if (PatternDecl->isStaticDataMember() &&
3772 (PatternDecl = PatternDecl->getFirstDecl())->hasInit() &&
3774 // FIXME: Factor out the duplicated instantiation context setup/tear down
3776 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
3777 if (Inst.isInvalid())
3780 // If we're performing recursive template instantiation, create our own
3781 // queue of pending implicit instantiations that we will instantiate
3782 // later, while we're still within our own instantiation context.
3783 std::unique_ptr<SavePendingInstantiationsAndVTableUsesRAII>
3784 SavePendingInstantiationsAndVTableUses;
3786 SavePendingInstantiationsAndVTableUses.reset(
3787 new SavePendingInstantiationsAndVTableUsesRAII(*this));
3790 LocalInstantiationScope Local(*this);
3792 // Enter the scope of this instantiation. We don't use
3793 // PushDeclContext because we don't have a scope.
3794 ContextRAII PreviousContext(*this, Var->getDeclContext());
3795 InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs);
3796 PreviousContext.pop();
3798 // FIXME: Need to inform the ASTConsumer that we instantiated the
3801 // This variable may have local implicit instantiations that need to be
3802 // instantiated within this scope.
3803 PerformPendingInstantiations(/*LocalOnly=*/true);
3808 // Define any newly required vtables.
3809 DefineUsedVTables();
3811 // Instantiate any pending implicit instantiations found during the
3812 // instantiation of this template.
3813 PerformPendingInstantiations();
3815 // Restore PendingInstantiations and VTableUses.
3816 SavePendingInstantiationsAndVTableUses.reset();
3820 // Find actual definition
3821 Def = PatternDecl->getDefinition(getASTContext());
3823 // If this is a static data member, find its out-of-line definition.
3824 assert(Var->isStaticDataMember() && "not a static data member?");
3825 PatternDecl = Var->getInstantiatedFromStaticDataMember();
3827 assert(PatternDecl && "data member was not instantiated from a template?");
3828 assert(PatternDecl->isStaticDataMember() && "not a static data member?");
3829 Def = PatternDecl->getOutOfLineDefinition();
3832 // If we don't have a definition of the variable template, we won't perform
3833 // any instantiation. Rather, we rely on the user to instantiate this
3834 // definition (or provide a specialization for it) in another translation
3837 if (DefinitionRequired) {
3839 Diag(PointOfInstantiation,
3840 diag::err_explicit_instantiation_undefined_var_template) << Var;
3842 Diag(PointOfInstantiation,
3843 diag::err_explicit_instantiation_undefined_member)
3844 << 2 << Var->getDeclName() << Var->getDeclContext();
3845 Diag(PatternDecl->getLocation(),
3846 diag::note_explicit_instantiation_here);
3848 Var->setInvalidDecl();
3849 } else if (Var->getTemplateSpecializationKind()
3850 == TSK_ExplicitInstantiationDefinition) {
3851 PendingInstantiations.push_back(
3852 std::make_pair(Var, PointOfInstantiation));
3858 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
3860 // Never instantiate an explicit specialization.
3861 if (TSK == TSK_ExplicitSpecialization)
3864 // C++11 [temp.explicit]p10:
3865 // Except for inline functions, [...] explicit instantiation declarations
3866 // have the effect of suppressing the implicit instantiation of the entity
3867 // to which they refer.
3868 if (TSK == TSK_ExplicitInstantiationDeclaration)
3871 // Make sure to pass the instantiated variable to the consumer at the end.
3872 struct PassToConsumerRAII {
3873 ASTConsumer &Consumer;
3876 PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
3877 : Consumer(Consumer), Var(Var) { }
3879 ~PassToConsumerRAII() {
3880 Consumer.HandleCXXStaticMemberVarInstantiation(Var);
3882 } PassToConsumerRAII(Consumer, Var);
3884 // If we already have a definition, we're done.
3885 if (VarDecl *Def = Var->getDefinition()) {
3886 // We may be explicitly instantiating something we've already implicitly
3888 Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
3889 PointOfInstantiation);
3893 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
3894 if (Inst.isInvalid())
3897 // If we're performing recursive template instantiation, create our own
3898 // queue of pending implicit instantiations that we will instantiate later,
3899 // while we're still within our own instantiation context.
3900 SavePendingLocalImplicitInstantiationsRAII
3901 SavedPendingLocalImplicitInstantiations(*this);
3902 std::unique_ptr<SavePendingInstantiationsAndVTableUsesRAII>
3903 SavePendingInstantiationsAndVTableUses;
3905 SavePendingInstantiationsAndVTableUses.reset(
3906 new SavePendingInstantiationsAndVTableUsesRAII(*this));
3909 // Enter the scope of this instantiation. We don't use
3910 // PushDeclContext because we don't have a scope.
3911 ContextRAII PreviousContext(*this, Var->getDeclContext());
3912 LocalInstantiationScope Local(*this);
3914 VarDecl *OldVar = Var;
3916 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
3918 else if (Var->isStaticDataMember() &&
3919 Var->getLexicalDeclContext()->isRecord()) {
3920 // We need to instantiate the definition of a static data member template,
3921 // and all we have is the in-class declaration of it. Instantiate a separate
3922 // declaration of the definition.
3923 TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(),
3925 Var = cast_or_null<VarDecl>(Instantiator.VisitVarTemplateSpecializationDecl(
3926 VarSpec->getSpecializedTemplate(), Def, nullptr,
3927 VarSpec->getTemplateArgsInfo(), VarSpec->getTemplateArgs().asArray()));
3929 llvm::PointerUnion<VarTemplateDecl *,
3930 VarTemplatePartialSpecializationDecl *> PatternPtr =
3931 VarSpec->getSpecializedTemplateOrPartial();
3932 if (VarTemplatePartialSpecializationDecl *Partial =
3933 PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>())
3934 cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf(
3935 Partial, &VarSpec->getTemplateInstantiationArgs());
3937 // Merge the definition with the declaration.
3938 LookupResult R(*this, Var->getDeclName(), Var->getLocation(),
3939 LookupOrdinaryName, ForRedeclaration);
3941 MergeVarDecl(Var, R);
3943 // Attach the initializer.
3944 InstantiateVariableInitializer(Var, Def, TemplateArgs);
3947 // Complete the existing variable's definition with an appropriately
3948 // substituted type and initializer.
3949 Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs);
3951 PreviousContext.pop();
3954 PassToConsumerRAII.Var = Var;
3955 Var->setTemplateSpecializationKind(OldVar->getTemplateSpecializationKind(),
3956 OldVar->getPointOfInstantiation());
3959 // This variable may have local implicit instantiations that need to be
3960 // instantiated within this scope.
3961 PerformPendingInstantiations(/*LocalOnly=*/true);
3966 // Define any newly required vtables.
3967 DefineUsedVTables();
3969 // Instantiate any pending implicit instantiations found during the
3970 // instantiation of this template.
3971 PerformPendingInstantiations();
3973 // Restore PendingInstantiations and VTableUses.
3974 SavePendingInstantiationsAndVTableUses.reset();
3979 Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
3980 const CXXConstructorDecl *Tmpl,
3981 const MultiLevelTemplateArgumentList &TemplateArgs) {
3983 SmallVector<CXXCtorInitializer*, 4> NewInits;
3984 bool AnyErrors = Tmpl->isInvalidDecl();
3986 // Instantiate all the initializers.
3987 for (const auto *Init : Tmpl->inits()) {
3988 // Only instantiate written initializers, let Sema re-construct implicit
3990 if (!Init->isWritten())
3993 SourceLocation EllipsisLoc;
3995 if (Init->isPackExpansion()) {
3996 // This is a pack expansion. We should expand it now.
3997 TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
3998 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
3999 collectUnexpandedParameterPacks(BaseTL, Unexpanded);
4000 collectUnexpandedParameterPacks(Init->getInit(), Unexpanded);
4001 bool ShouldExpand = false;
4002 bool RetainExpansion = false;
4003 Optional<unsigned> NumExpansions;
4004 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
4005 BaseTL.getSourceRange(),
4007 TemplateArgs, ShouldExpand,
4011 New->setInvalidDecl();
4014 assert(ShouldExpand && "Partial instantiation of base initializer?");
4016 // Loop over all of the arguments in the argument pack(s),
4017 for (unsigned I = 0; I != *NumExpansions; ++I) {
4018 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
4020 // Instantiate the initializer.
4021 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
4022 /*CXXDirectInit=*/true);
4023 if (TempInit.isInvalid()) {
4028 // Instantiate the base type.
4029 TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
4031 Init->getSourceLocation(),
4032 New->getDeclName());
4038 // Build the initializer.
4039 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
4040 BaseTInfo, TempInit.get(),
4043 if (NewInit.isInvalid()) {
4048 NewInits.push_back(NewInit.get());
4054 // Instantiate the initializer.
4055 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
4056 /*CXXDirectInit=*/true);
4057 if (TempInit.isInvalid()) {
4062 MemInitResult NewInit;
4063 if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
4064 TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
4066 Init->getSourceLocation(),
4067 New->getDeclName());
4070 New->setInvalidDecl();
4074 if (Init->isBaseInitializer())
4075 NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.get(),
4076 New->getParent(), EllipsisLoc);
4078 NewInit = BuildDelegatingInitializer(TInfo, TempInit.get(),
4079 cast<CXXRecordDecl>(CurContext->getParent()));
4080 } else if (Init->isMemberInitializer()) {
4081 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
4082 Init->getMemberLocation(),
4087 New->setInvalidDecl();
4091 NewInit = BuildMemberInitializer(Member, TempInit.get(),
4092 Init->getSourceLocation());
4093 } else if (Init->isIndirectMemberInitializer()) {
4094 IndirectFieldDecl *IndirectMember =
4095 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
4096 Init->getMemberLocation(),
4097 Init->getIndirectMember(), TemplateArgs));
4099 if (!IndirectMember) {
4101 New->setInvalidDecl();
4105 NewInit = BuildMemberInitializer(IndirectMember, TempInit.get(),
4106 Init->getSourceLocation());
4109 if (NewInit.isInvalid()) {
4111 New->setInvalidDecl();
4113 NewInits.push_back(NewInit.get());
4117 // Assign all the initializers to the new constructor.
4118 ActOnMemInitializers(New,
4119 /*FIXME: ColonLoc */
4125 // TODO: this could be templated if the various decl types used the
4126 // same method name.
4127 static bool isInstantiationOf(ClassTemplateDecl *Pattern,
4128 ClassTemplateDecl *Instance) {
4129 Pattern = Pattern->getCanonicalDecl();
4132 Instance = Instance->getCanonicalDecl();
4133 if (Pattern == Instance) return true;
4134 Instance = Instance->getInstantiatedFromMemberTemplate();
4140 static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
4141 FunctionTemplateDecl *Instance) {
4142 Pattern = Pattern->getCanonicalDecl();
4145 Instance = Instance->getCanonicalDecl();
4146 if (Pattern == Instance) return true;
4147 Instance = Instance->getInstantiatedFromMemberTemplate();
4154 isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
4155 ClassTemplatePartialSpecializationDecl *Instance) {
4157 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
4159 Instance = cast<ClassTemplatePartialSpecializationDecl>(
4160 Instance->getCanonicalDecl());
4161 if (Pattern == Instance)
4163 Instance = Instance->getInstantiatedFromMember();
4169 static bool isInstantiationOf(CXXRecordDecl *Pattern,
4170 CXXRecordDecl *Instance) {
4171 Pattern = Pattern->getCanonicalDecl();
4174 Instance = Instance->getCanonicalDecl();
4175 if (Pattern == Instance) return true;
4176 Instance = Instance->getInstantiatedFromMemberClass();
4182 static bool isInstantiationOf(FunctionDecl *Pattern,
4183 FunctionDecl *Instance) {
4184 Pattern = Pattern->getCanonicalDecl();
4187 Instance = Instance->getCanonicalDecl();
4188 if (Pattern == Instance) return true;
4189 Instance = Instance->getInstantiatedFromMemberFunction();
4195 static bool isInstantiationOf(EnumDecl *Pattern,
4196 EnumDecl *Instance) {
4197 Pattern = Pattern->getCanonicalDecl();
4200 Instance = Instance->getCanonicalDecl();
4201 if (Pattern == Instance) return true;
4202 Instance = Instance->getInstantiatedFromMemberEnum();
4208 static bool isInstantiationOf(UsingShadowDecl *Pattern,
4209 UsingShadowDecl *Instance,
4211 return declaresSameEntity(C.getInstantiatedFromUsingShadowDecl(Instance),
4215 static bool isInstantiationOf(UsingDecl *Pattern,
4216 UsingDecl *Instance,
4218 return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern);
4221 static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
4222 UsingDecl *Instance,
4224 return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern);
4227 static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
4228 UsingDecl *Instance,
4230 return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern);
4233 static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
4234 VarDecl *Instance) {
4235 assert(Instance->isStaticDataMember());
4237 Pattern = Pattern->getCanonicalDecl();
4240 Instance = Instance->getCanonicalDecl();
4241 if (Pattern == Instance) return true;
4242 Instance = Instance->getInstantiatedFromStaticDataMember();
4248 // Other is the prospective instantiation
4249 // D is the prospective pattern
4250 static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
4251 if (D->getKind() != Other->getKind()) {
4252 if (UnresolvedUsingTypenameDecl *UUD
4253 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
4254 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
4255 return isInstantiationOf(UUD, UD, Ctx);
4259 if (UnresolvedUsingValueDecl *UUD
4260 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
4261 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
4262 return isInstantiationOf(UUD, UD, Ctx);
4269 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
4270 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
4272 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
4273 return isInstantiationOf(cast<FunctionDecl>(D), Function);
4275 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
4276 return isInstantiationOf(cast<EnumDecl>(D), Enum);
4278 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
4279 if (Var->isStaticDataMember())
4280 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
4282 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
4283 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
4285 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
4286 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
4288 if (ClassTemplatePartialSpecializationDecl *PartialSpec
4289 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
4290 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
4293 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
4294 if (!Field->getDeclName()) {
4295 // This is an unnamed field.
4296 return declaresSameEntity(Ctx.getInstantiatedFromUnnamedFieldDecl(Field),
4297 cast<FieldDecl>(D));
4301 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
4302 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
4304 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
4305 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
4307 return D->getDeclName() && isa<NamedDecl>(Other) &&
4308 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
4311 template<typename ForwardIterator>
4312 static NamedDecl *findInstantiationOf(ASTContext &Ctx,
4314 ForwardIterator first,
4315 ForwardIterator last) {
4316 for (; first != last; ++first)
4317 if (isInstantiationOf(Ctx, D, *first))
4318 return cast<NamedDecl>(*first);
4323 /// \brief Finds the instantiation of the given declaration context
4324 /// within the current instantiation.
4326 /// \returns NULL if there was an error
4327 DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
4328 const MultiLevelTemplateArgumentList &TemplateArgs) {
4329 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
4330 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
4331 return cast_or_null<DeclContext>(ID);
4335 /// \brief Find the instantiation of the given declaration within the
4336 /// current instantiation.
4338 /// This routine is intended to be used when \p D is a declaration
4339 /// referenced from within a template, that needs to mapped into the
4340 /// corresponding declaration within an instantiation. For example,
4344 /// template<typename T>
4347 /// KnownValue = sizeof(T)
4350 /// bool getKind() const { return KnownValue; }
4353 /// template struct X<int>;
4356 /// In the instantiation of <tt>X<int>::getKind()</tt>, we need to map the
4357 /// \p EnumConstantDecl for \p KnownValue (which refers to
4358 /// <tt>X<T>::<Kind>::KnownValue</tt>) to its instantiation
4359 /// (<tt>X<int>::<Kind>::KnownValue</tt>). \p FindInstantiatedDecl performs
4360 /// this mapping from within the instantiation of <tt>X<int></tt>.
4361 NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
4362 const MultiLevelTemplateArgumentList &TemplateArgs) {
4363 DeclContext *ParentDC = D->getDeclContext();
4364 // FIXME: Parmeters of pointer to functions (y below) that are themselves
4365 // parameters (p below) can have their ParentDC set to the translation-unit
4366 // - thus we can not consistently check if the ParentDC of such a parameter
4367 // is Dependent or/and a FunctionOrMethod.
4368 // For e.g. this code, during Template argument deduction tries to
4369 // find an instantiated decl for (T y) when the ParentDC for y is
4370 // the translation unit.
4371 // e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {}
4372 // float baz(float(*)()) { return 0.0; }
4374 // The better fix here is perhaps to ensure that a ParmVarDecl, by the time
4375 // it gets here, always has a FunctionOrMethod as its ParentDC??
4377 // - as long as we have a ParmVarDecl whose parent is non-dependent and
4378 // whose type is not instantiation dependent, do nothing to the decl
4379 // - otherwise find its instantiated decl.
4380 if (isa<ParmVarDecl>(D) && !ParentDC->isDependentContext() &&
4381 !cast<ParmVarDecl>(D)->getType()->isInstantiationDependentType())
4383 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
4384 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
4385 (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext()) ||
4386 (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) {
4387 // D is a local of some kind. Look into the map of local
4388 // declarations to their instantiations.
4389 if (CurrentInstantiationScope) {
4390 if (auto Found = CurrentInstantiationScope->findInstantiationOf(D)) {
4391 if (Decl *FD = Found->dyn_cast<Decl *>())
4392 return cast<NamedDecl>(FD);
4394 int PackIdx = ArgumentPackSubstitutionIndex;
4395 assert(PackIdx != -1 &&
4396 "found declaration pack but not pack expanding");
4397 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
4398 return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
4402 // If we're performing a partial substitution during template argument
4403 // deduction, we may not have values for template parameters yet. They
4404 // just map to themselves.
4405 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
4406 isa<TemplateTemplateParmDecl>(D))
4409 if (D->isInvalidDecl())
4412 // If we didn't find the decl, then we must have a label decl that hasn't
4413 // been found yet. Lazily instantiate it and return it now.
4414 assert(isa<LabelDecl>(D));
4416 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
4417 assert(Inst && "Failed to instantiate label??");
4419 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
4420 return cast<LabelDecl>(Inst);
4423 // For variable template specializations, update those that are still
4425 if (VarTemplateSpecializationDecl *VarSpec =
4426 dyn_cast<VarTemplateSpecializationDecl>(D)) {
4427 bool InstantiationDependent = false;
4428 const TemplateArgumentListInfo &VarTemplateArgs =
4429 VarSpec->getTemplateArgsInfo();
4430 if (TemplateSpecializationType::anyDependentTemplateArguments(
4431 VarTemplateArgs, InstantiationDependent))
4432 D = cast<NamedDecl>(
4433 SubstDecl(D, VarSpec->getDeclContext(), TemplateArgs));
4437 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
4438 if (!Record->isDependentContext())
4441 // Determine whether this record is the "templated" declaration describing
4442 // a class template or class template partial specialization.
4443 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
4445 ClassTemplate = ClassTemplate->getCanonicalDecl();
4446 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4447 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
4448 ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
4450 // Walk the current context to find either the record or an instantiation of
4452 DeclContext *DC = CurContext;
4453 while (!DC->isFileContext()) {
4454 // If we're performing substitution while we're inside the template
4455 // definition, we'll find our own context. We're done.
4456 if (DC->Equals(Record))
4459 if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
4460 // Check whether we're in the process of instantiating a class template
4461 // specialization of the template we're mapping.
4462 if (ClassTemplateSpecializationDecl *InstSpec
4463 = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
4464 ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
4465 if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
4469 // Check whether we're in the process of instantiating a member class.
4470 if (isInstantiationOf(Record, InstRecord))
4474 // Move to the outer template scope.
4475 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
4476 if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){
4477 DC = FD->getLexicalDeclContext();
4482 DC = DC->getParent();
4485 // Fall through to deal with other dependent record types (e.g.,
4486 // anonymous unions in class templates).
4489 if (!ParentDC->isDependentContext())
4492 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
4496 if (ParentDC != D->getDeclContext()) {
4497 // We performed some kind of instantiation in the parent context,
4498 // so now we need to look into the instantiated parent context to
4499 // find the instantiation of the declaration D.
4501 // If our context used to be dependent, we may need to instantiate
4502 // it before performing lookup into that context.
4503 bool IsBeingInstantiated = false;
4504 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
4505 if (!Spec->isDependentContext()) {
4506 QualType T = Context.getTypeDeclType(Spec);
4507 const RecordType *Tag = T->getAs<RecordType>();
4508 assert(Tag && "type of non-dependent record is not a RecordType");
4509 if (Tag->isBeingDefined())
4510 IsBeingInstantiated = true;
4511 if (!Tag->isBeingDefined() &&
4512 RequireCompleteType(Loc, T, diag::err_incomplete_type))
4515 ParentDC = Tag->getDecl();
4519 NamedDecl *Result = nullptr;
4520 if (D->getDeclName()) {
4521 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
4522 Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
4524 // Since we don't have a name for the entity we're looking for,
4525 // our only option is to walk through all of the declarations to
4526 // find that name. This will occur in a few cases:
4528 // - anonymous struct/union within a template
4529 // - unnamed class/struct/union/enum within a template
4531 // FIXME: Find a better way to find these instantiations!
4532 Result = findInstantiationOf(Context, D,
4533 ParentDC->decls_begin(),
4534 ParentDC->decls_end());
4538 if (isa<UsingShadowDecl>(D)) {
4539 // UsingShadowDecls can instantiate to nothing because of using hiding.
4540 } else if (Diags.hasErrorOccurred()) {
4541 // We've already complained about something, so most likely this
4542 // declaration failed to instantiate. There's no point in complaining
4543 // further, since this is normal in invalid code.
4544 } else if (IsBeingInstantiated) {
4545 // The class in which this member exists is currently being
4546 // instantiated, and we haven't gotten around to instantiating this
4547 // member yet. This can happen when the code uses forward declarations
4548 // of member classes, and introduces ordering dependencies via
4549 // template instantiation.
4550 Diag(Loc, diag::err_member_not_yet_instantiated)
4552 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
4553 Diag(D->getLocation(), diag::note_non_instantiated_member_here);
4554 } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
4555 // This enumeration constant was found when the template was defined,
4556 // but can't be found in the instantiation. This can happen if an
4557 // unscoped enumeration member is explicitly specialized.
4558 EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
4559 EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
4561 assert(Spec->getTemplateSpecializationKind() ==
4562 TSK_ExplicitSpecialization);
4563 Diag(Loc, diag::err_enumerator_does_not_exist)
4565 << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
4566 Diag(Spec->getLocation(), diag::note_enum_specialized_here)
4567 << Context.getTypeDeclType(Spec);
4569 // We should have found something, but didn't.
4570 llvm_unreachable("Unable to find instantiation of declaration!");
4580 /// \brief Performs template instantiation for all implicit template
4581 /// instantiations we have seen until this point.
4582 void Sema::PerformPendingInstantiations(bool LocalOnly) {
4583 while (!PendingLocalImplicitInstantiations.empty() ||
4584 (!LocalOnly && !PendingInstantiations.empty())) {
4585 PendingImplicitInstantiation Inst;
4587 if (PendingLocalImplicitInstantiations.empty()) {
4588 Inst = PendingInstantiations.front();
4589 PendingInstantiations.pop_front();
4591 Inst = PendingLocalImplicitInstantiations.front();
4592 PendingLocalImplicitInstantiations.pop_front();
4595 // Instantiate function definitions
4596 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
4597 PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(),
4598 "instantiating function definition");
4599 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
4600 TSK_ExplicitInstantiationDefinition;
4601 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true,
4602 DefinitionRequired);
4606 // Instantiate variable definitions
4607 VarDecl *Var = cast<VarDecl>(Inst.first);
4609 assert((Var->isStaticDataMember() ||
4610 isa<VarTemplateSpecializationDecl>(Var)) &&
4611 "Not a static data member, nor a variable template"
4612 " specialization?");
4614 // Don't try to instantiate declarations if the most recent redeclaration
4616 if (Var->getMostRecentDecl()->isInvalidDecl())
4619 // Check if the most recent declaration has changed the specialization kind
4620 // and removed the need for implicit instantiation.
4621 switch (Var->getMostRecentDecl()->getTemplateSpecializationKind()) {
4622 case TSK_Undeclared:
4623 llvm_unreachable("Cannot instantitiate an undeclared specialization.");
4624 case TSK_ExplicitInstantiationDeclaration:
4625 case TSK_ExplicitSpecialization:
4626 continue; // No longer need to instantiate this type.
4627 case TSK_ExplicitInstantiationDefinition:
4628 // We only need an instantiation if the pending instantiation *is* the
4629 // explicit instantiation.
4630 if (Var != Var->getMostRecentDecl()) continue;
4631 case TSK_ImplicitInstantiation:
4635 PrettyDeclStackTraceEntry CrashInfo(*this, Var, SourceLocation(),
4636 "instantiating variable definition");
4637 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
4638 TSK_ExplicitInstantiationDefinition;
4640 // Instantiate static data member definitions or variable template
4642 InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true,
4643 DefinitionRequired);
4647 void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
4648 const MultiLevelTemplateArgumentList &TemplateArgs) {
4649 for (auto DD : Pattern->ddiags()) {
4650 switch (DD->getKind()) {
4651 case DependentDiagnostic::Access:
4652 HandleDependentAccessCheck(*DD, TemplateArgs);