blob: cc9cb6317a1aeba14f0d8a20b092433d53f3e6b1 [file] [log] [blame]
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001//===--- SemaTemplateInstantiateDecl.cpp - C++ Template Decl Instantiation ===/
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//===----------------------------------------------------------------------===/
8//
9// This file implements C++ template instantiation for declarations.
10//
11//===----------------------------------------------------------------------===/
John McCall2d887082010-08-25 22:03:47 +000012#include "clang/Sema/SemaInternal.h"
Douglas Gregoraba43bb2009-05-26 20:50:29 +000013#include "clang/AST/ASTConsumer.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000014#include "clang/AST/ASTContext.h"
15#include "clang/AST/DeclTemplate.h"
16#include "clang/AST/DeclVisitor.h"
John McCall0c01d182010-03-24 05:22:00 +000017#include "clang/AST/DependentDiagnostic.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000018#include "clang/AST/Expr.h"
Douglas Gregora88cfbf2009-12-12 18:16:41 +000019#include "clang/AST/ExprCXX.h"
John McCall21ef0fa2010-03-11 09:03:00 +000020#include "clang/AST/TypeLoc.h"
Douglas Gregor83ddad32009-08-26 21:14:46 +000021#include "clang/Lex/Preprocessor.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000022#include "clang/Sema/Lookup.h"
23#include "clang/Sema/PrettyDeclStackTrace.h"
24#include "clang/Sema/Template.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000025
26using namespace clang;
27
John McCallb6217662010-03-15 10:12:16 +000028bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
29 DeclaratorDecl *NewDecl) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +000030 if (!OldDecl->getQualifierLoc())
31 return false;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +000032
Douglas Gregorc22b5ff2011-02-25 02:25:35 +000033 NestedNameSpecifierLoc NewQualifierLoc
NAKAMURA Takumia789ca92011-10-08 11:31:46 +000034 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +000035 TemplateArgs);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +000036
Douglas Gregorc22b5ff2011-02-25 02:25:35 +000037 if (!NewQualifierLoc)
John McCallb6217662010-03-15 10:12:16 +000038 return true;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +000039
Douglas Gregorc22b5ff2011-02-25 02:25:35 +000040 NewDecl->setQualifierInfo(NewQualifierLoc);
John McCallb6217662010-03-15 10:12:16 +000041 return false;
42}
43
44bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
45 TagDecl *NewDecl) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +000046 if (!OldDecl->getQualifierLoc())
47 return false;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +000048
Douglas Gregorc22b5ff2011-02-25 02:25:35 +000049 NestedNameSpecifierLoc NewQualifierLoc
NAKAMURA Takumia789ca92011-10-08 11:31:46 +000050 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +000051 TemplateArgs);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +000052
Douglas Gregorc22b5ff2011-02-25 02:25:35 +000053 if (!NewQualifierLoc)
John McCallb6217662010-03-15 10:12:16 +000054 return true;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +000055
Douglas Gregorc22b5ff2011-02-25 02:25:35 +000056 NewDecl->setQualifierInfo(NewQualifierLoc);
John McCallb6217662010-03-15 10:12:16 +000057 return false;
58}
59
DeLesley Hutchins7b9ff0c2012-01-20 22:37:06 +000060// Include attribute instantiation code.
61#include "clang/Sema/AttrTemplateInstantiate.inc"
62
Richard Smithf6565a92013-02-22 08:32:16 +000063static void instantiateDependentAlignedAttr(
64 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
65 const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion) {
66 if (Aligned->isAlignmentExpr()) {
67 // The alignment expression is a constant expression.
68 EnterExpressionEvaluationContext Unevaluated(S, Sema::ConstantEvaluated);
69 ExprResult Result = S.SubstExpr(Aligned->getAlignmentExpr(), TemplateArgs);
70 if (!Result.isInvalid())
71 S.AddAlignedAttr(Aligned->getLocation(), New, Result.takeAs<Expr>(),
72 Aligned->getSpellingListIndex(), IsPackExpansion);
73 } else {
74 TypeSourceInfo *Result = S.SubstType(Aligned->getAlignmentType(),
75 TemplateArgs, Aligned->getLocation(),
76 DeclarationName());
77 if (Result)
78 S.AddAlignedAttr(Aligned->getLocation(), New, Result,
79 Aligned->getSpellingListIndex(), IsPackExpansion);
80 }
81}
82
83static void instantiateDependentAlignedAttr(
84 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
85 const AlignedAttr *Aligned, Decl *New) {
86 if (!Aligned->isPackExpansion()) {
87 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
88 return;
89 }
90
91 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
92 if (Aligned->isAlignmentExpr())
93 S.collectUnexpandedParameterPacks(Aligned->getAlignmentExpr(),
94 Unexpanded);
95 else
96 S.collectUnexpandedParameterPacks(Aligned->getAlignmentType()->getTypeLoc(),
97 Unexpanded);
98 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
99
100 // Determine whether we can expand this attribute pack yet.
101 bool Expand = true, RetainExpansion = false;
102 Optional<unsigned> NumExpansions;
103 // FIXME: Use the actual location of the ellipsis.
104 SourceLocation EllipsisLoc = Aligned->getLocation();
105 if (S.CheckParameterPacksForExpansion(EllipsisLoc, Aligned->getRange(),
106 Unexpanded, TemplateArgs, Expand,
107 RetainExpansion, NumExpansions))
108 return;
109
110 if (!Expand) {
111 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, -1);
112 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, true);
113 } else {
114 for (unsigned I = 0; I != *NumExpansions; ++I) {
115 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, I);
116 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
117 }
118 }
119}
120
John McCall1d8d1cc2010-08-01 02:01:53 +0000121void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
DeLesley Hutchins23323e02012-01-20 22:50:54 +0000122 const Decl *Tmpl, Decl *New,
123 LateInstantiatedAttrVec *LateAttrs,
124 LocalInstantiationScope *OuterMostScope) {
Sean Huntcf807c42010-08-18 23:23:40 +0000125 for (AttrVec::const_iterator i = Tmpl->attr_begin(), e = Tmpl->attr_end();
126 i != e; ++i) {
127 const Attr *TmplAttr = *i;
DeLesley Hutchins23323e02012-01-20 22:50:54 +0000128
Chandler Carruth4ced79f2010-06-25 03:22:07 +0000129 // FIXME: This should be generalized to more than just the AlignedAttr.
Richard Smithf6565a92013-02-22 08:32:16 +0000130 const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr);
131 if (Aligned && Aligned->isAlignmentDependent()) {
132 instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New);
133 continue;
Chandler Carruth4ced79f2010-06-25 03:22:07 +0000134 }
135
Richard Smithf6565a92013-02-22 08:32:16 +0000136 assert(!TmplAttr->isPackExpansion());
DeLesley Hutchins23323e02012-01-20 22:50:54 +0000137 if (TmplAttr->isLateParsed() && LateAttrs) {
138 // Late parsed attributes must be instantiated and attached after the
139 // enclosing class has been instantiated. See Sema::InstantiateClass.
140 LocalInstantiationScope *Saved = 0;
141 if (CurrentInstantiationScope)
142 Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
143 LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
144 } else {
Richard Smithcafeb942013-06-07 02:33:37 +0000145 // Allow 'this' within late-parsed attributes.
146 NamedDecl *ND = dyn_cast<NamedDecl>(New);
147 CXXRecordDecl *ThisContext =
148 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
149 CXXThisScopeRAII ThisScope(*this, ThisContext, /*TypeQuals*/0,
150 ND && ND->isCXXInstanceMember());
151
Benjamin Kramer5bbc3852012-02-06 11:13:08 +0000152 Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
153 *this, TemplateArgs);
Rafael Espindola31c195a2012-05-15 14:09:55 +0000154 if (NewAttr)
155 New->addAttr(NewAttr);
DeLesley Hutchins23323e02012-01-20 22:50:54 +0000156 }
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000157 }
158}
159
Douglas Gregor4f722be2009-03-25 15:45:12 +0000160Decl *
161TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000162 llvm_unreachable("Translation units cannot be instantiated");
Douglas Gregor4f722be2009-03-25 15:45:12 +0000163}
164
165Decl *
Chris Lattner57ad3782011-02-17 20:34:02 +0000166TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
167 LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
168 D->getIdentifier());
169 Owner->addDecl(Inst);
170 return Inst;
171}
172
173Decl *
Douglas Gregor4f722be2009-03-25 15:45:12 +0000174TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000175 llvm_unreachable("Namespaces cannot be instantiated");
Douglas Gregor4f722be2009-03-25 15:45:12 +0000176}
177
John McCall3dbd3d52010-02-16 06:53:13 +0000178Decl *
179TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
180 NamespaceAliasDecl *Inst
181 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
182 D->getNamespaceLoc(),
183 D->getAliasLoc(),
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +0000184 D->getIdentifier(),
185 D->getQualifierLoc(),
John McCall3dbd3d52010-02-16 06:53:13 +0000186 D->getTargetNameLoc(),
187 D->getNamespace());
188 Owner->addDecl(Inst);
189 return Inst;
190}
191
Richard Smith3e4c6c42011-05-05 21:57:07 +0000192Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
193 bool IsTypeAlias) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000194 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000195 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor561f8122011-07-01 01:22:09 +0000196 if (DI->getType()->isInstantiationDependentType() ||
Douglas Gregor836adf62010-05-24 17:22:01 +0000197 DI->getType()->isVariablyModifiedType()) {
John McCallba6a9bd2009-10-24 08:00:42 +0000198 DI = SemaRef.SubstType(DI, TemplateArgs,
199 D->getLocation(), D->getDeclName());
200 if (!DI) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000201 Invalid = true;
John McCalla93c9342009-12-07 02:54:59 +0000202 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000203 }
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000204 } else {
205 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000206 }
Mike Stump1eb44332009-09-09 15:08:12 +0000207
Richard Smithb5b37d12012-10-23 00:32:41 +0000208 // HACK: g++ has a bug where it gets the value kind of ?: wrong.
209 // libstdc++ relies upon this bug in its implementation of common_type.
210 // If we happen to be processing that implementation, fake up the g++ ?:
211 // semantics. See LWG issue 2141 for more information on the bug.
212 const DecltypeType *DT = DI->getType()->getAs<DecltypeType>();
213 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
214 if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) &&
215 DT->isReferenceType() &&
216 RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() &&
217 RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") &&
218 D->getIdentifier() && D->getIdentifier()->isStr("type") &&
219 SemaRef.getSourceManager().isInSystemHeader(D->getLocStart()))
220 // Fold it to the (non-reference) type which g++ would have produced.
221 DI = SemaRef.Context.getTrivialTypeSourceInfo(
222 DI->getType().getNonReferenceType());
223
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000224 // Create the new typedef
Richard Smith162e1c12011-04-15 14:24:37 +0000225 TypedefNameDecl *Typedef;
226 if (IsTypeAlias)
227 Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
228 D->getLocation(), D->getIdentifier(), DI);
229 else
230 Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
231 D->getLocation(), D->getIdentifier(), DI);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000232 if (Invalid)
233 Typedef->setInvalidDecl();
234
John McCallcde5a402011-02-01 08:20:08 +0000235 // If the old typedef was the name for linkage purposes of an anonymous
236 // tag decl, re-establish that relationship for the new typedef.
237 if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
238 TagDecl *oldTag = oldTagType->getDecl();
Douglas Gregorc61361b2013-03-08 22:15:15 +0000239 if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) {
John McCallcde5a402011-02-01 08:20:08 +0000240 TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
John McCall83972f12013-03-09 00:54:27 +0000241 assert(!newTag->hasNameForLinkage());
Richard Smith162e1c12011-04-15 14:24:37 +0000242 newTag->setTypedefNameForAnonDecl(Typedef);
John McCallcde5a402011-02-01 08:20:08 +0000243 }
Douglas Gregord57a38e2010-04-23 16:25:07 +0000244 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000245
Douglas Gregoref96ee02012-01-14 16:38:05 +0000246 if (TypedefNameDecl *Prev = D->getPreviousDecl()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000247 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
248 TemplateArgs);
Douglas Gregorb7107222011-03-04 19:46:35 +0000249 if (!InstPrev)
250 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000251
Rafael Espindola5df37bd2011-12-26 22:42:47 +0000252 TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
253
254 // If the typedef types are not identical, reject them.
255 SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
256
257 Typedef->setPreviousDeclaration(InstPrevTypedef);
John McCall5126fd02009-12-30 00:31:22 +0000258 }
259
John McCall1d8d1cc2010-08-01 02:01:53 +0000260 SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
Douglas Gregord57a38e2010-04-23 16:25:07 +0000261
John McCall46460a62010-01-20 21:53:11 +0000262 Typedef->setAccess(D->getAccess());
Mike Stump1eb44332009-09-09 15:08:12 +0000263
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000264 return Typedef;
265}
266
Richard Smith162e1c12011-04-15 14:24:37 +0000267Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
Richard Smith3e4c6c42011-05-05 21:57:07 +0000268 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
269 Owner->addDecl(Typedef);
270 return Typedef;
Richard Smith162e1c12011-04-15 14:24:37 +0000271}
272
273Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
Richard Smith3e4c6c42011-05-05 21:57:07 +0000274 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
275 Owner->addDecl(Typedef);
276 return Typedef;
277}
278
279Decl *
280TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
281 // Create a local instantiation scope for this type alias template, which
282 // will contain the instantiations of the template parameters.
283 LocalInstantiationScope Scope(SemaRef);
284
285 TemplateParameterList *TempParams = D->getTemplateParameters();
286 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
287 if (!InstParams)
288 return 0;
289
290 TypeAliasDecl *Pattern = D->getTemplatedDecl();
291
292 TypeAliasTemplateDecl *PrevAliasTemplate = 0;
Douglas Gregoref96ee02012-01-14 16:38:05 +0000293 if (Pattern->getPreviousDecl()) {
Richard Smith3e4c6c42011-05-05 21:57:07 +0000294 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
David Blaikie3bc93e32012-12-19 00:45:41 +0000295 if (!Found.empty()) {
296 PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front());
Richard Smith3e4c6c42011-05-05 21:57:07 +0000297 }
298 }
299
300 TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
301 InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
302 if (!AliasInst)
303 return 0;
304
305 TypeAliasTemplateDecl *Inst
306 = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
307 D->getDeclName(), InstParams, AliasInst);
308 if (PrevAliasTemplate)
309 Inst->setPreviousDeclaration(PrevAliasTemplate);
310
311 Inst->setAccess(D->getAccess());
312
313 if (!PrevAliasTemplate)
314 Inst->setInstantiatedFromMemberTemplate(D);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000315
Richard Smith3e4c6c42011-05-05 21:57:07 +0000316 Owner->addDecl(Inst);
317
318 return Inst;
Richard Smith162e1c12011-04-15 14:24:37 +0000319}
320
Larisse Voufoef4579c2013-08-06 01:03:05 +0000321// FIXME: Revise for static member templates.
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000322Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
Larisse Voufo567f9172013-08-22 00:59:14 +0000323 return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false);
Larisse Voufoef4579c2013-08-06 01:03:05 +0000324}
325
Larisse Voufo567f9172013-08-22 00:59:14 +0000326Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D,
327 bool InstantiatingVarTemplate) {
Larisse Voufoef4579c2013-08-06 01:03:05 +0000328
Douglas Gregor9901c572010-05-21 00:31:19 +0000329 // If this is the variable for an anonymous struct or union,
330 // instantiate the anonymous struct/union type first.
331 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
332 if (RecordTy->getDecl()->isAnonymousStructOrUnion())
333 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
334 return 0;
335
John McCallce3ff2b2009-08-25 22:02:44 +0000336 // Do substitution on the type of the declaration
John McCalla93c9342009-12-07 02:54:59 +0000337 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
John McCall0a5fa062009-10-21 02:39:02 +0000338 TemplateArgs,
339 D->getTypeSpecStartLoc(),
340 D->getDeclName());
341 if (!DI)
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000342 return 0;
343
Douglas Gregorc6dbc3f2010-09-12 07:37:24 +0000344 if (DI->getType()->isFunctionType()) {
345 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
346 << D->isStaticDataMember() << DI->getType();
347 return 0;
348 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000349
Larisse Voufoef4579c2013-08-06 01:03:05 +0000350 // Build the instantiated declaration.
351 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner, D->getInnerLocStart(),
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000352 D->getLocation(), D->getIdentifier(),
Larisse Voufoef4579c2013-08-06 01:03:05 +0000353 DI->getType(), DI, D->getStorageClass());
Mike Stump1eb44332009-09-09 15:08:12 +0000354
Douglas Gregor9aab9c42011-12-10 01:22:52 +0000355 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +0000356 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
Douglas Gregor9aab9c42011-12-10 01:22:52 +0000357 SemaRef.inferObjCARCLifetime(Var))
358 Var->setInvalidDecl();
359
Larisse Voufoef4579c2013-08-06 01:03:05 +0000360 // Substitute the nested name specifier, if any.
361 if (SubstQualifier(D, Var))
362 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000363
Larisse Voufoef4579c2013-08-06 01:03:05 +0000364 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs,
Larisse Voufo567f9172013-08-22 00:59:14 +0000365 StartingScope, InstantiatingVarTemplate);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000366 return Var;
367}
368
Abramo Bagnara6206d532010-06-05 05:09:32 +0000369Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
370 AccessSpecDecl* AD
371 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
372 D->getAccessSpecifierLoc(), D->getColonLoc());
373 Owner->addHiddenDecl(AD);
374 return AD;
375}
376
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000377Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
378 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000379 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor561f8122011-07-01 01:22:09 +0000380 if (DI->getType()->isInstantiationDependentType() ||
Douglas Gregor836adf62010-05-24 17:22:01 +0000381 DI->getType()->isVariablyModifiedType()) {
John McCall07fb6be2009-10-22 23:33:21 +0000382 DI = SemaRef.SubstType(DI, TemplateArgs,
383 D->getLocation(), D->getDeclName());
384 if (!DI) {
John McCalla93c9342009-12-07 02:54:59 +0000385 DI = D->getTypeSourceInfo();
John McCall07fb6be2009-10-22 23:33:21 +0000386 Invalid = true;
387 } else if (DI->getType()->isFunctionType()) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000388 // C++ [temp.arg.type]p3:
389 // If a declaration acquires a function type through a type
390 // dependent on a template-parameter and this causes a
391 // declaration that does not use the syntactic form of a
392 // function declarator to have function type, the program is
393 // ill-formed.
394 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
John McCall07fb6be2009-10-22 23:33:21 +0000395 << DI->getType();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000396 Invalid = true;
397 }
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000398 } else {
399 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000400 }
401
402 Expr *BitWidth = D->getBitWidth();
403 if (Invalid)
404 BitWidth = 0;
405 else if (BitWidth) {
Richard Smithf6702a32011-12-20 02:08:33 +0000406 // The bit-width expression is a constant expression.
407 EnterExpressionEvaluationContext Unevaluated(SemaRef,
408 Sema::ConstantEvaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000409
John McCall60d7b3a2010-08-24 06:29:42 +0000410 ExprResult InstantiatedBitWidth
John McCallce3ff2b2009-08-25 22:02:44 +0000411 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000412 if (InstantiatedBitWidth.isInvalid()) {
413 Invalid = true;
414 BitWidth = 0;
415 } else
Anders Carlssone9146f22009-05-01 19:49:17 +0000416 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000417 }
418
John McCall07fb6be2009-10-22 23:33:21 +0000419 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
420 DI->getType(), DI,
Mike Stump1eb44332009-09-09 15:08:12 +0000421 cast<RecordDecl>(Owner),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000422 D->getLocation(),
423 D->isMutable(),
424 BitWidth,
Richard Smithca523302012-06-10 03:12:00 +0000425 D->getInClassInitStyle(),
Richard Smith703b6012012-05-23 04:22:22 +0000426 D->getInnerLocStart(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000427 D->getAccess(),
428 0);
Douglas Gregor663b5a02009-10-14 20:14:33 +0000429 if (!Field) {
430 cast<Decl>(Owner)->setInvalidDecl();
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000431 return 0;
Douglas Gregor663b5a02009-10-14 20:14:33 +0000432 }
Mike Stump1eb44332009-09-09 15:08:12 +0000433
DeLesley Hutchins23323e02012-01-20 22:50:54 +0000434 SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000435
Richard Smithbe507b62013-02-01 08:12:08 +0000436 if (Field->hasAttrs())
437 SemaRef.CheckAlignasUnderalignment(Field);
438
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000439 if (Invalid)
440 Field->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000441
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000442 if (!Field->getDeclName()) {
443 // Keep track of where this decl came from.
444 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000445 }
Douglas Gregor9901c572010-05-21 00:31:19 +0000446 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
447 if (Parent->isAnonymousStructOrUnion() &&
Sebastian Redl7a126a42010-08-31 00:36:30 +0000448 Parent->getRedeclContext()->isFunctionOrMethod())
Douglas Gregor9901c572010-05-21 00:31:19 +0000449 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000450 }
Mike Stump1eb44332009-09-09 15:08:12 +0000451
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000452 Field->setImplicit(D->isImplicit());
John McCall46460a62010-01-20 21:53:11 +0000453 Field->setAccess(D->getAccess());
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000454 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000455
456 return Field;
457}
458
John McCall76da55d2013-04-16 07:28:30 +0000459Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) {
460 bool Invalid = false;
461 TypeSourceInfo *DI = D->getTypeSourceInfo();
462
463 if (DI->getType()->isVariablyModifiedType()) {
464 SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified)
465 << D->getName();
466 Invalid = true;
467 } else if (DI->getType()->isInstantiationDependentType()) {
468 DI = SemaRef.SubstType(DI, TemplateArgs,
469 D->getLocation(), D->getDeclName());
470 if (!DI) {
471 DI = D->getTypeSourceInfo();
472 Invalid = true;
473 } else if (DI->getType()->isFunctionType()) {
474 // C++ [temp.arg.type]p3:
475 // If a declaration acquires a function type through a type
476 // dependent on a template-parameter and this causes a
477 // declaration that does not use the syntactic form of a
478 // function declarator to have function type, the program is
479 // ill-formed.
480 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
481 << DI->getType();
482 Invalid = true;
483 }
484 } else {
485 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
486 }
487
488 MSPropertyDecl *Property = new (SemaRef.Context)
489 MSPropertyDecl(Owner, D->getLocation(),
490 D->getDeclName(), DI->getType(), DI,
491 D->getLocStart(),
492 D->getGetterId(), D->getSetterId());
493
494 SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs,
495 StartingScope);
496
497 if (Invalid)
498 Property->setInvalidDecl();
499
500 Property->setAccess(D->getAccess());
501 Owner->addDecl(Property);
502
503 return Property;
504}
505
Francois Pichet87c2e122010-11-21 06:08:52 +0000506Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
507 NamedDecl **NamedChain =
508 new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
509
510 int i = 0;
511 for (IndirectFieldDecl::chain_iterator PI =
512 D->chain_begin(), PE = D->chain_end();
Douglas Gregorb7107222011-03-04 19:46:35 +0000513 PI != PE; ++PI) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000514 NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), *PI,
Douglas Gregorb7107222011-03-04 19:46:35 +0000515 TemplateArgs);
516 if (!Next)
517 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000518
Douglas Gregorb7107222011-03-04 19:46:35 +0000519 NamedChain[i++] = Next;
520 }
Francois Pichet87c2e122010-11-21 06:08:52 +0000521
Francois Pichet40e17752010-12-09 10:07:54 +0000522 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
Francois Pichet87c2e122010-11-21 06:08:52 +0000523 IndirectFieldDecl* IndirectField
524 = IndirectFieldDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Francois Pichet40e17752010-12-09 10:07:54 +0000525 D->getIdentifier(), T,
Francois Pichet87c2e122010-11-21 06:08:52 +0000526 NamedChain, D->getChainingSize());
527
528
529 IndirectField->setImplicit(D->isImplicit());
530 IndirectField->setAccess(D->getAccess());
531 Owner->addDecl(IndirectField);
532 return IndirectField;
533}
534
John McCall02cace72009-08-28 07:59:38 +0000535Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
John McCall02cace72009-08-28 07:59:38 +0000536 // Handle friend type expressions by simply substituting template
Douglas Gregor06245bf2010-04-07 17:57:12 +0000537 // parameters into the pattern type and checking the result.
John McCall32f2fb52010-03-25 18:04:51 +0000538 if (TypeSourceInfo *Ty = D->getFriendType()) {
Chandler Carruth4fb86f82011-05-01 00:51:33 +0000539 TypeSourceInfo *InstTy;
540 // If this is an unsupported friend, don't bother substituting template
541 // arguments into it. The actual type referred to won't be used by any
542 // parts of Clang, and may not be valid for instantiating. Just use the
543 // same info for the instantiated friend.
544 if (D->isUnsupportedFriend()) {
545 InstTy = Ty;
546 } else {
547 InstTy = SemaRef.SubstType(Ty, TemplateArgs,
548 D->getLocation(), DeclarationName());
549 }
550 if (!InstTy)
Douglas Gregor7557a132009-12-24 20:56:24 +0000551 return 0;
John McCall02cace72009-08-28 07:59:38 +0000552
Richard Smithd6f80da2012-09-20 01:31:00 +0000553 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getLocStart(),
Abramo Bagnara0216df82011-10-29 20:52:52 +0000554 D->getFriendLoc(), InstTy);
Douglas Gregor06245bf2010-04-07 17:57:12 +0000555 if (!FD)
556 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000557
Douglas Gregor06245bf2010-04-07 17:57:12 +0000558 FD->setAccess(AS_public);
John McCall9a34edb2010-10-19 01:40:49 +0000559 FD->setUnsupportedFriend(D->isUnsupportedFriend());
Douglas Gregor06245bf2010-04-07 17:57:12 +0000560 Owner->addDecl(FD);
561 return FD;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000562 }
563
Douglas Gregor06245bf2010-04-07 17:57:12 +0000564 NamedDecl *ND = D->getFriendDecl();
565 assert(ND && "friend decl must be a decl or a type!");
566
John McCallaf2094e2010-04-08 09:05:18 +0000567 // All of the Visit implementations for the various potential friend
568 // declarations have to be carefully written to work for friend
569 // objects, with the most important detail being that the target
570 // decl should almost certainly not be placed in Owner.
571 Decl *NewND = Visit(ND);
Douglas Gregor06245bf2010-04-07 17:57:12 +0000572 if (!NewND) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000573
John McCall02cace72009-08-28 07:59:38 +0000574 FriendDecl *FD =
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000575 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor06245bf2010-04-07 17:57:12 +0000576 cast<NamedDecl>(NewND), D->getFriendLoc());
John McCall5fee1102009-08-29 03:50:18 +0000577 FD->setAccess(AS_public);
John McCall9a34edb2010-10-19 01:40:49 +0000578 FD->setUnsupportedFriend(D->isUnsupportedFriend());
John McCall02cace72009-08-28 07:59:38 +0000579 Owner->addDecl(FD);
580 return FD;
John McCallfd810b12009-08-14 02:03:10 +0000581}
582
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000583Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
584 Expr *AssertExpr = D->getAssertExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000585
Richard Smithf6702a32011-12-20 02:08:33 +0000586 // The expression in a static assertion is a constant expression.
587 EnterExpressionEvaluationContext Unevaluated(SemaRef,
588 Sema::ConstantEvaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000589
John McCall60d7b3a2010-08-24 06:29:42 +0000590 ExprResult InstantiatedAssertExpr
John McCallce3ff2b2009-08-25 22:02:44 +0000591 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000592 if (InstantiatedAssertExpr.isInvalid())
593 return 0;
594
Richard Smithe3f470a2012-07-11 22:37:56 +0000595 return SemaRef.BuildStaticAssertDeclaration(D->getLocation(),
John McCall9ae2f072010-08-23 23:25:46 +0000596 InstantiatedAssertExpr.get(),
Richard Smithe3f470a2012-07-11 22:37:56 +0000597 D->getMessage(),
598 D->getRParenLoc(),
599 D->isFailed());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000600}
601
602Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Richard Smith38f0df32012-03-26 04:58:10 +0000603 EnumDecl *PrevDecl = 0;
604 if (D->getPreviousDecl()) {
605 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
606 D->getPreviousDecl(),
607 TemplateArgs);
608 if (!Prev) return 0;
609 PrevDecl = cast<EnumDecl>(Prev);
610 }
611
Abramo Bagnaraba877ad2011-03-09 14:09:51 +0000612 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000613 D->getLocation(), D->getIdentifier(),
Richard Smith38f0df32012-03-26 04:58:10 +0000614 PrevDecl, D->isScoped(),
Abramo Bagnaraa88cefd2010-12-03 18:54:17 +0000615 D->isScopedUsingClassTag(), D->isFixed());
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000616 if (D->isFixed()) {
Richard Smithf1c66b42012-03-14 23:13:10 +0000617 if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000618 // If we have type source information for the underlying type, it means it
619 // has been explicitly set by the user. Perform substitution on it before
620 // moving on.
621 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
Richard Smithf1c66b42012-03-14 23:13:10 +0000622 TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
623 DeclarationName());
624 if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000625 Enum->setIntegerType(SemaRef.Context.IntTy);
Richard Smithf1c66b42012-03-14 23:13:10 +0000626 else
627 Enum->setIntegerTypeSourceInfo(NewTI);
628 } else {
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000629 assert(!D->getIntegerType()->isDependentType()
630 && "Dependent type without type source info");
631 Enum->setIntegerType(D->getIntegerType());
632 }
633 }
634
John McCall5b629aa2010-10-22 23:36:17 +0000635 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
636
Richard Smithf1c66b42012-03-14 23:13:10 +0000637 Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000638 Enum->setAccess(D->getAccess());
John McCallb6217662010-03-15 10:12:16 +0000639 if (SubstQualifier(D, Enum)) return 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000640 Owner->addDecl(Enum);
Richard Smithf1c66b42012-03-14 23:13:10 +0000641
Richard Smith4ca93d92012-03-26 04:08:46 +0000642 EnumDecl *Def = D->getDefinition();
643 if (Def && Def != D) {
644 // If this is an out-of-line definition of an enum member template, check
645 // that the underlying types match in the instantiation of both
646 // declarations.
647 if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
648 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
649 QualType DefnUnderlying =
650 SemaRef.SubstType(TI->getType(), TemplateArgs,
651 UnderlyingLoc, DeclarationName());
652 SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
653 DefnUnderlying, Enum);
654 }
655 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000656
Douglas Gregor96084f12010-03-01 19:00:07 +0000657 if (D->getDeclContext()->isFunctionOrMethod())
658 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000659
Richard Smithf1c66b42012-03-14 23:13:10 +0000660 // C++11 [temp.inst]p1: The implicit instantiation of a class template
661 // specialization causes the implicit instantiation of the declarations, but
662 // not the definitions of scoped member enumerations.
663 // FIXME: There appears to be no wording for what happens for an enum defined
Richard Smith38f0df32012-03-26 04:58:10 +0000664 // within a block scope, but we treat that much like a member template. Only
665 // instantiate the definition when visiting the definition in that case, since
666 // we will visit all redeclarations.
667 if (!Enum->isScoped() && Def &&
668 (!D->getDeclContext()->isFunctionOrMethod() || D->isCompleteDefinition()))
Richard Smith4ca93d92012-03-26 04:08:46 +0000669 InstantiateEnumDefinition(Enum, Def);
Richard Smithf1c66b42012-03-14 23:13:10 +0000670
671 return Enum;
672}
673
674void TemplateDeclInstantiator::InstantiateEnumDefinition(
675 EnumDecl *Enum, EnumDecl *Pattern) {
676 Enum->startDefinition();
677
Richard Smith1af83c42012-03-23 03:33:32 +0000678 // Update the location to refer to the definition.
679 Enum->setLocation(Pattern->getLocation());
680
Chris Lattner5f9e2722011-07-23 10:55:15 +0000681 SmallVector<Decl*, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000682
683 EnumConstantDecl *LastEnumConst = 0;
Richard Smithf1c66b42012-03-14 23:13:10 +0000684 for (EnumDecl::enumerator_iterator EC = Pattern->enumerator_begin(),
685 ECEnd = Pattern->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000686 EC != ECEnd; ++EC) {
687 // The specified value for the enumerator.
John McCall60d7b3a2010-08-24 06:29:42 +0000688 ExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000689 if (Expr *UninstValue = EC->getInitExpr()) {
Richard Smithf6702a32011-12-20 02:08:33 +0000690 // The enumerator's value expression is a constant expression.
Mike Stump1eb44332009-09-09 15:08:12 +0000691 EnterExpressionEvaluationContext Unevaluated(SemaRef,
Richard Smithf6702a32011-12-20 02:08:33 +0000692 Sema::ConstantEvaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000693
John McCallce3ff2b2009-08-25 22:02:44 +0000694 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000695 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000696
697 // Drop the initial value and continue.
698 bool isInvalid = false;
699 if (Value.isInvalid()) {
700 Value = SemaRef.Owned((Expr *)0);
701 isInvalid = true;
702 }
703
Mike Stump1eb44332009-09-09 15:08:12 +0000704 EnumConstantDecl *EnumConst
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000705 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
706 EC->getLocation(), EC->getIdentifier(),
John McCall9ae2f072010-08-23 23:25:46 +0000707 Value.get());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000708
709 if (isInvalid) {
710 if (EnumConst)
711 EnumConst->setInvalidDecl();
712 Enum->setInvalidDecl();
713 }
714
715 if (EnumConst) {
David Blaikie581deb32012-06-06 20:45:41 +0000716 SemaRef.InstantiateAttrs(TemplateArgs, *EC, EnumConst);
John McCall5b629aa2010-10-22 23:36:17 +0000717
John McCall3b85ecf2010-01-23 22:37:59 +0000718 EnumConst->setAccess(Enum->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000719 Enum->addDecl(EnumConst);
John McCalld226f652010-08-21 09:40:31 +0000720 Enumerators.push_back(EnumConst);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000721 LastEnumConst = EnumConst;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000722
Richard Smithf1c66b42012-03-14 23:13:10 +0000723 if (Pattern->getDeclContext()->isFunctionOrMethod() &&
724 !Enum->isScoped()) {
Douglas Gregor96084f12010-03-01 19:00:07 +0000725 // If the enumeration is within a function or method, record the enum
726 // constant as a local.
David Blaikie581deb32012-06-06 20:45:41 +0000727 SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst);
Douglas Gregor96084f12010-03-01 19:00:07 +0000728 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000729 }
730 }
Mike Stump1eb44332009-09-09 15:08:12 +0000731
Richard Smithf1c66b42012-03-14 23:13:10 +0000732 // FIXME: Fixup LBraceLoc
733 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(),
734 Enum->getRBraceLoc(), Enum,
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +0000735 Enumerators,
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000736 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000737}
738
Douglas Gregor6477b692009-03-25 15:04:13 +0000739Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000740 llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
Douglas Gregor6477b692009-03-25 15:04:13 +0000741}
742
John McCalle29ba202009-08-20 01:44:21 +0000743Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
John McCall93ba8572010-03-25 06:39:04 +0000744 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
745
Douglas Gregor550d9b22009-10-31 17:21:17 +0000746 // Create a local instantiation scope for this class template, which
747 // will contain the instantiations of the template parameters.
John McCall2a7fb272010-08-25 05:32:35 +0000748 LocalInstantiationScope Scope(SemaRef);
John McCalle29ba202009-08-20 01:44:21 +0000749 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000750 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000751 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000752 return NULL;
John McCalle29ba202009-08-20 01:44:21 +0000753
754 CXXRecordDecl *Pattern = D->getTemplatedDecl();
John McCall93ba8572010-03-25 06:39:04 +0000755
756 // Instantiate the qualifier. We have to do this first in case
757 // we're a friend declaration, because if we are then we need to put
758 // the new declaration in the appropriate context.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000759 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
760 if (QualifierLoc) {
761 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
762 TemplateArgs);
763 if (!QualifierLoc)
764 return 0;
John McCall93ba8572010-03-25 06:39:04 +0000765 }
766
767 CXXRecordDecl *PrevDecl = 0;
768 ClassTemplateDecl *PrevClassTemplate = 0;
769
Douglas Gregoref96ee02012-01-14 16:38:05 +0000770 if (!isFriend && Pattern->getPreviousDecl()) {
Nick Lewycky37574f52010-11-08 23:29:42 +0000771 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
David Blaikie3bc93e32012-12-19 00:45:41 +0000772 if (!Found.empty()) {
773 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
Nick Lewycky37574f52010-11-08 23:29:42 +0000774 if (PrevClassTemplate)
775 PrevDecl = PrevClassTemplate->getTemplatedDecl();
776 }
777 }
778
John McCall93ba8572010-03-25 06:39:04 +0000779 // If this isn't a friend, then it's a member template, in which
780 // case we just want to build the instantiation in the
781 // specialization. If it is a friend, we want to build it in
782 // the appropriate context.
783 DeclContext *DC = Owner;
784 if (isFriend) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000785 if (QualifierLoc) {
John McCall93ba8572010-03-25 06:39:04 +0000786 CXXScopeSpec SS;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000787 SS.Adopt(QualifierLoc);
John McCall93ba8572010-03-25 06:39:04 +0000788 DC = SemaRef.computeDeclContext(SS);
789 if (!DC) return 0;
790 } else {
791 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
792 Pattern->getDeclContext(),
793 TemplateArgs);
794 }
795
796 // Look for a previous declaration of the template in the owning
797 // context.
798 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
799 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
800 SemaRef.LookupQualifiedName(R, DC);
801
802 if (R.isSingleResult()) {
803 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
804 if (PrevClassTemplate)
805 PrevDecl = PrevClassTemplate->getTemplatedDecl();
806 }
807
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000808 if (!PrevClassTemplate && QualifierLoc) {
John McCall93ba8572010-03-25 06:39:04 +0000809 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
Douglas Gregor1eabb7d2010-03-31 23:17:41 +0000810 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000811 << QualifierLoc.getSourceRange();
John McCall93ba8572010-03-25 06:39:04 +0000812 return 0;
813 }
814
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000815 bool AdoptedPreviousTemplateParams = false;
John McCall93ba8572010-03-25 06:39:04 +0000816 if (PrevClassTemplate) {
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000817 bool Complain = true;
818
819 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
820 // template for struct std::tr1::__detail::_Map_base, where the
821 // template parameters of the friend declaration don't match the
822 // template parameters of the original declaration. In this one
823 // case, we don't complain about the ill-formed friend
824 // declaration.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000825 if (isFriend && Pattern->getIdentifier() &&
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000826 Pattern->getIdentifier()->isStr("_Map_base") &&
827 DC->isNamespace() &&
828 cast<NamespaceDecl>(DC)->getIdentifier() &&
829 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
830 DeclContext *DCParent = DC->getParent();
831 if (DCParent->isNamespace() &&
832 cast<NamespaceDecl>(DCParent)->getIdentifier() &&
833 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
834 DeclContext *DCParent2 = DCParent->getParent();
835 if (DCParent2->isNamespace() &&
836 cast<NamespaceDecl>(DCParent2)->getIdentifier() &&
837 cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") &&
838 DCParent2->getParent()->isTranslationUnit())
839 Complain = false;
840 }
841 }
842
John McCall93ba8572010-03-25 06:39:04 +0000843 TemplateParameterList *PrevParams
844 = PrevClassTemplate->getTemplateParameters();
845
846 // Make sure the parameter lists match.
847 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000848 Complain,
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000849 Sema::TPL_TemplateMatch)) {
850 if (Complain)
851 return 0;
852
853 AdoptedPreviousTemplateParams = true;
854 InstParams = PrevParams;
855 }
John McCall93ba8572010-03-25 06:39:04 +0000856
857 // Do some additional validation, then merge default arguments
858 // from the existing declarations.
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000859 if (!AdoptedPreviousTemplateParams &&
860 SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
John McCall93ba8572010-03-25 06:39:04 +0000861 Sema::TPC_ClassTemplate))
862 return 0;
863 }
864 }
865
John McCalle29ba202009-08-20 01:44:21 +0000866 CXXRecordDecl *RecordInst
John McCall93ba8572010-03-25 06:39:04 +0000867 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +0000868 Pattern->getLocStart(), Pattern->getLocation(),
869 Pattern->getIdentifier(), PrevDecl,
Douglas Gregorf0510d42009-10-12 23:11:44 +0000870 /*DelayTypeCreation=*/true);
John McCalle29ba202009-08-20 01:44:21 +0000871
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000872 if (QualifierLoc)
873 RecordInst->setQualifierInfo(QualifierLoc);
John McCallb6217662010-03-15 10:12:16 +0000874
John McCalle29ba202009-08-20 01:44:21 +0000875 ClassTemplateDecl *Inst
John McCall93ba8572010-03-25 06:39:04 +0000876 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
877 D->getIdentifier(), InstParams, RecordInst,
878 PrevClassTemplate);
John McCalle29ba202009-08-20 01:44:21 +0000879 RecordInst->setDescribedClassTemplate(Inst);
John McCallea7390c2010-04-08 20:25:50 +0000880
John McCall93ba8572010-03-25 06:39:04 +0000881 if (isFriend) {
John McCallea7390c2010-04-08 20:25:50 +0000882 if (PrevClassTemplate)
883 Inst->setAccess(PrevClassTemplate->getAccess());
884 else
885 Inst->setAccess(D->getAccess());
886
Richard Smith22050f22013-07-17 23:53:16 +0000887 Inst->setObjectOfFriendDecl();
John McCall93ba8572010-03-25 06:39:04 +0000888 // TODO: do we want to track the instantiation progeny of this
889 // friend target decl?
890 } else {
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000891 Inst->setAccess(D->getAccess());
Nick Lewycky37574f52010-11-08 23:29:42 +0000892 if (!PrevClassTemplate)
893 Inst->setInstantiatedFromMemberTemplate(D);
John McCall93ba8572010-03-25 06:39:04 +0000894 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000895
Douglas Gregorf0510d42009-10-12 23:11:44 +0000896 // Trigger creation of the type for the instantiation.
John McCall3cb0ebd2010-03-10 03:28:59 +0000897 SemaRef.Context.getInjectedClassNameType(RecordInst,
Douglas Gregor24bae922010-07-08 18:37:38 +0000898 Inst->getInjectedClassNameSpecialization());
John McCallea7390c2010-04-08 20:25:50 +0000899
Douglas Gregor259571e2009-10-30 22:42:42 +0000900 // Finish handling of friends.
John McCall93ba8572010-03-25 06:39:04 +0000901 if (isFriend) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +0000902 DC->makeDeclVisibleInContext(Inst);
Abramo Bagnara4c515482011-11-26 13:33:46 +0000903 Inst->setLexicalDeclContext(Owner);
904 RecordInst->setLexicalDeclContext(Owner);
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000905 return Inst;
Douglas Gregor259571e2009-10-30 22:42:42 +0000906 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000907
Abramo Bagnara4c515482011-11-26 13:33:46 +0000908 if (D->isOutOfLine()) {
909 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
910 RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
911 }
912
John McCalle29ba202009-08-20 01:44:21 +0000913 Owner->addDecl(Inst);
Douglas Gregord65587f2010-11-10 19:44:59 +0000914
915 if (!PrevClassTemplate) {
916 // Queue up any out-of-line partial specializations of this member
917 // class template; the client will force their instantiation once
918 // the enclosing class has been instantiated.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000919 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
Douglas Gregord65587f2010-11-10 19:44:59 +0000920 D->getPartialSpecializations(PartialSpecs);
921 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
922 if (PartialSpecs[I]->isOutOfLine())
923 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
924 }
925
John McCalle29ba202009-08-20 01:44:21 +0000926 return Inst;
927}
928
Douglas Gregord60e1052009-08-27 16:57:43 +0000929Decl *
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000930TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
931 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregored9c0f92009-10-29 00:04:11 +0000932 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000933
Douglas Gregored9c0f92009-10-29 00:04:11 +0000934 // Lookup the already-instantiated declaration in the instantiation
935 // of the class template and return that.
936 DeclContext::lookup_result Found
937 = Owner->lookup(ClassTemplate->getDeclName());
David Blaikie3bc93e32012-12-19 00:45:41 +0000938 if (Found.empty())
Douglas Gregored9c0f92009-10-29 00:04:11 +0000939 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000940
Douglas Gregored9c0f92009-10-29 00:04:11 +0000941 ClassTemplateDecl *InstClassTemplate
David Blaikie3bc93e32012-12-19 00:45:41 +0000942 = dyn_cast<ClassTemplateDecl>(Found.front());
Douglas Gregored9c0f92009-10-29 00:04:11 +0000943 if (!InstClassTemplate)
944 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000945
Douglas Gregord65587f2010-11-10 19:44:59 +0000946 if (ClassTemplatePartialSpecializationDecl *Result
947 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
948 return Result;
949
950 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000951}
952
Larisse Voufoef4579c2013-08-06 01:03:05 +0000953Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) {
954 assert(D->getTemplatedDecl()->isStaticDataMember() &&
955 "Only static data member templates are allowed.");
Larisse Voufoef4579c2013-08-06 01:03:05 +0000956
957 // Create a local instantiation scope for this variable template, which
958 // will contain the instantiations of the template parameters.
959 LocalInstantiationScope Scope(SemaRef);
960 TemplateParameterList *TempParams = D->getTemplateParameters();
961 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
962 if (!InstParams)
963 return NULL;
964
965 VarDecl *Pattern = D->getTemplatedDecl();
966 VarTemplateDecl *PrevVarTemplate = 0;
967
968 if (Pattern->getPreviousDecl()) {
969 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
970 if (!Found.empty())
971 PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
972 }
973
Richard Smithdd9459f2013-08-13 18:18:50 +0000974 VarDecl *VarInst =
Larisse Voufo567f9172013-08-22 00:59:14 +0000975 cast_or_null<VarDecl>(VisitVarDecl(Pattern,
976 /*InstantiatingVarTemplate=*/true));
Larisse Voufoef4579c2013-08-06 01:03:05 +0000977
978 DeclContext *DC = Owner;
979
Larisse Voufoef4579c2013-08-06 01:03:05 +0000980 VarTemplateDecl *Inst = VarTemplateDecl::Create(
981 SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams,
982 VarInst, PrevVarTemplate);
983 VarInst->setDescribedVarTemplate(Inst);
984
985 Inst->setAccess(D->getAccess());
986 if (!PrevVarTemplate)
987 Inst->setInstantiatedFromMemberTemplate(D);
988
989 if (D->isOutOfLine()) {
990 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
991 VarInst->setLexicalDeclContext(D->getLexicalDeclContext());
992 }
993
994 Owner->addDecl(Inst);
995
996 if (!PrevVarTemplate) {
997 // Queue up any out-of-line partial specializations of this member
998 // variable template; the client will force their instantiation once
999 // the enclosing class has been instantiated.
1000 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1001 D->getPartialSpecializations(PartialSpecs);
1002 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
1003 if (PartialSpecs[I]->isOutOfLine())
1004 OutOfLineVarPartialSpecs.push_back(
1005 std::make_pair(Inst, PartialSpecs[I]));
1006 }
1007
1008 return Inst;
1009}
1010
1011Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl(
1012 VarTemplatePartialSpecializationDecl *D) {
1013 assert(D->isStaticDataMember() &&
1014 "Only static data member templates are allowed.");
Larisse Voufoef4579c2013-08-06 01:03:05 +00001015
1016 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
1017
1018 // Lookup the already-instantiated declaration and return that.
1019 DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName());
1020 assert(!Found.empty() && "Instantiation found nothing?");
1021
1022 VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1023 assert(InstVarTemplate && "Instantiation did not find a variable template?");
1024
1025 if (VarTemplatePartialSpecializationDecl *Result =
1026 InstVarTemplate->findPartialSpecInstantiatedFromMember(D))
1027 return Result;
1028
1029 return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D);
1030}
1031
Douglas Gregor7974c3b2009-10-07 17:21:34 +00001032Decl *
Douglas Gregord60e1052009-08-27 16:57:43 +00001033TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00001034 // Create a local instantiation scope for this function template, which
1035 // will contain the instantiations of the template parameters and then get
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001036 // merged with the local instantiation scope for the function template
Douglas Gregor550d9b22009-10-31 17:21:17 +00001037 // itself.
John McCall2a7fb272010-08-25 05:32:35 +00001038 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor895162d2010-04-30 18:55:50 +00001039
Douglas Gregord60e1052009-08-27 16:57:43 +00001040 TemplateParameterList *TempParams = D->getTemplateParameters();
1041 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +00001042 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +00001043 return NULL;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001044
Douglas Gregora735b202009-10-13 14:39:41 +00001045 FunctionDecl *Instantiated = 0;
1046 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001047 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
Douglas Gregora735b202009-10-13 14:39:41 +00001048 InstParams));
1049 else
1050 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001051 D->getTemplatedDecl(),
Douglas Gregora735b202009-10-13 14:39:41 +00001052 InstParams));
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001053
Douglas Gregora735b202009-10-13 14:39:41 +00001054 if (!Instantiated)
Douglas Gregord60e1052009-08-27 16:57:43 +00001055 return 0;
1056
Mike Stump1eb44332009-09-09 15:08:12 +00001057 // Link the instantiated function template declaration to the function
Douglas Gregord60e1052009-08-27 16:57:43 +00001058 // template from which it was instantiated.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001059 FunctionTemplateDecl *InstTemplate
Douglas Gregora735b202009-10-13 14:39:41 +00001060 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregor37d681852009-10-12 22:27:17 +00001061 InstTemplate->setAccess(D->getAccess());
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001062 assert(InstTemplate &&
Douglas Gregora735b202009-10-13 14:39:41 +00001063 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCalle976ffe2009-12-14 23:19:40 +00001064
John McCallb1a56e72010-03-26 23:10:15 +00001065 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
1066
John McCalle976ffe2009-12-14 23:19:40 +00001067 // Link the instantiation back to the pattern *unless* this is a
1068 // non-definition friend declaration.
1069 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
John McCallb1a56e72010-03-26 23:10:15 +00001070 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregora735b202009-10-13 14:39:41 +00001071 InstTemplate->setInstantiatedFromMemberTemplate(D);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001072
John McCallb1a56e72010-03-26 23:10:15 +00001073 // Make declarations visible in the appropriate context.
John McCall1f2e1a92012-08-10 03:15:35 +00001074 if (!isFriend) {
Douglas Gregora735b202009-10-13 14:39:41 +00001075 Owner->addDecl(InstTemplate);
John McCall1f2e1a92012-08-10 03:15:35 +00001076 } else if (InstTemplate->getDeclContext()->isRecord() &&
1077 !D->getPreviousDecl()) {
1078 SemaRef.CheckFriendAccess(InstTemplate);
1079 }
John McCallb1a56e72010-03-26 23:10:15 +00001080
Douglas Gregord60e1052009-08-27 16:57:43 +00001081 return InstTemplate;
1082}
1083
Douglas Gregord475b8d2009-03-25 21:17:03 +00001084Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
1085 CXXRecordDecl *PrevDecl = 0;
1086 if (D->isInjectedClassName())
1087 PrevDecl = cast<CXXRecordDecl>(Owner);
Douglas Gregoref96ee02012-01-14 16:38:05 +00001088 else if (D->getPreviousDecl()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001089 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
Douglas Gregoref96ee02012-01-14 16:38:05 +00001090 D->getPreviousDecl(),
John McCall6c1c1b82009-12-15 22:29:06 +00001091 TemplateArgs);
1092 if (!Prev) return 0;
1093 PrevDecl = cast<CXXRecordDecl>(Prev);
1094 }
Douglas Gregord475b8d2009-03-25 21:17:03 +00001095
1096 CXXRecordDecl *Record
Mike Stump1eb44332009-09-09 15:08:12 +00001097 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001098 D->getLocStart(), D->getLocation(),
1099 D->getIdentifier(), PrevDecl);
John McCallb6217662010-03-15 10:12:16 +00001100
1101 // Substitute the nested name specifier, if any.
1102 if (SubstQualifier(D, Record))
1103 return 0;
1104
Douglas Gregord475b8d2009-03-25 21:17:03 +00001105 Record->setImplicit(D->isImplicit());
Eli Friedmaneaba1af2009-08-27 19:11:42 +00001106 // FIXME: Check against AS_none is an ugly hack to work around the issue that
1107 // the tag decls introduced by friend class declarations don't have an access
1108 // specifier. Remove once this area of the code gets sorted out.
1109 if (D->getAccess() != AS_none)
1110 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +00001111 if (!D->isInjectedClassName())
Douglas Gregorf6b11852009-10-08 15:14:33 +00001112 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +00001113
John McCall02cace72009-08-28 07:59:38 +00001114 // If the original function was part of a friend declaration,
1115 // inherit its namespace state.
Richard Smith22050f22013-07-17 23:53:16 +00001116 if (D->getFriendObjectKind())
1117 Record->setObjectOfFriendDecl();
John McCall02cace72009-08-28 07:59:38 +00001118
Douglas Gregor9901c572010-05-21 00:31:19 +00001119 // Make sure that anonymous structs and unions are recorded.
1120 if (D->isAnonymousStructOrUnion()) {
1121 Record->setAnonymousStructOrUnion(true);
Sebastian Redl7a126a42010-08-31 00:36:30 +00001122 if (Record->getDeclContext()->getRedeclContext()->isFunctionOrMethod())
Douglas Gregor9901c572010-05-21 00:31:19 +00001123 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
1124 }
Anders Carlssond8b285f2009-09-01 04:26:58 +00001125
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001126 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +00001127 return Record;
1128}
1129
Douglas Gregor71074fd2012-09-13 21:56:43 +00001130/// \brief Adjust the given function type for an instantiation of the
1131/// given declaration, to cope with modifications to the function's type that
1132/// aren't reflected in the type-source information.
1133///
1134/// \param D The declaration we're instantiating.
1135/// \param TInfo The already-instantiated type.
1136static QualType adjustFunctionTypeForInstantiation(ASTContext &Context,
1137 FunctionDecl *D,
1138 TypeSourceInfo *TInfo) {
Douglas Gregorbed51fe2012-09-13 22:01:49 +00001139 const FunctionProtoType *OrigFunc
1140 = D->getType()->castAs<FunctionProtoType>();
1141 const FunctionProtoType *NewFunc
1142 = TInfo->getType()->castAs<FunctionProtoType>();
1143 if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
1144 return TInfo->getType();
1145
1146 FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
1147 NewEPI.ExtInfo = OrigFunc->getExtInfo();
1148 return Context.getFunctionType(NewFunc->getResultType(),
Reid Kleckner0567a792013-06-10 20:51:09 +00001149 NewFunc->getArgTypes(), NewEPI);
Douglas Gregor71074fd2012-09-13 21:56:43 +00001150}
1151
John McCall02cace72009-08-28 07:59:38 +00001152/// Normal class members are of more specific types and therefore
1153/// don't make it here. This function serves two purposes:
1154/// 1) instantiating function templates
1155/// 2) substituting friend declarations
1156/// FIXME: preserve function definitions in case #2
Douglas Gregor7557a132009-12-24 20:56:24 +00001157Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
Douglas Gregora735b202009-10-13 14:39:41 +00001158 TemplateParameterList *TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +00001159 // Check whether there is already a function template specialization for
1160 // this declaration.
1161 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
John McCallb0cb0222010-03-27 05:57:59 +00001162 if (FunctionTemplate && !TemplateParams) {
Richard Smithc95d4132013-05-03 23:46:09 +00001163 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Mike Stump1eb44332009-09-09 15:08:12 +00001164
Douglas Gregor1e1e9722012-03-28 14:34:23 +00001165 void *InsertPos = 0;
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001166 FunctionDecl *SpecFunc
Richard Smithc95d4132013-05-03 23:46:09 +00001167 = FunctionTemplate->findSpecialization(Innermost.begin(), Innermost.size(),
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001168 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001169
Douglas Gregor127102b2009-06-29 20:59:39 +00001170 // If we already have a function template specialization, return it.
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001171 if (SpecFunc)
1172 return SpecFunc;
Douglas Gregor127102b2009-06-29 20:59:39 +00001173 }
Mike Stump1eb44332009-09-09 15:08:12 +00001174
John McCallb0cb0222010-03-27 05:57:59 +00001175 bool isFriend;
1176 if (FunctionTemplate)
1177 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1178 else
1179 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1180
Douglas Gregor79c22782010-01-16 20:21:20 +00001181 bool MergeWithParentScope = (TemplateParams != 0) ||
Douglas Gregorb212d9a2010-05-21 21:25:08 +00001182 Owner->isFunctionOrMethod() ||
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001183 !(isa<Decl>(Owner) &&
Douglas Gregor79c22782010-01-16 20:21:20 +00001184 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall2a7fb272010-08-25 05:32:35 +00001185 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +00001186
Chris Lattner5f9e2722011-07-23 10:55:15 +00001187 SmallVector<ParmVarDecl *, 4> Params;
David Blaikie64b4b432011-11-10 05:42:04 +00001188 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
John McCall21ef0fa2010-03-11 09:03:00 +00001189 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001190 return 0;
Douglas Gregor71074fd2012-09-13 21:56:43 +00001191 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
John McCallfd810b12009-08-14 02:03:10 +00001192
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001193 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1194 if (QualifierLoc) {
1195 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1196 TemplateArgs);
1197 if (!QualifierLoc)
1198 return 0;
John McCalld325daa2010-03-26 04:53:08 +00001199 }
1200
John McCall68b6b872010-02-06 01:50:47 +00001201 // If we're instantiating a local function declaration, put the result
1202 // in the owner; otherwise we need to find the instantiated context.
1203 DeclContext *DC;
1204 if (D->getDeclContext()->isFunctionOrMethod())
1205 DC = Owner;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001206 else if (isFriend && QualifierLoc) {
John McCalld325daa2010-03-26 04:53:08 +00001207 CXXScopeSpec SS;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001208 SS.Adopt(QualifierLoc);
John McCalld325daa2010-03-26 04:53:08 +00001209 DC = SemaRef.computeDeclContext(SS);
1210 if (!DC) return 0;
1211 } else {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001212 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001213 TemplateArgs);
John McCalld325daa2010-03-26 04:53:08 +00001214 }
John McCall68b6b872010-02-06 01:50:47 +00001215
John McCall02cace72009-08-28 07:59:38 +00001216 FunctionDecl *Function =
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001217 FunctionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
Abramo Bagnara635311f2012-10-04 21:40:42 +00001218 D->getNameInfo(), T, TInfo,
Rafael Espindola459ef032013-04-16 02:29:15 +00001219 D->getCanonicalDecl()->getStorageClass(),
Richard Smithaf1fc7a2011-08-15 21:04:07 +00001220 D->isInlineSpecified(), D->hasWrittenPrototype(),
Richard Smith86c3ae42012-02-13 03:54:03 +00001221 D->isConstexpr());
Enea Zaffanellade9ed712013-07-19 18:02:36 +00001222 Function->setRangeEnd(D->getSourceRange().getEnd());
John McCallb6217662010-03-15 10:12:16 +00001223
Richard Smithd4497dd2013-01-25 00:08:28 +00001224 if (D->isInlined())
1225 Function->setImplicitlyInline();
1226
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001227 if (QualifierLoc)
1228 Function->setQualifierInfo(QualifierLoc);
John McCallb6217662010-03-15 10:12:16 +00001229
John McCallb1a56e72010-03-26 23:10:15 +00001230 DeclContext *LexicalDC = Owner;
1231 if (!isFriend && D->isOutOfLine()) {
1232 assert(D->getDeclContext()->isFileContext());
1233 LexicalDC = D->getDeclContext();
1234 }
1235
1236 Function->setLexicalDeclContext(LexicalDC);
Mike Stump1eb44332009-09-09 15:08:12 +00001237
Douglas Gregore53060f2009-06-25 22:08:12 +00001238 // Attach the parameters
Reid Klecknerc66e7e92013-07-31 21:00:18 +00001239 for (unsigned P = 0; P < Params.size(); ++P)
1240 if (Params[P])
1241 Params[P]->setOwningFunction(Function);
David Blaikie4278c652011-09-21 18:16:56 +00001242 Function->setParams(Params);
John McCall02cace72009-08-28 07:59:38 +00001243
Douglas Gregorac7c2c82010-05-17 16:38:00 +00001244 SourceLocation InstantiateAtPOI;
Douglas Gregora735b202009-10-13 14:39:41 +00001245 if (TemplateParams) {
1246 // Our resulting instantiation is actually a function template, since we
1247 // are substituting only the outer template parameters. For example, given
1248 //
1249 // template<typename T>
1250 // struct X {
1251 // template<typename U> friend void f(T, U);
1252 // };
1253 //
1254 // X<int> x;
1255 //
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001256 // We are instantiating the friend function template "f" within X<int>,
Douglas Gregora735b202009-10-13 14:39:41 +00001257 // which means substituting int for T, but leaving "f" as a friend function
1258 // template.
1259 // Build the function template itself.
John McCalld325daa2010-03-26 04:53:08 +00001260 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
Douglas Gregora735b202009-10-13 14:39:41 +00001261 Function->getLocation(),
1262 Function->getDeclName(),
1263 TemplateParams, Function);
1264 Function->setDescribedFunctionTemplate(FunctionTemplate);
John McCallb1a56e72010-03-26 23:10:15 +00001265
1266 FunctionTemplate->setLexicalDeclContext(LexicalDC);
John McCalld325daa2010-03-26 04:53:08 +00001267
1268 if (isFriend && D->isThisDeclarationADefinition()) {
1269 // TODO: should we remember this connection regardless of whether
1270 // the friend declaration provided a body?
1271 FunctionTemplate->setInstantiatedFromMemberTemplate(
1272 D->getDescribedFunctionTemplate());
1273 }
Douglas Gregor66724ea2009-11-14 01:20:54 +00001274 } else if (FunctionTemplate) {
1275 // Record this function template specialization.
Richard Smithc95d4132013-05-03 23:46:09 +00001276 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Douglas Gregor838db382010-02-11 01:19:42 +00001277 Function->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00001278 TemplateArgumentList::CreateCopy(SemaRef.Context,
Richard Smithc95d4132013-05-03 23:46:09 +00001279 Innermost.begin(),
1280 Innermost.size()),
Douglas Gregor1e1e9722012-03-28 14:34:23 +00001281 /*InsertPos=*/0);
Chandler Carruth80f5b162011-08-18 09:09:59 +00001282 } else if (isFriend) {
1283 // Note, we need this connection even if the friend doesn't have a body.
1284 // Its body may exist but not have been attached yet due to deferred
1285 // parsing.
1286 // FIXME: It might be cleaner to set this when attaching the body to the
1287 // friend function declaration, however that would require finding all the
1288 // instantiations and modifying them.
John McCalld325daa2010-03-26 04:53:08 +00001289 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
John McCall02cace72009-08-28 07:59:38 +00001290 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001291
Douglas Gregore53060f2009-06-25 22:08:12 +00001292 if (InitFunctionInstantiation(Function, D))
1293 Function->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001294
John McCallaf2094e2010-04-08 09:05:18 +00001295 bool isExplicitSpecialization = false;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001296
John McCall68263142009-11-18 22:49:29 +00001297 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
1298 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
1299
John McCallaf2094e2010-04-08 09:05:18 +00001300 if (DependentFunctionTemplateSpecializationInfo *Info
1301 = D->getDependentSpecializationInfo()) {
1302 assert(isFriend && "non-friend has dependent specialization info?");
1303
1304 // This needs to be set now for future sanity.
Richard Smith22050f22013-07-17 23:53:16 +00001305 Function->setObjectOfFriendDecl();
John McCallaf2094e2010-04-08 09:05:18 +00001306
1307 // Instantiate the explicit template arguments.
1308 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1309 Info->getRAngleLoc());
Douglas Gregore02e2622010-12-22 21:19:48 +00001310 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1311 ExplicitArgs, TemplateArgs))
1312 return 0;
John McCallaf2094e2010-04-08 09:05:18 +00001313
1314 // Map the candidate templates to their instantiations.
1315 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1316 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1317 Info->getTemplate(I),
1318 TemplateArgs);
1319 if (!Temp) return 0;
1320
1321 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1322 }
1323
1324 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1325 &ExplicitArgs,
1326 Previous))
1327 Function->setInvalidDecl();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001328
John McCallaf2094e2010-04-08 09:05:18 +00001329 isExplicitSpecialization = true;
1330
1331 } else if (TemplateParams || !FunctionTemplate) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001332 // Look only into the namespace where the friend would be declared to
1333 // find a previous declaration. This is the innermost enclosing namespace,
Douglas Gregora735b202009-10-13 14:39:41 +00001334 // as described in ActOnFriendFunctionDecl.
John McCall68263142009-11-18 22:49:29 +00001335 SemaRef.LookupQualifiedName(Previous, DC);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001336
Douglas Gregora735b202009-10-13 14:39:41 +00001337 // In C++, the previous declaration we find might be a tag type
1338 // (class or enum). In this case, the new declaration will hide the
1339 // tag type. Note that this does does not apply if we're declaring a
1340 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001341 if (Previous.isSingleTagDecl())
1342 Previous.clear();
Douglas Gregora735b202009-10-13 14:39:41 +00001343 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001344
John McCall9f54ad42009-12-10 09:41:52 +00001345 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00001346 isExplicitSpecialization);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001347
John McCall76d32642010-04-24 01:30:58 +00001348 NamedDecl *PrincipalDecl = (TemplateParams
1349 ? cast<NamedDecl>(FunctionTemplate)
1350 : Function);
1351
Douglas Gregora735b202009-10-13 14:39:41 +00001352 // If the original function was part of a friend declaration,
1353 // inherit its namespace state and add it to the owner.
John McCalld325daa2010-03-26 04:53:08 +00001354 if (isFriend) {
Richard Smith22050f22013-07-17 23:53:16 +00001355 PrincipalDecl->setObjectOfFriendDecl();
Richard Smith1b7f9cb2012-03-13 03:12:56 +00001356 DC->makeDeclVisibleInContext(PrincipalDecl);
Gabor Greifab297ac2010-08-30 21:10:05 +00001357
Gabor Greif77535df2010-08-30 22:25:56 +00001358 bool queuedInstantiation = false;
Gabor Greifab297ac2010-08-30 21:10:05 +00001359
Richard Smith53e53512011-10-19 00:54:10 +00001360 // C++98 [temp.friend]p5: When a function is defined in a friend function
1361 // declaration in a class template, the function is defined at each
1362 // instantiation of the class template. The function is defined even if it
1363 // is never used.
1364 // C++11 [temp.friend]p4: When a function is defined in a friend function
1365 // declaration in a class template, the function is instantiated when the
1366 // function is odr-used.
1367 //
1368 // If -Wc++98-compat is enabled, we go through the motions of checking for a
1369 // redefinition, but don't instantiate the function.
Richard Smith80ad52f2013-01-02 11:42:31 +00001370 if ((!SemaRef.getLangOpts().CPlusPlus11 ||
Richard Smith53e53512011-10-19 00:54:10 +00001371 SemaRef.Diags.getDiagnosticLevel(
1372 diag::warn_cxx98_compat_friend_redefinition,
1373 Function->getLocation())
1374 != DiagnosticsEngine::Ignored) &&
Douglas Gregor238058c2010-05-18 05:45:02 +00001375 D->isThisDeclarationADefinition()) {
1376 // Check for a function body.
1377 const FunctionDecl *Definition = 0;
Sean Hunt10620eb2011-05-06 20:44:56 +00001378 if (Function->isDefined(Definition) &&
Douglas Gregor238058c2010-05-18 05:45:02 +00001379 Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
Richard Smith53e53512011-10-19 00:54:10 +00001380 SemaRef.Diag(Function->getLocation(),
Richard Smith80ad52f2013-01-02 11:42:31 +00001381 SemaRef.getLangOpts().CPlusPlus11 ?
Richard Smith53e53512011-10-19 00:54:10 +00001382 diag::warn_cxx98_compat_friend_redefinition :
1383 diag::err_redefinition) << Function->getDeclName();
Douglas Gregor238058c2010-05-18 05:45:02 +00001384 SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
Richard Smith80ad52f2013-01-02 11:42:31 +00001385 if (!SemaRef.getLangOpts().CPlusPlus11)
Richard Smith53e53512011-10-19 00:54:10 +00001386 Function->setInvalidDecl();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001387 }
Douglas Gregor238058c2010-05-18 05:45:02 +00001388 // Check for redefinitions due to other instantiations of this or
1389 // a similar friend function.
1390 else for (FunctionDecl::redecl_iterator R = Function->redecls_begin(),
1391 REnd = Function->redecls_end();
1392 R != REnd; ++R) {
Gabor Greif13a8aff2010-08-28 15:42:30 +00001393 if (*R == Function)
1394 continue;
Gabor Greifab297ac2010-08-30 21:10:05 +00001395 switch (R->getFriendObjectKind()) {
1396 case Decl::FOK_None:
Richard Smith80ad52f2013-01-02 11:42:31 +00001397 if (!SemaRef.getLangOpts().CPlusPlus11 &&
Richard Smith53e53512011-10-19 00:54:10 +00001398 !queuedInstantiation && R->isUsed(false)) {
Gabor Greifab297ac2010-08-30 21:10:05 +00001399 if (MemberSpecializationInfo *MSInfo
1400 = Function->getMemberSpecializationInfo()) {
1401 if (MSInfo->getPointOfInstantiation().isInvalid()) {
1402 SourceLocation Loc = R->getLocation(); // FIXME
1403 MSInfo->setPointOfInstantiation(Loc);
1404 SemaRef.PendingLocalImplicitInstantiations.push_back(
1405 std::make_pair(Function, Loc));
1406 queuedInstantiation = true;
1407 }
1408 }
1409 }
1410 break;
1411 default:
Douglas Gregor238058c2010-05-18 05:45:02 +00001412 if (const FunctionDecl *RPattern
Gabor Greif6a557d82010-08-28 15:46:56 +00001413 = R->getTemplateInstantiationPattern())
Sean Hunt10620eb2011-05-06 20:44:56 +00001414 if (RPattern->isDefined(RPattern)) {
Richard Smith53e53512011-10-19 00:54:10 +00001415 SemaRef.Diag(Function->getLocation(),
Richard Smith80ad52f2013-01-02 11:42:31 +00001416 SemaRef.getLangOpts().CPlusPlus11 ?
Richard Smith53e53512011-10-19 00:54:10 +00001417 diag::warn_cxx98_compat_friend_redefinition :
1418 diag::err_redefinition)
Douglas Gregor238058c2010-05-18 05:45:02 +00001419 << Function->getDeclName();
Gabor Greif6a557d82010-08-28 15:46:56 +00001420 SemaRef.Diag(R->getLocation(), diag::note_previous_definition);
Richard Smith80ad52f2013-01-02 11:42:31 +00001421 if (!SemaRef.getLangOpts().CPlusPlus11)
Richard Smith53e53512011-10-19 00:54:10 +00001422 Function->setInvalidDecl();
Douglas Gregor238058c2010-05-18 05:45:02 +00001423 break;
1424 }
1425 }
1426 }
1427 }
Douglas Gregora735b202009-10-13 14:39:41 +00001428 }
1429
John McCall76d32642010-04-24 01:30:58 +00001430 if (Function->isOverloadedOperator() && !DC->isRecord() &&
1431 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1432 PrincipalDecl->setNonMemberOperator();
1433
Sean Hunteb88ae52011-05-23 21:07:59 +00001434 assert(!D->isDefaulted() && "only methods should be defaulted");
Douglas Gregore53060f2009-06-25 22:08:12 +00001435 return Function;
1436}
1437
Douglas Gregord60e1052009-08-27 16:57:43 +00001438Decl *
1439TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001440 TemplateParameterList *TemplateParams,
1441 bool IsClassScopeSpecialization) {
Douglas Gregor6b906862009-08-21 00:16:32 +00001442 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
Douglas Gregord60e1052009-08-27 16:57:43 +00001443 if (FunctionTemplate && !TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +00001444 // We are creating a function template specialization from a function
1445 // template. Check whether there is already a function template
Douglas Gregord60e1052009-08-27 16:57:43 +00001446 // specialization for this particular set of template arguments.
Richard Smithc95d4132013-05-03 23:46:09 +00001447 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Mike Stump1eb44332009-09-09 15:08:12 +00001448
Douglas Gregor1e1e9722012-03-28 14:34:23 +00001449 void *InsertPos = 0;
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001450 FunctionDecl *SpecFunc
Richard Smithc95d4132013-05-03 23:46:09 +00001451 = FunctionTemplate->findSpecialization(Innermost.begin(),
1452 Innermost.size(),
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001453 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001454
Douglas Gregor6b906862009-08-21 00:16:32 +00001455 // If we already have a function template specialization, return it.
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001456 if (SpecFunc)
1457 return SpecFunc;
Douglas Gregor6b906862009-08-21 00:16:32 +00001458 }
1459
John McCallb0cb0222010-03-27 05:57:59 +00001460 bool isFriend;
1461 if (FunctionTemplate)
1462 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1463 else
1464 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1465
Douglas Gregor79c22782010-01-16 20:21:20 +00001466 bool MergeWithParentScope = (TemplateParams != 0) ||
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001467 !(isa<Decl>(Owner) &&
Douglas Gregor79c22782010-01-16 20:21:20 +00001468 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall2a7fb272010-08-25 05:32:35 +00001469 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Douglas Gregor48dd19b2009-05-14 21:44:34 +00001470
John McCall4eab39f2010-10-19 02:26:41 +00001471 // Instantiate enclosing template arguments for friends.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001472 SmallVector<TemplateParameterList *, 4> TempParamLists;
John McCall4eab39f2010-10-19 02:26:41 +00001473 unsigned NumTempParamLists = 0;
1474 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
1475 TempParamLists.set_size(NumTempParamLists);
1476 for (unsigned I = 0; I != NumTempParamLists; ++I) {
1477 TemplateParameterList *TempParams = D->getTemplateParameterList(I);
1478 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1479 if (!InstParams)
1480 return NULL;
1481 TempParamLists[I] = InstParams;
1482 }
1483 }
1484
Chris Lattner5f9e2722011-07-23 10:55:15 +00001485 SmallVector<ParmVarDecl *, 4> Params;
Benjamin Kramerdc370c12012-01-20 14:42:32 +00001486 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
John McCall21ef0fa2010-03-11 09:03:00 +00001487 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001488 return 0;
Douglas Gregor71074fd2012-09-13 21:56:43 +00001489 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001490
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001491 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1492 if (QualifierLoc) {
1493 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
John McCallb0cb0222010-03-27 05:57:59 +00001494 TemplateArgs);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001495 if (!QualifierLoc)
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001496 return 0;
John McCallb0cb0222010-03-27 05:57:59 +00001497 }
1498
1499 DeclContext *DC = Owner;
1500 if (isFriend) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001501 if (QualifierLoc) {
John McCallb0cb0222010-03-27 05:57:59 +00001502 CXXScopeSpec SS;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001503 SS.Adopt(QualifierLoc);
John McCallb0cb0222010-03-27 05:57:59 +00001504 DC = SemaRef.computeDeclContext(SS);
John McCallc54d6882010-10-19 05:01:53 +00001505
1506 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
1507 return 0;
John McCallb0cb0222010-03-27 05:57:59 +00001508 } else {
1509 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1510 D->getDeclContext(),
1511 TemplateArgs);
1512 }
1513 if (!DC) return 0;
1514 }
1515
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001516 // Build the instantiated method declaration.
John McCallb0cb0222010-03-27 05:57:59 +00001517 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
Douglas Gregordec06662009-08-21 18:42:58 +00001518 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001519
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001520 SourceLocation StartLoc = D->getInnerLocStart();
Abramo Bagnara25777432010-08-11 22:01:17 +00001521 DeclarationNameInfo NameInfo
1522 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
Douglas Gregor17e32f32009-08-21 22:43:28 +00001523 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001524 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001525 StartLoc, NameInfo, T, TInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00001526 Constructor->isExplicit(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001527 Constructor->isInlineSpecified(),
Richard Smith86c3ae42012-02-13 03:54:03 +00001528 false, Constructor->isConstexpr());
Richard Smithb5eb3f52013-05-17 02:19:35 +00001529
Richard Smith4841ca52013-04-10 05:48:59 +00001530 // Claim that the instantiation of a constructor or constructor template
1531 // inherits the same constructor that the template does.
Richard Smithb5eb3f52013-05-17 02:19:35 +00001532 if (CXXConstructorDecl *Inh = const_cast<CXXConstructorDecl *>(
1533 Constructor->getInheritedConstructor())) {
1534 // If we're instantiating a specialization of a function template, our
1535 // "inherited constructor" will actually itself be a function template.
1536 // Instantiate a declaration of it, too.
1537 if (FunctionTemplate) {
1538 assert(!TemplateParams && Inh->getDescribedFunctionTemplate() &&
1539 !Inh->getParent()->isDependentContext() &&
1540 "inheriting constructor template in dependent context?");
1541 Sema::InstantiatingTemplate Inst(SemaRef, Constructor->getLocation(),
1542 Inh);
1543 if (Inst)
1544 return 0;
1545 Sema::ContextRAII SavedContext(SemaRef, Inh->getDeclContext());
1546 LocalInstantiationScope LocalScope(SemaRef);
1547
1548 // Use the same template arguments that we deduced for the inheriting
1549 // constructor. There's no way they could be deduced differently.
1550 MultiLevelTemplateArgumentList InheritedArgs;
1551 InheritedArgs.addOuterTemplateArguments(TemplateArgs.getInnermost());
1552 Inh = cast_or_null<CXXConstructorDecl>(
1553 SemaRef.SubstDecl(Inh, Inh->getDeclContext(), InheritedArgs));
1554 if (!Inh)
1555 return 0;
1556 }
Richard Smith4841ca52013-04-10 05:48:59 +00001557 cast<CXXConstructorDecl>(Method)->setInheritedConstructor(Inh);
Richard Smithb5eb3f52013-05-17 02:19:35 +00001558 }
Douglas Gregor17e32f32009-08-21 22:43:28 +00001559 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001560 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001561 StartLoc, NameInfo, T, TInfo,
Abramo Bagnara25777432010-08-11 22:01:17 +00001562 Destructor->isInlineSpecified(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001563 false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001564 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001565 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001566 StartLoc, NameInfo, T, TInfo,
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001567 Conversion->isInlineSpecified(),
Douglas Gregorf5251602011-03-08 17:10:18 +00001568 Conversion->isExplicit(),
Richard Smith86c3ae42012-02-13 03:54:03 +00001569 Conversion->isConstexpr(),
Richard Smith9f569cc2011-10-01 02:31:28 +00001570 Conversion->getLocEnd());
Douglas Gregordec06662009-08-21 18:42:58 +00001571 } else {
Rafael Espindola72fdc892013-04-15 12:38:20 +00001572 StorageClass SC = D->isStatic() ? SC_Static : SC_None;
Abramo Bagnara25777432010-08-11 22:01:17 +00001573 Method = CXXMethodDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001574 StartLoc, NameInfo, T, TInfo,
Rafael Espindola72fdc892013-04-15 12:38:20 +00001575 SC, D->isInlineSpecified(),
Richard Smith86c3ae42012-02-13 03:54:03 +00001576 D->isConstexpr(), D->getLocEnd());
Douglas Gregordec06662009-08-21 18:42:58 +00001577 }
Douglas Gregor6b906862009-08-21 00:16:32 +00001578
Richard Smithd4497dd2013-01-25 00:08:28 +00001579 if (D->isInlined())
1580 Method->setImplicitlyInline();
1581
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001582 if (QualifierLoc)
1583 Method->setQualifierInfo(QualifierLoc);
John McCallb6217662010-03-15 10:12:16 +00001584
Douglas Gregord60e1052009-08-27 16:57:43 +00001585 if (TemplateParams) {
1586 // Our resulting instantiation is actually a function template, since we
1587 // are substituting only the outer template parameters. For example, given
Mike Stump1eb44332009-09-09 15:08:12 +00001588 //
Douglas Gregord60e1052009-08-27 16:57:43 +00001589 // template<typename T>
1590 // struct X {
1591 // template<typename U> void f(T, U);
1592 // };
1593 //
1594 // X<int> x;
1595 //
1596 // We are instantiating the member template "f" within X<int>, which means
1597 // substituting int for T, but leaving "f" as a member function template.
1598 // Build the function template itself.
1599 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1600 Method->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001601 Method->getDeclName(),
Douglas Gregord60e1052009-08-27 16:57:43 +00001602 TemplateParams, Method);
John McCallb0cb0222010-03-27 05:57:59 +00001603 if (isFriend) {
1604 FunctionTemplate->setLexicalDeclContext(Owner);
Richard Smith22050f22013-07-17 23:53:16 +00001605 FunctionTemplate->setObjectOfFriendDecl();
John McCallb0cb0222010-03-27 05:57:59 +00001606 } else if (D->isOutOfLine())
Mike Stump1eb44332009-09-09 15:08:12 +00001607 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregord60e1052009-08-27 16:57:43 +00001608 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001609 } else if (FunctionTemplate) {
1610 // Record this function template specialization.
Richard Smithc95d4132013-05-03 23:46:09 +00001611 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Douglas Gregor838db382010-02-11 01:19:42 +00001612 Method->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00001613 TemplateArgumentList::CreateCopy(SemaRef.Context,
Richard Smithc95d4132013-05-03 23:46:09 +00001614 Innermost.begin(),
1615 Innermost.size()),
Douglas Gregor1e1e9722012-03-28 14:34:23 +00001616 /*InsertPos=*/0);
John McCallb0cb0222010-03-27 05:57:59 +00001617 } else if (!isFriend) {
Douglas Gregor66724ea2009-11-14 01:20:54 +00001618 // Record that this is an instantiation of a member function.
Douglas Gregor2db32322009-10-07 23:56:10 +00001619 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001620 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001621
Mike Stump1eb44332009-09-09 15:08:12 +00001622 // If we are instantiating a member function defined
Douglas Gregor7caa6822009-07-24 20:34:43 +00001623 // out-of-line, the instantiation will have the same lexical
1624 // context (which will be a namespace scope) as the template.
John McCallb0cb0222010-03-27 05:57:59 +00001625 if (isFriend) {
John McCall4eab39f2010-10-19 02:26:41 +00001626 if (NumTempParamLists)
1627 Method->setTemplateParameterListsInfo(SemaRef.Context,
1628 NumTempParamLists,
1629 TempParamLists.data());
1630
John McCallb0cb0222010-03-27 05:57:59 +00001631 Method->setLexicalDeclContext(Owner);
Richard Smith22050f22013-07-17 23:53:16 +00001632 Method->setObjectOfFriendDecl();
John McCallb0cb0222010-03-27 05:57:59 +00001633 } else if (D->isOutOfLine())
Douglas Gregor7caa6822009-07-24 20:34:43 +00001634 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00001635
Douglas Gregor5545e162009-03-24 00:38:23 +00001636 // Attach the parameters
1637 for (unsigned P = 0; P < Params.size(); ++P)
1638 Params[P]->setOwningFunction(Method);
David Blaikie4278c652011-09-21 18:16:56 +00001639 Method->setParams(Params);
Douglas Gregor5545e162009-03-24 00:38:23 +00001640
1641 if (InitMethodInstantiation(Method, D))
1642 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001643
Abramo Bagnara25777432010-08-11 22:01:17 +00001644 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
1645 Sema::ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00001646
John McCallb0cb0222010-03-27 05:57:59 +00001647 if (!FunctionTemplate || TemplateParams || isFriend) {
1648 SemaRef.LookupQualifiedName(Previous, Record);
Mike Stump1eb44332009-09-09 15:08:12 +00001649
Douglas Gregordec06662009-08-21 18:42:58 +00001650 // In C++, the previous declaration we find might be a tag type
1651 // (class or enum). In this case, the new declaration will hide the
1652 // tag type. Note that this does does not apply if we're declaring a
1653 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001654 if (Previous.isSingleTagDecl())
1655 Previous.clear();
Douglas Gregordec06662009-08-21 18:42:58 +00001656 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001657
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001658 if (!IsClassScopeSpecialization)
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00001659 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001660
Douglas Gregor4ba31362009-12-01 17:24:26 +00001661 if (D->isPure())
1662 SemaRef.CheckPureMethod(Method, SourceRange());
1663
John McCall1f2e1a92012-08-10 03:15:35 +00001664 // Propagate access. For a non-friend declaration, the access is
1665 // whatever we're propagating from. For a friend, it should be the
1666 // previous declaration we just found.
1667 if (isFriend && Method->getPreviousDecl())
1668 Method->setAccess(Method->getPreviousDecl()->getAccess());
1669 else
1670 Method->setAccess(D->getAccess());
1671 if (FunctionTemplate)
1672 FunctionTemplate->setAccess(Method->getAccess());
John McCall46460a62010-01-20 21:53:11 +00001673
Anders Carlsson9eefa222011-01-20 06:52:44 +00001674 SemaRef.CheckOverrideControl(Method);
1675
Eli Friedman3bc45152011-11-15 22:39:08 +00001676 // If a function is defined as defaulted or deleted, mark it as such now.
Richard Smithac713512012-12-08 02:53:02 +00001677 if (D->isExplicitlyDefaulted())
1678 SemaRef.SetDeclDefaulted(Method, Method->getLocation());
Eli Friedman3bc45152011-11-15 22:39:08 +00001679 if (D->isDeletedAsWritten())
Richard Smithac713512012-12-08 02:53:02 +00001680 SemaRef.SetDeclDeleted(Method, Method->getLocation());
Eli Friedman3bc45152011-11-15 22:39:08 +00001681
John McCall1f2e1a92012-08-10 03:15:35 +00001682 // If there's a function template, let our caller handle it.
John McCallb0cb0222010-03-27 05:57:59 +00001683 if (FunctionTemplate) {
John McCall1f2e1a92012-08-10 03:15:35 +00001684 // do nothing
1685
1686 // Don't hide a (potentially) valid declaration with an invalid one.
John McCallb0cb0222010-03-27 05:57:59 +00001687 } else if (Method->isInvalidDecl() && !Previous.empty()) {
John McCall1f2e1a92012-08-10 03:15:35 +00001688 // do nothing
1689
1690 // Otherwise, check access to friends and make them visible.
1691 } else if (isFriend) {
1692 // We only need to re-check access for methods which we didn't
1693 // manage to match during parsing.
1694 if (!D->getPreviousDecl())
1695 SemaRef.CheckFriendAccess(Method);
1696
1697 Record->makeDeclVisibleInContext(Method);
1698
1699 // Otherwise, add the declaration. We don't need to do this for
1700 // class-scope specializations because we'll have matched them with
1701 // the appropriate template.
1702 } else if (!IsClassScopeSpecialization) {
1703 Owner->addDecl(Method);
John McCallb0cb0222010-03-27 05:57:59 +00001704 }
Sean Hunteb88ae52011-05-23 21:07:59 +00001705
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001706 return Method;
1707}
1708
Douglas Gregor615c5d42009-03-24 16:43:20 +00001709Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +00001710 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +00001711}
1712
Douglas Gregor03b2b072009-03-24 00:15:49 +00001713Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001714 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +00001715}
1716
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001717Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001718 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001719}
1720
Eli Friedmanded99792013-06-27 23:21:55 +00001721Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
David Blaikie66874fb2013-02-21 01:47:18 +00001722 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0, None,
1723 /*ExpectParameterPack=*/ false);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001724}
1725
John McCalle29ba202009-08-20 01:44:21 +00001726Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1727 TemplateTypeParmDecl *D) {
1728 // TODO: don't always clone when decls are refcounted.
Chandler Carruth4fb86f82011-05-01 00:51:33 +00001729 assert(D->getTypeForDecl()->isTemplateTypeParmType());
Mike Stump1eb44332009-09-09 15:08:12 +00001730
John McCalle29ba202009-08-20 01:44:21 +00001731 TemplateTypeParmDecl *Inst =
Abramo Bagnara344577e2011-03-06 15:48:19 +00001732 TemplateTypeParmDecl::Create(SemaRef.Context, Owner,
1733 D->getLocStart(), D->getLocation(),
Chandler Carruth4fb86f82011-05-01 00:51:33 +00001734 D->getDepth() - TemplateArgs.getNumLevels(),
1735 D->getIndex(), D->getIdentifier(),
John McCalle29ba202009-08-20 01:44:21 +00001736 D->wasDeclaredWithTypename(),
1737 D->isParameterPack());
Douglas Gregor9a299e02011-03-04 17:52:15 +00001738 Inst->setAccess(AS_public);
John McCalle29ba202009-08-20 01:44:21 +00001739
David Majnemer9d57b8d2013-08-28 23:48:32 +00001740 if (D->hasDefaultArgument()) {
1741 TypeSourceInfo *InstantiatedDefaultArg =
1742 SemaRef.SubstType(D->getDefaultArgumentInfo(), TemplateArgs,
1743 D->getDefaultArgumentLoc(), D->getDeclName());
1744 if (InstantiatedDefaultArg)
1745 Inst->setDefaultArgument(InstantiatedDefaultArg, false);
1746 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001747
1748 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor550d9b22009-10-31 17:21:17 +00001749 // scope.
1750 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001751
John McCalle29ba202009-08-20 01:44:21 +00001752 return Inst;
1753}
1754
Douglas Gregor33642df2009-10-23 23:25:44 +00001755Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1756 NonTypeTemplateParmDecl *D) {
1757 // Substitute into the type of the non-type template parameter.
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001758 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001759 SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
1760 SmallVector<QualType, 4> ExpandedParameterPackTypes;
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001761 bool IsExpandedParameterPack = false;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001762 TypeSourceInfo *DI;
Douglas Gregor33642df2009-10-23 23:25:44 +00001763 QualType T;
Douglas Gregor33642df2009-10-23 23:25:44 +00001764 bool Invalid = false;
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001765
1766 if (D->isExpandedParameterPack()) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001767 // The non-type template parameter pack is an already-expanded pack
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001768 // expansion of types. Substitute into each of the expanded types.
1769 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
1770 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
1771 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
1772 TypeSourceInfo *NewDI =SemaRef.SubstType(D->getExpansionTypeSourceInfo(I),
1773 TemplateArgs,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001774 D->getLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001775 D->getDeclName());
1776 if (!NewDI)
1777 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001778
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001779 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1780 QualType NewT =SemaRef.CheckNonTypeTemplateParameterType(NewDI->getType(),
1781 D->getLocation());
1782 if (NewT.isNull())
1783 return 0;
1784 ExpandedParameterPackTypes.push_back(NewT);
1785 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001786
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001787 IsExpandedParameterPack = true;
1788 DI = D->getTypeSourceInfo();
1789 T = DI->getType();
Richard Smith6964b3f2012-09-07 02:06:42 +00001790 } else if (D->isPackExpansion()) {
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001791 // The non-type template parameter pack's type is a pack expansion of types.
1792 // Determine whether we need to expand this parameter pack into separate
1793 // types.
David Blaikie39e6ab42013-02-18 22:06:02 +00001794 PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>();
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001795 TypeLoc Pattern = Expansion.getPatternLoc();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001796 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001797 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001798
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001799 // Determine whether the set of unexpanded parameter packs can and should
1800 // be expanded.
1801 bool Expand = true;
1802 bool RetainExpansion = false;
David Blaikiedc84cd52013-02-20 22:23:23 +00001803 Optional<unsigned> OrigNumExpansions
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001804 = Expansion.getTypePtr()->getNumExpansions();
David Blaikiedc84cd52013-02-20 22:23:23 +00001805 Optional<unsigned> NumExpansions = OrigNumExpansions;
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001806 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
1807 Pattern.getSourceRange(),
David Blaikiea71f9d02011-09-22 02:34:54 +00001808 Unexpanded,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001809 TemplateArgs,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001810 Expand, RetainExpansion,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001811 NumExpansions))
1812 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001813
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001814 if (Expand) {
1815 for (unsigned I = 0; I != *NumExpansions; ++I) {
1816 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
1817 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001818 D->getLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001819 D->getDeclName());
1820 if (!NewDI)
1821 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001822
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001823 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1824 QualType NewT = SemaRef.CheckNonTypeTemplateParameterType(
1825 NewDI->getType(),
1826 D->getLocation());
1827 if (NewT.isNull())
1828 return 0;
1829 ExpandedParameterPackTypes.push_back(NewT);
1830 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001831
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001832 // Note that we have an expanded parameter pack. The "type" of this
1833 // expanded parameter pack is the original expansion type, but callers
1834 // will end up using the expanded parameter pack types for type-checking.
1835 IsExpandedParameterPack = true;
1836 DI = D->getTypeSourceInfo();
1837 T = DI->getType();
1838 } else {
1839 // We cannot fully expand the pack expansion now, so substitute into the
1840 // pattern and create a new pack expansion type.
1841 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
1842 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001843 D->getLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001844 D->getDeclName());
1845 if (!NewPattern)
1846 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001847
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001848 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
1849 NumExpansions);
1850 if (!DI)
1851 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001852
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001853 T = DI->getType();
1854 }
1855 } else {
1856 // Simple case: substitution into a parameter that is not a parameter pack.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001857 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001858 D->getLocation(), D->getDeclName());
1859 if (!DI)
1860 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001861
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001862 // Check that this type is acceptable for a non-type template parameter.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001863 T = SemaRef.CheckNonTypeTemplateParameterType(DI->getType(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001864 D->getLocation());
1865 if (T.isNull()) {
1866 T = SemaRef.Context.IntTy;
1867 Invalid = true;
1868 }
Douglas Gregor33642df2009-10-23 23:25:44 +00001869 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001870
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001871 NonTypeTemplateParmDecl *Param;
1872 if (IsExpandedParameterPack)
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001873 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001874 D->getInnerLocStart(),
1875 D->getLocation(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001876 D->getDepth() - TemplateArgs.getNumLevels(),
1877 D->getPosition(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001878 D->getIdentifier(), T,
1879 DI,
1880 ExpandedParameterPackTypes.data(),
1881 ExpandedParameterPackTypes.size(),
1882 ExpandedParameterPackTypesAsWritten.data());
1883 else
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001884 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001885 D->getInnerLocStart(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001886 D->getLocation(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001887 D->getDepth() - TemplateArgs.getNumLevels(),
1888 D->getPosition(),
1889 D->getIdentifier(), T,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001890 D->isParameterPack(), DI);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001891
Douglas Gregor9a299e02011-03-04 17:52:15 +00001892 Param->setAccess(AS_public);
Douglas Gregor33642df2009-10-23 23:25:44 +00001893 if (Invalid)
1894 Param->setInvalidDecl();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001895
David Majnemer9d57b8d2013-08-28 23:48:32 +00001896 if (D->hasDefaultArgument()) {
1897 ExprResult Value = SemaRef.SubstExpr(D->getDefaultArgument(), TemplateArgs);
1898 if (!Value.isInvalid())
1899 Param->setDefaultArgument(Value.get(), false);
1900 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001901
1902 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor550d9b22009-10-31 17:21:17 +00001903 // scope.
1904 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor33642df2009-10-23 23:25:44 +00001905 return Param;
1906}
1907
Richard Smith6964b3f2012-09-07 02:06:42 +00001908static void collectUnexpandedParameterPacks(
1909 Sema &S,
1910 TemplateParameterList *Params,
1911 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
1912 for (TemplateParameterList::const_iterator I = Params->begin(),
1913 E = Params->end(); I != E; ++I) {
1914 if ((*I)->isTemplateParameterPack())
1915 continue;
1916 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*I))
1917 S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
1918 Unexpanded);
1919 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(*I))
1920 collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
1921 Unexpanded);
1922 }
1923}
1924
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001925Decl *
Douglas Gregor9106ef72009-11-11 16:58:32 +00001926TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1927 TemplateTemplateParmDecl *D) {
1928 // Instantiate the template parameter list of the template template parameter.
1929 TemplateParameterList *TempParams = D->getTemplateParameters();
1930 TemplateParameterList *InstParams;
Richard Smith6964b3f2012-09-07 02:06:42 +00001931 SmallVector<TemplateParameterList*, 8> ExpandedParams;
1932
1933 bool IsExpandedParameterPack = false;
1934
1935 if (D->isExpandedParameterPack()) {
1936 // The template template parameter pack is an already-expanded pack
1937 // expansion of template parameters. Substitute into each of the expanded
1938 // parameters.
1939 ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
1940 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
1941 I != N; ++I) {
1942 LocalInstantiationScope Scope(SemaRef);
1943 TemplateParameterList *Expansion =
1944 SubstTemplateParams(D->getExpansionTemplateParameters(I));
1945 if (!Expansion)
1946 return 0;
1947 ExpandedParams.push_back(Expansion);
1948 }
1949
1950 IsExpandedParameterPack = true;
1951 InstParams = TempParams;
1952 } else if (D->isPackExpansion()) {
1953 // The template template parameter pack expands to a pack of template
1954 // template parameters. Determine whether we need to expand this parameter
1955 // pack into separate parameters.
1956 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1957 collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(),
1958 Unexpanded);
1959
1960 // Determine whether the set of unexpanded parameter packs can and should
1961 // be expanded.
1962 bool Expand = true;
1963 bool RetainExpansion = false;
David Blaikiedc84cd52013-02-20 22:23:23 +00001964 Optional<unsigned> NumExpansions;
Richard Smith6964b3f2012-09-07 02:06:42 +00001965 if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(),
1966 TempParams->getSourceRange(),
1967 Unexpanded,
1968 TemplateArgs,
1969 Expand, RetainExpansion,
1970 NumExpansions))
1971 return 0;
1972
1973 if (Expand) {
1974 for (unsigned I = 0; I != *NumExpansions; ++I) {
1975 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
1976 LocalInstantiationScope Scope(SemaRef);
1977 TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
1978 if (!Expansion)
1979 return 0;
1980 ExpandedParams.push_back(Expansion);
1981 }
1982
1983 // Note that we have an expanded parameter pack. The "type" of this
1984 // expanded parameter pack is the original expansion type, but callers
1985 // will end up using the expanded parameter pack types for type-checking.
1986 IsExpandedParameterPack = true;
1987 InstParams = TempParams;
1988 } else {
1989 // We cannot fully expand the pack expansion now, so just substitute
1990 // into the pattern.
1991 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
1992
1993 LocalInstantiationScope Scope(SemaRef);
1994 InstParams = SubstTemplateParams(TempParams);
1995 if (!InstParams)
1996 return 0;
1997 }
1998 } else {
Douglas Gregor9106ef72009-11-11 16:58:32 +00001999 // Perform the actual substitution of template parameters within a new,
2000 // local instantiation scope.
John McCall2a7fb272010-08-25 05:32:35 +00002001 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor9106ef72009-11-11 16:58:32 +00002002 InstParams = SubstTemplateParams(TempParams);
2003 if (!InstParams)
Richard Smith6964b3f2012-09-07 02:06:42 +00002004 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002005 }
2006
Douglas Gregor9106ef72009-11-11 16:58:32 +00002007 // Build the template template parameter.
Richard Smith6964b3f2012-09-07 02:06:42 +00002008 TemplateTemplateParmDecl *Param;
2009 if (IsExpandedParameterPack)
2010 Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
2011 D->getLocation(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002012 D->getDepth() - TemplateArgs.getNumLevels(),
Richard Smith6964b3f2012-09-07 02:06:42 +00002013 D->getPosition(),
2014 D->getIdentifier(), InstParams,
2015 ExpandedParams);
2016 else
2017 Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
2018 D->getLocation(),
2019 D->getDepth() - TemplateArgs.getNumLevels(),
2020 D->getPosition(),
2021 D->isParameterPack(),
2022 D->getIdentifier(), InstParams);
David Majnemer9d57b8d2013-08-28 23:48:32 +00002023 if (D->hasDefaultArgument()) {
2024 NestedNameSpecifierLoc QualifierLoc =
2025 D->getDefaultArgument().getTemplateQualifierLoc();
2026 QualifierLoc =
2027 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs);
2028 TemplateName TName = SemaRef.SubstTemplateName(
2029 QualifierLoc, D->getDefaultArgument().getArgument().getAsTemplate(),
2030 D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs);
2031 if (!TName.isNull())
2032 Param->setDefaultArgument(
2033 TemplateArgumentLoc(TemplateArgument(TName),
2034 D->getDefaultArgument().getTemplateQualifierLoc(),
2035 D->getDefaultArgument().getTemplateNameLoc()),
2036 false);
2037 }
Douglas Gregor9a299e02011-03-04 17:52:15 +00002038 Param->setAccess(AS_public);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002039
2040 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor9106ef72009-11-11 16:58:32 +00002041 // scope.
2042 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002043
Douglas Gregor9106ef72009-11-11 16:58:32 +00002044 return Param;
2045}
2046
Douglas Gregor48c32a72009-11-17 06:07:40 +00002047Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregordb992412011-02-25 16:33:46 +00002048 // Using directives are never dependent (and never contain any types or
2049 // expressions), so they require no explicit instantiation work.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002050
Douglas Gregor48c32a72009-11-17 06:07:40 +00002051 UsingDirectiveDecl *Inst
2052 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002053 D->getNamespaceKeyLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00002054 D->getQualifierLoc(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002055 D->getIdentLocation(),
2056 D->getNominatedNamespace(),
Douglas Gregor48c32a72009-11-17 06:07:40 +00002057 D->getCommonAncestor());
Abramo Bagnara536afbe2012-09-05 09:55:10 +00002058
2059 // Add the using directive to its declaration context
2060 // only if this is not a function or method.
2061 if (!Owner->isFunctionOrMethod())
2062 Owner->addDecl(Inst);
2063
Douglas Gregor48c32a72009-11-17 06:07:40 +00002064 return Inst;
2065}
2066
John McCalled976492009-12-04 22:46:56 +00002067Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
Douglas Gregor1b398202010-09-29 17:58:28 +00002068
2069 // The nested name specifier may be dependent, for example
2070 // template <typename T> struct t {
2071 // struct s1 { T f1(); };
2072 // struct s2 : s1 { using s1::f1; };
2073 // };
2074 // template struct t<int>;
2075 // Here, in using s1::f1, s1 refers to t<T>::s1;
2076 // we need to substitute for t<int>::s1.
Douglas Gregor5149f372011-02-25 15:54:31 +00002077 NestedNameSpecifierLoc QualifierLoc
2078 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
2079 TemplateArgs);
2080 if (!QualifierLoc)
Douglas Gregordc355712011-02-25 00:36:19 +00002081 return 0;
Douglas Gregor1b398202010-09-29 17:58:28 +00002082
2083 // The name info is non-dependent, so no transformation
2084 // is required.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002085 DeclarationNameInfo NameInfo = D->getNameInfo();
John McCalled976492009-12-04 22:46:56 +00002086
John McCall9f54ad42009-12-10 09:41:52 +00002087 // We only need to do redeclaration lookups if we're in a class
2088 // scope (in fact, it's not really even possible in non-class
2089 // scopes).
2090 bool CheckRedeclaration = Owner->isRecord();
2091
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002092 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
2093 Sema::ForRedeclaration);
John McCall9f54ad42009-12-10 09:41:52 +00002094
John McCalled976492009-12-04 22:46:56 +00002095 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00002096 D->getUsingLoc(),
Douglas Gregor5149f372011-02-25 15:54:31 +00002097 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002098 NameInfo,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00002099 D->hasTypename());
John McCalled976492009-12-04 22:46:56 +00002100
Douglas Gregor5149f372011-02-25 15:54:31 +00002101 CXXScopeSpec SS;
2102 SS.Adopt(QualifierLoc);
John McCall9f54ad42009-12-10 09:41:52 +00002103 if (CheckRedeclaration) {
2104 Prev.setHideTags(false);
2105 SemaRef.LookupQualifiedName(Prev, Owner);
2106
2107 // Check for invalid redeclarations.
Enea Zaffanella8d030c72013-07-22 10:54:09 +00002108 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(),
2109 D->hasTypename(), SS,
John McCall9f54ad42009-12-10 09:41:52 +00002110 D->getLocation(), Prev))
2111 NewUD->setInvalidDecl();
2112
2113 }
2114
2115 if (!NewUD->isInvalidDecl() &&
Enea Zaffanella8d030c72013-07-22 10:54:09 +00002116 SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), SS,
John McCalled976492009-12-04 22:46:56 +00002117 D->getLocation()))
2118 NewUD->setInvalidDecl();
John McCall9f54ad42009-12-10 09:41:52 +00002119
John McCalled976492009-12-04 22:46:56 +00002120 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
2121 NewUD->setAccess(D->getAccess());
2122 Owner->addDecl(NewUD);
2123
John McCall9f54ad42009-12-10 09:41:52 +00002124 // Don't process the shadow decls for an invalid decl.
2125 if (NewUD->isInvalidDecl())
2126 return NewUD;
2127
Richard Smithc5a89a12012-04-02 01:30:27 +00002128 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
2129 if (SemaRef.CheckInheritingConstructorUsingDecl(NewUD))
2130 NewUD->setInvalidDecl();
2131 return NewUD;
2132 }
2133
John McCall323c3102009-12-22 22:26:37 +00002134 bool isFunctionScope = Owner->isFunctionOrMethod();
2135
John McCall9f54ad42009-12-10 09:41:52 +00002136 // Process the shadow decls.
2137 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
2138 I != E; ++I) {
2139 UsingShadowDecl *Shadow = *I;
2140 NamedDecl *InstTarget =
Douglas Gregorb7107222011-03-04 19:46:35 +00002141 cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
2142 Shadow->getLocation(),
2143 Shadow->getTargetDecl(),
2144 TemplateArgs));
2145 if (!InstTarget)
2146 return 0;
John McCall9f54ad42009-12-10 09:41:52 +00002147
2148 if (CheckRedeclaration &&
2149 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
2150 continue;
2151
2152 UsingShadowDecl *InstShadow
2153 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
2154 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCall323c3102009-12-22 22:26:37 +00002155
2156 if (isFunctionScope)
2157 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall9f54ad42009-12-10 09:41:52 +00002158 }
John McCalled976492009-12-04 22:46:56 +00002159
2160 return NewUD;
2161}
2162
2163Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall9f54ad42009-12-10 09:41:52 +00002164 // Ignore these; we handle them in bulk when processing the UsingDecl.
2165 return 0;
John McCalled976492009-12-04 22:46:56 +00002166}
2167
John McCall7ba107a2009-11-18 02:36:19 +00002168Decl * TemplateDeclInstantiator
2169 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Douglas Gregor5149f372011-02-25 15:54:31 +00002170 NestedNameSpecifierLoc QualifierLoc
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002171 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
Douglas Gregor5149f372011-02-25 15:54:31 +00002172 TemplateArgs);
2173 if (!QualifierLoc)
Anders Carlsson0dde18e2009-08-28 15:18:15 +00002174 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002175
Anders Carlsson0dde18e2009-08-28 15:18:15 +00002176 CXXScopeSpec SS;
Douglas Gregor5149f372011-02-25 15:54:31 +00002177 SS.Adopt(QualifierLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00002178
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002179 // Since NameInfo refers to a typename, it cannot be a C++ special name.
Benjamin Krameraccaf192012-11-14 15:08:31 +00002180 // Hence, no transformation is required for it.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002181 DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002182 NamedDecl *UD =
John McCall9488ea12009-11-17 05:59:44 +00002183 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002184 D->getUsingLoc(), SS, NameInfo, 0,
John McCall7ba107a2009-11-18 02:36:19 +00002185 /*instantiation*/ true,
2186 /*typename*/ true, D->getTypenameLoc());
Douglas Gregor4469e8a2010-05-19 17:02:24 +00002187 if (UD)
John McCalled976492009-12-04 22:46:56 +00002188 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
2189
John McCall7ba107a2009-11-18 02:36:19 +00002190 return UD;
2191}
2192
2193Decl * TemplateDeclInstantiator
2194 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregor5149f372011-02-25 15:54:31 +00002195 NestedNameSpecifierLoc QualifierLoc
2196 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), TemplateArgs);
2197 if (!QualifierLoc)
John McCall7ba107a2009-11-18 02:36:19 +00002198 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002199
John McCall7ba107a2009-11-18 02:36:19 +00002200 CXXScopeSpec SS;
Douglas Gregor5149f372011-02-25 15:54:31 +00002201 SS.Adopt(QualifierLoc);
John McCall7ba107a2009-11-18 02:36:19 +00002202
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002203 DeclarationNameInfo NameInfo
2204 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2205
John McCall7ba107a2009-11-18 02:36:19 +00002206 NamedDecl *UD =
2207 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002208 D->getUsingLoc(), SS, NameInfo, 0,
John McCall7ba107a2009-11-18 02:36:19 +00002209 /*instantiation*/ true,
2210 /*typename*/ false, SourceLocation());
Douglas Gregor4469e8a2010-05-19 17:02:24 +00002211 if (UD)
John McCalled976492009-12-04 22:46:56 +00002212 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
2213
Anders Carlsson0d8df782009-08-29 19:37:28 +00002214 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +00002215}
2216
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002217
2218Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
2219 ClassScopeFunctionSpecializationDecl *Decl) {
2220 CXXMethodDecl *OldFD = Decl->getSpecialization();
Nico Weber6b020092012-06-25 17:21:05 +00002221 CXXMethodDecl *NewFD = cast<CXXMethodDecl>(VisitCXXMethodDecl(OldFD,
2222 0, true));
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002223
2224 LookupResult Previous(SemaRef, NewFD->getNameInfo(), Sema::LookupOrdinaryName,
2225 Sema::ForRedeclaration);
2226
Nico Weber6b020092012-06-25 17:21:05 +00002227 TemplateArgumentListInfo TemplateArgs;
2228 TemplateArgumentListInfo* TemplateArgsPtr = 0;
2229 if (Decl->hasExplicitTemplateArgs()) {
2230 TemplateArgs = Decl->templateArgs();
2231 TemplateArgsPtr = &TemplateArgs;
2232 }
2233
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002234 SemaRef.LookupQualifiedName(Previous, SemaRef.CurContext);
Nico Weber6b020092012-06-25 17:21:05 +00002235 if (SemaRef.CheckFunctionTemplateSpecialization(NewFD, TemplateArgsPtr,
2236 Previous)) {
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002237 NewFD->setInvalidDecl();
2238 return NewFD;
2239 }
2240
2241 // Associate the specialization with the pattern.
2242 FunctionDecl *Specialization = cast<FunctionDecl>(Previous.getFoundDecl());
2243 assert(Specialization && "Class scope Specialization is null");
2244 SemaRef.Context.setClassScopeSpecializationPattern(Specialization, OldFD);
2245
2246 return NewFD;
2247}
2248
Alexey Bataevc6400582013-03-22 06:34:35 +00002249Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
2250 OMPThreadPrivateDecl *D) {
Alexey Bataev6af701f2013-05-13 04:18:18 +00002251 SmallVector<Expr *, 5> Vars;
2252 for (ArrayRef<Expr *>::iterator I = D->varlist_begin(),
2253 E = D->varlist_end();
Alexey Bataevc6400582013-03-22 06:34:35 +00002254 I != E; ++I) {
2255 Expr *Var = SemaRef.SubstExpr(*I, TemplateArgs).take();
2256 assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
Alexey Bataev6af701f2013-05-13 04:18:18 +00002257 Vars.push_back(Var);
Alexey Bataevc6400582013-03-22 06:34:35 +00002258 }
2259
2260 OMPThreadPrivateDecl *TD =
2261 SemaRef.CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
2262
2263 return TD;
2264}
2265
Eli Friedmanded99792013-06-27 23:21:55 +00002266Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
2267 return VisitFunctionDecl(D, 0);
2268}
2269
2270Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
2271 return VisitCXXMethodDecl(D, 0);
2272}
2273
2274Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
2275 llvm_unreachable("There are only CXXRecordDecls in C++");
2276}
2277
2278Decl *
2279TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
2280 ClassTemplateSpecializationDecl *D) {
2281 llvm_unreachable("Only ClassTemplatePartialSpecializationDecls occur"
2282 "inside templates");
2283}
2284
Larisse Voufoef4579c2013-08-06 01:03:05 +00002285Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
2286 VarTemplateSpecializationDecl *D) {
2287
2288 TemplateArgumentListInfo VarTemplateArgsInfo;
2289 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
2290 assert(VarTemplate &&
2291 "A template specialization without specialized template?");
2292
2293 // Substitute the current template arguments.
2294 const TemplateArgumentListInfo &TemplateArgsInfo = D->getTemplateArgsInfo();
2295 VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo.getLAngleLoc());
2296 VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo.getRAngleLoc());
2297
2298 if (SemaRef.Subst(TemplateArgsInfo.getArgumentArray(),
2299 TemplateArgsInfo.size(), VarTemplateArgsInfo, TemplateArgs))
2300 return 0;
2301
2302 // Check that the template argument list is well-formed for this template.
2303 SmallVector<TemplateArgument, 4> Converted;
2304 bool ExpansionIntoFixedList = false;
2305 if (SemaRef.CheckTemplateArgumentList(
2306 VarTemplate, VarTemplate->getLocStart(),
2307 const_cast<TemplateArgumentListInfo &>(VarTemplateArgsInfo), false,
2308 Converted, &ExpansionIntoFixedList))
2309 return 0;
2310
2311 // Find the variable template specialization declaration that
2312 // corresponds to these arguments.
2313 void *InsertPos = 0;
2314 if (VarTemplateSpecializationDecl *VarSpec = VarTemplate->findSpecialization(
2315 Converted.data(), Converted.size(), InsertPos))
2316 // If we already have a variable template specialization, return it.
2317 return VarSpec;
2318
2319 return VisitVarTemplateSpecializationDecl(VarTemplate, D, InsertPos,
2320 VarTemplateArgsInfo, Converted);
2321}
2322
2323Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
2324 VarTemplateDecl *VarTemplate, VarDecl *D, void *InsertPos,
2325 const TemplateArgumentListInfo &TemplateArgsInfo,
2326 SmallVectorImpl<TemplateArgument> &Converted) {
2327
2328 // If this is the variable for an anonymous struct or union,
2329 // instantiate the anonymous struct/union type first.
2330 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
2331 if (RecordTy->getDecl()->isAnonymousStructOrUnion())
2332 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
2333 return 0;
2334
2335 // Do substitution on the type of the declaration
2336 TypeSourceInfo *DI =
2337 SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
2338 D->getTypeSpecStartLoc(), D->getDeclName());
2339 if (!DI)
2340 return 0;
2341
2342 if (DI->getType()->isFunctionType()) {
2343 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
2344 << D->isStaticDataMember() << DI->getType();
2345 return 0;
2346 }
2347
2348 // Build the instantiated declaration
2349 VarTemplateSpecializationDecl *Var = VarTemplateSpecializationDecl::Create(
2350 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
2351 VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted.data(),
2352 Converted.size());
2353 Var->setTemplateArgsInfo(TemplateArgsInfo);
2354 VarTemplate->AddSpecialization(Var, InsertPos);
2355
2356 // Substitute the nested name specifier, if any.
2357 if (SubstQualifier(D, Var))
2358 return 0;
2359
2360 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs,
2361 StartingScope);
2362
2363 return Var;
2364}
2365
Eli Friedmanded99792013-06-27 23:21:55 +00002366Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
2367 llvm_unreachable("@defs is not supported in Objective-C++");
2368}
2369
2370Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
2371 // FIXME: We need to be able to instantiate FriendTemplateDecls.
2372 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
2373 DiagnosticsEngine::Error,
2374 "cannot instantiate %0 yet");
2375 SemaRef.Diag(D->getLocation(), DiagID)
2376 << D->getDeclKindName();
2377
2378 return 0;
2379}
2380
2381Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) {
2382 llvm_unreachable("Unexpected decl");
2383}
2384
John McCallce3ff2b2009-08-25 22:02:44 +00002385Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +00002386 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +00002387 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor2fa98002010-02-16 19:28:15 +00002388 if (D->isInvalidDecl())
2389 return 0;
2390
Douglas Gregor8dbc2692009-03-17 21:15:40 +00002391 return Instantiator.Visit(D);
2392}
2393
John McCalle29ba202009-08-20 01:44:21 +00002394/// \brief Instantiates a nested template parameter list in the current
2395/// instantiation context.
2396///
2397/// \param L The parameter list to instantiate
2398///
2399/// \returns NULL if there was an error
2400TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +00002401TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +00002402 // Get errors for all the parameters before bailing out.
2403 bool Invalid = false;
2404
2405 unsigned N = L->size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00002406 typedef SmallVector<NamedDecl *, 8> ParamVector;
John McCalle29ba202009-08-20 01:44:21 +00002407 ParamVector Params;
2408 Params.reserve(N);
2409 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
2410 PI != PE; ++PI) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002411 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCalle29ba202009-08-20 01:44:21 +00002412 Params.push_back(D);
Douglas Gregor9148c3f2009-11-11 19:13:48 +00002413 Invalid = Invalid || !D || D->isInvalidDecl();
John McCalle29ba202009-08-20 01:44:21 +00002414 }
2415
2416 // Clean up if we had an error.
Douglas Gregorff331c12010-07-25 18:17:45 +00002417 if (Invalid)
John McCalle29ba202009-08-20 01:44:21 +00002418 return NULL;
John McCalle29ba202009-08-20 01:44:21 +00002419
2420 TemplateParameterList *InstL
2421 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
2422 L->getLAngleLoc(), &Params.front(), N,
2423 L->getRAngleLoc());
2424 return InstL;
Mike Stump1eb44332009-09-09 15:08:12 +00002425}
John McCalle29ba202009-08-20 01:44:21 +00002426
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002427/// \brief Instantiate the declaration of a class template partial
Douglas Gregored9c0f92009-10-29 00:04:11 +00002428/// specialization.
2429///
2430/// \param ClassTemplate the (instantiated) class template that is partially
2431// specialized by the instantiation of \p PartialSpec.
2432///
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002433/// \param PartialSpec the (uninstantiated) class template partial
Douglas Gregored9c0f92009-10-29 00:04:11 +00002434/// specialization that we are instantiating.
2435///
Douglas Gregord65587f2010-11-10 19:44:59 +00002436/// \returns The instantiated partial specialization, if successful; otherwise,
2437/// NULL to indicate an error.
2438ClassTemplatePartialSpecializationDecl *
Douglas Gregored9c0f92009-10-29 00:04:11 +00002439TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
2440 ClassTemplateDecl *ClassTemplate,
2441 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00002442 // Create a local instantiation scope for this class template partial
2443 // specialization, which will contain the instantiations of the template
2444 // parameters.
John McCall2a7fb272010-08-25 05:32:35 +00002445 LocalInstantiationScope Scope(SemaRef);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002446
Douglas Gregored9c0f92009-10-29 00:04:11 +00002447 // Substitute into the template parameters of the class template partial
2448 // specialization.
2449 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
2450 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2451 if (!InstParams)
Douglas Gregord65587f2010-11-10 19:44:59 +00002452 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002453
Douglas Gregored9c0f92009-10-29 00:04:11 +00002454 // Substitute into the template arguments of the class template partial
2455 // specialization.
Enea Zaffanellac1cef082013-08-10 07:24:53 +00002456 const ASTTemplateArgumentListInfo *TemplArgInfo
2457 = PartialSpec->getTemplateArgsAsWritten();
2458 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
2459 TemplArgInfo->RAngleLoc);
2460 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
2461 TemplArgInfo->NumTemplateArgs,
Douglas Gregore02e2622010-12-22 21:19:48 +00002462 InstTemplateArgs, TemplateArgs))
2463 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002464
Douglas Gregored9c0f92009-10-29 00:04:11 +00002465 // Check that the template argument list is well-formed for this
2466 // class template.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002467 SmallVector<TemplateArgument, 4> Converted;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002468 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002469 PartialSpec->getLocation(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002470 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002471 false,
2472 Converted))
Douglas Gregord65587f2010-11-10 19:44:59 +00002473 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00002474
2475 // Figure out where to insert this class template partial specialization
2476 // in the member template's set of class template partial specializations.
Douglas Gregored9c0f92009-10-29 00:04:11 +00002477 void *InsertPos = 0;
2478 ClassTemplateSpecializationDecl *PrevDecl
Douglas Gregor910f8002010-11-07 23:05:16 +00002479 = ClassTemplate->findPartialSpecialization(Converted.data(),
2480 Converted.size(), InsertPos);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002481
Douglas Gregored9c0f92009-10-29 00:04:11 +00002482 // Build the canonical type that describes the converted template
2483 // arguments of the class template partial specialization.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002484 QualType CanonType
Douglas Gregored9c0f92009-10-29 00:04:11 +00002485 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
Douglas Gregor910f8002010-11-07 23:05:16 +00002486 Converted.data(),
2487 Converted.size());
Douglas Gregored9c0f92009-10-29 00:04:11 +00002488
2489 // Build the fully-sugared type for this class template
2490 // specialization as the user wrote in the specialization
2491 // itself. This means that we'll pretty-print the type retrieved
2492 // from the specialization's declaration the way that the user
2493 // actually wrote the specialization, rather than formatting the
2494 // name based on the "canonical" representation used to store the
2495 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00002496 TypeSourceInfo *WrittenTy
2497 = SemaRef.Context.getTemplateSpecializationTypeInfo(
2498 TemplateName(ClassTemplate),
2499 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00002500 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002501 CanonType);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002502
Douglas Gregored9c0f92009-10-29 00:04:11 +00002503 if (PrevDecl) {
2504 // We've already seen a partial specialization with the same template
2505 // parameters and template arguments. This can happen, for example, when
2506 // substituting the outer template arguments ends up causing two
2507 // class template partial specializations of a member class template
2508 // to have identical forms, e.g.,
2509 //
2510 // template<typename T, typename U>
2511 // struct Outer {
2512 // template<typename X, typename Y> struct Inner;
2513 // template<typename Y> struct Inner<T, Y>;
2514 // template<typename Y> struct Inner<U, Y>;
2515 // };
2516 //
2517 // Outer<int, int> outer; // error: the partial specializations of Inner
2518 // // have the same signature.
2519 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
Douglas Gregord65587f2010-11-10 19:44:59 +00002520 << WrittenTy->getType();
Douglas Gregored9c0f92009-10-29 00:04:11 +00002521 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
2522 << SemaRef.Context.getTypeDeclType(PrevDecl);
Douglas Gregord65587f2010-11-10 19:44:59 +00002523 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00002524 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002525
2526
Douglas Gregored9c0f92009-10-29 00:04:11 +00002527 // Create the class template partial specialization declaration.
2528 ClassTemplatePartialSpecializationDecl *InstPartialSpec
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002529 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
Douglas Gregor13c85772010-05-06 00:28:52 +00002530 PartialSpec->getTagKind(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002531 Owner,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002532 PartialSpec->getLocStart(),
2533 PartialSpec->getLocation(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00002534 InstParams,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002535 ClassTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00002536 Converted.data(),
2537 Converted.size(),
John McCalld5532b62009-11-23 01:53:49 +00002538 InstTemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00002539 CanonType,
Richard Smith37fd27d2013-08-22 23:27:37 +00002540 0);
John McCallb6217662010-03-15 10:12:16 +00002541 // Substitute the nested name specifier, if any.
2542 if (SubstQualifier(PartialSpec, InstPartialSpec))
2543 return 0;
2544
Douglas Gregored9c0f92009-10-29 00:04:11 +00002545 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
Douglas Gregor4469e8a2010-05-19 17:02:24 +00002546 InstPartialSpec->setTypeAsWritten(WrittenTy);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002547
Douglas Gregored9c0f92009-10-29 00:04:11 +00002548 // Add this partial specialization to the set of class template partial
2549 // specializations.
Douglas Gregor1e1e9722012-03-28 14:34:23 +00002550 ClassTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/0);
Douglas Gregord65587f2010-11-10 19:44:59 +00002551 return InstPartialSpec;
Douglas Gregored9c0f92009-10-29 00:04:11 +00002552}
2553
Larisse Voufoef4579c2013-08-06 01:03:05 +00002554/// \brief Instantiate the declaration of a variable template partial
2555/// specialization.
2556///
2557/// \param VarTemplate the (instantiated) variable template that is partially
2558/// specialized by the instantiation of \p PartialSpec.
2559///
2560/// \param PartialSpec the (uninstantiated) variable template partial
2561/// specialization that we are instantiating.
2562///
2563/// \returns The instantiated partial specialization, if successful; otherwise,
2564/// NULL to indicate an error.
2565VarTemplatePartialSpecializationDecl *
2566TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization(
2567 VarTemplateDecl *VarTemplate,
2568 VarTemplatePartialSpecializationDecl *PartialSpec) {
2569 // Create a local instantiation scope for this variable template partial
2570 // specialization, which will contain the instantiations of the template
2571 // parameters.
2572 LocalInstantiationScope Scope(SemaRef);
2573
2574 // Substitute into the template parameters of the variable template partial
2575 // specialization.
2576 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
2577 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2578 if (!InstParams)
2579 return 0;
2580
2581 // Substitute into the template arguments of the variable template partial
2582 // specialization.
Enea Zaffanellac1cef082013-08-10 07:24:53 +00002583 const ASTTemplateArgumentListInfo *TemplArgInfo
2584 = PartialSpec->getTemplateArgsAsWritten();
2585 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
2586 TemplArgInfo->RAngleLoc);
2587 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
2588 TemplArgInfo->NumTemplateArgs,
Larisse Voufoef4579c2013-08-06 01:03:05 +00002589 InstTemplateArgs, TemplateArgs))
2590 return 0;
2591
2592 // Check that the template argument list is well-formed for this
2593 // class template.
2594 SmallVector<TemplateArgument, 4> Converted;
2595 if (SemaRef.CheckTemplateArgumentList(VarTemplate, PartialSpec->getLocation(),
2596 InstTemplateArgs, false, Converted))
2597 return 0;
2598
2599 // Figure out where to insert this variable template partial specialization
2600 // in the member template's set of variable template partial specializations.
2601 void *InsertPos = 0;
2602 VarTemplateSpecializationDecl *PrevDecl =
2603 VarTemplate->findPartialSpecialization(Converted.data(), Converted.size(),
2604 InsertPos);
2605
2606 // Build the canonical type that describes the converted template
2607 // arguments of the variable template partial specialization.
2608 QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
2609 TemplateName(VarTemplate), Converted.data(), Converted.size());
2610
2611 // Build the fully-sugared type for this variable template
2612 // specialization as the user wrote in the specialization
2613 // itself. This means that we'll pretty-print the type retrieved
2614 // from the specialization's declaration the way that the user
2615 // actually wrote the specialization, rather than formatting the
2616 // name based on the "canonical" representation used to store the
2617 // template arguments in the specialization.
2618 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
2619 TemplateName(VarTemplate), PartialSpec->getLocation(), InstTemplateArgs,
2620 CanonType);
2621
2622 if (PrevDecl) {
2623 // We've already seen a partial specialization with the same template
2624 // parameters and template arguments. This can happen, for example, when
2625 // substituting the outer template arguments ends up causing two
2626 // variable template partial specializations of a member variable template
2627 // to have identical forms, e.g.,
2628 //
2629 // template<typename T, typename U>
2630 // struct Outer {
2631 // template<typename X, typename Y> pair<X,Y> p;
2632 // template<typename Y> pair<T, Y> p;
2633 // template<typename Y> pair<U, Y> p;
2634 // };
2635 //
2636 // Outer<int, int> outer; // error: the partial specializations of Inner
2637 // // have the same signature.
2638 SemaRef.Diag(PartialSpec->getLocation(),
2639 diag::err_var_partial_spec_redeclared)
2640 << WrittenTy->getType();
2641 SemaRef.Diag(PrevDecl->getLocation(),
2642 diag::note_var_prev_partial_spec_here);
2643 return 0;
2644 }
2645
2646 // Do substitution on the type of the declaration
2647 TypeSourceInfo *DI = SemaRef.SubstType(
2648 PartialSpec->getTypeSourceInfo(), TemplateArgs,
2649 PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName());
2650 if (!DI)
2651 return 0;
2652
2653 if (DI->getType()->isFunctionType()) {
2654 SemaRef.Diag(PartialSpec->getLocation(),
2655 diag::err_variable_instantiates_to_function)
2656 << PartialSpec->isStaticDataMember() << DI->getType();
2657 return 0;
2658 }
2659
2660 // Create the variable template partial specialization declaration.
2661 VarTemplatePartialSpecializationDecl *InstPartialSpec =
2662 VarTemplatePartialSpecializationDecl::Create(
2663 SemaRef.Context, Owner, PartialSpec->getInnerLocStart(),
2664 PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(),
2665 DI, PartialSpec->getStorageClass(), Converted.data(),
Richard Smith37fd27d2013-08-22 23:27:37 +00002666 Converted.size(), InstTemplateArgs);
Larisse Voufoef4579c2013-08-06 01:03:05 +00002667
2668 // Substitute the nested name specifier, if any.
2669 if (SubstQualifier(PartialSpec, InstPartialSpec))
2670 return 0;
2671
2672 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
2673 InstPartialSpec->setTypeAsWritten(WrittenTy);
2674
Larisse Voufoef4579c2013-08-06 01:03:05 +00002675 // Add this partial specialization to the set of variable template partial
2676 // specializations. The instantiation of the initializer is not necessary.
2677 VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/0);
Larisse Voufo04592e72013-08-22 00:28:27 +00002678
2679 // Set the initializer, to use as pattern for initialization.
2680 if (VarDecl *Def = PartialSpec->getDefinition(SemaRef.getASTContext()))
2681 PartialSpec = cast<VarTemplatePartialSpecializationDecl>(Def);
2682 SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs,
2683 LateAttrs, StartingScope);
2684 InstPartialSpec->setInit(PartialSpec->getInit());
2685
Larisse Voufoef4579c2013-08-06 01:03:05 +00002686 return InstPartialSpec;
2687}
2688
John McCall21ef0fa2010-03-11 09:03:00 +00002689TypeSourceInfo*
John McCallce3ff2b2009-08-25 22:02:44 +00002690TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002691 SmallVectorImpl<ParmVarDecl *> &Params) {
John McCall21ef0fa2010-03-11 09:03:00 +00002692 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
2693 assert(OldTInfo && "substituting function without type source info");
2694 assert(Params.empty() && "parameter vector is non-empty at start");
Douglas Gregorcefc3af2012-04-16 07:05:22 +00002695
2696 CXXRecordDecl *ThisContext = 0;
2697 unsigned ThisTypeQuals = 0;
2698 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Richard Smithcafeb942013-06-07 02:33:37 +00002699 ThisContext = cast<CXXRecordDecl>(Owner);
Douglas Gregorcefc3af2012-04-16 07:05:22 +00002700 ThisTypeQuals = Method->getTypeQualifiers();
2701 }
2702
John McCall6cd3b9f2010-04-09 17:38:44 +00002703 TypeSourceInfo *NewTInfo
2704 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
2705 D->getTypeSpecStartLoc(),
Douglas Gregorcefc3af2012-04-16 07:05:22 +00002706 D->getDeclName(),
2707 ThisContext, ThisTypeQuals);
John McCall21ef0fa2010-03-11 09:03:00 +00002708 if (!NewTInfo)
2709 return 0;
Douglas Gregor5545e162009-03-24 00:38:23 +00002710
Reid Klecknerc66e7e92013-07-31 21:00:18 +00002711 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
2712 if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
2713 if (NewTInfo != OldTInfo) {
2714 // Get parameters from the new type info.
Abramo Bagnara140a2bd2010-12-13 22:27:55 +00002715 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
David Blaikie39e6ab42013-02-18 22:06:02 +00002716 FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
Richard Smith500d7292012-07-18 01:29:05 +00002717 unsigned NewIdx = 0;
David Blaikie39e6ab42013-02-18 22:06:02 +00002718 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumArgs();
Douglas Gregor12c9c002011-01-07 16:43:16 +00002719 OldIdx != NumOldParams; ++OldIdx) {
David Blaikie39e6ab42013-02-18 22:06:02 +00002720 ParmVarDecl *OldParam = OldProtoLoc.getArg(OldIdx);
Richard Smith500d7292012-07-18 01:29:05 +00002721 LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
2722
David Blaikiedc84cd52013-02-20 22:23:23 +00002723 Optional<unsigned> NumArgumentsInExpansion;
Richard Smith500d7292012-07-18 01:29:05 +00002724 if (OldParam->isParameterPack())
2725 NumArgumentsInExpansion =
2726 SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
2727 TemplateArgs);
2728 if (!NumArgumentsInExpansion) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002729 // Simple case: normal parameter, or a parameter pack that's
Douglas Gregor12c9c002011-01-07 16:43:16 +00002730 // instantiated to a (still-dependent) parameter pack.
David Blaikie39e6ab42013-02-18 22:06:02 +00002731 ParmVarDecl *NewParam = NewProtoLoc.getArg(NewIdx++);
Douglas Gregor12c9c002011-01-07 16:43:16 +00002732 Params.push_back(NewParam);
Richard Smith500d7292012-07-18 01:29:05 +00002733 Scope->InstantiatedLocal(OldParam, NewParam);
2734 } else {
2735 // Parameter pack expansion: make the instantiation an argument pack.
2736 Scope->MakeInstantiatedLocalArgPack(OldParam);
2737 for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
David Blaikie39e6ab42013-02-18 22:06:02 +00002738 ParmVarDecl *NewParam = NewProtoLoc.getArg(NewIdx++);
Richard Smith500d7292012-07-18 01:29:05 +00002739 Params.push_back(NewParam);
2740 Scope->InstantiatedLocalPackArg(OldParam, NewParam);
2741 }
Douglas Gregor12c9c002011-01-07 16:43:16 +00002742 }
Douglas Gregor6920cdc2010-05-03 15:32:18 +00002743 }
Reid Klecknerc66e7e92013-07-31 21:00:18 +00002744 } else {
2745 // The function type itself was not dependent and therefore no
2746 // substitution occurred. However, we still need to instantiate
2747 // the function parameters themselves.
2748 const FunctionProtoType *OldProto =
2749 cast<FunctionProtoType>(OldProtoLoc.getType());
David Blaikie39e6ab42013-02-18 22:06:02 +00002750 for (unsigned i = 0, i_end = OldProtoLoc.getNumArgs(); i != i_end; ++i) {
Reid Klecknerc66e7e92013-07-31 21:00:18 +00002751 ParmVarDecl *OldParam = OldProtoLoc.getArg(i);
2752 if (!OldParam) {
2753 Params.push_back(SemaRef.BuildParmVarDeclForTypedef(
2754 D, D->getLocation(), OldProto->getArgType(i)));
2755 continue;
2756 }
2757
Eli Friedmanded99792013-06-27 23:21:55 +00002758 ParmVarDecl *Parm =
Reid Klecknerc66e7e92013-07-31 21:00:18 +00002759 cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam));
Douglas Gregor6920cdc2010-05-03 15:32:18 +00002760 if (!Parm)
2761 return 0;
2762 Params.push_back(Parm);
2763 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00002764 }
Reid Klecknerc66e7e92013-07-31 21:00:18 +00002765 } else {
2766 // If the type of this function, after ignoring parentheses, is not
2767 // *directly* a function type, then we're instantiating a function that
2768 // was declared via a typedef or with attributes, e.g.,
2769 //
2770 // typedef int functype(int, int);
2771 // functype func;
2772 // int __cdecl meth(int, int);
2773 //
2774 // In this case, we'll just go instantiate the ParmVarDecls that we
2775 // synthesized in the method declaration.
2776 SmallVector<QualType, 4> ParamTypes;
2777 if (SemaRef.SubstParmTypes(D->getLocation(), D->param_begin(),
2778 D->getNumParams(), TemplateArgs, ParamTypes,
2779 &Params))
2780 return 0;
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00002781 }
Reid Klecknerc66e7e92013-07-31 21:00:18 +00002782
John McCall21ef0fa2010-03-11 09:03:00 +00002783 return NewTInfo;
Douglas Gregor5545e162009-03-24 00:38:23 +00002784}
2785
Richard Smithe6975e92012-04-17 00:58:00 +00002786/// Introduce the instantiated function parameters into the local
2787/// instantiation scope, and set the parameter names to those used
2788/// in the template.
2789static void addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function,
2790 const FunctionDecl *PatternDecl,
2791 LocalInstantiationScope &Scope,
2792 const MultiLevelTemplateArgumentList &TemplateArgs) {
2793 unsigned FParamIdx = 0;
2794 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
2795 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
2796 if (!PatternParam->isParameterPack()) {
2797 // Simple case: not a parameter pack.
2798 assert(FParamIdx < Function->getNumParams());
2799 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
2800 FunctionParam->setDeclName(PatternParam->getDeclName());
2801 Scope.InstantiatedLocal(PatternParam, FunctionParam);
2802 ++FParamIdx;
2803 continue;
2804 }
2805
2806 // Expand the parameter pack.
2807 Scope.MakeInstantiatedLocalArgPack(PatternParam);
David Blaikiedc84cd52013-02-20 22:23:23 +00002808 Optional<unsigned> NumArgumentsInExpansion
Richard Smithe6975e92012-04-17 00:58:00 +00002809 = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
Richard Smith500d7292012-07-18 01:29:05 +00002810 assert(NumArgumentsInExpansion &&
2811 "should only be called when all template arguments are known");
2812 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
Richard Smithe6975e92012-04-17 00:58:00 +00002813 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
2814 FunctionParam->setDeclName(PatternParam->getDeclName());
2815 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
2816 ++FParamIdx;
2817 }
2818 }
2819}
2820
2821static void InstantiateExceptionSpec(Sema &SemaRef, FunctionDecl *New,
2822 const FunctionProtoType *Proto,
2823 const MultiLevelTemplateArgumentList &TemplateArgs) {
Richard Smith13bffc52012-04-19 00:08:28 +00002824 assert(Proto->getExceptionSpecType() != EST_Uninstantiated);
2825
Richard Smithe6975e92012-04-17 00:58:00 +00002826 // C++11 [expr.prim.general]p3:
2827 // If a declaration declares a member function or member function
2828 // template of a class X, the expression this is a prvalue of type
2829 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
2830 // and the end of the function-definition, member-declarator, or
2831 // declarator.
2832 CXXRecordDecl *ThisContext = 0;
2833 unsigned ThisTypeQuals = 0;
2834 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(New)) {
2835 ThisContext = Method->getParent();
2836 ThisTypeQuals = Method->getTypeQualifiers();
2837 }
2838 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals,
Richard Smith80ad52f2013-01-02 11:42:31 +00002839 SemaRef.getLangOpts().CPlusPlus11);
Richard Smithe6975e92012-04-17 00:58:00 +00002840
2841 // The function has an exception specification or a "noreturn"
2842 // attribute. Substitute into each of the exception types.
2843 SmallVector<QualType, 4> Exceptions;
2844 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
2845 // FIXME: Poor location information!
2846 if (const PackExpansionType *PackExpansion
2847 = Proto->getExceptionType(I)->getAs<PackExpansionType>()) {
2848 // We have a pack expansion. Instantiate it.
2849 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2850 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
2851 Unexpanded);
2852 assert(!Unexpanded.empty() &&
2853 "Pack expansion without parameter packs?");
2854
2855 bool Expand = false;
2856 bool RetainExpansion = false;
Richard Smithcafeb942013-06-07 02:33:37 +00002857 Optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
Richard Smithe6975e92012-04-17 00:58:00 +00002858 if (SemaRef.CheckParameterPacksForExpansion(New->getLocation(),
2859 SourceRange(),
2860 Unexpanded,
2861 TemplateArgs,
2862 Expand,
2863 RetainExpansion,
2864 NumExpansions))
2865 break;
2866
2867 if (!Expand) {
2868 // We can't expand this pack expansion into separate arguments yet;
2869 // just substitute into the pattern and create a new pack expansion
2870 // type.
2871 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2872 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2873 TemplateArgs,
2874 New->getLocation(), New->getDeclName());
2875 if (T.isNull())
2876 break;
2877
2878 T = SemaRef.Context.getPackExpansionType(T, NumExpansions);
2879 Exceptions.push_back(T);
2880 continue;
2881 }
2882
2883 // Substitute into the pack expansion pattern for each template
2884 bool Invalid = false;
2885 for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
2886 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, ArgIdx);
2887
2888 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2889 TemplateArgs,
2890 New->getLocation(), New->getDeclName());
2891 if (T.isNull()) {
2892 Invalid = true;
2893 break;
2894 }
2895
2896 Exceptions.push_back(T);
2897 }
2898
2899 if (Invalid)
2900 break;
2901
2902 continue;
2903 }
2904
2905 QualType T
2906 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
2907 New->getLocation(), New->getDeclName());
2908 if (T.isNull() ||
2909 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
2910 continue;
2911
2912 Exceptions.push_back(T);
2913 }
2914 Expr *NoexceptExpr = 0;
2915 if (Expr *OldNoexceptExpr = Proto->getNoexceptExpr()) {
2916 EnterExpressionEvaluationContext Unevaluated(SemaRef,
2917 Sema::ConstantEvaluated);
2918 ExprResult E = SemaRef.SubstExpr(OldNoexceptExpr, TemplateArgs);
2919 if (E.isUsable())
2920 E = SemaRef.CheckBooleanCondition(E.get(), E.get()->getLocStart());
2921
2922 if (E.isUsable()) {
2923 NoexceptExpr = E.take();
2924 if (!NoexceptExpr->isTypeDependent() &&
2925 !NoexceptExpr->isValueDependent())
Douglas Gregorab41fe92012-05-04 22:38:52 +00002926 NoexceptExpr
2927 = SemaRef.VerifyIntegerConstantExpression(NoexceptExpr,
2928 0, diag::err_noexcept_needs_constant_expression,
2929 /*AllowFold*/ false).take();
Richard Smithe6975e92012-04-17 00:58:00 +00002930 }
2931 }
2932
2933 // Rebuild the function type
2934 const FunctionProtoType *NewProto
2935 = New->getType()->getAs<FunctionProtoType>();
2936 assert(NewProto && "Template instantiation without function prototype?");
2937
2938 FunctionProtoType::ExtProtoInfo EPI = NewProto->getExtProtoInfo();
2939 EPI.ExceptionSpecType = Proto->getExceptionSpecType();
2940 EPI.NumExceptions = Exceptions.size();
2941 EPI.Exceptions = Exceptions.data();
2942 EPI.NoexceptExpr = NoexceptExpr;
2943
2944 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
Reid Kleckner0567a792013-06-10 20:51:09 +00002945 NewProto->getArgTypes(), EPI));
Richard Smithe6975e92012-04-17 00:58:00 +00002946}
2947
2948void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
2949 FunctionDecl *Decl) {
Richard Smith13bffc52012-04-19 00:08:28 +00002950 const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
2951 if (Proto->getExceptionSpecType() != EST_Uninstantiated)
Richard Smithe6975e92012-04-17 00:58:00 +00002952 return;
2953
2954 InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
2955 InstantiatingTemplate::ExceptionSpecification());
Richard Smithb9d0b762012-07-27 04:22:15 +00002956 if (Inst) {
2957 // We hit the instantiation depth limit. Clear the exception specification
2958 // so that our callers don't have to cope with EST_Uninstantiated.
2959 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
2960 EPI.ExceptionSpecType = EST_None;
2961 Decl->setType(Context.getFunctionType(Proto->getResultType(),
Reid Kleckner0567a792013-06-10 20:51:09 +00002962 Proto->getArgTypes(), EPI));
Richard Smithe6975e92012-04-17 00:58:00 +00002963 return;
Richard Smithb9d0b762012-07-27 04:22:15 +00002964 }
Richard Smithe6975e92012-04-17 00:58:00 +00002965
2966 // Enter the scope of this instantiation. We don't use
2967 // PushDeclContext because we don't have a scope.
2968 Sema::ContextRAII savedContext(*this, Decl);
2969 LocalInstantiationScope Scope(*this);
2970
2971 MultiLevelTemplateArgumentList TemplateArgs =
2972 getTemplateInstantiationArgs(Decl, 0, /*RelativeToPrimary*/true);
2973
Richard Smith13bffc52012-04-19 00:08:28 +00002974 FunctionDecl *Template = Proto->getExceptionSpecTemplate();
2975 addInstantiatedParametersToScope(*this, Decl, Template, Scope, TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +00002976
Richard Smith13bffc52012-04-19 00:08:28 +00002977 ::InstantiateExceptionSpec(*this, Decl,
2978 Template->getType()->castAs<FunctionProtoType>(),
2979 TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +00002980}
2981
Mike Stump1eb44332009-09-09 15:08:12 +00002982/// \brief Initializes the common fields of an instantiation function
Douglas Gregore53060f2009-06-25 22:08:12 +00002983/// declaration (New) from the corresponding fields of its template (Tmpl).
2984///
2985/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00002986bool
2987TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregore53060f2009-06-25 22:08:12 +00002988 FunctionDecl *Tmpl) {
David Blaikie85f485a2012-07-16 18:50:45 +00002989 if (Tmpl->isDeleted())
Sean Hunt10620eb2011-05-06 20:44:56 +00002990 New->setDeletedAsWritten();
Mike Stump1eb44332009-09-09 15:08:12 +00002991
Douglas Gregorcca9e962009-07-01 22:01:06 +00002992 // If we are performing substituting explicitly-specified template arguments
2993 // or deduced template arguments into a function template and we reach this
2994 // point, we are now past the point where SFINAE applies and have committed
Mike Stump1eb44332009-09-09 15:08:12 +00002995 // to keeping the new function template specialization. We therefore
2996 // convert the active template instantiation for the function template
Douglas Gregorcca9e962009-07-01 22:01:06 +00002997 // into a template instantiation for this specific function template
2998 // specialization, which is not a SFINAE context, so that we diagnose any
2999 // further errors in the declaration itself.
3000 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
3001 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
3002 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
3003 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump1eb44332009-09-09 15:08:12 +00003004 if (FunctionTemplateDecl *FunTmpl
Nick Lewycky4a9e60f2012-11-16 08:40:59 +00003005 = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003006 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorcca9e962009-07-01 22:01:06 +00003007 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +00003008 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +00003009 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
Nick Lewycky4a9e60f2012-11-16 08:40:59 +00003010 ActiveInst.Entity = New;
Douglas Gregorcca9e962009-07-01 22:01:06 +00003011 }
3012 }
Mike Stump1eb44332009-09-09 15:08:12 +00003013
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00003014 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
3015 assert(Proto && "Function template without prototype?");
3016
Sebastian Redl60618fa2011-03-12 11:50:43 +00003017 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
John McCalle23cf432010-12-14 08:05:40 +00003018 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
John McCalle23cf432010-12-14 08:05:40 +00003019
Richard Smithe6975e92012-04-17 00:58:00 +00003020 // DR1330: In C++11, defer instantiation of a non-trivial
3021 // exception specification.
Richard Smith80ad52f2013-01-02 11:42:31 +00003022 if (SemaRef.getLangOpts().CPlusPlus11 &&
Richard Smithe6975e92012-04-17 00:58:00 +00003023 EPI.ExceptionSpecType != EST_None &&
3024 EPI.ExceptionSpecType != EST_DynamicNone &&
3025 EPI.ExceptionSpecType != EST_BasicNoexcept) {
Richard Smith13bffc52012-04-19 00:08:28 +00003026 FunctionDecl *ExceptionSpecTemplate = Tmpl;
3027 if (EPI.ExceptionSpecType == EST_Uninstantiated)
3028 ExceptionSpecTemplate = EPI.ExceptionSpecTemplate;
Richard Smith4841ca52013-04-10 05:48:59 +00003029 ExceptionSpecificationType NewEST = EST_Uninstantiated;
3030 if (EPI.ExceptionSpecType == EST_Unevaluated)
3031 NewEST = EST_Unevaluated;
Richard Smith13bffc52012-04-19 00:08:28 +00003032
Richard Smithe6975e92012-04-17 00:58:00 +00003033 // Mark the function has having an uninstantiated exception specification.
3034 const FunctionProtoType *NewProto
3035 = New->getType()->getAs<FunctionProtoType>();
3036 assert(NewProto && "Template instantiation without function prototype?");
3037 EPI = NewProto->getExtProtoInfo();
Richard Smith4841ca52013-04-10 05:48:59 +00003038 EPI.ExceptionSpecType = NewEST;
Richard Smithe6975e92012-04-17 00:58:00 +00003039 EPI.ExceptionSpecDecl = New;
Richard Smith13bffc52012-04-19 00:08:28 +00003040 EPI.ExceptionSpecTemplate = ExceptionSpecTemplate;
Reid Kleckner0567a792013-06-10 20:51:09 +00003041 New->setType(SemaRef.Context.getFunctionType(
3042 NewProto->getResultType(), NewProto->getArgTypes(), EPI));
Richard Smithe6975e92012-04-17 00:58:00 +00003043 } else {
3044 ::InstantiateExceptionSpec(SemaRef, New, Proto, TemplateArgs);
3045 }
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00003046 }
3047
Rafael Espindola19f74ac2011-07-06 15:46:09 +00003048 // Get the definition. Leaves the variable unchanged if undefined.
Richard Smithe6975e92012-04-17 00:58:00 +00003049 const FunctionDecl *Definition = Tmpl;
Rafael Espindola19f74ac2011-07-06 15:46:09 +00003050 Tmpl->isDefined(Definition);
3051
DeLesley Hutchins23323e02012-01-20 22:50:54 +00003052 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
3053 LateAttrs, StartingScope);
Douglas Gregor7cf84d62010-06-15 17:05:35 +00003054
Douglas Gregore53060f2009-06-25 22:08:12 +00003055 return false;
3056}
3057
Douglas Gregor5545e162009-03-24 00:38:23 +00003058/// \brief Initializes common fields of an instantiated method
3059/// declaration (New) from the corresponding fields of its template
3060/// (Tmpl).
3061///
3062/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00003063bool
3064TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor5545e162009-03-24 00:38:23 +00003065 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +00003066 if (InitFunctionInstantiation(New, Tmpl))
3067 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003068
Douglas Gregor5545e162009-03-24 00:38:23 +00003069 New->setAccess(Tmpl->getAccess());
Fariborz Jahaniane7184df2009-12-03 18:44:40 +00003070 if (Tmpl->isVirtualAsWritten())
Douglas Gregor85606eb2010-09-28 20:50:54 +00003071 New->setVirtualAsWritten(true);
Douglas Gregor5545e162009-03-24 00:38:23 +00003072
Douglas Gregor5545e162009-03-24 00:38:23 +00003073 // FIXME: New needs a pointer to Tmpl
3074 return false;
3075}
Douglas Gregora58861f2009-05-13 20:28:22 +00003076
3077/// \brief Instantiate the definition of the given function from its
3078/// template.
3079///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00003080/// \param PointOfInstantiation the point at which the instantiation was
3081/// required. Note that this is not precisely a "point of instantiation"
3082/// for the function, but it's close.
3083///
Douglas Gregora58861f2009-05-13 20:28:22 +00003084/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00003085/// function template specialization or member function of a class template
3086/// specialization.
3087///
3088/// \param Recursive if true, recursively instantiates any functions that
3089/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00003090///
3091/// \param DefinitionRequired if true, then we are performing an explicit
3092/// instantiation where the body of the function is required. Complain if
3093/// there is no such body.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00003094void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00003095 FunctionDecl *Function,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00003096 bool Recursive,
3097 bool DefinitionRequired) {
Sean Hunt10620eb2011-05-06 20:44:56 +00003098 if (Function->isInvalidDecl() || Function->isDefined())
Douglas Gregor54dabfc2009-05-14 23:26:13 +00003099 return;
3100
Francois Pichetaf0f4d02011-08-14 03:52:19 +00003101 // Never instantiate an explicit specialization except if it is a class scope
3102 // explicit specialization.
3103 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
3104 !Function->getClassScopeSpecializationPattern())
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003105 return;
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00003106
Douglas Gregor1eee0e72009-05-14 21:06:31 +00003107 // Find the function body that we'll be substituting.
Douglas Gregor3b846b62009-10-27 20:53:28 +00003108 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Sean Huntf996e052011-05-27 20:00:14 +00003109 assert(PatternDecl && "instantiating a non-template");
3110
3111 Stmt *Pattern = PatternDecl->getBody(PatternDecl);
3112 assert(PatternDecl && "template definition is not a template");
3113 if (!Pattern) {
3114 // Try to find a defaulted definition
3115 PatternDecl->isDefined(PatternDecl);
Sean Huntdfab8542011-05-25 22:02:25 +00003116 }
Sean Huntf996e052011-05-27 20:00:14 +00003117 assert(PatternDecl && "template definition is not a template");
Douglas Gregor1eee0e72009-05-14 21:06:31 +00003118
Francois Pichet8387e2a2011-04-22 22:18:13 +00003119 // Postpone late parsed template instantiations.
Sean Huntf996e052011-05-27 20:00:14 +00003120 if (PatternDecl->isLateTemplateParsed() &&
Nick Lewycky8a29bc02011-05-12 03:51:24 +00003121 !LateTemplateParser) {
Francois Pichet8387e2a2011-04-22 22:18:13 +00003122 PendingInstantiations.push_back(
3123 std::make_pair(Function, PointOfInstantiation));
3124 return;
3125 }
3126
David Majnemer360d23e2013-08-16 08:29:13 +00003127 // Call the LateTemplateParser callback if there is a need to late parse
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003128 // a templated function definition.
Sean Huntf996e052011-05-27 20:00:14 +00003129 if (!Pattern && PatternDecl->isLateTemplateParsed() &&
Francois Pichet8387e2a2011-04-22 22:18:13 +00003130 LateTemplateParser) {
Richard Smithac32d902013-08-07 21:41:30 +00003131 // FIXME: Optimize to allow individual templates to be deserialized.
3132 if (PatternDecl->isFromASTFile())
3133 ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap);
3134
3135 LateParsedTemplate *LPT = LateParsedTemplateMap.lookup(PatternDecl);
3136 assert(LPT && "missing LateParsedTemplate");
3137 LateTemplateParser(OpaqueParser, *LPT);
Francois Pichet8387e2a2011-04-22 22:18:13 +00003138 Pattern = PatternDecl->getBody(PatternDecl);
3139 }
3140
Sean Huntf996e052011-05-27 20:00:14 +00003141 if (!Pattern && !PatternDecl->isDefaulted()) {
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00003142 if (DefinitionRequired) {
3143 if (Function->getPrimaryTemplate())
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003144 Diag(PointOfInstantiation,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00003145 diag::err_explicit_instantiation_undefined_func_template)
3146 << Function->getPrimaryTemplate();
3147 else
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003148 Diag(PointOfInstantiation,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00003149 diag::err_explicit_instantiation_undefined_member)
3150 << 1 << Function->getDeclName() << Function->getDeclContext();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003151
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00003152 if (PatternDecl)
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003153 Diag(PatternDecl->getLocation(),
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00003154 diag::note_explicit_instantiation_here);
Douglas Gregorcfe833b2010-05-17 17:57:54 +00003155 Function->setInvalidDecl();
Chandler Carruth58e390e2010-08-25 08:27:02 +00003156 } else if (Function->getTemplateSpecializationKind()
3157 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00003158 PendingInstantiations.push_back(
Chandler Carruth58e390e2010-08-25 08:27:02 +00003159 std::make_pair(Function, PointOfInstantiation));
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00003160 }
Chandler Carruth58e390e2010-08-25 08:27:02 +00003161
Douglas Gregor1eee0e72009-05-14 21:06:31 +00003162 return;
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00003163 }
Douglas Gregor1eee0e72009-05-14 21:06:31 +00003164
Richard Smith60e141e2013-05-04 07:00:32 +00003165 // C++1y [temp.explicit]p10:
3166 // Except for inline functions, declarations with types deduced from their
3167 // initializer or return value, and class template specializations, other
3168 // explicit instantiation declarations have the effect of suppressing the
3169 // implicit instantiation of the entity to which they refer.
Mike Stump1eb44332009-09-09 15:08:12 +00003170 if (Function->getTemplateSpecializationKind()
Douglas Gregord0e3daf2009-09-04 22:48:11 +00003171 == TSK_ExplicitInstantiationDeclaration &&
Richard Smith60e141e2013-05-04 07:00:32 +00003172 !PatternDecl->isInlined() &&
Richard Smith37e849a2013-08-14 20:16:31 +00003173 !PatternDecl->getResultType()->getContainedAutoType())
Douglas Gregord0e3daf2009-09-04 22:48:11 +00003174 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003175
Richard Smithd4497dd2013-01-25 00:08:28 +00003176 if (PatternDecl->isInlined())
3177 Function->setImplicitlyInline();
3178
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00003179 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
3180 if (Inst)
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003181 return;
3182
Abramo Bagnarae9946242011-11-18 08:08:52 +00003183 // Copy the inner loc start from the pattern.
3184 Function->setInnerLocStart(PatternDecl->getInnerLocStart());
3185
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00003186 // If we're performing recursive template instantiation, create our own
3187 // queue of pending implicit instantiations that we will instantiate later,
3188 // while we're still within our own instantiation context.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003189 SmallVector<VTableUse, 16> SavedVTableUses;
Chandler Carruth62c78d52010-08-25 08:44:16 +00003190 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
Faisal Vali86648b12013-06-26 02:34:24 +00003191 std::deque<PendingImplicitInstantiation>
3192 SavedPendingLocalImplicitInstantiations;
3193 SavedPendingLocalImplicitInstantiations.swap(
3194 PendingLocalImplicitInstantiations);
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00003195 if (Recursive) {
3196 VTableUses.swap(SavedVTableUses);
Chandler Carruth62c78d52010-08-25 08:44:16 +00003197 PendingInstantiations.swap(SavedPendingInstantiations);
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00003198 }
Mike Stump1eb44332009-09-09 15:08:12 +00003199
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003200 EnterExpressionEvaluationContext EvalContext(*this,
John McCallf312b1e2010-08-26 23:41:50 +00003201 Sema::PotentiallyEvaluated);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00003202
Douglas Gregor54dabfc2009-05-14 23:26:13 +00003203 // Introduce a new scope where local variable instantiations will be
Douglas Gregor60406be2010-01-16 22:29:39 +00003204 // recorded, unless we're actually a member function within a local
3205 // class, in which case we need to merge our results with the parent
3206 // scope (of the enclosing function).
3207 bool MergeWithParentScope = false;
3208 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
3209 MergeWithParentScope = Rec->isLocalClass();
3210
3211 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +00003212
Richard Smith1d28caf2012-12-11 01:14:52 +00003213 if (PatternDecl->isDefaulted())
Sean Huntcd10dec2011-05-23 23:14:04 +00003214 SetDeclDefaulted(Function, PatternDecl->getLocation());
Richard Smith1d28caf2012-12-11 01:14:52 +00003215 else {
3216 ActOnStartOfFunctionDef(0, Function);
3217
3218 // Enter the scope of this instantiation. We don't use
3219 // PushDeclContext because we don't have a scope.
3220 Sema::ContextRAII savedContext(*this, Function);
3221
3222 MultiLevelTemplateArgumentList TemplateArgs =
3223 getTemplateInstantiationArgs(Function, 0, false, PatternDecl);
3224
3225 addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope,
3226 TemplateArgs);
3227
Sean Huntcd10dec2011-05-23 23:14:04 +00003228 // If this is a constructor, instantiate the member initializers.
3229 if (const CXXConstructorDecl *Ctor =
3230 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
3231 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
3232 TemplateArgs);
3233 }
3234
3235 // Instantiate the function body.
3236 StmtResult Body = SubstStmt(Pattern, TemplateArgs);
3237
3238 if (Body.isInvalid())
3239 Function->setInvalidDecl();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003240
Sean Huntcd10dec2011-05-23 23:14:04 +00003241 ActOnFinishFunctionBody(Function, Body.get(),
3242 /*IsInstantiation=*/true);
Richard Smith1d28caf2012-12-11 01:14:52 +00003243
3244 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
3245
3246 savedContext.pop();
Mike Stump1eb44332009-09-09 15:08:12 +00003247 }
3248
Douglas Gregoraba43bb2009-05-26 20:50:29 +00003249 DeclGroupRef DG(Function);
3250 Consumer.HandleTopLevelDecl(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00003251
Douglas Gregor60406be2010-01-16 22:29:39 +00003252 // This class may have local implicit instantiations that need to be
3253 // instantiation within this scope.
Chandler Carruth62c78d52010-08-25 08:44:16 +00003254 PerformPendingInstantiations(/*LocalOnly=*/true);
Douglas Gregor60406be2010-01-16 22:29:39 +00003255 Scope.Exit();
3256
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00003257 if (Recursive) {
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00003258 // Define any pending vtables.
3259 DefineUsedVTables();
3260
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00003261 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00003262 // instantiation of this template.
Chandler Carruth62c78d52010-08-25 08:44:16 +00003263 PerformPendingInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00003264
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00003265 // Restore the set of pending vtables.
Nick Lewycky81559102011-05-31 07:58:42 +00003266 assert(VTableUses.empty() &&
3267 "VTableUses should be empty before it is discarded.");
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00003268 VTableUses.swap(SavedVTableUses);
3269
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00003270 // Restore the set of pending implicit instantiations.
Nick Lewycky81559102011-05-31 07:58:42 +00003271 assert(PendingInstantiations.empty() &&
3272 "PendingInstantiations should be empty before it is discarded.");
Chandler Carruth62c78d52010-08-25 08:44:16 +00003273 PendingInstantiations.swap(SavedPendingInstantiations);
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00003274 }
Faisal Vali86648b12013-06-26 02:34:24 +00003275 SavedPendingLocalImplicitInstantiations.swap(
3276 PendingLocalImplicitInstantiations);
Douglas Gregora58861f2009-05-13 20:28:22 +00003277}
3278
Larisse Voufoef4579c2013-08-06 01:03:05 +00003279VarTemplateSpecializationDecl *Sema::BuildVarTemplateInstantiation(
3280 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
3281 const TemplateArgumentList &TemplateArgList,
3282 const TemplateArgumentListInfo &TemplateArgsInfo,
3283 SmallVectorImpl<TemplateArgument> &Converted,
3284 SourceLocation PointOfInstantiation, void *InsertPos,
3285 LateInstantiatedAttrVec *LateAttrs,
3286 LocalInstantiationScope *StartingScope) {
3287 if (FromVar->isInvalidDecl())
3288 return 0;
3289
3290 InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar);
3291 if (Inst)
3292 return 0;
3293
3294 MultiLevelTemplateArgumentList TemplateArgLists;
3295 TemplateArgLists.addOuterTemplateArguments(&TemplateArgList);
3296
3297 TemplateDeclInstantiator Instantiator(
3298 *this, VarTemplate->getDeclContext(),
3299 MultiLevelTemplateArgumentList(TemplateArgList));
3300
3301 // TODO: Set LateAttrs and StartingScope ...
3302
3303 return cast_or_null<VarTemplateSpecializationDecl>(
3304 Instantiator.VisitVarTemplateSpecializationDecl(
3305 VarTemplate, FromVar, InsertPos, TemplateArgsInfo, Converted));
3306}
3307
3308/// \brief Instantiates a variable template specialization by completing it
3309/// with appropriate type information and initializer.
3310VarTemplateSpecializationDecl *Sema::CompleteVarTemplateSpecializationDecl(
3311 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
3312 const MultiLevelTemplateArgumentList &TemplateArgs) {
3313
3314 // Do substitution on the type of the declaration
Larisse Voufo04592e72013-08-22 00:28:27 +00003315 MultiLevelTemplateArgumentList Innermost;
3316 Innermost.addOuterTemplateArguments(TemplateArgs.getInnermost());
Larisse Voufoef4579c2013-08-06 01:03:05 +00003317 TypeSourceInfo *DI =
Larisse Voufo04592e72013-08-22 00:28:27 +00003318 SubstType(PatternDecl->getTypeSourceInfo(), Innermost,
Larisse Voufoef4579c2013-08-06 01:03:05 +00003319 PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName());
3320 if (!DI)
3321 return 0;
3322
3323 // Update the type of this variable template specialization.
3324 VarSpec->setType(DI->getType());
3325
3326 // Instantiate the initializer.
3327 InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs);
3328
3329 return VarSpec;
3330}
3331
3332/// BuildVariableInstantiation - Used after a new variable has been created.
3333/// Sets basic variable data and decides whether to postpone the
3334/// variable instantiation.
3335void Sema::BuildVariableInstantiation(
3336 VarDecl *NewVar, VarDecl *OldVar,
3337 const MultiLevelTemplateArgumentList &TemplateArgs,
Larisse Voufo567f9172013-08-22 00:59:14 +00003338 LateInstantiatedAttrVec *LateAttrs, LocalInstantiationScope *StartingScope,
3339 bool InstantiatingVarTemplate) {
Larisse Voufoef4579c2013-08-06 01:03:05 +00003340
3341 // If we are instantiating a static data member defined
3342 // out-of-line, the instantiation will have the same lexical
3343 // context (which will be a namespace scope) as the template.
3344 if (OldVar->isOutOfLine())
3345 NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext());
3346 NewVar->setTSCSpec(OldVar->getTSCSpec());
3347 NewVar->setInitStyle(OldVar->getInitStyle());
3348 NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl());
3349 NewVar->setConstexpr(OldVar->isConstexpr());
Richard Smithdd9459f2013-08-13 18:18:50 +00003350 NewVar->setPreviousDeclInSameBlockScope(
3351 OldVar->isPreviousDeclInSameBlockScope());
Larisse Voufoef4579c2013-08-06 01:03:05 +00003352 NewVar->setAccess(OldVar->getAccess());
3353
3354 if (!OldVar->isStaticDataMember()) {
Eli Friedman86164e82013-09-05 00:02:25 +00003355 NewVar->setIsUsed(OldVar->isUsed(false));
Larisse Voufoef4579c2013-08-06 01:03:05 +00003356 NewVar->setReferenced(OldVar->isReferenced());
3357 }
3358
3359 InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope);
3360
3361 if (NewVar->hasAttrs())
3362 CheckAlignasUnderalignment(NewVar);
3363
Larisse Voufoef4579c2013-08-06 01:03:05 +00003364 LookupResult Previous(*this, NewVar->getDeclName(), NewVar->getLocation(),
3365 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
3366
Richard Smithdd9459f2013-08-13 18:18:50 +00003367 if (NewVar->getLexicalDeclContext()->isFunctionOrMethod() &&
3368 OldVar->getPreviousDecl()) {
3369 // We have a previous declaration. Use that one, so we merge with the
3370 // right type.
3371 if (NamedDecl *NewPrev = FindInstantiatedDecl(
3372 NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs))
3373 Previous.addDecl(NewPrev);
3374 } else if (!isa<VarTemplateSpecializationDecl>(NewVar) &&
3375 OldVar->hasLinkage())
Larisse Voufoef4579c2013-08-06 01:03:05 +00003376 LookupQualifiedName(Previous, NewVar->getDeclContext(), false);
Larisse Voufo567f9172013-08-22 00:59:14 +00003377 CheckVariableDeclaration(NewVar, Previous);
Larisse Voufoef4579c2013-08-06 01:03:05 +00003378
3379 if (OldVar->isOutOfLine()) {
3380 OldVar->getLexicalDeclContext()->addDecl(NewVar);
Larisse Voufo567f9172013-08-22 00:59:14 +00003381 if (!InstantiatingVarTemplate)
Larisse Voufoef4579c2013-08-06 01:03:05 +00003382 NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar);
3383 } else {
Larisse Voufo567f9172013-08-22 00:59:14 +00003384 if (!InstantiatingVarTemplate)
Larisse Voufoef4579c2013-08-06 01:03:05 +00003385 NewVar->getDeclContext()->addDecl(NewVar);
3386 if (NewVar->getDeclContext()->isFunctionOrMethod())
3387 CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar);
3388 }
3389
3390 // Link instantiations of static data members back to the template from
3391 // which they were instantiated.
Larisse Voufo567f9172013-08-22 00:59:14 +00003392 if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate)
Larisse Voufoef4579c2013-08-06 01:03:05 +00003393 NewVar->setInstantiationOfStaticDataMember(OldVar,
3394 TSK_ImplicitInstantiation);
3395
3396 if (isa<VarTemplateSpecializationDecl>(NewVar)) {
3397 // Do not instantiate the variable just yet.
Larisse Voufo567f9172013-08-22 00:59:14 +00003398 } else if (InstantiatingVarTemplate) {
Larisse Voufo04592e72013-08-22 00:28:27 +00003399 assert(!NewVar->getInit() &&
3400 "A variable should not have an initializer if it is templated"
3401 " and we are instantiating its template");
3402 NewVar->setInit(OldVar->getInit());
Larisse Voufoef4579c2013-08-06 01:03:05 +00003403 } else
3404 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
3405
3406 // Diagnose unused local variables with dependent types, where the diagnostic
3407 // will have been deferred.
3408 if (!NewVar->isInvalidDecl() &&
3409 NewVar->getDeclContext()->isFunctionOrMethod() && !NewVar->isUsed() &&
3410 OldVar->getType()->isDependentType())
3411 DiagnoseUnusedDecl(NewVar);
3412}
3413
3414/// \brief Instantiate the initializer of a variable.
3415void Sema::InstantiateVariableInitializer(
3416 VarDecl *Var, VarDecl *OldVar,
3417 const MultiLevelTemplateArgumentList &TemplateArgs) {
3418
3419 if (Var->getAnyInitializer())
3420 // We already have an initializer in the class.
3421 return;
3422
3423 if (OldVar->getInit()) {
3424 if (Var->isStaticDataMember() && !OldVar->isOutOfLine())
3425 PushExpressionEvaluationContext(Sema::ConstantEvaluated, OldVar);
3426 else
3427 PushExpressionEvaluationContext(Sema::PotentiallyEvaluated, OldVar);
3428
3429 // Instantiate the initializer.
3430 ExprResult Init =
3431 SubstInitializer(OldVar->getInit(), TemplateArgs,
3432 OldVar->getInitStyle() == VarDecl::CallInit);
3433 if (!Init.isInvalid()) {
3434 bool TypeMayContainAuto = true;
3435 if (Init.get()) {
3436 bool DirectInit = OldVar->isDirectInit();
3437 AddInitializerToDecl(Var, Init.take(), DirectInit, TypeMayContainAuto);
3438 } else
3439 ActOnUninitializedDecl(Var, TypeMayContainAuto);
3440 } else {
3441 // FIXME: Not too happy about invalidating the declaration
3442 // because of a bogus initializer.
3443 Var->setInvalidDecl();
3444 }
3445
3446 PopExpressionEvaluationContext();
3447 } else if ((!Var->isStaticDataMember() || Var->isOutOfLine()) &&
3448 !Var->isCXXForRangeDecl())
3449 ActOnUninitializedDecl(Var, false);
3450}
3451
Douglas Gregora58861f2009-05-13 20:28:22 +00003452/// \brief Instantiate the definition of the given variable from its
3453/// template.
3454///
Douglas Gregor7caa6822009-07-24 20:34:43 +00003455/// \param PointOfInstantiation the point at which the instantiation was
3456/// required. Note that this is not precisely a "point of instantiation"
3457/// for the function, but it's close.
3458///
3459/// \param Var the already-instantiated declaration of a static member
3460/// variable of a class template specialization.
3461///
3462/// \param Recursive if true, recursively instantiates any functions that
3463/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00003464///
3465/// \param DefinitionRequired if true, then we are performing an explicit
3466/// instantiation where an out-of-line definition of the member variable
3467/// is required. Complain if there is no such definition.
Douglas Gregor7caa6822009-07-24 20:34:43 +00003468void Sema::InstantiateStaticDataMemberDefinition(
3469 SourceLocation PointOfInstantiation,
3470 VarDecl *Var,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00003471 bool Recursive,
3472 bool DefinitionRequired) {
Larisse Voufoef4579c2013-08-06 01:03:05 +00003473 InstantiateVariableDefinition(PointOfInstantiation, Var, Recursive,
3474 DefinitionRequired);
3475}
3476
3477void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
3478 VarDecl *Var, bool Recursive,
3479 bool DefinitionRequired) {
3480
Douglas Gregor7caa6822009-07-24 20:34:43 +00003481 if (Var->isInvalidDecl())
3482 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003483
Larisse Voufoef4579c2013-08-06 01:03:05 +00003484 VarTemplateSpecializationDecl *VarSpec =
3485 dyn_cast<VarTemplateSpecializationDecl>(Var);
3486 assert((VarSpec || Var->isStaticDataMember()) &&
3487 "Not a static data member, nor a variable template specialization?");
3488 VarDecl *PatternDecl = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003489
Larisse Voufoef4579c2013-08-06 01:03:05 +00003490 // If this is a variable template specialization, make sure that it is
3491 // non-dependent, then find its instantiation pattern.
3492 if (VarSpec) {
3493 bool InstantiationDependent = false;
3494 assert(!TemplateSpecializationType::anyDependentTemplateArguments(
3495 VarSpec->getTemplateArgsInfo(), InstantiationDependent) &&
3496 "Only instantiate variable template specializations that are "
3497 "not type-dependent");
Larisse Voufo3151b7c2013-08-06 03:57:41 +00003498 (void)InstantiationDependent;
Larisse Voufoef4579c2013-08-06 01:03:05 +00003499
3500 // Find the variable initialization that we'll be substituting.
3501 assert(VarSpec->getSpecializedTemplate() &&
3502 "Specialization without specialized template?");
3503 llvm::PointerUnion<VarTemplateDecl *,
3504 VarTemplatePartialSpecializationDecl *> PatternPtr =
3505 VarSpec->getSpecializedTemplateOrPartial();
Larisse Voufo439d6652013-08-13 02:02:26 +00003506 if (PatternPtr.is<VarTemplatePartialSpecializationDecl *>()) {
Larisse Voufoef4579c2013-08-06 01:03:05 +00003507 PatternDecl = cast<VarDecl>(
3508 PatternPtr.get<VarTemplatePartialSpecializationDecl *>());
Larisse Voufo439d6652013-08-13 02:02:26 +00003509
3510 // Find actual definition
3511 if (VarDecl *Def = PatternDecl->getDefinition(getASTContext()))
3512 PatternDecl = Def;
3513 } else {
3514 VarTemplateDecl *PatternTemplate = PatternPtr.get<VarTemplateDecl *>();
3515
3516 // Find actual definition
3517 if (VarTemplateDecl *Def = PatternTemplate->getDefinition())
3518 PatternTemplate = Def;
3519
3520 PatternDecl = PatternTemplate->getTemplatedDecl();
3521 }
Larisse Voufoef4579c2013-08-06 01:03:05 +00003522 assert(PatternDecl && "instantiating a non-template");
3523 }
3524
3525 // If this is a static data member, find its out-of-line definition.
3526 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
3527 if (Var->isStaticDataMember()) {
3528 assert(Def && "This data member was not instantiated from a template?");
3529 assert(Def->isStaticDataMember() && "Not a static data member?");
3530 Def = Def->getOutOfLineDefinition();
3531 }
3532
3533 // If the instantiation pattern does not have an initializer, or if an
3534 // out-of-line definition is not found, we won't perform any instantiation.
3535 // Rather, we rely on the user to instantiate this definition (or provide
3536 // a specialization for it) in another translation unit.
3537 if ((VarSpec && !PatternDecl->getInit()) ||
3538 (!VarSpec && Var->isStaticDataMember() && !Def)) {
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00003539 if (DefinitionRequired) {
Larisse Voufoef4579c2013-08-06 01:03:05 +00003540 if (!Var->isStaticDataMember()) {
3541 Diag(PointOfInstantiation,
3542 diag::err_explicit_instantiation_undefined_var_template)
3543 << PatternDecl;
3544 Diag(PatternDecl->getLocation(),
3545 diag::note_explicit_instantiation_here);
3546 } else {
3547 Def = Var->getInstantiatedFromStaticDataMember();
3548 Diag(PointOfInstantiation,
3549 diag::err_explicit_instantiation_undefined_member)
3550 << 3 << Var->getDeclName() << Var->getDeclContext();
3551 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
3552 }
3553 if (VarSpec)
3554 Var->setInvalidDecl();
Chandler Carruth58e390e2010-08-25 08:27:02 +00003555 } else if (Var->getTemplateSpecializationKind()
3556 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00003557 PendingInstantiations.push_back(
Chandler Carruth58e390e2010-08-25 08:27:02 +00003558 std::make_pair(Var, PointOfInstantiation));
3559 }
3560
Douglas Gregor7caa6822009-07-24 20:34:43 +00003561 return;
3562 }
3563
Rafael Espindola234fe652012-03-05 10:54:55 +00003564 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
3565
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003566 // Never instantiate an explicit specialization.
Rafael Espindola234fe652012-03-05 10:54:55 +00003567 if (TSK == TSK_ExplicitSpecialization)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003568 return;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003569
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003570 // C++0x [temp.explicit]p9:
3571 // Except for inline functions, other explicit instantiation declarations
3572 // have the effect of suppressing the implicit instantiation of the entity
3573 // to which they refer.
Larisse Voufoef4579c2013-08-06 01:03:05 +00003574 //
3575 // C++11 [temp.explicit]p10:
3576 // Except for inline functions, [...] explicit instantiation declarations
3577 // have the effect of suppressing the implicit instantiation of the entity
3578 // to which they refer.
Rafael Espindola234fe652012-03-05 10:54:55 +00003579 if (TSK == TSK_ExplicitInstantiationDeclaration)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003580 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003581
Argyrios Kyrtzidisafda9052013-02-24 00:05:01 +00003582 // Make sure to pass the instantiated variable to the consumer at the end.
3583 struct PassToConsumerRAII {
3584 ASTConsumer &Consumer;
3585 VarDecl *Var;
3586
3587 PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
3588 : Consumer(Consumer), Var(Var) { }
3589
3590 ~PassToConsumerRAII() {
Larisse Voufoef4579c2013-08-06 01:03:05 +00003591 if (Var->isStaticDataMember())
3592 Consumer.HandleCXXStaticMemberVarInstantiation(Var);
3593 else {
3594 DeclGroupRef DG(Var);
3595 Consumer.HandleTopLevelDecl(DG);
3596 }
Argyrios Kyrtzidisafda9052013-02-24 00:05:01 +00003597 }
3598 } PassToConsumerRAII(Consumer, Var);
Rafael Espindola02503932012-03-08 15:51:03 +00003599
Larisse Voufoef4579c2013-08-06 01:03:05 +00003600 if (!VarSpec) {
3601 // If we already have a definition, we're done.
3602 if (VarDecl *Def = Var->getDefinition()) {
3603 // We may be explicitly instantiating something we've already implicitly
3604 // instantiated.
3605 Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
3606 PointOfInstantiation);
3607 return;
3608 }
Nick Lewycky95e38722012-04-04 02:38:36 +00003609 }
Douglas Gregorf15748a2011-06-03 03:35:07 +00003610
Douglas Gregor7caa6822009-07-24 20:34:43 +00003611 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
3612 if (Inst)
3613 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003614
Douglas Gregor7caa6822009-07-24 20:34:43 +00003615 // If we're performing recursive template instantiation, create our own
3616 // queue of pending implicit instantiations that we will instantiate later,
3617 // while we're still within our own instantiation context.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003618 SmallVector<VTableUse, 16> SavedVTableUses;
Chandler Carruth62c78d52010-08-25 08:44:16 +00003619 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
Nick Lewycky81559102011-05-31 07:58:42 +00003620 if (Recursive) {
3621 VTableUses.swap(SavedVTableUses);
Chandler Carruth62c78d52010-08-25 08:44:16 +00003622 PendingInstantiations.swap(SavedPendingInstantiations);
Nick Lewycky81559102011-05-31 07:58:42 +00003623 }
Mike Stump1eb44332009-09-09 15:08:12 +00003624
Douglas Gregor7caa6822009-07-24 20:34:43 +00003625 // Enter the scope of this instantiation. We don't use
3626 // PushDeclContext because we don't have a scope.
Larisse Voufoef4579c2013-08-06 01:03:05 +00003627 ContextRAII PreviousContext(*this, Var->getDeclContext());
Douglas Gregor7bdc1522012-02-16 21:36:18 +00003628 LocalInstantiationScope Local(*this);
John McCallf5ba7e02011-02-14 20:37:25 +00003629
Larisse Voufoef4579c2013-08-06 01:03:05 +00003630 VarDecl *OldVar = Var;
3631 if (!VarSpec)
3632 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
3633 getTemplateInstantiationArgs(Var)));
3634 else
3635 // Construct a VarTemplateSpecializationDecl to avoid name clashing with
3636 // the primary template. (Note that unlike function declarations, variable
3637 // declarations cannot be overloaded.)
3638 // In fact, there is no need to construct a new declaration from scratch.
3639 // Thus, simply complete its definition with an appropriately substituted
3640 // type and initializer.
3641 Var = CompleteVarTemplateSpecializationDecl(
3642 VarSpec, PatternDecl, getTemplateInstantiationArgs(Var));
3643
3644 PreviousContext.pop();
Douglas Gregor7caa6822009-07-24 20:34:43 +00003645
3646 if (Var) {
Douglas Gregor583f33b2009-10-15 18:07:02 +00003647 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
Larisse Voufoef4579c2013-08-06 01:03:05 +00003648 if (!VarSpec)
3649 assert(MSInfo && "Missing member specialization information?");
3650
3651 PassToConsumerRAII.Var = Var;
3652 if (MSInfo)
3653 Var->setTemplateSpecializationKind(
3654 MSInfo->getTemplateSpecializationKind(),
3655 MSInfo->getPointOfInstantiation());
Douglas Gregor7caa6822009-07-24 20:34:43 +00003656 }
Larisse Voufoef4579c2013-08-06 01:03:05 +00003657
3658 // This variable may have local implicit instantiations that need to be
3659 // instantiated within this scope.
3660 PerformPendingInstantiations(/*LocalOnly=*/true);
3661
Douglas Gregor7bdc1522012-02-16 21:36:18 +00003662 Local.Exit();
3663
Douglas Gregor7caa6822009-07-24 20:34:43 +00003664 if (Recursive) {
Nick Lewycky81559102011-05-31 07:58:42 +00003665 // Define any newly required vtables.
3666 DefineUsedVTables();
3667
Douglas Gregor7caa6822009-07-24 20:34:43 +00003668 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00003669 // instantiation of this template.
Chandler Carruth62c78d52010-08-25 08:44:16 +00003670 PerformPendingInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00003671
Nick Lewycky81559102011-05-31 07:58:42 +00003672 // Restore the set of pending vtables.
3673 assert(VTableUses.empty() &&
Larisse Voufoef4579c2013-08-06 01:03:05 +00003674 "VTableUses should be empty before it is discarded.");
Nick Lewycky81559102011-05-31 07:58:42 +00003675 VTableUses.swap(SavedVTableUses);
3676
Douglas Gregor7caa6822009-07-24 20:34:43 +00003677 // Restore the set of pending implicit instantiations.
Nick Lewycky81559102011-05-31 07:58:42 +00003678 assert(PendingInstantiations.empty() &&
Larisse Voufoef4579c2013-08-06 01:03:05 +00003679 "PendingInstantiations should be empty before it is discarded.");
Chandler Carruth62c78d52010-08-25 08:44:16 +00003680 PendingInstantiations.swap(SavedPendingInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00003681 }
Douglas Gregora58861f2009-05-13 20:28:22 +00003682}
Douglas Gregor815215d2009-05-27 05:35:12 +00003683
Anders Carlsson09025312009-08-29 05:16:22 +00003684void
3685Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
3686 const CXXConstructorDecl *Tmpl,
3687 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00003688
Richard Trieu90ab75b2011-09-09 03:18:59 +00003689 SmallVector<CXXCtorInitializer*, 4> NewInits;
Richard Smith54b3ba82012-09-25 00:23:05 +00003690 bool AnyErrors = Tmpl->isInvalidDecl();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003691
Anders Carlsson09025312009-08-29 05:16:22 +00003692 // Instantiate all the initializers.
3693 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00003694 InitsEnd = Tmpl->init_end();
3695 Inits != InitsEnd; ++Inits) {
Sean Huntcbb67482011-01-08 20:30:50 +00003696 CXXCtorInitializer *Init = *Inits;
Anders Carlsson09025312009-08-29 05:16:22 +00003697
Chandler Carruth030ef472010-09-03 21:54:20 +00003698 // Only instantiate written initializers, let Sema re-construct implicit
3699 // ones.
3700 if (!Init->isWritten())
3701 continue;
3702
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003703 SourceLocation EllipsisLoc;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003704
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003705 if (Init->isPackExpansion()) {
3706 // This is a pack expansion. We should expand it now.
Douglas Gregor76852c22011-11-01 01:16:03 +00003707 TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
Nick Lewycky98a75582013-06-13 00:45:47 +00003708 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003709 collectUnexpandedParameterPacks(BaseTL, Unexpanded);
Nick Lewycky98a75582013-06-13 00:45:47 +00003710 collectUnexpandedParameterPacks(Init->getInit(), Unexpanded);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003711 bool ShouldExpand = false;
Douglas Gregord3731192011-01-10 07:32:04 +00003712 bool RetainExpansion = false;
David Blaikiedc84cd52013-02-20 22:23:23 +00003713 Optional<unsigned> NumExpansions;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003714 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003715 BaseTL.getSourceRange(),
David Blaikiea71f9d02011-09-22 02:34:54 +00003716 Unexpanded,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003717 TemplateArgs, ShouldExpand,
Douglas Gregord3731192011-01-10 07:32:04 +00003718 RetainExpansion,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003719 NumExpansions)) {
3720 AnyErrors = true;
3721 New->setInvalidDecl();
3722 continue;
3723 }
3724 assert(ShouldExpand && "Partial instantiation of base initializer?");
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003725
3726 // Loop over all of the arguments in the argument pack(s),
Douglas Gregorcded4f62011-01-14 17:04:44 +00003727 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003728 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
3729
3730 // Instantiate the initializer.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003731 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
3732 /*CXXDirectInit=*/true);
3733 if (TempInit.isInvalid()) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003734 AnyErrors = true;
3735 break;
3736 }
3737
3738 // Instantiate the base type.
Douglas Gregor76852c22011-11-01 01:16:03 +00003739 TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003740 TemplateArgs,
3741 Init->getSourceLocation(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003742 New->getDeclName());
3743 if (!BaseTInfo) {
3744 AnyErrors = true;
3745 break;
3746 }
3747
3748 // Build the initializer.
Sebastian Redl6df65482011-09-24 17:48:25 +00003749 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003750 BaseTInfo, TempInit.take(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003751 New->getParent(),
3752 SourceLocation());
3753 if (NewInit.isInvalid()) {
3754 AnyErrors = true;
3755 break;
3756 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003757
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003758 NewInits.push_back(NewInit.get());
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003759 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003760
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003761 continue;
3762 }
3763
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00003764 // Instantiate the initializer.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003765 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
3766 /*CXXDirectInit=*/true);
3767 if (TempInit.isInvalid()) {
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00003768 AnyErrors = true;
3769 continue;
Anders Carlsson09025312009-08-29 05:16:22 +00003770 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003771
Anders Carlsson09025312009-08-29 05:16:22 +00003772 MemInitResult NewInit;
Douglas Gregor76852c22011-11-01 01:16:03 +00003773 if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
3774 TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
3775 TemplateArgs,
3776 Init->getSourceLocation(),
3777 New->getDeclName());
3778 if (!TInfo) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003779 AnyErrors = true;
Douglas Gregor802ab452009-12-02 22:36:29 +00003780 New->setInvalidDecl();
3781 continue;
3782 }
Sebastian Redl6df65482011-09-24 17:48:25 +00003783
Douglas Gregor76852c22011-11-01 01:16:03 +00003784 if (Init->isBaseInitializer())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003785 NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.take(),
Douglas Gregor76852c22011-11-01 01:16:03 +00003786 New->getParent(), EllipsisLoc);
3787 else
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003788 NewInit = BuildDelegatingInitializer(TInfo, TempInit.take(),
Douglas Gregor76852c22011-11-01 01:16:03 +00003789 cast<CXXRecordDecl>(CurContext->getParent()));
Anders Carlsson09025312009-08-29 05:16:22 +00003790 } else if (Init->isMemberInitializer()) {
Douglas Gregorb7107222011-03-04 19:46:35 +00003791 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
Francois Pichet00eb3f92010-12-04 09:14:42 +00003792 Init->getMemberLocation(),
3793 Init->getMember(),
3794 TemplateArgs));
Douglas Gregorb7107222011-03-04 19:46:35 +00003795 if (!Member) {
3796 AnyErrors = true;
3797 New->setInvalidDecl();
3798 continue;
3799 }
Mike Stump1eb44332009-09-09 15:08:12 +00003800
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003801 NewInit = BuildMemberInitializer(Member, TempInit.take(),
Sebastian Redl6df65482011-09-24 17:48:25 +00003802 Init->getSourceLocation());
Francois Pichet00eb3f92010-12-04 09:14:42 +00003803 } else if (Init->isIndirectMemberInitializer()) {
3804 IndirectFieldDecl *IndirectMember =
Douglas Gregorb7107222011-03-04 19:46:35 +00003805 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
Francois Pichet00eb3f92010-12-04 09:14:42 +00003806 Init->getMemberLocation(),
3807 Init->getIndirectMember(), TemplateArgs));
3808
Douglas Gregorb7107222011-03-04 19:46:35 +00003809 if (!IndirectMember) {
3810 AnyErrors = true;
3811 New->setInvalidDecl();
Sebastian Redl6df65482011-09-24 17:48:25 +00003812 continue;
Douglas Gregorb7107222011-03-04 19:46:35 +00003813 }
Sebastian Redl6df65482011-09-24 17:48:25 +00003814
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003815 NewInit = BuildMemberInitializer(IndirectMember, TempInit.take(),
Sebastian Redl6df65482011-09-24 17:48:25 +00003816 Init->getSourceLocation());
Anders Carlsson09025312009-08-29 05:16:22 +00003817 }
3818
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003819 if (NewInit.isInvalid()) {
3820 AnyErrors = true;
Anders Carlsson09025312009-08-29 05:16:22 +00003821 New->setInvalidDecl();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003822 } else {
Richard Trieu90ab75b2011-09-09 03:18:59 +00003823 NewInits.push_back(NewInit.get());
Anders Carlsson09025312009-08-29 05:16:22 +00003824 }
3825 }
Mike Stump1eb44332009-09-09 15:08:12 +00003826
Anders Carlsson09025312009-08-29 05:16:22 +00003827 // Assign all the initializers to the new constructor.
John McCalld226f652010-08-21 09:40:31 +00003828 ActOnMemInitializers(New,
Anders Carlsson09025312009-08-29 05:16:22 +00003829 /*FIXME: ColonLoc */
3830 SourceLocation(),
David Blaikie93c86172013-01-17 05:26:25 +00003831 NewInits,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003832 AnyErrors);
Anders Carlsson09025312009-08-29 05:16:22 +00003833}
3834
John McCall52a575a2009-08-29 08:11:13 +00003835// TODO: this could be templated if the various decl types used the
3836// same method name.
3837static bool isInstantiationOf(ClassTemplateDecl *Pattern,
3838 ClassTemplateDecl *Instance) {
3839 Pattern = Pattern->getCanonicalDecl();
3840
3841 do {
3842 Instance = Instance->getCanonicalDecl();
3843 if (Pattern == Instance) return true;
3844 Instance = Instance->getInstantiatedFromMemberTemplate();
3845 } while (Instance);
3846
3847 return false;
3848}
3849
Douglas Gregor0d696532009-09-28 06:34:35 +00003850static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
3851 FunctionTemplateDecl *Instance) {
3852 Pattern = Pattern->getCanonicalDecl();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003853
Douglas Gregor0d696532009-09-28 06:34:35 +00003854 do {
3855 Instance = Instance->getCanonicalDecl();
3856 if (Pattern == Instance) return true;
3857 Instance = Instance->getInstantiatedFromMemberTemplate();
3858 } while (Instance);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003859
Douglas Gregor0d696532009-09-28 06:34:35 +00003860 return false;
3861}
3862
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003863static bool
Douglas Gregored9c0f92009-10-29 00:04:11 +00003864isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
3865 ClassTemplatePartialSpecializationDecl *Instance) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003866 Pattern
Douglas Gregored9c0f92009-10-29 00:04:11 +00003867 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
3868 do {
3869 Instance = cast<ClassTemplatePartialSpecializationDecl>(
3870 Instance->getCanonicalDecl());
3871 if (Pattern == Instance)
3872 return true;
3873 Instance = Instance->getInstantiatedFromMember();
3874 } while (Instance);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003875
Douglas Gregored9c0f92009-10-29 00:04:11 +00003876 return false;
3877}
3878
John McCall52a575a2009-08-29 08:11:13 +00003879static bool isInstantiationOf(CXXRecordDecl *Pattern,
3880 CXXRecordDecl *Instance) {
3881 Pattern = Pattern->getCanonicalDecl();
3882
3883 do {
3884 Instance = Instance->getCanonicalDecl();
3885 if (Pattern == Instance) return true;
3886 Instance = Instance->getInstantiatedFromMemberClass();
3887 } while (Instance);
3888
3889 return false;
3890}
3891
3892static bool isInstantiationOf(FunctionDecl *Pattern,
3893 FunctionDecl *Instance) {
3894 Pattern = Pattern->getCanonicalDecl();
3895
3896 do {
3897 Instance = Instance->getCanonicalDecl();
3898 if (Pattern == Instance) return true;
3899 Instance = Instance->getInstantiatedFromMemberFunction();
3900 } while (Instance);
3901
3902 return false;
3903}
3904
3905static bool isInstantiationOf(EnumDecl *Pattern,
3906 EnumDecl *Instance) {
3907 Pattern = Pattern->getCanonicalDecl();
3908
3909 do {
3910 Instance = Instance->getCanonicalDecl();
3911 if (Pattern == Instance) return true;
3912 Instance = Instance->getInstantiatedFromMemberEnum();
3913 } while (Instance);
3914
3915 return false;
3916}
3917
John McCalled976492009-12-04 22:46:56 +00003918static bool isInstantiationOf(UsingShadowDecl *Pattern,
3919 UsingShadowDecl *Instance,
3920 ASTContext &C) {
3921 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
3922}
3923
3924static bool isInstantiationOf(UsingDecl *Pattern,
3925 UsingDecl *Instance,
3926 ASTContext &C) {
3927 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
3928}
3929
John McCall7ba107a2009-11-18 02:36:19 +00003930static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
3931 UsingDecl *Instance,
3932 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00003933 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCall7ba107a2009-11-18 02:36:19 +00003934}
3935
3936static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson0d8df782009-08-29 19:37:28 +00003937 UsingDecl *Instance,
3938 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00003939 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00003940}
3941
John McCall52a575a2009-08-29 08:11:13 +00003942static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
3943 VarDecl *Instance) {
3944 assert(Instance->isStaticDataMember());
3945
3946 Pattern = Pattern->getCanonicalDecl();
3947
3948 do {
3949 Instance = Instance->getCanonicalDecl();
3950 if (Pattern == Instance) return true;
3951 Instance = Instance->getInstantiatedFromStaticDataMember();
3952 } while (Instance);
3953
3954 return false;
3955}
3956
John McCalled976492009-12-04 22:46:56 +00003957// Other is the prospective instantiation
3958// D is the prospective pattern
Douglas Gregor815215d2009-05-27 05:35:12 +00003959static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00003960 if (D->getKind() != Other->getKind()) {
John McCall7ba107a2009-11-18 02:36:19 +00003961 if (UnresolvedUsingTypenameDecl *UUD
3962 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3963 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
3964 return isInstantiationOf(UUD, UD, Ctx);
3965 }
3966 }
3967
3968 if (UnresolvedUsingValueDecl *UUD
3969 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00003970 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
3971 return isInstantiationOf(UUD, UD, Ctx);
3972 }
3973 }
Douglas Gregor815215d2009-05-27 05:35:12 +00003974
Anders Carlsson0d8df782009-08-29 19:37:28 +00003975 return false;
3976 }
Mike Stump1eb44332009-09-09 15:08:12 +00003977
John McCall52a575a2009-08-29 08:11:13 +00003978 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
3979 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00003980
John McCall52a575a2009-08-29 08:11:13 +00003981 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
3982 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00003983
John McCall52a575a2009-08-29 08:11:13 +00003984 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
3985 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00003986
Douglas Gregor7caa6822009-07-24 20:34:43 +00003987 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00003988 if (Var->isStaticDataMember())
3989 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
3990
3991 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
3992 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00003993
Douglas Gregor0d696532009-09-28 06:34:35 +00003994 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
3995 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
3996
Douglas Gregored9c0f92009-10-29 00:04:11 +00003997 if (ClassTemplatePartialSpecializationDecl *PartialSpec
3998 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
3999 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
4000 PartialSpec);
4001
Anders Carlssond8b285f2009-09-01 04:26:58 +00004002 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
4003 if (!Field->getDeclName()) {
4004 // This is an unnamed field.
Mike Stump1eb44332009-09-09 15:08:12 +00004005 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlssond8b285f2009-09-01 04:26:58 +00004006 cast<FieldDecl>(D);
4007 }
4008 }
Mike Stump1eb44332009-09-09 15:08:12 +00004009
John McCalled976492009-12-04 22:46:56 +00004010 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
4011 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
4012
4013 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
4014 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
4015
Douglas Gregor815215d2009-05-27 05:35:12 +00004016 return D->getDeclName() && isa<NamedDecl>(Other) &&
4017 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
4018}
4019
4020template<typename ForwardIterator>
Mike Stump1eb44332009-09-09 15:08:12 +00004021static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor815215d2009-05-27 05:35:12 +00004022 NamedDecl *D,
4023 ForwardIterator first,
4024 ForwardIterator last) {
4025 for (; first != last; ++first)
4026 if (isInstantiationOf(Ctx, D, *first))
4027 return cast<NamedDecl>(*first);
4028
4029 return 0;
4030}
4031
John McCall02cace72009-08-28 07:59:38 +00004032/// \brief Finds the instantiation of the given declaration context
4033/// within the current instantiation.
4034///
4035/// \returns NULL if there was an error
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00004036DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
Douglas Gregore95b4092009-09-16 18:34:49 +00004037 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCall02cace72009-08-28 07:59:38 +00004038 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00004039 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +00004040 return cast_or_null<DeclContext>(ID);
4041 } else return DC;
4042}
4043
Douglas Gregored961e72009-05-27 17:54:46 +00004044/// \brief Find the instantiation of the given declaration within the
4045/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00004046///
4047/// This routine is intended to be used when \p D is a declaration
4048/// referenced from within a template, that needs to mapped into the
4049/// corresponding declaration within an instantiation. For example,
4050/// given:
4051///
4052/// \code
4053/// template<typename T>
4054/// struct X {
4055/// enum Kind {
4056/// KnownValue = sizeof(T)
4057/// };
4058///
4059/// bool getKind() const { return KnownValue; }
4060/// };
4061///
4062/// template struct X<int>;
4063/// \endcode
4064///
Serge Pavlov041d10c2013-07-10 04:59:14 +00004065/// In the instantiation of <tt>X<int>::getKind()</tt>, we need to map the
4066/// \p EnumConstantDecl for \p KnownValue (which refers to
4067/// <tt>X<T>::<Kind>::KnownValue</tt>) to its instantiation
4068/// (<tt>X<int>::<Kind>::KnownValue</tt>). \p FindInstantiatedDecl performs
4069/// this mapping from within the instantiation of <tt>X<int></tt>.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00004070NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
Douglas Gregore95b4092009-09-16 18:34:49 +00004071 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor815215d2009-05-27 05:35:12 +00004072 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor550d9b22009-10-31 17:21:17 +00004073 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
Douglas Gregor6d3e6272010-02-05 19:54:12 +00004074 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
Douglas Gregor7bdc1522012-02-16 21:36:18 +00004075 (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext()) ||
4076 (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) {
Douglas Gregor2bba76b2009-05-27 17:07:49 +00004077 // D is a local of some kind. Look into the map of local
4078 // declarations to their instantiations.
Chris Lattnerd8e54992011-02-17 19:47:42 +00004079 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
4080 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
4081 = CurrentInstantiationScope->findInstantiationOf(D);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00004082
Chris Lattner57ad3782011-02-17 20:34:02 +00004083 if (Found) {
4084 if (Decl *FD = Found->dyn_cast<Decl *>())
4085 return cast<NamedDecl>(FD);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00004086
Richard Smith9a4db032012-09-12 00:56:43 +00004087 int PackIdx = ArgumentPackSubstitutionIndex;
4088 assert(PackIdx != -1 && "found declaration pack but not pack expanding");
Chris Lattner57ad3782011-02-17 20:34:02 +00004089 return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
4090 }
4091
Serge Pavlovdc49d522013-07-15 06:14:07 +00004092 // If we're performing a partial substitution during template argument
4093 // deduction, we may not have values for template parameters yet. They
4094 // just map to themselves.
4095 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
4096 isa<TemplateTemplateParmDecl>(D))
4097 return D;
4098
Serge Pavlov29a46e62013-08-10 12:00:21 +00004099 if (D->isInvalidDecl())
4100 return 0;
4101
Chris Lattner57ad3782011-02-17 20:34:02 +00004102 // If we didn't find the decl, then we must have a label decl that hasn't
4103 // been found yet. Lazily instantiate it and return it now.
4104 assert(isa<LabelDecl>(D));
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00004105
Chris Lattner57ad3782011-02-17 20:34:02 +00004106 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
4107 assert(Inst && "Failed to instantiate label??");
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00004108
Chris Lattner57ad3782011-02-17 20:34:02 +00004109 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
4110 return cast<LabelDecl>(Inst);
Douglas Gregor2bba76b2009-05-27 17:07:49 +00004111 }
Douglas Gregor815215d2009-05-27 05:35:12 +00004112
Larisse Voufoef4579c2013-08-06 01:03:05 +00004113 // For variable template specializations, update those that are still
4114 // type-dependent.
4115 if (VarTemplateSpecializationDecl *VarSpec =
4116 dyn_cast<VarTemplateSpecializationDecl>(D)) {
4117 bool InstantiationDependent = false;
4118 const TemplateArgumentListInfo &VarTemplateArgs =
4119 VarSpec->getTemplateArgsInfo();
4120 if (TemplateSpecializationType::anyDependentTemplateArguments(
4121 VarTemplateArgs, InstantiationDependent))
4122 D = cast<NamedDecl>(
4123 SubstDecl(D, VarSpec->getDeclContext(), TemplateArgs));
4124 return D;
4125 }
4126
Douglas Gregore95b4092009-09-16 18:34:49 +00004127 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
4128 if (!Record->isDependentContext())
4129 return D;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00004130
Douglas Gregor2c1227c2011-11-07 17:43:18 +00004131 // Determine whether this record is the "templated" declaration describing
4132 // a class template or class template partial specialization.
Douglas Gregore95b4092009-09-16 18:34:49 +00004133 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
Douglas Gregor2c1227c2011-11-07 17:43:18 +00004134 if (ClassTemplate)
4135 ClassTemplate = ClassTemplate->getCanonicalDecl();
4136 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4137 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
4138 ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
Larisse Voufoef4579c2013-08-06 01:03:05 +00004139
Douglas Gregor2c1227c2011-11-07 17:43:18 +00004140 // Walk the current context to find either the record or an instantiation of
4141 // it.
4142 DeclContext *DC = CurContext;
4143 while (!DC->isFileContext()) {
4144 // If we're performing substitution while we're inside the template
4145 // definition, we'll find our own context. We're done.
4146 if (DC->Equals(Record))
4147 return Record;
Larisse Voufoef4579c2013-08-06 01:03:05 +00004148
Douglas Gregor2c1227c2011-11-07 17:43:18 +00004149 if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
4150 // Check whether we're in the process of instantiating a class template
4151 // specialization of the template we're mapping.
4152 if (ClassTemplateSpecializationDecl *InstSpec
4153 = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
4154 ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
4155 if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
4156 return InstRecord;
4157 }
Larisse Voufoef4579c2013-08-06 01:03:05 +00004158
Douglas Gregor2c1227c2011-11-07 17:43:18 +00004159 // Check whether we're in the process of instantiating a member class.
4160 if (isInstantiationOf(Record, InstRecord))
4161 return InstRecord;
Douglas Gregore95b4092009-09-16 18:34:49 +00004162 }
Larisse Voufoef4579c2013-08-06 01:03:05 +00004163
Douglas Gregor2c1227c2011-11-07 17:43:18 +00004164 // Move to the outer template scope.
4165 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
4166 if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){
4167 DC = FD->getLexicalDeclContext();
4168 continue;
4169 }
John McCall52a575a2009-08-29 08:11:13 +00004170 }
Larisse Voufoef4579c2013-08-06 01:03:05 +00004171
Douglas Gregor2c1227c2011-11-07 17:43:18 +00004172 DC = DC->getParent();
John McCall52a575a2009-08-29 08:11:13 +00004173 }
Douglas Gregor8b013bd2010-02-05 22:40:03 +00004174
Douglas Gregore95b4092009-09-16 18:34:49 +00004175 // Fall through to deal with other dependent record types (e.g.,
4176 // anonymous unions in class templates).
4177 }
John McCall52a575a2009-08-29 08:11:13 +00004178
Douglas Gregore95b4092009-09-16 18:34:49 +00004179 if (!ParentDC->isDependentContext())
4180 return D;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00004181
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00004182 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00004183 if (!ParentDC)
Douglas Gregor44c73842009-09-01 17:53:10 +00004184 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004185
Douglas Gregor815215d2009-05-27 05:35:12 +00004186 if (ParentDC != D->getDeclContext()) {
4187 // We performed some kind of instantiation in the parent context,
4188 // so now we need to look into the instantiated parent context to
4189 // find the instantiation of the declaration D.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00004190
John McCall3cb0ebd2010-03-10 03:28:59 +00004191 // If our context used to be dependent, we may need to instantiate
4192 // it before performing lookup into that context.
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00004193 bool IsBeingInstantiated = false;
John McCall3cb0ebd2010-03-10 03:28:59 +00004194 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00004195 if (!Spec->isDependentContext()) {
4196 QualType T = Context.getTypeDeclType(Spec);
John McCall3cb0ebd2010-03-10 03:28:59 +00004197 const RecordType *Tag = T->getAs<RecordType>();
4198 assert(Tag && "type of non-dependent record is not a RecordType");
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00004199 if (Tag->isBeingDefined())
4200 IsBeingInstantiated = true;
John McCall3cb0ebd2010-03-10 03:28:59 +00004201 if (!Tag->isBeingDefined() &&
4202 RequireCompleteType(Loc, T, diag::err_incomplete_type))
4203 return 0;
Douglas Gregora43064c2010-11-05 23:22:45 +00004204
4205 ParentDC = Tag->getDecl();
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00004206 }
4207 }
4208
Douglas Gregor815215d2009-05-27 05:35:12 +00004209 NamedDecl *Result = 0;
4210 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004211 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
David Blaikie3bc93e32012-12-19 00:45:41 +00004212 Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
Douglas Gregor815215d2009-05-27 05:35:12 +00004213 } else {
4214 // Since we don't have a name for the entity we're looking for,
4215 // our only option is to walk through all of the declarations to
4216 // find that name. This will occur in a few cases:
4217 //
4218 // - anonymous struct/union within a template
4219 // - unnamed class/struct/union/enum within a template
4220 //
4221 // FIXME: Find a better way to find these instantiations!
Mike Stump1eb44332009-09-09 15:08:12 +00004222 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004223 ParentDC->decls_begin(),
4224 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00004225 }
Mike Stump1eb44332009-09-09 15:08:12 +00004226
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00004227 if (!Result) {
4228 if (isa<UsingShadowDecl>(D)) {
4229 // UsingShadowDecls can instantiate to nothing because of using hiding.
4230 } else if (Diags.hasErrorOccurred()) {
4231 // We've already complained about something, so most likely this
4232 // declaration failed to instantiate. There's no point in complaining
4233 // further, since this is normal in invalid code.
4234 } else if (IsBeingInstantiated) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00004235 // The class in which this member exists is currently being
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00004236 // instantiated, and we haven't gotten around to instantiating this
4237 // member yet. This can happen when the code uses forward declarations
4238 // of member classes, and introduces ordering dependencies via
4239 // template instantiation.
4240 Diag(Loc, diag::err_member_not_yet_instantiated)
4241 << D->getDeclName()
4242 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
4243 Diag(D->getLocation(), diag::note_non_instantiated_member_here);
Richard Smith0724b7c2012-03-26 20:28:16 +00004244 } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
4245 // This enumeration constant was found when the template was defined,
4246 // but can't be found in the instantiation. This can happen if an
4247 // unscoped enumeration member is explicitly specialized.
4248 EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
4249 EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
4250 TemplateArgs));
4251 assert(Spec->getTemplateSpecializationKind() ==
4252 TSK_ExplicitSpecialization);
4253 Diag(Loc, diag::err_enumerator_does_not_exist)
4254 << D->getDeclName()
4255 << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
4256 Diag(Spec->getLocation(), diag::note_enum_specialized_here)
4257 << Context.getTypeDeclType(Spec);
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00004258 } else {
4259 // We should have found something, but didn't.
4260 llvm_unreachable("Unable to find instantiation of declaration!");
4261 }
4262 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00004263
Douglas Gregor815215d2009-05-27 05:35:12 +00004264 D = Result;
4265 }
4266
Douglas Gregor815215d2009-05-27 05:35:12 +00004267 return D;
4268}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00004269
Mike Stump1eb44332009-09-09 15:08:12 +00004270/// \brief Performs template instantiation for all implicit template
Douglas Gregord7f37bf2009-06-22 23:06:13 +00004271/// instantiations we have seen until this point.
Nick Lewycky81559102011-05-31 07:58:42 +00004272void Sema::PerformPendingInstantiations(bool LocalOnly) {
Douglas Gregor6e4a3f52011-07-28 19:49:54 +00004273 // Load pending instantiations from the external source.
4274 if (!LocalOnly && ExternalSource) {
Richard Smithb9d0b762012-07-27 04:22:15 +00004275 SmallVector<PendingImplicitInstantiation, 4> Pending;
Douglas Gregor6e4a3f52011-07-28 19:49:54 +00004276 ExternalSource->ReadPendingInstantiations(Pending);
4277 PendingInstantiations.insert(PendingInstantiations.begin(),
4278 Pending.begin(), Pending.end());
4279 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00004280
Douglas Gregor60406be2010-01-16 22:29:39 +00004281 while (!PendingLocalImplicitInstantiations.empty() ||
Chandler Carruth62c78d52010-08-25 08:44:16 +00004282 (!LocalOnly && !PendingInstantiations.empty())) {
Douglas Gregor60406be2010-01-16 22:29:39 +00004283 PendingImplicitInstantiation Inst;
4284
4285 if (PendingLocalImplicitInstantiations.empty()) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00004286 Inst = PendingInstantiations.front();
4287 PendingInstantiations.pop_front();
Douglas Gregor60406be2010-01-16 22:29:39 +00004288 } else {
4289 Inst = PendingLocalImplicitInstantiations.front();
4290 PendingLocalImplicitInstantiations.pop_front();
4291 }
Mike Stump1eb44332009-09-09 15:08:12 +00004292
Douglas Gregor7caa6822009-07-24 20:34:43 +00004293 // Instantiate function definitions
4294 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
John McCallf312b1e2010-08-26 23:41:50 +00004295 PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(),
4296 "instantiating function definition");
Chandler Carruth58e390e2010-08-25 08:27:02 +00004297 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
4298 TSK_ExplicitInstantiationDefinition;
4299 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true,
4300 DefinitionRequired);
Douglas Gregor7caa6822009-07-24 20:34:43 +00004301 continue;
4302 }
Mike Stump1eb44332009-09-09 15:08:12 +00004303
Larisse Voufoef4579c2013-08-06 01:03:05 +00004304 // Instantiate variable definitions
Douglas Gregor7caa6822009-07-24 20:34:43 +00004305 VarDecl *Var = cast<VarDecl>(Inst.first);
Larisse Voufoef4579c2013-08-06 01:03:05 +00004306
4307 assert((Var->isStaticDataMember() ||
4308 isa<VarTemplateSpecializationDecl>(Var)) &&
4309 "Not a static data member, nor a variable template"
4310 " specialization?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00004311
Chandler Carruth291b4412010-02-13 10:17:50 +00004312 // Don't try to instantiate declarations if the most recent redeclaration
4313 // is invalid.
Douglas Gregoref96ee02012-01-14 16:38:05 +00004314 if (Var->getMostRecentDecl()->isInvalidDecl())
Chandler Carruth291b4412010-02-13 10:17:50 +00004315 continue;
4316
4317 // Check if the most recent declaration has changed the specialization kind
4318 // and removed the need for implicit instantiation.
Douglas Gregoref96ee02012-01-14 16:38:05 +00004319 switch (Var->getMostRecentDecl()->getTemplateSpecializationKind()) {
Chandler Carruth291b4412010-02-13 10:17:50 +00004320 case TSK_Undeclared:
David Blaikieb219cfc2011-09-23 05:06:16 +00004321 llvm_unreachable("Cannot instantitiate an undeclared specialization.");
Chandler Carruth291b4412010-02-13 10:17:50 +00004322 case TSK_ExplicitInstantiationDeclaration:
Chandler Carruth291b4412010-02-13 10:17:50 +00004323 case TSK_ExplicitSpecialization:
Chandler Carruth58e390e2010-08-25 08:27:02 +00004324 continue; // No longer need to instantiate this type.
4325 case TSK_ExplicitInstantiationDefinition:
4326 // We only need an instantiation if the pending instantiation *is* the
4327 // explicit instantiation.
Douglas Gregoref96ee02012-01-14 16:38:05 +00004328 if (Var != Var->getMostRecentDecl()) continue;
Chandler Carruth291b4412010-02-13 10:17:50 +00004329 case TSK_ImplicitInstantiation:
4330 break;
4331 }
4332
Larisse Voufoef4579c2013-08-06 01:03:05 +00004333 PrettyDeclStackTraceEntry CrashInfo(*this, Var, SourceLocation(),
4334 "instantiating variable definition");
Chandler Carruth58e390e2010-08-25 08:27:02 +00004335 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
4336 TSK_ExplicitInstantiationDefinition;
Larisse Voufoef4579c2013-08-06 01:03:05 +00004337
4338 // Instantiate static data member definitions or variable template
4339 // specializations.
4340 InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true,
4341 DefinitionRequired);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00004342 }
4343}
John McCall0c01d182010-03-24 05:22:00 +00004344
4345void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
4346 const MultiLevelTemplateArgumentList &TemplateArgs) {
4347 for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(),
4348 E = Pattern->ddiag_end(); I != E; ++I) {
4349 DependentDiagnostic *DD = *I;
4350
4351 switch (DD->getKind()) {
4352 case DependentDiagnostic::Access:
4353 HandleDependentAccessCheck(*DD, TemplateArgs);
4354 break;
4355 }
4356 }
4357}