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/Sema/Lookup.h"
14 #include "clang/Sema/PrettyDeclStackTrace.h"
15 #include "clang/Sema/Template.h"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/DeclTemplate.h"
19 #include "clang/AST/DeclVisitor.h"
20 #include "clang/AST/DependentDiagnostic.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/TypeLoc.h"
24 #include "clang/Lex/Preprocessor.h"
26 using namespace clang;
28 bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
29 DeclaratorDecl *NewDecl) {
30 if (!OldDecl->getQualifierLoc())
33 NestedNameSpecifierLoc NewQualifierLoc
34 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
40 NewDecl->setQualifierInfo(NewQualifierLoc);
44 bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
46 if (!OldDecl->getQualifierLoc())
49 NestedNameSpecifierLoc NewQualifierLoc
50 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
56 NewDecl->setQualifierInfo(NewQualifierLoc);
60 // Include attribute instantiation code.
61 #include "clang/Sema/AttrTemplateInstantiate.inc"
63 void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
64 const Decl *Tmpl, Decl *New,
65 LateInstantiatedAttrVec *LateAttrs,
66 LocalInstantiationScope *OuterMostScope) {
67 for (AttrVec::const_iterator i = Tmpl->attr_begin(), e = Tmpl->attr_end();
69 const Attr *TmplAttr = *i;
71 // FIXME: This should be generalized to more than just the AlignedAttr.
72 if (const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr)) {
73 if (Aligned->isAlignmentDependent()) {
74 if (Aligned->isAlignmentExpr()) {
75 // The alignment expression is a constant expression.
76 EnterExpressionEvaluationContext Unevaluated(*this,
77 Sema::ConstantEvaluated);
79 ExprResult Result = SubstExpr(Aligned->getAlignmentExpr(),
81 if (!Result.isInvalid())
82 AddAlignedAttr(Aligned->getLocation(), New, Result.takeAs<Expr>(),
83 Aligned->getIsMSDeclSpec());
85 TypeSourceInfo *Result = SubstType(Aligned->getAlignmentType(),
87 Aligned->getLocation(),
90 AddAlignedAttr(Aligned->getLocation(), New, Result,
91 Aligned->getIsMSDeclSpec());
97 if (TmplAttr->isLateParsed() && LateAttrs) {
98 // Late parsed attributes must be instantiated and attached after the
99 // enclosing class has been instantiated. See Sema::InstantiateClass.
100 LocalInstantiationScope *Saved = 0;
101 if (CurrentInstantiationScope)
102 Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
103 LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
105 Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
106 *this, TemplateArgs);
108 New->addAttr(NewAttr);
114 TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
115 llvm_unreachable("Translation units cannot be instantiated");
119 TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
120 LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
122 Owner->addDecl(Inst);
127 TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
128 llvm_unreachable("Namespaces cannot be instantiated");
132 TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
133 NamespaceAliasDecl *Inst
134 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
135 D->getNamespaceLoc(),
138 D->getQualifierLoc(),
139 D->getTargetNameLoc(),
141 Owner->addDecl(Inst);
145 Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
147 bool Invalid = false;
148 TypeSourceInfo *DI = D->getTypeSourceInfo();
149 if (DI->getType()->isInstantiationDependentType() ||
150 DI->getType()->isVariablyModifiedType()) {
151 DI = SemaRef.SubstType(DI, TemplateArgs,
152 D->getLocation(), D->getDeclName());
155 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
158 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
161 // HACK: g++ has a bug where it gets the value kind of ?: wrong.
162 // libstdc++ relies upon this bug in its implementation of common_type.
163 // If we happen to be processing that implementation, fake up the g++ ?:
164 // semantics. See LWG issue 2141 for more information on the bug.
165 const DecltypeType *DT = DI->getType()->getAs<DecltypeType>();
166 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
167 if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) &&
168 DT->isReferenceType() &&
169 RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() &&
170 RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") &&
171 D->getIdentifier() && D->getIdentifier()->isStr("type") &&
172 SemaRef.getSourceManager().isInSystemHeader(D->getLocStart()))
173 // Fold it to the (non-reference) type which g++ would have produced.
174 DI = SemaRef.Context.getTrivialTypeSourceInfo(
175 DI->getType().getNonReferenceType());
177 // Create the new typedef
178 TypedefNameDecl *Typedef;
180 Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
181 D->getLocation(), D->getIdentifier(), DI);
183 Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
184 D->getLocation(), D->getIdentifier(), DI);
186 Typedef->setInvalidDecl();
188 // If the old typedef was the name for linkage purposes of an anonymous
189 // tag decl, re-establish that relationship for the new typedef.
190 if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
191 TagDecl *oldTag = oldTagType->getDecl();
192 if (oldTag->getTypedefNameForAnonDecl() == D) {
193 TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
194 assert(!newTag->getIdentifier() && !newTag->getTypedefNameForAnonDecl());
195 newTag->setTypedefNameForAnonDecl(Typedef);
199 if (TypedefNameDecl *Prev = D->getPreviousDecl()) {
200 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
205 TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
207 // If the typedef types are not identical, reject them.
208 SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
210 Typedef->setPreviousDeclaration(InstPrevTypedef);
213 SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
215 Typedef->setAccess(D->getAccess());
220 Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
221 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
222 Owner->addDecl(Typedef);
226 Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
227 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
228 Owner->addDecl(Typedef);
233 TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
234 // Create a local instantiation scope for this type alias template, which
235 // will contain the instantiations of the template parameters.
236 LocalInstantiationScope Scope(SemaRef);
238 TemplateParameterList *TempParams = D->getTemplateParameters();
239 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
243 TypeAliasDecl *Pattern = D->getTemplatedDecl();
245 TypeAliasTemplateDecl *PrevAliasTemplate = 0;
246 if (Pattern->getPreviousDecl()) {
247 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
248 if (Found.first != Found.second) {
249 PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(*Found.first);
253 TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
254 InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
258 TypeAliasTemplateDecl *Inst
259 = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
260 D->getDeclName(), InstParams, AliasInst);
261 if (PrevAliasTemplate)
262 Inst->setPreviousDeclaration(PrevAliasTemplate);
264 Inst->setAccess(D->getAccess());
266 if (!PrevAliasTemplate)
267 Inst->setInstantiatedFromMemberTemplate(D);
269 Owner->addDecl(Inst);
274 Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
275 // If this is the variable for an anonymous struct or union,
276 // instantiate the anonymous struct/union type first.
277 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
278 if (RecordTy->getDecl()->isAnonymousStructOrUnion())
279 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
282 // Do substitution on the type of the declaration
283 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
285 D->getTypeSpecStartLoc(),
290 if (DI->getType()->isFunctionType()) {
291 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
292 << D->isStaticDataMember() << DI->getType();
296 // Build the instantiated declaration
297 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
298 D->getInnerLocStart(),
299 D->getLocation(), D->getIdentifier(),
301 D->getStorageClass(),
302 D->getStorageClassAsWritten());
303 Var->setThreadSpecified(D->isThreadSpecified());
304 Var->setInitStyle(D->getInitStyle());
305 Var->setCXXForRangeDecl(D->isCXXForRangeDecl());
306 Var->setConstexpr(D->isConstexpr());
308 // Substitute the nested name specifier, if any.
309 if (SubstQualifier(D, Var))
312 // If we are instantiating a static data member defined
313 // out-of-line, the instantiation will have the same lexical
314 // context (which will be a namespace scope) as the template.
315 if (D->isOutOfLine())
316 Var->setLexicalDeclContext(D->getLexicalDeclContext());
318 Var->setAccess(D->getAccess());
320 if (!D->isStaticDataMember()) {
321 Var->setUsed(D->isUsed(false));
322 Var->setReferenced(D->isReferenced());
325 // FIXME: In theory, we could have a previous declaration for variables that
326 // are not static data members.
327 // FIXME: having to fake up a LookupResult is dumb.
328 LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(),
329 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
330 if (D->isStaticDataMember())
331 SemaRef.LookupQualifiedName(Previous, Owner, false);
333 // In ARC, infer 'retaining' for variables of retainable type.
334 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
335 SemaRef.inferObjCARCLifetime(Var))
336 Var->setInvalidDecl();
338 SemaRef.CheckVariableDeclaration(Var, Previous);
340 if (D->isOutOfLine()) {
341 D->getLexicalDeclContext()->addDecl(Var);
342 Owner->makeDeclVisibleInContext(Var);
345 if (Owner->isFunctionOrMethod())
346 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Var);
348 SemaRef.InstantiateAttrs(TemplateArgs, D, Var, LateAttrs, StartingScope);
350 // Link instantiations of static data members back to the template from
351 // which they were instantiated.
352 if (Var->isStaticDataMember())
353 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D,
354 TSK_ImplicitInstantiation);
356 if (Var->getAnyInitializer()) {
357 // We already have an initializer in the class.
358 } else if (D->getInit()) {
359 if (Var->isStaticDataMember() && !D->isOutOfLine())
360 SemaRef.PushExpressionEvaluationContext(Sema::ConstantEvaluated, D);
362 SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated, D);
364 // Instantiate the initializer.
365 ExprResult Init = SemaRef.SubstInitializer(D->getInit(), TemplateArgs,
366 D->getInitStyle() == VarDecl::CallInit);
367 if (!Init.isInvalid()) {
368 bool TypeMayContainAuto = true;
370 bool DirectInit = D->isDirectInit();
371 SemaRef.AddInitializerToDecl(Var, Init.take(), DirectInit,
374 SemaRef.ActOnUninitializedDecl(Var, TypeMayContainAuto);
376 // FIXME: Not too happy about invalidating the declaration
377 // because of a bogus initializer.
378 Var->setInvalidDecl();
381 SemaRef.PopExpressionEvaluationContext();
382 } else if ((!Var->isStaticDataMember() || Var->isOutOfLine()) &&
383 !Var->isCXXForRangeDecl())
384 SemaRef.ActOnUninitializedDecl(Var, false);
386 // Diagnose unused local variables with dependent types, where the diagnostic
387 // will have been deferred.
388 if (!Var->isInvalidDecl() && Owner->isFunctionOrMethod() && !Var->isUsed() &&
389 D->getType()->isDependentType())
390 SemaRef.DiagnoseUnusedDecl(Var);
395 Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
397 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
398 D->getAccessSpecifierLoc(), D->getColonLoc());
399 Owner->addHiddenDecl(AD);
403 Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
404 bool Invalid = false;
405 TypeSourceInfo *DI = D->getTypeSourceInfo();
406 if (DI->getType()->isInstantiationDependentType() ||
407 DI->getType()->isVariablyModifiedType()) {
408 DI = SemaRef.SubstType(DI, TemplateArgs,
409 D->getLocation(), D->getDeclName());
411 DI = D->getTypeSourceInfo();
413 } else if (DI->getType()->isFunctionType()) {
414 // C++ [temp.arg.type]p3:
415 // If a declaration acquires a function type through a type
416 // dependent on a template-parameter and this causes a
417 // declaration that does not use the syntactic form of a
418 // function declarator to have function type, the program is
420 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
425 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
428 Expr *BitWidth = D->getBitWidth();
432 // The bit-width expression is a constant expression.
433 EnterExpressionEvaluationContext Unevaluated(SemaRef,
434 Sema::ConstantEvaluated);
436 ExprResult InstantiatedBitWidth
437 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
438 if (InstantiatedBitWidth.isInvalid()) {
442 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
445 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
447 cast<RecordDecl>(Owner),
451 D->getInClassInitStyle(),
452 D->getInnerLocStart(),
456 cast<Decl>(Owner)->setInvalidDecl();
460 SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
463 Field->setInvalidDecl();
465 if (!Field->getDeclName()) {
466 // Keep track of where this decl came from.
467 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
469 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
470 if (Parent->isAnonymousStructOrUnion() &&
471 Parent->getRedeclContext()->isFunctionOrMethod())
472 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
475 Field->setImplicit(D->isImplicit());
476 Field->setAccess(D->getAccess());
477 Owner->addDecl(Field);
482 Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
483 NamedDecl **NamedChain =
484 new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
487 for (IndirectFieldDecl::chain_iterator PI =
488 D->chain_begin(), PE = D->chain_end();
490 NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), *PI,
495 NamedChain[i++] = Next;
498 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
499 IndirectFieldDecl* IndirectField
500 = IndirectFieldDecl::Create(SemaRef.Context, Owner, D->getLocation(),
501 D->getIdentifier(), T,
502 NamedChain, D->getChainingSize());
505 IndirectField->setImplicit(D->isImplicit());
506 IndirectField->setAccess(D->getAccess());
507 Owner->addDecl(IndirectField);
508 return IndirectField;
511 Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
512 // Handle friend type expressions by simply substituting template
513 // parameters into the pattern type and checking the result.
514 if (TypeSourceInfo *Ty = D->getFriendType()) {
515 TypeSourceInfo *InstTy;
516 // If this is an unsupported friend, don't bother substituting template
517 // arguments into it. The actual type referred to won't be used by any
518 // parts of Clang, and may not be valid for instantiating. Just use the
519 // same info for the instantiated friend.
520 if (D->isUnsupportedFriend()) {
523 InstTy = SemaRef.SubstType(Ty, TemplateArgs,
524 D->getLocation(), DeclarationName());
529 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getLocStart(),
530 D->getFriendLoc(), InstTy);
534 FD->setAccess(AS_public);
535 FD->setUnsupportedFriend(D->isUnsupportedFriend());
540 NamedDecl *ND = D->getFriendDecl();
541 assert(ND && "friend decl must be a decl or a type!");
543 // All of the Visit implementations for the various potential friend
544 // declarations have to be carefully written to work for friend
545 // objects, with the most important detail being that the target
546 // decl should almost certainly not be placed in Owner.
547 Decl *NewND = Visit(ND);
548 if (!NewND) return 0;
551 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
552 cast<NamedDecl>(NewND), D->getFriendLoc());
553 FD->setAccess(AS_public);
554 FD->setUnsupportedFriend(D->isUnsupportedFriend());
559 Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
560 Expr *AssertExpr = D->getAssertExpr();
562 // The expression in a static assertion is a constant expression.
563 EnterExpressionEvaluationContext Unevaluated(SemaRef,
564 Sema::ConstantEvaluated);
566 ExprResult InstantiatedAssertExpr
567 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
568 if (InstantiatedAssertExpr.isInvalid())
571 return SemaRef.BuildStaticAssertDeclaration(D->getLocation(),
572 InstantiatedAssertExpr.get(),
578 Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
579 EnumDecl *PrevDecl = 0;
580 if (D->getPreviousDecl()) {
581 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
582 D->getPreviousDecl(),
585 PrevDecl = cast<EnumDecl>(Prev);
588 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
589 D->getLocation(), D->getIdentifier(),
590 PrevDecl, D->isScoped(),
591 D->isScopedUsingClassTag(), D->isFixed());
593 if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
594 // If we have type source information for the underlying type, it means it
595 // has been explicitly set by the user. Perform substitution on it before
597 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
598 TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
600 if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
601 Enum->setIntegerType(SemaRef.Context.IntTy);
603 Enum->setIntegerTypeSourceInfo(NewTI);
605 assert(!D->getIntegerType()->isDependentType()
606 && "Dependent type without type source info");
607 Enum->setIntegerType(D->getIntegerType());
611 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
613 Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
614 Enum->setAccess(D->getAccess());
615 if (SubstQualifier(D, Enum)) return 0;
616 Owner->addDecl(Enum);
618 EnumDecl *Def = D->getDefinition();
619 if (Def && Def != D) {
620 // If this is an out-of-line definition of an enum member template, check
621 // that the underlying types match in the instantiation of both
623 if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
624 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
625 QualType DefnUnderlying =
626 SemaRef.SubstType(TI->getType(), TemplateArgs,
627 UnderlyingLoc, DeclarationName());
628 SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
629 DefnUnderlying, Enum);
633 if (D->getDeclContext()->isFunctionOrMethod())
634 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
636 // C++11 [temp.inst]p1: The implicit instantiation of a class template
637 // specialization causes the implicit instantiation of the declarations, but
638 // not the definitions of scoped member enumerations.
639 // FIXME: There appears to be no wording for what happens for an enum defined
640 // within a block scope, but we treat that much like a member template. Only
641 // instantiate the definition when visiting the definition in that case, since
642 // we will visit all redeclarations.
643 if (!Enum->isScoped() && Def &&
644 (!D->getDeclContext()->isFunctionOrMethod() || D->isCompleteDefinition()))
645 InstantiateEnumDefinition(Enum, Def);
650 void TemplateDeclInstantiator::InstantiateEnumDefinition(
651 EnumDecl *Enum, EnumDecl *Pattern) {
652 Enum->startDefinition();
654 // Update the location to refer to the definition.
655 Enum->setLocation(Pattern->getLocation());
657 SmallVector<Decl*, 4> Enumerators;
659 EnumConstantDecl *LastEnumConst = 0;
660 for (EnumDecl::enumerator_iterator EC = Pattern->enumerator_begin(),
661 ECEnd = Pattern->enumerator_end();
663 // The specified value for the enumerator.
664 ExprResult Value = SemaRef.Owned((Expr *)0);
665 if (Expr *UninstValue = EC->getInitExpr()) {
666 // The enumerator's value expression is a constant expression.
667 EnterExpressionEvaluationContext Unevaluated(SemaRef,
668 Sema::ConstantEvaluated);
670 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
673 // Drop the initial value and continue.
674 bool isInvalid = false;
675 if (Value.isInvalid()) {
676 Value = SemaRef.Owned((Expr *)0);
680 EnumConstantDecl *EnumConst
681 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
682 EC->getLocation(), EC->getIdentifier(),
687 EnumConst->setInvalidDecl();
688 Enum->setInvalidDecl();
692 SemaRef.InstantiateAttrs(TemplateArgs, *EC, EnumConst);
694 EnumConst->setAccess(Enum->getAccess());
695 Enum->addDecl(EnumConst);
696 Enumerators.push_back(EnumConst);
697 LastEnumConst = EnumConst;
699 if (Pattern->getDeclContext()->isFunctionOrMethod() &&
701 // If the enumeration is within a function or method, record the enum
702 // constant as a local.
703 SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst);
708 // FIXME: Fixup LBraceLoc
709 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(),
710 Enum->getRBraceLoc(), Enum,
711 Enumerators.data(), Enumerators.size(),
715 Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
716 llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
719 Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
720 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
722 // Create a local instantiation scope for this class template, which
723 // will contain the instantiations of the template parameters.
724 LocalInstantiationScope Scope(SemaRef);
725 TemplateParameterList *TempParams = D->getTemplateParameters();
726 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
730 CXXRecordDecl *Pattern = D->getTemplatedDecl();
732 // Instantiate the qualifier. We have to do this first in case
733 // we're a friend declaration, because if we are then we need to put
734 // the new declaration in the appropriate context.
735 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
737 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
743 CXXRecordDecl *PrevDecl = 0;
744 ClassTemplateDecl *PrevClassTemplate = 0;
746 if (!isFriend && Pattern->getPreviousDecl()) {
747 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
748 if (Found.first != Found.second) {
749 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(*Found.first);
750 if (PrevClassTemplate)
751 PrevDecl = PrevClassTemplate->getTemplatedDecl();
755 // If this isn't a friend, then it's a member template, in which
756 // case we just want to build the instantiation in the
757 // specialization. If it is a friend, we want to build it in
758 // the appropriate context.
759 DeclContext *DC = Owner;
763 SS.Adopt(QualifierLoc);
764 DC = SemaRef.computeDeclContext(SS);
767 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
768 Pattern->getDeclContext(),
772 // Look for a previous declaration of the template in the owning
774 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
775 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
776 SemaRef.LookupQualifiedName(R, DC);
778 if (R.isSingleResult()) {
779 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
780 if (PrevClassTemplate)
781 PrevDecl = PrevClassTemplate->getTemplatedDecl();
784 if (!PrevClassTemplate && QualifierLoc) {
785 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
786 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
787 << QualifierLoc.getSourceRange();
791 bool AdoptedPreviousTemplateParams = false;
792 if (PrevClassTemplate) {
793 bool Complain = true;
795 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
796 // template for struct std::tr1::__detail::_Map_base, where the
797 // template parameters of the friend declaration don't match the
798 // template parameters of the original declaration. In this one
799 // case, we don't complain about the ill-formed friend
801 if (isFriend && Pattern->getIdentifier() &&
802 Pattern->getIdentifier()->isStr("_Map_base") &&
804 cast<NamespaceDecl>(DC)->getIdentifier() &&
805 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
806 DeclContext *DCParent = DC->getParent();
807 if (DCParent->isNamespace() &&
808 cast<NamespaceDecl>(DCParent)->getIdentifier() &&
809 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
810 DeclContext *DCParent2 = DCParent->getParent();
811 if (DCParent2->isNamespace() &&
812 cast<NamespaceDecl>(DCParent2)->getIdentifier() &&
813 cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") &&
814 DCParent2->getParent()->isTranslationUnit())
819 TemplateParameterList *PrevParams
820 = PrevClassTemplate->getTemplateParameters();
822 // Make sure the parameter lists match.
823 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
825 Sema::TPL_TemplateMatch)) {
829 AdoptedPreviousTemplateParams = true;
830 InstParams = PrevParams;
833 // Do some additional validation, then merge default arguments
834 // from the existing declarations.
835 if (!AdoptedPreviousTemplateParams &&
836 SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
837 Sema::TPC_ClassTemplate))
842 CXXRecordDecl *RecordInst
843 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
844 Pattern->getLocStart(), Pattern->getLocation(),
845 Pattern->getIdentifier(), PrevDecl,
846 /*DelayTypeCreation=*/true);
849 RecordInst->setQualifierInfo(QualifierLoc);
851 ClassTemplateDecl *Inst
852 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
853 D->getIdentifier(), InstParams, RecordInst,
855 RecordInst->setDescribedClassTemplate(Inst);
858 if (PrevClassTemplate)
859 Inst->setAccess(PrevClassTemplate->getAccess());
861 Inst->setAccess(D->getAccess());
863 Inst->setObjectOfFriendDecl(PrevClassTemplate != 0);
864 // TODO: do we want to track the instantiation progeny of this
865 // friend target decl?
867 Inst->setAccess(D->getAccess());
868 if (!PrevClassTemplate)
869 Inst->setInstantiatedFromMemberTemplate(D);
872 // Trigger creation of the type for the instantiation.
873 SemaRef.Context.getInjectedClassNameType(RecordInst,
874 Inst->getInjectedClassNameSpecialization());
876 // Finish handling of friends.
878 DC->makeDeclVisibleInContext(Inst);
879 Inst->setLexicalDeclContext(Owner);
880 RecordInst->setLexicalDeclContext(Owner);
884 if (D->isOutOfLine()) {
885 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
886 RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
889 Owner->addDecl(Inst);
891 if (!PrevClassTemplate) {
892 // Queue up any out-of-line partial specializations of this member
893 // class template; the client will force their instantiation once
894 // the enclosing class has been instantiated.
895 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
896 D->getPartialSpecializations(PartialSpecs);
897 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
898 if (PartialSpecs[I]->isOutOfLine())
899 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
906 TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
907 ClassTemplatePartialSpecializationDecl *D) {
908 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
910 // Lookup the already-instantiated declaration in the instantiation
911 // of the class template and return that.
912 DeclContext::lookup_result Found
913 = Owner->lookup(ClassTemplate->getDeclName());
914 if (Found.first == Found.second)
917 ClassTemplateDecl *InstClassTemplate
918 = dyn_cast<ClassTemplateDecl>(*Found.first);
919 if (!InstClassTemplate)
922 if (ClassTemplatePartialSpecializationDecl *Result
923 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
926 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
930 TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
931 // Create a local instantiation scope for this function template, which
932 // will contain the instantiations of the template parameters and then get
933 // merged with the local instantiation scope for the function template
935 LocalInstantiationScope Scope(SemaRef);
937 TemplateParameterList *TempParams = D->getTemplateParameters();
938 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
942 FunctionDecl *Instantiated = 0;
943 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
944 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
947 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
948 D->getTemplatedDecl(),
954 // Link the instantiated function template declaration to the function
955 // template from which it was instantiated.
956 FunctionTemplateDecl *InstTemplate
957 = Instantiated->getDescribedFunctionTemplate();
958 InstTemplate->setAccess(D->getAccess());
959 assert(InstTemplate &&
960 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
962 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
964 // Link the instantiation back to the pattern *unless* this is a
965 // non-definition friend declaration.
966 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
967 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
968 InstTemplate->setInstantiatedFromMemberTemplate(D);
970 // Make declarations visible in the appropriate context.
972 Owner->addDecl(InstTemplate);
973 } else if (InstTemplate->getDeclContext()->isRecord() &&
974 !D->getPreviousDecl()) {
975 SemaRef.CheckFriendAccess(InstTemplate);
981 Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
982 CXXRecordDecl *PrevDecl = 0;
983 if (D->isInjectedClassName())
984 PrevDecl = cast<CXXRecordDecl>(Owner);
985 else if (D->getPreviousDecl()) {
986 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
987 D->getPreviousDecl(),
990 PrevDecl = cast<CXXRecordDecl>(Prev);
993 CXXRecordDecl *Record
994 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
995 D->getLocStart(), D->getLocation(),
996 D->getIdentifier(), PrevDecl);
998 // Substitute the nested name specifier, if any.
999 if (SubstQualifier(D, Record))
1002 Record->setImplicit(D->isImplicit());
1003 // FIXME: Check against AS_none is an ugly hack to work around the issue that
1004 // the tag decls introduced by friend class declarations don't have an access
1005 // specifier. Remove once this area of the code gets sorted out.
1006 if (D->getAccess() != AS_none)
1007 Record->setAccess(D->getAccess());
1008 if (!D->isInjectedClassName())
1009 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
1011 // If the original function was part of a friend declaration,
1012 // inherit its namespace state.
1013 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
1014 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
1016 // Make sure that anonymous structs and unions are recorded.
1017 if (D->isAnonymousStructOrUnion()) {
1018 Record->setAnonymousStructOrUnion(true);
1019 if (Record->getDeclContext()->getRedeclContext()->isFunctionOrMethod())
1020 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
1023 Owner->addDecl(Record);
1027 /// \brief Adjust the given function type for an instantiation of the
1028 /// given declaration, to cope with modifications to the function's type that
1029 /// aren't reflected in the type-source information.
1031 /// \param D The declaration we're instantiating.
1032 /// \param TInfo The already-instantiated type.
1033 static QualType adjustFunctionTypeForInstantiation(ASTContext &Context,
1035 TypeSourceInfo *TInfo) {
1036 const FunctionProtoType *OrigFunc
1037 = D->getType()->castAs<FunctionProtoType>();
1038 const FunctionProtoType *NewFunc
1039 = TInfo->getType()->castAs<FunctionProtoType>();
1040 if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
1041 return TInfo->getType();
1043 FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
1044 NewEPI.ExtInfo = OrigFunc->getExtInfo();
1045 return Context.getFunctionType(NewFunc->getResultType(),
1046 NewFunc->arg_type_begin(),
1047 NewFunc->getNumArgs(),
1051 /// Normal class members are of more specific types and therefore
1052 /// don't make it here. This function serves two purposes:
1053 /// 1) instantiating function templates
1054 /// 2) substituting friend declarations
1055 /// FIXME: preserve function definitions in case #2
1056 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
1057 TemplateParameterList *TemplateParams) {
1058 // Check whether there is already a function template specialization for
1059 // this declaration.
1060 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1061 if (FunctionTemplate && !TemplateParams) {
1062 std::pair<const TemplateArgument *, unsigned> Innermost
1063 = TemplateArgs.getInnermost();
1065 void *InsertPos = 0;
1066 FunctionDecl *SpecFunc
1067 = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
1070 // If we already have a function template specialization, return it.
1076 if (FunctionTemplate)
1077 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1079 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1081 bool MergeWithParentScope = (TemplateParams != 0) ||
1082 Owner->isFunctionOrMethod() ||
1083 !(isa<Decl>(Owner) &&
1084 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1085 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
1087 SmallVector<ParmVarDecl *, 4> Params;
1088 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
1091 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
1093 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1095 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1101 // If we're instantiating a local function declaration, put the result
1102 // in the owner; otherwise we need to find the instantiated context.
1104 if (D->getDeclContext()->isFunctionOrMethod())
1106 else if (isFriend && QualifierLoc) {
1108 SS.Adopt(QualifierLoc);
1109 DC = SemaRef.computeDeclContext(SS);
1112 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
1116 FunctionDecl *Function =
1117 FunctionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
1118 D->getNameInfo(), T, TInfo,
1119 D->getStorageClass(), D->getStorageClassAsWritten(),
1120 D->isInlineSpecified(), D->hasWrittenPrototype(),
1124 Function->setQualifierInfo(QualifierLoc);
1126 DeclContext *LexicalDC = Owner;
1127 if (!isFriend && D->isOutOfLine()) {
1128 assert(D->getDeclContext()->isFileContext());
1129 LexicalDC = D->getDeclContext();
1132 Function->setLexicalDeclContext(LexicalDC);
1134 // Attach the parameters
1135 if (isa<FunctionProtoType>(Function->getType().IgnoreParens())) {
1136 // Adopt the already-instantiated parameters into our own context.
1137 for (unsigned P = 0; P < Params.size(); ++P)
1139 Params[P]->setOwningFunction(Function);
1141 // Since we were instantiated via a typedef of a function type, create
1143 const FunctionProtoType *Proto
1144 = Function->getType()->getAs<FunctionProtoType>();
1145 assert(Proto && "No function prototype in template instantiation?");
1146 for (FunctionProtoType::arg_type_iterator AI = Proto->arg_type_begin(),
1147 AE = Proto->arg_type_end(); AI != AE; ++AI) {
1149 = SemaRef.BuildParmVarDeclForTypedef(Function, Function->getLocation(),
1151 Param->setScopeInfo(0, Params.size());
1152 Params.push_back(Param);
1155 Function->setParams(Params);
1157 SourceLocation InstantiateAtPOI;
1158 if (TemplateParams) {
1159 // Our resulting instantiation is actually a function template, since we
1160 // are substituting only the outer template parameters. For example, given
1162 // template<typename T>
1164 // template<typename U> friend void f(T, U);
1169 // We are instantiating the friend function template "f" within X<int>,
1170 // which means substituting int for T, but leaving "f" as a friend function
1172 // Build the function template itself.
1173 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
1174 Function->getLocation(),
1175 Function->getDeclName(),
1176 TemplateParams, Function);
1177 Function->setDescribedFunctionTemplate(FunctionTemplate);
1179 FunctionTemplate->setLexicalDeclContext(LexicalDC);
1181 if (isFriend && D->isThisDeclarationADefinition()) {
1182 // TODO: should we remember this connection regardless of whether
1183 // the friend declaration provided a body?
1184 FunctionTemplate->setInstantiatedFromMemberTemplate(
1185 D->getDescribedFunctionTemplate());
1187 } else if (FunctionTemplate) {
1188 // Record this function template specialization.
1189 std::pair<const TemplateArgument *, unsigned> Innermost
1190 = TemplateArgs.getInnermost();
1191 Function->setFunctionTemplateSpecialization(FunctionTemplate,
1192 TemplateArgumentList::CreateCopy(SemaRef.Context,
1196 } else if (isFriend) {
1197 // Note, we need this connection even if the friend doesn't have a body.
1198 // Its body may exist but not have been attached yet due to deferred
1200 // FIXME: It might be cleaner to set this when attaching the body to the
1201 // friend function declaration, however that would require finding all the
1202 // instantiations and modifying them.
1203 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
1206 if (InitFunctionInstantiation(Function, D))
1207 Function->setInvalidDecl();
1209 bool isExplicitSpecialization = false;
1211 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
1212 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
1214 if (DependentFunctionTemplateSpecializationInfo *Info
1215 = D->getDependentSpecializationInfo()) {
1216 assert(isFriend && "non-friend has dependent specialization info?");
1218 // This needs to be set now for future sanity.
1219 Function->setObjectOfFriendDecl(/*HasPrevious*/ true);
1221 // Instantiate the explicit template arguments.
1222 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1223 Info->getRAngleLoc());
1224 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1225 ExplicitArgs, TemplateArgs))
1228 // Map the candidate templates to their instantiations.
1229 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1230 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1231 Info->getTemplate(I),
1233 if (!Temp) return 0;
1235 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1238 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1241 Function->setInvalidDecl();
1243 isExplicitSpecialization = true;
1245 } else if (TemplateParams || !FunctionTemplate) {
1246 // Look only into the namespace where the friend would be declared to
1247 // find a previous declaration. This is the innermost enclosing namespace,
1248 // as described in ActOnFriendFunctionDecl.
1249 SemaRef.LookupQualifiedName(Previous, DC);
1251 // In C++, the previous declaration we find might be a tag type
1252 // (class or enum). In this case, the new declaration will hide the
1253 // tag type. Note that this does does not apply if we're declaring a
1254 // typedef (C++ [dcl.typedef]p4).
1255 if (Previous.isSingleTagDecl())
1259 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
1260 isExplicitSpecialization);
1262 NamedDecl *PrincipalDecl = (TemplateParams
1263 ? cast<NamedDecl>(FunctionTemplate)
1266 // If the original function was part of a friend declaration,
1267 // inherit its namespace state and add it to the owner.
1269 NamedDecl *PrevDecl;
1271 PrevDecl = FunctionTemplate->getPreviousDecl();
1273 PrevDecl = Function->getPreviousDecl();
1275 PrincipalDecl->setObjectOfFriendDecl(PrevDecl != 0);
1276 DC->makeDeclVisibleInContext(PrincipalDecl);
1278 bool queuedInstantiation = false;
1280 // C++98 [temp.friend]p5: When a function is defined in a friend function
1281 // declaration in a class template, the function is defined at each
1282 // instantiation of the class template. The function is defined even if it
1284 // C++11 [temp.friend]p4: When a function is defined in a friend function
1285 // declaration in a class template, the function is instantiated when the
1286 // function is odr-used.
1288 // If -Wc++98-compat is enabled, we go through the motions of checking for a
1289 // redefinition, but don't instantiate the function.
1290 if ((!SemaRef.getLangOpts().CPlusPlus0x ||
1291 SemaRef.Diags.getDiagnosticLevel(
1292 diag::warn_cxx98_compat_friend_redefinition,
1293 Function->getLocation())
1294 != DiagnosticsEngine::Ignored) &&
1295 D->isThisDeclarationADefinition()) {
1296 // Check for a function body.
1297 const FunctionDecl *Definition = 0;
1298 if (Function->isDefined(Definition) &&
1299 Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
1300 SemaRef.Diag(Function->getLocation(),
1301 SemaRef.getLangOpts().CPlusPlus0x ?
1302 diag::warn_cxx98_compat_friend_redefinition :
1303 diag::err_redefinition) << Function->getDeclName();
1304 SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
1305 if (!SemaRef.getLangOpts().CPlusPlus0x)
1306 Function->setInvalidDecl();
1308 // Check for redefinitions due to other instantiations of this or
1309 // a similar friend function.
1310 else for (FunctionDecl::redecl_iterator R = Function->redecls_begin(),
1311 REnd = Function->redecls_end();
1315 switch (R->getFriendObjectKind()) {
1316 case Decl::FOK_None:
1317 if (!SemaRef.getLangOpts().CPlusPlus0x &&
1318 !queuedInstantiation && R->isUsed(false)) {
1319 if (MemberSpecializationInfo *MSInfo
1320 = Function->getMemberSpecializationInfo()) {
1321 if (MSInfo->getPointOfInstantiation().isInvalid()) {
1322 SourceLocation Loc = R->getLocation(); // FIXME
1323 MSInfo->setPointOfInstantiation(Loc);
1324 SemaRef.PendingLocalImplicitInstantiations.push_back(
1325 std::make_pair(Function, Loc));
1326 queuedInstantiation = true;
1332 if (const FunctionDecl *RPattern
1333 = R->getTemplateInstantiationPattern())
1334 if (RPattern->isDefined(RPattern)) {
1335 SemaRef.Diag(Function->getLocation(),
1336 SemaRef.getLangOpts().CPlusPlus0x ?
1337 diag::warn_cxx98_compat_friend_redefinition :
1338 diag::err_redefinition)
1339 << Function->getDeclName();
1340 SemaRef.Diag(R->getLocation(), diag::note_previous_definition);
1341 if (!SemaRef.getLangOpts().CPlusPlus0x)
1342 Function->setInvalidDecl();
1350 if (Function->isOverloadedOperator() && !DC->isRecord() &&
1351 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1352 PrincipalDecl->setNonMemberOperator();
1354 assert(!D->isDefaulted() && "only methods should be defaulted");
1359 TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
1360 TemplateParameterList *TemplateParams,
1361 bool IsClassScopeSpecialization) {
1362 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1363 if (FunctionTemplate && !TemplateParams) {
1364 // We are creating a function template specialization from a function
1365 // template. Check whether there is already a function template
1366 // specialization for this particular set of template arguments.
1367 std::pair<const TemplateArgument *, unsigned> Innermost
1368 = TemplateArgs.getInnermost();
1370 void *InsertPos = 0;
1371 FunctionDecl *SpecFunc
1372 = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
1375 // If we already have a function template specialization, return it.
1381 if (FunctionTemplate)
1382 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1384 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1386 bool MergeWithParentScope = (TemplateParams != 0) ||
1387 !(isa<Decl>(Owner) &&
1388 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1389 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
1391 // Instantiate enclosing template arguments for friends.
1392 SmallVector<TemplateParameterList *, 4> TempParamLists;
1393 unsigned NumTempParamLists = 0;
1394 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
1395 TempParamLists.set_size(NumTempParamLists);
1396 for (unsigned I = 0; I != NumTempParamLists; ++I) {
1397 TemplateParameterList *TempParams = D->getTemplateParameterList(I);
1398 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1401 TempParamLists[I] = InstParams;
1405 SmallVector<ParmVarDecl *, 4> Params;
1406 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
1409 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
1411 // \brief If the type of this function, after ignoring parentheses,
1412 // is not *directly* a function type, then we're instantiating a function
1413 // that was declared via a typedef, e.g.,
1415 // typedef int functype(int, int);
1418 // In this case, we'll just go instantiate the ParmVarDecls that we
1419 // synthesized in the method declaration.
1420 if (!isa<FunctionProtoType>(T.IgnoreParens())) {
1421 assert(!Params.size() && "Instantiating type could not yield parameters");
1422 SmallVector<QualType, 4> ParamTypes;
1423 if (SemaRef.SubstParmTypes(D->getLocation(), D->param_begin(),
1424 D->getNumParams(), TemplateArgs, ParamTypes,
1429 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1431 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1437 DeclContext *DC = Owner;
1441 SS.Adopt(QualifierLoc);
1442 DC = SemaRef.computeDeclContext(SS);
1444 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
1447 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1448 D->getDeclContext(),
1454 // Build the instantiated method declaration.
1455 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1456 CXXMethodDecl *Method = 0;
1458 SourceLocation StartLoc = D->getInnerLocStart();
1459 DeclarationNameInfo NameInfo
1460 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
1461 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
1462 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
1463 StartLoc, NameInfo, T, TInfo,
1464 Constructor->isExplicit(),
1465 Constructor->isInlineSpecified(),
1466 false, Constructor->isConstexpr());
1467 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
1468 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
1469 StartLoc, NameInfo, T, TInfo,
1470 Destructor->isInlineSpecified(),
1472 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
1473 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
1474 StartLoc, NameInfo, T, TInfo,
1475 Conversion->isInlineSpecified(),
1476 Conversion->isExplicit(),
1477 Conversion->isConstexpr(),
1478 Conversion->getLocEnd());
1480 Method = CXXMethodDecl::Create(SemaRef.Context, Record,
1481 StartLoc, NameInfo, T, TInfo,
1483 D->getStorageClassAsWritten(),
1484 D->isInlineSpecified(),
1485 D->isConstexpr(), D->getLocEnd());
1489 Method->setQualifierInfo(QualifierLoc);
1491 if (TemplateParams) {
1492 // Our resulting instantiation is actually a function template, since we
1493 // are substituting only the outer template parameters. For example, given
1495 // template<typename T>
1497 // template<typename U> void f(T, U);
1502 // We are instantiating the member template "f" within X<int>, which means
1503 // substituting int for T, but leaving "f" as a member function template.
1504 // Build the function template itself.
1505 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1506 Method->getLocation(),
1507 Method->getDeclName(),
1508 TemplateParams, Method);
1510 FunctionTemplate->setLexicalDeclContext(Owner);
1511 FunctionTemplate->setObjectOfFriendDecl(true);
1512 } else if (D->isOutOfLine())
1513 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
1514 Method->setDescribedFunctionTemplate(FunctionTemplate);
1515 } else if (FunctionTemplate) {
1516 // Record this function template specialization.
1517 std::pair<const TemplateArgument *, unsigned> Innermost
1518 = TemplateArgs.getInnermost();
1519 Method->setFunctionTemplateSpecialization(FunctionTemplate,
1520 TemplateArgumentList::CreateCopy(SemaRef.Context,
1524 } else if (!isFriend) {
1525 // Record that this is an instantiation of a member function.
1526 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
1529 // If we are instantiating a member function defined
1530 // out-of-line, the instantiation will have the same lexical
1531 // context (which will be a namespace scope) as the template.
1533 if (NumTempParamLists)
1534 Method->setTemplateParameterListsInfo(SemaRef.Context,
1536 TempParamLists.data());
1538 Method->setLexicalDeclContext(Owner);
1539 Method->setObjectOfFriendDecl(true);
1540 } else if (D->isOutOfLine())
1541 Method->setLexicalDeclContext(D->getLexicalDeclContext());
1543 // Attach the parameters
1544 for (unsigned P = 0; P < Params.size(); ++P)
1545 Params[P]->setOwningFunction(Method);
1546 Method->setParams(Params);
1548 if (InitMethodInstantiation(Method, D))
1549 Method->setInvalidDecl();
1551 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
1552 Sema::ForRedeclaration);
1554 if (!FunctionTemplate || TemplateParams || isFriend) {
1555 SemaRef.LookupQualifiedName(Previous, Record);
1557 // In C++, the previous declaration we find might be a tag type
1558 // (class or enum). In this case, the new declaration will hide the
1559 // tag type. Note that this does does not apply if we're declaring a
1560 // typedef (C++ [dcl.typedef]p4).
1561 if (Previous.isSingleTagDecl())
1565 if (!IsClassScopeSpecialization)
1566 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false);
1569 SemaRef.CheckPureMethod(Method, SourceRange());
1571 // Propagate access. For a non-friend declaration, the access is
1572 // whatever we're propagating from. For a friend, it should be the
1573 // previous declaration we just found.
1574 if (isFriend && Method->getPreviousDecl())
1575 Method->setAccess(Method->getPreviousDecl()->getAccess());
1577 Method->setAccess(D->getAccess());
1578 if (FunctionTemplate)
1579 FunctionTemplate->setAccess(Method->getAccess());
1581 SemaRef.CheckOverrideControl(Method);
1583 // If a function is defined as defaulted or deleted, mark it as such now.
1584 if (D->isDefaulted())
1585 Method->setDefaulted();
1586 if (D->isDeletedAsWritten())
1587 Method->setDeletedAsWritten();
1589 // If there's a function template, let our caller handle it.
1590 if (FunctionTemplate) {
1593 // Don't hide a (potentially) valid declaration with an invalid one.
1594 } else if (Method->isInvalidDecl() && !Previous.empty()) {
1597 // Otherwise, check access to friends and make them visible.
1598 } else if (isFriend) {
1599 // We only need to re-check access for methods which we didn't
1600 // manage to match during parsing.
1601 if (!D->getPreviousDecl())
1602 SemaRef.CheckFriendAccess(Method);
1604 Record->makeDeclVisibleInContext(Method);
1606 // Otherwise, add the declaration. We don't need to do this for
1607 // class-scope specializations because we'll have matched them with
1608 // the appropriate template.
1609 } else if (!IsClassScopeSpecialization) {
1610 Owner->addDecl(Method);
1613 if (D->isExplicitlyDefaulted()) {
1614 SemaRef.SetDeclDefaulted(Method, Method->getLocation());
1616 assert(!D->isDefaulted() &&
1617 "should not implicitly default uninstantiated function");
1623 Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
1624 return VisitCXXMethodDecl(D);
1627 Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
1628 return VisitCXXMethodDecl(D);
1631 Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
1632 return VisitCXXMethodDecl(D);
1635 ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
1636 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0,
1637 llvm::Optional<unsigned>(),
1638 /*ExpectParameterPack=*/false);
1641 Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1642 TemplateTypeParmDecl *D) {
1643 // TODO: don't always clone when decls are refcounted.
1644 assert(D->getTypeForDecl()->isTemplateTypeParmType());
1646 TemplateTypeParmDecl *Inst =
1647 TemplateTypeParmDecl::Create(SemaRef.Context, Owner,
1648 D->getLocStart(), D->getLocation(),
1649 D->getDepth() - TemplateArgs.getNumLevels(),
1650 D->getIndex(), D->getIdentifier(),
1651 D->wasDeclaredWithTypename(),
1652 D->isParameterPack());
1653 Inst->setAccess(AS_public);
1655 if (D->hasDefaultArgument())
1656 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
1658 // Introduce this template parameter's instantiation into the instantiation
1660 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1665 Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1666 NonTypeTemplateParmDecl *D) {
1667 // Substitute into the type of the non-type template parameter.
1668 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
1669 SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
1670 SmallVector<QualType, 4> ExpandedParameterPackTypes;
1671 bool IsExpandedParameterPack = false;
1674 bool Invalid = false;
1676 if (D->isExpandedParameterPack()) {
1677 // The non-type template parameter pack is an already-expanded pack
1678 // expansion of types. Substitute into each of the expanded types.
1679 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
1680 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
1681 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
1682 TypeSourceInfo *NewDI =SemaRef.SubstType(D->getExpansionTypeSourceInfo(I),
1689 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1690 QualType NewT =SemaRef.CheckNonTypeTemplateParameterType(NewDI->getType(),
1694 ExpandedParameterPackTypes.push_back(NewT);
1697 IsExpandedParameterPack = true;
1698 DI = D->getTypeSourceInfo();
1700 } else if (D->isPackExpansion()) {
1701 // The non-type template parameter pack's type is a pack expansion of types.
1702 // Determine whether we need to expand this parameter pack into separate
1704 PackExpansionTypeLoc Expansion = cast<PackExpansionTypeLoc>(TL);
1705 TypeLoc Pattern = Expansion.getPatternLoc();
1706 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1707 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
1709 // Determine whether the set of unexpanded parameter packs can and should
1712 bool RetainExpansion = false;
1713 llvm::Optional<unsigned> OrigNumExpansions
1714 = Expansion.getTypePtr()->getNumExpansions();
1715 llvm::Optional<unsigned> NumExpansions = OrigNumExpansions;
1716 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
1717 Pattern.getSourceRange(),
1720 Expand, RetainExpansion,
1725 for (unsigned I = 0; I != *NumExpansions; ++I) {
1726 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
1727 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
1733 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1734 QualType NewT = SemaRef.CheckNonTypeTemplateParameterType(
1739 ExpandedParameterPackTypes.push_back(NewT);
1742 // Note that we have an expanded parameter pack. The "type" of this
1743 // expanded parameter pack is the original expansion type, but callers
1744 // will end up using the expanded parameter pack types for type-checking.
1745 IsExpandedParameterPack = true;
1746 DI = D->getTypeSourceInfo();
1749 // We cannot fully expand the pack expansion now, so substitute into the
1750 // pattern and create a new pack expansion type.
1751 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
1752 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
1758 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
1766 // Simple case: substitution into a parameter that is not a parameter pack.
1767 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
1768 D->getLocation(), D->getDeclName());
1772 // Check that this type is acceptable for a non-type template parameter.
1773 T = SemaRef.CheckNonTypeTemplateParameterType(DI->getType(),
1776 T = SemaRef.Context.IntTy;
1781 NonTypeTemplateParmDecl *Param;
1782 if (IsExpandedParameterPack)
1783 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
1784 D->getInnerLocStart(),
1786 D->getDepth() - TemplateArgs.getNumLevels(),
1788 D->getIdentifier(), T,
1790 ExpandedParameterPackTypes.data(),
1791 ExpandedParameterPackTypes.size(),
1792 ExpandedParameterPackTypesAsWritten.data());
1794 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
1795 D->getInnerLocStart(),
1797 D->getDepth() - TemplateArgs.getNumLevels(),
1799 D->getIdentifier(), T,
1800 D->isParameterPack(), DI);
1802 Param->setAccess(AS_public);
1804 Param->setInvalidDecl();
1806 Param->setDefaultArgument(D->getDefaultArgument(), false);
1808 // Introduce this template parameter's instantiation into the instantiation
1810 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1814 static void collectUnexpandedParameterPacks(
1816 TemplateParameterList *Params,
1817 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
1818 for (TemplateParameterList::const_iterator I = Params->begin(),
1819 E = Params->end(); I != E; ++I) {
1820 if ((*I)->isTemplateParameterPack())
1822 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*I))
1823 S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
1825 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(*I))
1826 collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
1832 TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1833 TemplateTemplateParmDecl *D) {
1834 // Instantiate the template parameter list of the template template parameter.
1835 TemplateParameterList *TempParams = D->getTemplateParameters();
1836 TemplateParameterList *InstParams;
1837 SmallVector<TemplateParameterList*, 8> ExpandedParams;
1839 bool IsExpandedParameterPack = false;
1841 if (D->isExpandedParameterPack()) {
1842 // The template template parameter pack is an already-expanded pack
1843 // expansion of template parameters. Substitute into each of the expanded
1845 ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
1846 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
1848 LocalInstantiationScope Scope(SemaRef);
1849 TemplateParameterList *Expansion =
1850 SubstTemplateParams(D->getExpansionTemplateParameters(I));
1853 ExpandedParams.push_back(Expansion);
1856 IsExpandedParameterPack = true;
1857 InstParams = TempParams;
1858 } else if (D->isPackExpansion()) {
1859 // The template template parameter pack expands to a pack of template
1860 // template parameters. Determine whether we need to expand this parameter
1861 // pack into separate parameters.
1862 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1863 collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(),
1866 // Determine whether the set of unexpanded parameter packs can and should
1869 bool RetainExpansion = false;
1870 llvm::Optional<unsigned> NumExpansions;
1871 if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(),
1872 TempParams->getSourceRange(),
1875 Expand, RetainExpansion,
1880 for (unsigned I = 0; I != *NumExpansions; ++I) {
1881 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
1882 LocalInstantiationScope Scope(SemaRef);
1883 TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
1886 ExpandedParams.push_back(Expansion);
1889 // Note that we have an expanded parameter pack. The "type" of this
1890 // expanded parameter pack is the original expansion type, but callers
1891 // will end up using the expanded parameter pack types for type-checking.
1892 IsExpandedParameterPack = true;
1893 InstParams = TempParams;
1895 // We cannot fully expand the pack expansion now, so just substitute
1896 // into the pattern.
1897 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
1899 LocalInstantiationScope Scope(SemaRef);
1900 InstParams = SubstTemplateParams(TempParams);
1905 // Perform the actual substitution of template parameters within a new,
1906 // local instantiation scope.
1907 LocalInstantiationScope Scope(SemaRef);
1908 InstParams = SubstTemplateParams(TempParams);
1913 // Build the template template parameter.
1914 TemplateTemplateParmDecl *Param;
1915 if (IsExpandedParameterPack)
1916 Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
1918 D->getDepth() - TemplateArgs.getNumLevels(),
1920 D->getIdentifier(), InstParams,
1923 Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
1925 D->getDepth() - TemplateArgs.getNumLevels(),
1927 D->isParameterPack(),
1928 D->getIdentifier(), InstParams);
1929 Param->setDefaultArgument(D->getDefaultArgument(), false);
1930 Param->setAccess(AS_public);
1932 // Introduce this template parameter's instantiation into the instantiation
1934 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1939 Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1940 // Using directives are never dependent (and never contain any types or
1941 // expressions), so they require no explicit instantiation work.
1943 UsingDirectiveDecl *Inst
1944 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1945 D->getNamespaceKeyLocation(),
1946 D->getQualifierLoc(),
1947 D->getIdentLocation(),
1948 D->getNominatedNamespace(),
1949 D->getCommonAncestor());
1951 // Add the using directive to its declaration context
1952 // only if this is not a function or method.
1953 if (!Owner->isFunctionOrMethod())
1954 Owner->addDecl(Inst);
1959 Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
1961 // The nested name specifier may be dependent, for example
1962 // template <typename T> struct t {
1963 // struct s1 { T f1(); };
1964 // struct s2 : s1 { using s1::f1; };
1966 // template struct t<int>;
1967 // Here, in using s1::f1, s1 refers to t<T>::s1;
1968 // we need to substitute for t<int>::s1.
1969 NestedNameSpecifierLoc QualifierLoc
1970 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
1975 // The name info is non-dependent, so no transformation
1977 DeclarationNameInfo NameInfo = D->getNameInfo();
1979 // We only need to do redeclaration lookups if we're in a class
1980 // scope (in fact, it's not really even possible in non-class
1982 bool CheckRedeclaration = Owner->isRecord();
1984 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
1985 Sema::ForRedeclaration);
1987 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
1988 D->getUsingLocation(),
1994 SS.Adopt(QualifierLoc);
1995 if (CheckRedeclaration) {
1996 Prev.setHideTags(false);
1997 SemaRef.LookupQualifiedName(Prev, Owner);
1999 // Check for invalid redeclarations.
2000 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
2001 D->isTypeName(), SS,
2002 D->getLocation(), Prev))
2003 NewUD->setInvalidDecl();
2007 if (!NewUD->isInvalidDecl() &&
2008 SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
2010 NewUD->setInvalidDecl();
2012 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
2013 NewUD->setAccess(D->getAccess());
2014 Owner->addDecl(NewUD);
2016 // Don't process the shadow decls for an invalid decl.
2017 if (NewUD->isInvalidDecl())
2020 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
2021 if (SemaRef.CheckInheritingConstructorUsingDecl(NewUD))
2022 NewUD->setInvalidDecl();
2026 bool isFunctionScope = Owner->isFunctionOrMethod();
2028 // Process the shadow decls.
2029 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
2031 UsingShadowDecl *Shadow = *I;
2032 NamedDecl *InstTarget =
2033 cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
2034 Shadow->getLocation(),
2035 Shadow->getTargetDecl(),
2040 if (CheckRedeclaration &&
2041 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
2044 UsingShadowDecl *InstShadow
2045 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
2046 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
2048 if (isFunctionScope)
2049 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
2055 Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
2056 // Ignore these; we handle them in bulk when processing the UsingDecl.
2060 Decl * TemplateDeclInstantiator
2061 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
2062 NestedNameSpecifierLoc QualifierLoc
2063 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
2069 SS.Adopt(QualifierLoc);
2071 // Since NameInfo refers to a typename, it cannot be a C++ special name.
2072 // Hence, no tranformation is required for it.
2073 DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation());
2075 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
2076 D->getUsingLoc(), SS, NameInfo, 0,
2077 /*instantiation*/ true,
2078 /*typename*/ true, D->getTypenameLoc());
2080 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
2085 Decl * TemplateDeclInstantiator
2086 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
2087 NestedNameSpecifierLoc QualifierLoc
2088 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), TemplateArgs);
2093 SS.Adopt(QualifierLoc);
2095 DeclarationNameInfo NameInfo
2096 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2099 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
2100 D->getUsingLoc(), SS, NameInfo, 0,
2101 /*instantiation*/ true,
2102 /*typename*/ false, SourceLocation());
2104 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
2110 Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
2111 ClassScopeFunctionSpecializationDecl *Decl) {
2112 CXXMethodDecl *OldFD = Decl->getSpecialization();
2113 CXXMethodDecl *NewFD = cast<CXXMethodDecl>(VisitCXXMethodDecl(OldFD,
2116 LookupResult Previous(SemaRef, NewFD->getNameInfo(), Sema::LookupOrdinaryName,
2117 Sema::ForRedeclaration);
2119 TemplateArgumentListInfo TemplateArgs;
2120 TemplateArgumentListInfo* TemplateArgsPtr = 0;
2121 if (Decl->hasExplicitTemplateArgs()) {
2122 TemplateArgs = Decl->templateArgs();
2123 TemplateArgsPtr = &TemplateArgs;
2126 SemaRef.LookupQualifiedName(Previous, SemaRef.CurContext);
2127 if (SemaRef.CheckFunctionTemplateSpecialization(NewFD, TemplateArgsPtr,
2129 NewFD->setInvalidDecl();
2133 // Associate the specialization with the pattern.
2134 FunctionDecl *Specialization = cast<FunctionDecl>(Previous.getFoundDecl());
2135 assert(Specialization && "Class scope Specialization is null");
2136 SemaRef.Context.setClassScopeSpecializationPattern(Specialization, OldFD);
2141 Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
2142 const MultiLevelTemplateArgumentList &TemplateArgs) {
2143 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
2144 if (D->isInvalidDecl())
2147 return Instantiator.Visit(D);
2150 /// \brief Instantiates a nested template parameter list in the current
2151 /// instantiation context.
2153 /// \param L The parameter list to instantiate
2155 /// \returns NULL if there was an error
2156 TemplateParameterList *
2157 TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
2158 // Get errors for all the parameters before bailing out.
2159 bool Invalid = false;
2161 unsigned N = L->size();
2162 typedef SmallVector<NamedDecl *, 8> ParamVector;
2165 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
2167 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
2168 Params.push_back(D);
2169 Invalid = Invalid || !D || D->isInvalidDecl();
2172 // Clean up if we had an error.
2176 TemplateParameterList *InstL
2177 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
2178 L->getLAngleLoc(), &Params.front(), N,
2183 /// \brief Instantiate the declaration of a class template partial
2186 /// \param ClassTemplate the (instantiated) class template that is partially
2187 // specialized by the instantiation of \p PartialSpec.
2189 /// \param PartialSpec the (uninstantiated) class template partial
2190 /// specialization that we are instantiating.
2192 /// \returns The instantiated partial specialization, if successful; otherwise,
2193 /// NULL to indicate an error.
2194 ClassTemplatePartialSpecializationDecl *
2195 TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
2196 ClassTemplateDecl *ClassTemplate,
2197 ClassTemplatePartialSpecializationDecl *PartialSpec) {
2198 // Create a local instantiation scope for this class template partial
2199 // specialization, which will contain the instantiations of the template
2201 LocalInstantiationScope Scope(SemaRef);
2203 // Substitute into the template parameters of the class template partial
2205 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
2206 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2210 // Substitute into the template arguments of the class template partial
2212 TemplateArgumentListInfo InstTemplateArgs; // no angle locations
2213 if (SemaRef.Subst(PartialSpec->getTemplateArgsAsWritten(),
2214 PartialSpec->getNumTemplateArgsAsWritten(),
2215 InstTemplateArgs, TemplateArgs))
2218 // Check that the template argument list is well-formed for this
2220 SmallVector<TemplateArgument, 4> Converted;
2221 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
2222 PartialSpec->getLocation(),
2228 // Figure out where to insert this class template partial specialization
2229 // in the member template's set of class template partial specializations.
2230 void *InsertPos = 0;
2231 ClassTemplateSpecializationDecl *PrevDecl
2232 = ClassTemplate->findPartialSpecialization(Converted.data(),
2233 Converted.size(), InsertPos);
2235 // Build the canonical type that describes the converted template
2236 // arguments of the class template partial specialization.
2238 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
2242 // Build the fully-sugared type for this class template
2243 // specialization as the user wrote in the specialization
2244 // itself. This means that we'll pretty-print the type retrieved
2245 // from the specialization's declaration the way that the user
2246 // actually wrote the specialization, rather than formatting the
2247 // name based on the "canonical" representation used to store the
2248 // template arguments in the specialization.
2249 TypeSourceInfo *WrittenTy
2250 = SemaRef.Context.getTemplateSpecializationTypeInfo(
2251 TemplateName(ClassTemplate),
2252 PartialSpec->getLocation(),
2257 // We've already seen a partial specialization with the same template
2258 // parameters and template arguments. This can happen, for example, when
2259 // substituting the outer template arguments ends up causing two
2260 // class template partial specializations of a member class template
2261 // to have identical forms, e.g.,
2263 // template<typename T, typename U>
2265 // template<typename X, typename Y> struct Inner;
2266 // template<typename Y> struct Inner<T, Y>;
2267 // template<typename Y> struct Inner<U, Y>;
2270 // Outer<int, int> outer; // error: the partial specializations of Inner
2271 // // have the same signature.
2272 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
2273 << WrittenTy->getType();
2274 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
2275 << SemaRef.Context.getTypeDeclType(PrevDecl);
2280 // Create the class template partial specialization declaration.
2281 ClassTemplatePartialSpecializationDecl *InstPartialSpec
2282 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
2283 PartialSpec->getTagKind(),
2285 PartialSpec->getLocStart(),
2286 PartialSpec->getLocation(),
2294 ClassTemplate->getNextPartialSpecSequenceNumber());
2295 // Substitute the nested name specifier, if any.
2296 if (SubstQualifier(PartialSpec, InstPartialSpec))
2299 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
2300 InstPartialSpec->setTypeAsWritten(WrittenTy);
2302 // Add this partial specialization to the set of class template partial
2304 ClassTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/0);
2305 return InstPartialSpec;
2309 TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
2310 SmallVectorImpl<ParmVarDecl *> &Params) {
2311 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
2312 assert(OldTInfo && "substituting function without type source info");
2313 assert(Params.empty() && "parameter vector is non-empty at start");
2315 CXXRecordDecl *ThisContext = 0;
2316 unsigned ThisTypeQuals = 0;
2317 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
2318 ThisContext = Method->getParent();
2319 ThisTypeQuals = Method->getTypeQualifiers();
2322 TypeSourceInfo *NewTInfo
2323 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
2324 D->getTypeSpecStartLoc(),
2326 ThisContext, ThisTypeQuals);
2330 if (NewTInfo != OldTInfo) {
2331 // Get parameters from the new type info.
2332 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
2333 if (FunctionProtoTypeLoc *OldProtoLoc
2334 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
2335 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
2336 FunctionProtoTypeLoc *NewProtoLoc = cast<FunctionProtoTypeLoc>(&NewTL);
2337 assert(NewProtoLoc && "Missing prototype?");
2338 unsigned NewIdx = 0;
2339 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc->getNumArgs();
2340 OldIdx != NumOldParams; ++OldIdx) {
2341 ParmVarDecl *OldParam = OldProtoLoc->getArg(OldIdx);
2342 LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
2344 llvm::Optional<unsigned> NumArgumentsInExpansion;
2345 if (OldParam->isParameterPack())
2346 NumArgumentsInExpansion =
2347 SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
2349 if (!NumArgumentsInExpansion) {
2350 // Simple case: normal parameter, or a parameter pack that's
2351 // instantiated to a (still-dependent) parameter pack.
2352 ParmVarDecl *NewParam = NewProtoLoc->getArg(NewIdx++);
2353 Params.push_back(NewParam);
2354 Scope->InstantiatedLocal(OldParam, NewParam);
2356 // Parameter pack expansion: make the instantiation an argument pack.
2357 Scope->MakeInstantiatedLocalArgPack(OldParam);
2358 for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
2359 ParmVarDecl *NewParam = NewProtoLoc->getArg(NewIdx++);
2360 Params.push_back(NewParam);
2361 Scope->InstantiatedLocalPackArg(OldParam, NewParam);
2367 // The function type itself was not dependent and therefore no
2368 // substitution occurred. However, we still need to instantiate
2369 // the function parameters themselves.
2370 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
2371 if (FunctionProtoTypeLoc *OldProtoLoc
2372 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
2373 for (unsigned i = 0, i_end = OldProtoLoc->getNumArgs(); i != i_end; ++i) {
2374 ParmVarDecl *Parm = VisitParmVarDecl(OldProtoLoc->getArg(i));
2377 Params.push_back(Parm);
2384 /// Introduce the instantiated function parameters into the local
2385 /// instantiation scope, and set the parameter names to those used
2386 /// in the template.
2387 static void addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function,
2388 const FunctionDecl *PatternDecl,
2389 LocalInstantiationScope &Scope,
2390 const MultiLevelTemplateArgumentList &TemplateArgs) {
2391 unsigned FParamIdx = 0;
2392 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
2393 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
2394 if (!PatternParam->isParameterPack()) {
2395 // Simple case: not a parameter pack.
2396 assert(FParamIdx < Function->getNumParams());
2397 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
2398 FunctionParam->setDeclName(PatternParam->getDeclName());
2399 Scope.InstantiatedLocal(PatternParam, FunctionParam);
2404 // Expand the parameter pack.
2405 Scope.MakeInstantiatedLocalArgPack(PatternParam);
2406 llvm::Optional<unsigned> NumArgumentsInExpansion
2407 = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
2408 assert(NumArgumentsInExpansion &&
2409 "should only be called when all template arguments are known");
2410 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
2411 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
2412 FunctionParam->setDeclName(PatternParam->getDeclName());
2413 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
2419 static void InstantiateExceptionSpec(Sema &SemaRef, FunctionDecl *New,
2420 const FunctionProtoType *Proto,
2421 const MultiLevelTemplateArgumentList &TemplateArgs) {
2422 assert(Proto->getExceptionSpecType() != EST_Uninstantiated);
2424 // C++11 [expr.prim.general]p3:
2425 // If a declaration declares a member function or member function
2426 // template of a class X, the expression this is a prvalue of type
2427 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
2428 // and the end of the function-definition, member-declarator, or
2430 CXXRecordDecl *ThisContext = 0;
2431 unsigned ThisTypeQuals = 0;
2432 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(New)) {
2433 ThisContext = Method->getParent();
2434 ThisTypeQuals = Method->getTypeQualifiers();
2436 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals,
2437 SemaRef.getLangOpts().CPlusPlus0x);
2439 // The function has an exception specification or a "noreturn"
2440 // attribute. Substitute into each of the exception types.
2441 SmallVector<QualType, 4> Exceptions;
2442 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
2443 // FIXME: Poor location information!
2444 if (const PackExpansionType *PackExpansion
2445 = Proto->getExceptionType(I)->getAs<PackExpansionType>()) {
2446 // We have a pack expansion. Instantiate it.
2447 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2448 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
2450 assert(!Unexpanded.empty() &&
2451 "Pack expansion without parameter packs?");
2453 bool Expand = false;
2454 bool RetainExpansion = false;
2455 llvm::Optional<unsigned> NumExpansions
2456 = PackExpansion->getNumExpansions();
2457 if (SemaRef.CheckParameterPacksForExpansion(New->getLocation(),
2467 // We can't expand this pack expansion into separate arguments yet;
2468 // just substitute into the pattern and create a new pack expansion
2470 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2471 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2473 New->getLocation(), New->getDeclName());
2477 T = SemaRef.Context.getPackExpansionType(T, NumExpansions);
2478 Exceptions.push_back(T);
2482 // Substitute into the pack expansion pattern for each template
2483 bool Invalid = false;
2484 for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
2485 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, ArgIdx);
2487 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2489 New->getLocation(), New->getDeclName());
2495 Exceptions.push_back(T);
2505 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
2506 New->getLocation(), New->getDeclName());
2508 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
2511 Exceptions.push_back(T);
2513 Expr *NoexceptExpr = 0;
2514 if (Expr *OldNoexceptExpr = Proto->getNoexceptExpr()) {
2515 EnterExpressionEvaluationContext Unevaluated(SemaRef,
2516 Sema::ConstantEvaluated);
2517 ExprResult E = SemaRef.SubstExpr(OldNoexceptExpr, TemplateArgs);
2519 E = SemaRef.CheckBooleanCondition(E.get(), E.get()->getLocStart());
2522 NoexceptExpr = E.take();
2523 if (!NoexceptExpr->isTypeDependent() &&
2524 !NoexceptExpr->isValueDependent())
2526 = SemaRef.VerifyIntegerConstantExpression(NoexceptExpr,
2527 0, diag::err_noexcept_needs_constant_expression,
2528 /*AllowFold*/ false).take();
2532 // Rebuild the function type
2533 const FunctionProtoType *NewProto
2534 = New->getType()->getAs<FunctionProtoType>();
2535 assert(NewProto && "Template instantiation without function prototype?");
2537 FunctionProtoType::ExtProtoInfo EPI = NewProto->getExtProtoInfo();
2538 EPI.ExceptionSpecType = Proto->getExceptionSpecType();
2539 EPI.NumExceptions = Exceptions.size();
2540 EPI.Exceptions = Exceptions.data();
2541 EPI.NoexceptExpr = NoexceptExpr;
2543 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
2544 NewProto->arg_type_begin(),
2545 NewProto->getNumArgs(),
2549 void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
2550 FunctionDecl *Decl) {
2551 const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
2552 if (Proto->getExceptionSpecType() != EST_Uninstantiated)
2555 InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
2556 InstantiatingTemplate::ExceptionSpecification());
2558 // We hit the instantiation depth limit. Clear the exception specification
2559 // so that our callers don't have to cope with EST_Uninstantiated.
2560 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
2561 EPI.ExceptionSpecType = EST_None;
2562 Decl->setType(Context.getFunctionType(Proto->getResultType(),
2563 Proto->arg_type_begin(),
2564 Proto->getNumArgs(),
2569 // Enter the scope of this instantiation. We don't use
2570 // PushDeclContext because we don't have a scope.
2571 Sema::ContextRAII savedContext(*this, Decl);
2572 LocalInstantiationScope Scope(*this);
2574 MultiLevelTemplateArgumentList TemplateArgs =
2575 getTemplateInstantiationArgs(Decl, 0, /*RelativeToPrimary*/true);
2577 FunctionDecl *Template = Proto->getExceptionSpecTemplate();
2578 addInstantiatedParametersToScope(*this, Decl, Template, Scope, TemplateArgs);
2580 ::InstantiateExceptionSpec(*this, Decl,
2581 Template->getType()->castAs<FunctionProtoType>(),
2585 /// \brief Initializes the common fields of an instantiation function
2586 /// declaration (New) from the corresponding fields of its template (Tmpl).
2588 /// \returns true if there was an error
2590 TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
2591 FunctionDecl *Tmpl) {
2592 if (Tmpl->isDeleted())
2593 New->setDeletedAsWritten();
2595 // If we are performing substituting explicitly-specified template arguments
2596 // or deduced template arguments into a function template and we reach this
2597 // point, we are now past the point where SFINAE applies and have committed
2598 // to keeping the new function template specialization. We therefore
2599 // convert the active template instantiation for the function template
2600 // into a template instantiation for this specific function template
2601 // specialization, which is not a SFINAE context, so that we diagnose any
2602 // further errors in the declaration itself.
2603 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
2604 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
2605 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
2606 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
2607 if (FunctionTemplateDecl *FunTmpl
2608 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
2609 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
2610 "Deduction from the wrong function template?");
2612 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
2613 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
2617 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
2618 assert(Proto && "Function template without prototype?");
2620 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
2621 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
2623 // DR1330: In C++11, defer instantiation of a non-trivial
2624 // exception specification.
2625 if (SemaRef.getLangOpts().CPlusPlus0x &&
2626 EPI.ExceptionSpecType != EST_None &&
2627 EPI.ExceptionSpecType != EST_DynamicNone &&
2628 EPI.ExceptionSpecType != EST_BasicNoexcept) {
2629 FunctionDecl *ExceptionSpecTemplate = Tmpl;
2630 if (EPI.ExceptionSpecType == EST_Uninstantiated)
2631 ExceptionSpecTemplate = EPI.ExceptionSpecTemplate;
2632 assert(EPI.ExceptionSpecType != EST_Unevaluated &&
2633 "instantiating implicitly-declared special member");
2635 // Mark the function has having an uninstantiated exception specification.
2636 const FunctionProtoType *NewProto
2637 = New->getType()->getAs<FunctionProtoType>();
2638 assert(NewProto && "Template instantiation without function prototype?");
2639 EPI = NewProto->getExtProtoInfo();
2640 EPI.ExceptionSpecType = EST_Uninstantiated;
2641 EPI.ExceptionSpecDecl = New;
2642 EPI.ExceptionSpecTemplate = ExceptionSpecTemplate;
2643 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
2644 NewProto->arg_type_begin(),
2645 NewProto->getNumArgs(),
2648 ::InstantiateExceptionSpec(SemaRef, New, Proto, TemplateArgs);
2652 // Get the definition. Leaves the variable unchanged if undefined.
2653 const FunctionDecl *Definition = Tmpl;
2654 Tmpl->isDefined(Definition);
2656 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
2657 LateAttrs, StartingScope);
2662 /// \brief Initializes common fields of an instantiated method
2663 /// declaration (New) from the corresponding fields of its template
2666 /// \returns true if there was an error
2668 TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
2669 CXXMethodDecl *Tmpl) {
2670 if (InitFunctionInstantiation(New, Tmpl))
2673 New->setAccess(Tmpl->getAccess());
2674 if (Tmpl->isVirtualAsWritten())
2675 New->setVirtualAsWritten(true);
2677 // FIXME: attributes
2678 // FIXME: New needs a pointer to Tmpl
2682 /// \brief Instantiate the definition of the given function from its
2685 /// \param PointOfInstantiation the point at which the instantiation was
2686 /// required. Note that this is not precisely a "point of instantiation"
2687 /// for the function, but it's close.
2689 /// \param Function the already-instantiated declaration of a
2690 /// function template specialization or member function of a class template
2693 /// \param Recursive if true, recursively instantiates any functions that
2694 /// are required by this instantiation.
2696 /// \param DefinitionRequired if true, then we are performing an explicit
2697 /// instantiation where the body of the function is required. Complain if
2698 /// there is no such body.
2699 void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
2700 FunctionDecl *Function,
2702 bool DefinitionRequired) {
2703 if (Function->isInvalidDecl() || Function->isDefined())
2706 // Never instantiate an explicit specialization except if it is a class scope
2707 // explicit specialization.
2708 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
2709 !Function->getClassScopeSpecializationPattern())
2712 // Find the function body that we'll be substituting.
2713 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
2714 assert(PatternDecl && "instantiating a non-template");
2716 Stmt *Pattern = PatternDecl->getBody(PatternDecl);
2717 assert(PatternDecl && "template definition is not a template");
2719 // Try to find a defaulted definition
2720 PatternDecl->isDefined(PatternDecl);
2722 assert(PatternDecl && "template definition is not a template");
2724 // Postpone late parsed template instantiations.
2725 if (PatternDecl->isLateTemplateParsed() &&
2726 !LateTemplateParser) {
2727 PendingInstantiations.push_back(
2728 std::make_pair(Function, PointOfInstantiation));
2732 // Call the LateTemplateParser callback if there a need to late parse
2733 // a templated function definition.
2734 if (!Pattern && PatternDecl->isLateTemplateParsed() &&
2735 LateTemplateParser) {
2736 LateTemplateParser(OpaqueParser, PatternDecl);
2737 Pattern = PatternDecl->getBody(PatternDecl);
2740 if (!Pattern && !PatternDecl->isDefaulted()) {
2741 if (DefinitionRequired) {
2742 if (Function->getPrimaryTemplate())
2743 Diag(PointOfInstantiation,
2744 diag::err_explicit_instantiation_undefined_func_template)
2745 << Function->getPrimaryTemplate();
2747 Diag(PointOfInstantiation,
2748 diag::err_explicit_instantiation_undefined_member)
2749 << 1 << Function->getDeclName() << Function->getDeclContext();
2752 Diag(PatternDecl->getLocation(),
2753 diag::note_explicit_instantiation_here);
2754 Function->setInvalidDecl();
2755 } else if (Function->getTemplateSpecializationKind()
2756 == TSK_ExplicitInstantiationDefinition) {
2757 PendingInstantiations.push_back(
2758 std::make_pair(Function, PointOfInstantiation));
2764 // C++0x [temp.explicit]p9:
2765 // Except for inline functions, other explicit instantiation declarations
2766 // have the effect of suppressing the implicit instantiation of the entity
2767 // to which they refer.
2768 if (Function->getTemplateSpecializationKind()
2769 == TSK_ExplicitInstantiationDeclaration &&
2770 !PatternDecl->isInlined())
2773 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
2777 // Copy the inner loc start from the pattern.
2778 Function->setInnerLocStart(PatternDecl->getInnerLocStart());
2780 // If we're performing recursive template instantiation, create our own
2781 // queue of pending implicit instantiations that we will instantiate later,
2782 // while we're still within our own instantiation context.
2783 SmallVector<VTableUse, 16> SavedVTableUses;
2784 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
2786 VTableUses.swap(SavedVTableUses);
2787 PendingInstantiations.swap(SavedPendingInstantiations);
2790 EnterExpressionEvaluationContext EvalContext(*this,
2791 Sema::PotentiallyEvaluated);
2792 ActOnStartOfFunctionDef(0, Function);
2794 // Introduce a new scope where local variable instantiations will be
2795 // recorded, unless we're actually a member function within a local
2796 // class, in which case we need to merge our results with the parent
2797 // scope (of the enclosing function).
2798 bool MergeWithParentScope = false;
2799 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
2800 MergeWithParentScope = Rec->isLocalClass();
2802 LocalInstantiationScope Scope(*this, MergeWithParentScope);
2804 // Enter the scope of this instantiation. We don't use
2805 // PushDeclContext because we don't have a scope.
2806 Sema::ContextRAII savedContext(*this, Function);
2808 MultiLevelTemplateArgumentList TemplateArgs =
2809 getTemplateInstantiationArgs(Function, 0, false, PatternDecl);
2811 addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope,
2814 if (PatternDecl->isDefaulted()) {
2815 ActOnFinishFunctionBody(Function, 0, /*IsInstantiation=*/true);
2817 SetDeclDefaulted(Function, PatternDecl->getLocation());
2819 // If this is a constructor, instantiate the member initializers.
2820 if (const CXXConstructorDecl *Ctor =
2821 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
2822 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
2826 // Instantiate the function body.
2827 StmtResult Body = SubstStmt(Pattern, TemplateArgs);
2829 if (Body.isInvalid())
2830 Function->setInvalidDecl();
2832 ActOnFinishFunctionBody(Function, Body.get(),
2833 /*IsInstantiation=*/true);
2836 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
2840 DeclGroupRef DG(Function);
2841 Consumer.HandleTopLevelDecl(DG);
2843 // This class may have local implicit instantiations that need to be
2844 // instantiation within this scope.
2845 PerformPendingInstantiations(/*LocalOnly=*/true);
2849 // Define any pending vtables.
2850 DefineUsedVTables();
2852 // Instantiate any pending implicit instantiations found during the
2853 // instantiation of this template.
2854 PerformPendingInstantiations();
2856 // Restore the set of pending vtables.
2857 assert(VTableUses.empty() &&
2858 "VTableUses should be empty before it is discarded.");
2859 VTableUses.swap(SavedVTableUses);
2861 // Restore the set of pending implicit instantiations.
2862 assert(PendingInstantiations.empty() &&
2863 "PendingInstantiations should be empty before it is discarded.");
2864 PendingInstantiations.swap(SavedPendingInstantiations);
2868 /// \brief Instantiate the definition of the given variable from its
2871 /// \param PointOfInstantiation the point at which the instantiation was
2872 /// required. Note that this is not precisely a "point of instantiation"
2873 /// for the function, but it's close.
2875 /// \param Var the already-instantiated declaration of a static member
2876 /// variable of a class template specialization.
2878 /// \param Recursive if true, recursively instantiates any functions that
2879 /// are required by this instantiation.
2881 /// \param DefinitionRequired if true, then we are performing an explicit
2882 /// instantiation where an out-of-line definition of the member variable
2883 /// is required. Complain if there is no such definition.
2884 void Sema::InstantiateStaticDataMemberDefinition(
2885 SourceLocation PointOfInstantiation,
2888 bool DefinitionRequired) {
2889 if (Var->isInvalidDecl())
2892 // Find the out-of-line definition of this static data member.
2893 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
2894 assert(Def && "This data member was not instantiated from a template?");
2895 assert(Def->isStaticDataMember() && "Not a static data member?");
2896 Def = Def->getOutOfLineDefinition();
2899 // We did not find an out-of-line definition of this static data member,
2900 // so we won't perform any instantiation. Rather, we rely on the user to
2901 // instantiate this definition (or provide a specialization for it) in
2902 // another translation unit.
2903 if (DefinitionRequired) {
2904 Def = Var->getInstantiatedFromStaticDataMember();
2905 Diag(PointOfInstantiation,
2906 diag::err_explicit_instantiation_undefined_member)
2907 << 2 << Var->getDeclName() << Var->getDeclContext();
2908 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
2909 } else if (Var->getTemplateSpecializationKind()
2910 == TSK_ExplicitInstantiationDefinition) {
2911 PendingInstantiations.push_back(
2912 std::make_pair(Var, PointOfInstantiation));
2918 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
2920 // Never instantiate an explicit specialization.
2921 if (TSK == TSK_ExplicitSpecialization)
2924 // C++0x [temp.explicit]p9:
2925 // Except for inline functions, other explicit instantiation declarations
2926 // have the effect of suppressing the implicit instantiation of the entity
2927 // to which they refer.
2928 if (TSK == TSK_ExplicitInstantiationDeclaration)
2931 Consumer.HandleCXXStaticMemberVarInstantiation(Var);
2933 // If we already have a definition, we're done.
2934 if (VarDecl *Def = Var->getDefinition()) {
2935 // We may be explicitly instantiating something we've already implicitly
2937 Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
2938 PointOfInstantiation);
2942 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
2946 // If we're performing recursive template instantiation, create our own
2947 // queue of pending implicit instantiations that we will instantiate later,
2948 // while we're still within our own instantiation context.
2949 SmallVector<VTableUse, 16> SavedVTableUses;
2950 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
2952 VTableUses.swap(SavedVTableUses);
2953 PendingInstantiations.swap(SavedPendingInstantiations);
2956 // Enter the scope of this instantiation. We don't use
2957 // PushDeclContext because we don't have a scope.
2958 ContextRAII previousContext(*this, Var->getDeclContext());
2959 LocalInstantiationScope Local(*this);
2961 VarDecl *OldVar = Var;
2962 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
2963 getTemplateInstantiationArgs(Var)));
2965 previousContext.pop();
2968 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
2969 assert(MSInfo && "Missing member specialization information?");
2970 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
2971 MSInfo->getPointOfInstantiation());
2972 DeclGroupRef DG(Var);
2973 Consumer.HandleTopLevelDecl(DG);
2978 // Define any newly required vtables.
2979 DefineUsedVTables();
2981 // Instantiate any pending implicit instantiations found during the
2982 // instantiation of this template.
2983 PerformPendingInstantiations();
2985 // Restore the set of pending vtables.
2986 assert(VTableUses.empty() &&
2987 "VTableUses should be empty before it is discarded, "
2988 "while instantiating static data member.");
2989 VTableUses.swap(SavedVTableUses);
2991 // Restore the set of pending implicit instantiations.
2992 assert(PendingInstantiations.empty() &&
2993 "PendingInstantiations should be empty before it is discarded, "
2994 "while instantiating static data member.");
2995 PendingInstantiations.swap(SavedPendingInstantiations);
3000 Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
3001 const CXXConstructorDecl *Tmpl,
3002 const MultiLevelTemplateArgumentList &TemplateArgs) {
3004 SmallVector<CXXCtorInitializer*, 4> NewInits;
3005 bool AnyErrors = Tmpl->isInvalidDecl();
3007 // Instantiate all the initializers.
3008 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
3009 InitsEnd = Tmpl->init_end();
3010 Inits != InitsEnd; ++Inits) {
3011 CXXCtorInitializer *Init = *Inits;
3013 // Only instantiate written initializers, let Sema re-construct implicit
3015 if (!Init->isWritten())
3018 SourceLocation EllipsisLoc;
3020 if (Init->isPackExpansion()) {
3021 // This is a pack expansion. We should expand it now.
3022 TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
3023 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3024 collectUnexpandedParameterPacks(BaseTL, Unexpanded);
3025 bool ShouldExpand = false;
3026 bool RetainExpansion = false;
3027 llvm::Optional<unsigned> NumExpansions;
3028 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
3029 BaseTL.getSourceRange(),
3031 TemplateArgs, ShouldExpand,
3035 New->setInvalidDecl();
3038 assert(ShouldExpand && "Partial instantiation of base initializer?");
3040 // Loop over all of the arguments in the argument pack(s),
3041 for (unsigned I = 0; I != *NumExpansions; ++I) {
3042 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
3044 // Instantiate the initializer.
3045 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
3046 /*CXXDirectInit=*/true);
3047 if (TempInit.isInvalid()) {
3052 // Instantiate the base type.
3053 TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
3055 Init->getSourceLocation(),
3056 New->getDeclName());
3062 // Build the initializer.
3063 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
3064 BaseTInfo, TempInit.take(),
3067 if (NewInit.isInvalid()) {
3072 NewInits.push_back(NewInit.get());
3078 // Instantiate the initializer.
3079 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
3080 /*CXXDirectInit=*/true);
3081 if (TempInit.isInvalid()) {
3086 MemInitResult NewInit;
3087 if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
3088 TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
3090 Init->getSourceLocation(),
3091 New->getDeclName());
3094 New->setInvalidDecl();
3098 if (Init->isBaseInitializer())
3099 NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.take(),
3100 New->getParent(), EllipsisLoc);
3102 NewInit = BuildDelegatingInitializer(TInfo, TempInit.take(),
3103 cast<CXXRecordDecl>(CurContext->getParent()));
3104 } else if (Init->isMemberInitializer()) {
3105 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
3106 Init->getMemberLocation(),
3111 New->setInvalidDecl();
3115 NewInit = BuildMemberInitializer(Member, TempInit.take(),
3116 Init->getSourceLocation());
3117 } else if (Init->isIndirectMemberInitializer()) {
3118 IndirectFieldDecl *IndirectMember =
3119 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
3120 Init->getMemberLocation(),
3121 Init->getIndirectMember(), TemplateArgs));
3123 if (!IndirectMember) {
3125 New->setInvalidDecl();
3129 NewInit = BuildMemberInitializer(IndirectMember, TempInit.take(),
3130 Init->getSourceLocation());
3133 if (NewInit.isInvalid()) {
3135 New->setInvalidDecl();
3137 NewInits.push_back(NewInit.get());
3141 // Assign all the initializers to the new constructor.
3142 ActOnMemInitializers(New,
3143 /*FIXME: ColonLoc */
3145 NewInits.data(), NewInits.size(),
3149 ExprResult Sema::SubstInitializer(Expr *Init,
3150 const MultiLevelTemplateArgumentList &TemplateArgs,
3151 bool CXXDirectInit) {
3152 // Initializers are instantiated like expressions, except that various outer
3153 // layers are stripped.
3157 if (ExprWithCleanups *ExprTemp = dyn_cast<ExprWithCleanups>(Init))
3158 Init = ExprTemp->getSubExpr();
3160 while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
3161 Init = Binder->getSubExpr();
3163 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
3164 Init = ICE->getSubExprAsWritten();
3166 // If this is a direct-initializer, we take apart CXXConstructExprs.
3167 // Everything else is passed through.
3168 CXXConstructExpr *Construct;
3169 if (!CXXDirectInit || !(Construct = dyn_cast<CXXConstructExpr>(Init)) ||
3170 isa<CXXTemporaryObjectExpr>(Construct))
3171 return SubstExpr(Init, TemplateArgs);
3173 SmallVector<Expr*, 8> NewArgs;
3174 if (SubstExprs(Construct->getArgs(), Construct->getNumArgs(), true,
3175 TemplateArgs, NewArgs))
3178 // Treat an empty initializer like none.
3179 if (NewArgs.empty())
3180 return Owned((Expr*)0);
3182 // Build a ParenListExpr to represent anything else.
3183 // FIXME: Fake locations!
3184 SourceLocation Loc = PP.getLocForEndOfToken(Init->getLocStart());
3185 return ActOnParenListExpr(Loc, Loc, NewArgs);
3188 // TODO: this could be templated if the various decl types used the
3189 // same method name.
3190 static bool isInstantiationOf(ClassTemplateDecl *Pattern,
3191 ClassTemplateDecl *Instance) {
3192 Pattern = Pattern->getCanonicalDecl();
3195 Instance = Instance->getCanonicalDecl();
3196 if (Pattern == Instance) return true;
3197 Instance = Instance->getInstantiatedFromMemberTemplate();
3203 static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
3204 FunctionTemplateDecl *Instance) {
3205 Pattern = Pattern->getCanonicalDecl();
3208 Instance = Instance->getCanonicalDecl();
3209 if (Pattern == Instance) return true;
3210 Instance = Instance->getInstantiatedFromMemberTemplate();
3217 isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
3218 ClassTemplatePartialSpecializationDecl *Instance) {
3220 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
3222 Instance = cast<ClassTemplatePartialSpecializationDecl>(
3223 Instance->getCanonicalDecl());
3224 if (Pattern == Instance)
3226 Instance = Instance->getInstantiatedFromMember();
3232 static bool isInstantiationOf(CXXRecordDecl *Pattern,
3233 CXXRecordDecl *Instance) {
3234 Pattern = Pattern->getCanonicalDecl();
3237 Instance = Instance->getCanonicalDecl();
3238 if (Pattern == Instance) return true;
3239 Instance = Instance->getInstantiatedFromMemberClass();
3245 static bool isInstantiationOf(FunctionDecl *Pattern,
3246 FunctionDecl *Instance) {
3247 Pattern = Pattern->getCanonicalDecl();
3250 Instance = Instance->getCanonicalDecl();
3251 if (Pattern == Instance) return true;
3252 Instance = Instance->getInstantiatedFromMemberFunction();
3258 static bool isInstantiationOf(EnumDecl *Pattern,
3259 EnumDecl *Instance) {
3260 Pattern = Pattern->getCanonicalDecl();
3263 Instance = Instance->getCanonicalDecl();
3264 if (Pattern == Instance) return true;
3265 Instance = Instance->getInstantiatedFromMemberEnum();
3271 static bool isInstantiationOf(UsingShadowDecl *Pattern,
3272 UsingShadowDecl *Instance,
3274 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
3277 static bool isInstantiationOf(UsingDecl *Pattern,
3278 UsingDecl *Instance,
3280 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
3283 static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
3284 UsingDecl *Instance,
3286 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
3289 static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
3290 UsingDecl *Instance,
3292 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
3295 static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
3296 VarDecl *Instance) {
3297 assert(Instance->isStaticDataMember());
3299 Pattern = Pattern->getCanonicalDecl();
3302 Instance = Instance->getCanonicalDecl();
3303 if (Pattern == Instance) return true;
3304 Instance = Instance->getInstantiatedFromStaticDataMember();
3310 // Other is the prospective instantiation
3311 // D is the prospective pattern
3312 static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
3313 if (D->getKind() != Other->getKind()) {
3314 if (UnresolvedUsingTypenameDecl *UUD
3315 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3316 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
3317 return isInstantiationOf(UUD, UD, Ctx);
3321 if (UnresolvedUsingValueDecl *UUD
3322 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
3323 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
3324 return isInstantiationOf(UUD, UD, Ctx);
3331 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
3332 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
3334 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
3335 return isInstantiationOf(cast<FunctionDecl>(D), Function);
3337 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
3338 return isInstantiationOf(cast<EnumDecl>(D), Enum);
3340 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
3341 if (Var->isStaticDataMember())
3342 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
3344 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
3345 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
3347 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
3348 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
3350 if (ClassTemplatePartialSpecializationDecl *PartialSpec
3351 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
3352 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
3355 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
3356 if (!Field->getDeclName()) {
3357 // This is an unnamed field.
3358 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
3363 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
3364 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
3366 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
3367 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
3369 return D->getDeclName() && isa<NamedDecl>(Other) &&
3370 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
3373 template<typename ForwardIterator>
3374 static NamedDecl *findInstantiationOf(ASTContext &Ctx,
3376 ForwardIterator first,
3377 ForwardIterator last) {
3378 for (; first != last; ++first)
3379 if (isInstantiationOf(Ctx, D, *first))
3380 return cast<NamedDecl>(*first);
3385 /// \brief Finds the instantiation of the given declaration context
3386 /// within the current instantiation.
3388 /// \returns NULL if there was an error
3389 DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
3390 const MultiLevelTemplateArgumentList &TemplateArgs) {
3391 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
3392 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
3393 return cast_or_null<DeclContext>(ID);
3397 /// \brief Find the instantiation of the given declaration within the
3398 /// current instantiation.
3400 /// This routine is intended to be used when \p D is a declaration
3401 /// referenced from within a template, that needs to mapped into the
3402 /// corresponding declaration within an instantiation. For example,
3406 /// template<typename T>
3409 /// KnownValue = sizeof(T)
3412 /// bool getKind() const { return KnownValue; }
3415 /// template struct X<int>;
3418 /// In the instantiation of X<int>::getKind(), we need to map the
3419 /// EnumConstantDecl for KnownValue (which refers to
3420 /// X<T>::\<Kind>\::KnownValue) to its instantiation
3421 /// (X<int>::\<Kind>\::KnownValue). InstantiateCurrentDeclRef() performs
3422 /// this mapping from within the instantiation of X<int>.
3423 NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
3424 const MultiLevelTemplateArgumentList &TemplateArgs) {
3425 DeclContext *ParentDC = D->getDeclContext();
3426 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
3427 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
3428 (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext()) ||
3429 (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) {
3430 // D is a local of some kind. Look into the map of local
3431 // declarations to their instantiations.
3432 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
3433 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
3434 = CurrentInstantiationScope->findInstantiationOf(D);
3437 if (Decl *FD = Found->dyn_cast<Decl *>())
3438 return cast<NamedDecl>(FD);
3440 int PackIdx = ArgumentPackSubstitutionIndex;
3441 assert(PackIdx != -1 && "found declaration pack but not pack expanding");
3442 return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
3445 // If we didn't find the decl, then we must have a label decl that hasn't
3446 // been found yet. Lazily instantiate it and return it now.
3447 assert(isa<LabelDecl>(D));
3449 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
3450 assert(Inst && "Failed to instantiate label??");
3452 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
3453 return cast<LabelDecl>(Inst);
3456 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
3457 if (!Record->isDependentContext())
3460 // Determine whether this record is the "templated" declaration describing
3461 // a class template or class template partial specialization.
3462 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
3464 ClassTemplate = ClassTemplate->getCanonicalDecl();
3465 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
3466 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
3467 ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
3469 // Walk the current context to find either the record or an instantiation of
3471 DeclContext *DC = CurContext;
3472 while (!DC->isFileContext()) {
3473 // If we're performing substitution while we're inside the template
3474 // definition, we'll find our own context. We're done.
3475 if (DC->Equals(Record))
3478 if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
3479 // Check whether we're in the process of instantiating a class template
3480 // specialization of the template we're mapping.
3481 if (ClassTemplateSpecializationDecl *InstSpec
3482 = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
3483 ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
3484 if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
3488 // Check whether we're in the process of instantiating a member class.
3489 if (isInstantiationOf(Record, InstRecord))
3494 // Move to the outer template scope.
3495 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
3496 if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){
3497 DC = FD->getLexicalDeclContext();
3502 DC = DC->getParent();
3505 // Fall through to deal with other dependent record types (e.g.,
3506 // anonymous unions in class templates).
3509 if (!ParentDC->isDependentContext())
3512 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
3516 if (ParentDC != D->getDeclContext()) {
3517 // We performed some kind of instantiation in the parent context,
3518 // so now we need to look into the instantiated parent context to
3519 // find the instantiation of the declaration D.
3521 // If our context used to be dependent, we may need to instantiate
3522 // it before performing lookup into that context.
3523 bool IsBeingInstantiated = false;
3524 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
3525 if (!Spec->isDependentContext()) {
3526 QualType T = Context.getTypeDeclType(Spec);
3527 const RecordType *Tag = T->getAs<RecordType>();
3528 assert(Tag && "type of non-dependent record is not a RecordType");
3529 if (Tag->isBeingDefined())
3530 IsBeingInstantiated = true;
3531 if (!Tag->isBeingDefined() &&
3532 RequireCompleteType(Loc, T, diag::err_incomplete_type))
3535 ParentDC = Tag->getDecl();
3539 NamedDecl *Result = 0;
3540 if (D->getDeclName()) {
3541 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
3542 Result = findInstantiationOf(Context, D, Found.first, Found.second);
3544 // Since we don't have a name for the entity we're looking for,
3545 // our only option is to walk through all of the declarations to
3546 // find that name. This will occur in a few cases:
3548 // - anonymous struct/union within a template
3549 // - unnamed class/struct/union/enum within a template
3551 // FIXME: Find a better way to find these instantiations!
3552 Result = findInstantiationOf(Context, D,
3553 ParentDC->decls_begin(),
3554 ParentDC->decls_end());
3558 if (isa<UsingShadowDecl>(D)) {
3559 // UsingShadowDecls can instantiate to nothing because of using hiding.
3560 } else if (Diags.hasErrorOccurred()) {
3561 // We've already complained about something, so most likely this
3562 // declaration failed to instantiate. There's no point in complaining
3563 // further, since this is normal in invalid code.
3564 } else if (IsBeingInstantiated) {
3565 // The class in which this member exists is currently being
3566 // instantiated, and we haven't gotten around to instantiating this
3567 // member yet. This can happen when the code uses forward declarations
3568 // of member classes, and introduces ordering dependencies via
3569 // template instantiation.
3570 Diag(Loc, diag::err_member_not_yet_instantiated)
3572 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
3573 Diag(D->getLocation(), diag::note_non_instantiated_member_here);
3574 } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
3575 // This enumeration constant was found when the template was defined,
3576 // but can't be found in the instantiation. This can happen if an
3577 // unscoped enumeration member is explicitly specialized.
3578 EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
3579 EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
3581 assert(Spec->getTemplateSpecializationKind() ==
3582 TSK_ExplicitSpecialization);
3583 Diag(Loc, diag::err_enumerator_does_not_exist)
3585 << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
3586 Diag(Spec->getLocation(), diag::note_enum_specialized_here)
3587 << Context.getTypeDeclType(Spec);
3589 // We should have found something, but didn't.
3590 llvm_unreachable("Unable to find instantiation of declaration!");
3600 /// \brief Performs template instantiation for all implicit template
3601 /// instantiations we have seen until this point.
3602 void Sema::PerformPendingInstantiations(bool LocalOnly) {
3603 // Load pending instantiations from the external source.
3604 if (!LocalOnly && ExternalSource) {
3605 SmallVector<PendingImplicitInstantiation, 4> Pending;
3606 ExternalSource->ReadPendingInstantiations(Pending);
3607 PendingInstantiations.insert(PendingInstantiations.begin(),
3608 Pending.begin(), Pending.end());
3611 while (!PendingLocalImplicitInstantiations.empty() ||
3612 (!LocalOnly && !PendingInstantiations.empty())) {
3613 PendingImplicitInstantiation Inst;
3615 if (PendingLocalImplicitInstantiations.empty()) {
3616 Inst = PendingInstantiations.front();
3617 PendingInstantiations.pop_front();
3619 Inst = PendingLocalImplicitInstantiations.front();
3620 PendingLocalImplicitInstantiations.pop_front();
3623 // Instantiate function definitions
3624 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
3625 PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(),
3626 "instantiating function definition");
3627 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
3628 TSK_ExplicitInstantiationDefinition;
3629 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true,
3630 DefinitionRequired);
3634 // Instantiate static data member definitions.
3635 VarDecl *Var = cast<VarDecl>(Inst.first);
3636 assert(Var->isStaticDataMember() && "Not a static data member?");
3638 // Don't try to instantiate declarations if the most recent redeclaration
3640 if (Var->getMostRecentDecl()->isInvalidDecl())
3643 // Check if the most recent declaration has changed the specialization kind
3644 // and removed the need for implicit instantiation.
3645 switch (Var->getMostRecentDecl()->getTemplateSpecializationKind()) {
3646 case TSK_Undeclared:
3647 llvm_unreachable("Cannot instantitiate an undeclared specialization.");
3648 case TSK_ExplicitInstantiationDeclaration:
3649 case TSK_ExplicitSpecialization:
3650 continue; // No longer need to instantiate this type.
3651 case TSK_ExplicitInstantiationDefinition:
3652 // We only need an instantiation if the pending instantiation *is* the
3653 // explicit instantiation.
3654 if (Var != Var->getMostRecentDecl()) continue;
3655 case TSK_ImplicitInstantiation:
3659 PrettyDeclStackTraceEntry CrashInfo(*this, Var, Var->getLocation(),
3660 "instantiating static data member "
3663 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
3664 TSK_ExplicitInstantiationDefinition;
3665 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true,
3666 DefinitionRequired);
3670 void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
3671 const MultiLevelTemplateArgumentList &TemplateArgs) {
3672 for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(),
3673 E = Pattern->ddiag_end(); I != E; ++I) {
3674 DependentDiagnostic *DD = *I;
3676 switch (DD->getKind()) {
3677 case DependentDiagnostic::Access:
3678 HandleDependentAccessCheck(*DD, TemplateArgs);