blob: 33e83d07d6346d774efa396eee054eda1cb41c33 [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 {
Benjamin Kramer5bbc3852012-02-06 11:13:08 +0000145 Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
146 *this, TemplateArgs);
Rafael Espindola31c195a2012-05-15 14:09:55 +0000147 if (NewAttr)
148 New->addAttr(NewAttr);
DeLesley Hutchins23323e02012-01-20 22:50:54 +0000149 }
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000150 }
151}
152
Douglas Gregor4f722be2009-03-25 15:45:12 +0000153Decl *
154TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000155 llvm_unreachable("Translation units cannot be instantiated");
Douglas Gregor4f722be2009-03-25 15:45:12 +0000156}
157
158Decl *
Chris Lattner57ad3782011-02-17 20:34:02 +0000159TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
160 LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
161 D->getIdentifier());
162 Owner->addDecl(Inst);
163 return Inst;
164}
165
166Decl *
Douglas Gregor4f722be2009-03-25 15:45:12 +0000167TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000168 llvm_unreachable("Namespaces cannot be instantiated");
Douglas Gregor4f722be2009-03-25 15:45:12 +0000169}
170
John McCall3dbd3d52010-02-16 06:53:13 +0000171Decl *
172TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
173 NamespaceAliasDecl *Inst
174 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
175 D->getNamespaceLoc(),
176 D->getAliasLoc(),
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +0000177 D->getIdentifier(),
178 D->getQualifierLoc(),
John McCall3dbd3d52010-02-16 06:53:13 +0000179 D->getTargetNameLoc(),
180 D->getNamespace());
181 Owner->addDecl(Inst);
182 return Inst;
183}
184
Richard Smith3e4c6c42011-05-05 21:57:07 +0000185Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
186 bool IsTypeAlias) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000187 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000188 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor561f8122011-07-01 01:22:09 +0000189 if (DI->getType()->isInstantiationDependentType() ||
Douglas Gregor836adf62010-05-24 17:22:01 +0000190 DI->getType()->isVariablyModifiedType()) {
John McCallba6a9bd2009-10-24 08:00:42 +0000191 DI = SemaRef.SubstType(DI, TemplateArgs,
192 D->getLocation(), D->getDeclName());
193 if (!DI) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000194 Invalid = true;
John McCalla93c9342009-12-07 02:54:59 +0000195 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000196 }
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000197 } else {
198 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000199 }
Mike Stump1eb44332009-09-09 15:08:12 +0000200
Richard Smithb5b37d12012-10-23 00:32:41 +0000201 // HACK: g++ has a bug where it gets the value kind of ?: wrong.
202 // libstdc++ relies upon this bug in its implementation of common_type.
203 // If we happen to be processing that implementation, fake up the g++ ?:
204 // semantics. See LWG issue 2141 for more information on the bug.
205 const DecltypeType *DT = DI->getType()->getAs<DecltypeType>();
206 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
207 if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) &&
208 DT->isReferenceType() &&
209 RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() &&
210 RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") &&
211 D->getIdentifier() && D->getIdentifier()->isStr("type") &&
212 SemaRef.getSourceManager().isInSystemHeader(D->getLocStart()))
213 // Fold it to the (non-reference) type which g++ would have produced.
214 DI = SemaRef.Context.getTrivialTypeSourceInfo(
215 DI->getType().getNonReferenceType());
216
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000217 // Create the new typedef
Richard Smith162e1c12011-04-15 14:24:37 +0000218 TypedefNameDecl *Typedef;
219 if (IsTypeAlias)
220 Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
221 D->getLocation(), D->getIdentifier(), DI);
222 else
223 Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
224 D->getLocation(), D->getIdentifier(), DI);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000225 if (Invalid)
226 Typedef->setInvalidDecl();
227
John McCallcde5a402011-02-01 08:20:08 +0000228 // If the old typedef was the name for linkage purposes of an anonymous
229 // tag decl, re-establish that relationship for the new typedef.
230 if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
231 TagDecl *oldTag = oldTagType->getDecl();
Douglas Gregorc61361b2013-03-08 22:15:15 +0000232 if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) {
John McCallcde5a402011-02-01 08:20:08 +0000233 TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
John McCall83972f12013-03-09 00:54:27 +0000234 assert(!newTag->hasNameForLinkage());
Richard Smith162e1c12011-04-15 14:24:37 +0000235 newTag->setTypedefNameForAnonDecl(Typedef);
John McCallcde5a402011-02-01 08:20:08 +0000236 }
Douglas Gregord57a38e2010-04-23 16:25:07 +0000237 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000238
Douglas Gregoref96ee02012-01-14 16:38:05 +0000239 if (TypedefNameDecl *Prev = D->getPreviousDecl()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000240 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
241 TemplateArgs);
Douglas Gregorb7107222011-03-04 19:46:35 +0000242 if (!InstPrev)
243 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000244
Rafael Espindola5df37bd2011-12-26 22:42:47 +0000245 TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
246
247 // If the typedef types are not identical, reject them.
248 SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
249
250 Typedef->setPreviousDeclaration(InstPrevTypedef);
John McCall5126fd02009-12-30 00:31:22 +0000251 }
252
John McCall1d8d1cc2010-08-01 02:01:53 +0000253 SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
Douglas Gregord57a38e2010-04-23 16:25:07 +0000254
John McCall46460a62010-01-20 21:53:11 +0000255 Typedef->setAccess(D->getAccess());
Mike Stump1eb44332009-09-09 15:08:12 +0000256
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000257 return Typedef;
258}
259
Richard Smith162e1c12011-04-15 14:24:37 +0000260Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
Richard Smith3e4c6c42011-05-05 21:57:07 +0000261 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
262 Owner->addDecl(Typedef);
263 return Typedef;
Richard Smith162e1c12011-04-15 14:24:37 +0000264}
265
266Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
Richard Smith3e4c6c42011-05-05 21:57:07 +0000267 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
268 Owner->addDecl(Typedef);
269 return Typedef;
270}
271
272Decl *
273TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
274 // Create a local instantiation scope for this type alias template, which
275 // will contain the instantiations of the template parameters.
276 LocalInstantiationScope Scope(SemaRef);
277
278 TemplateParameterList *TempParams = D->getTemplateParameters();
279 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
280 if (!InstParams)
281 return 0;
282
283 TypeAliasDecl *Pattern = D->getTemplatedDecl();
284
285 TypeAliasTemplateDecl *PrevAliasTemplate = 0;
Douglas Gregoref96ee02012-01-14 16:38:05 +0000286 if (Pattern->getPreviousDecl()) {
Richard Smith3e4c6c42011-05-05 21:57:07 +0000287 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
David Blaikie3bc93e32012-12-19 00:45:41 +0000288 if (!Found.empty()) {
289 PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front());
Richard Smith3e4c6c42011-05-05 21:57:07 +0000290 }
291 }
292
293 TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
294 InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
295 if (!AliasInst)
296 return 0;
297
298 TypeAliasTemplateDecl *Inst
299 = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
300 D->getDeclName(), InstParams, AliasInst);
301 if (PrevAliasTemplate)
302 Inst->setPreviousDeclaration(PrevAliasTemplate);
303
304 Inst->setAccess(D->getAccess());
305
306 if (!PrevAliasTemplate)
307 Inst->setInstantiatedFromMemberTemplate(D);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000308
Richard Smith3e4c6c42011-05-05 21:57:07 +0000309 Owner->addDecl(Inst);
310
311 return Inst;
Richard Smith162e1c12011-04-15 14:24:37 +0000312}
313
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000314Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
Douglas Gregor9901c572010-05-21 00:31:19 +0000315 // If this is the variable for an anonymous struct or union,
316 // instantiate the anonymous struct/union type first.
317 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
318 if (RecordTy->getDecl()->isAnonymousStructOrUnion())
319 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
320 return 0;
321
John McCallce3ff2b2009-08-25 22:02:44 +0000322 // Do substitution on the type of the declaration
John McCalla93c9342009-12-07 02:54:59 +0000323 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
John McCall0a5fa062009-10-21 02:39:02 +0000324 TemplateArgs,
325 D->getTypeSpecStartLoc(),
326 D->getDeclName());
327 if (!DI)
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000328 return 0;
329
Douglas Gregorc6dbc3f2010-09-12 07:37:24 +0000330 if (DI->getType()->isFunctionType()) {
331 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
332 << D->isStaticDataMember() << DI->getType();
333 return 0;
334 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000335
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000336 // Build the instantiated declaration
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000337 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000338 D->getInnerLocStart(),
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000339 D->getLocation(), D->getIdentifier(),
John McCall0a5fa062009-10-21 02:39:02 +0000340 DI->getType(), DI,
Rafael Espindolad2615cc2013-04-03 19:27:57 +0000341 D->getStorageClass());
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000342 Var->setThreadSpecified(D->isThreadSpecified());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +0000343 Var->setInitStyle(D->getInitStyle());
Richard Smithad762fc2011-04-14 22:09:26 +0000344 Var->setCXXForRangeDecl(D->isCXXForRangeDecl());
Richard Smith796c1a12012-01-19 22:46:17 +0000345 Var->setConstexpr(D->isConstexpr());
Mike Stump1eb44332009-09-09 15:08:12 +0000346
John McCallb6217662010-03-15 10:12:16 +0000347 // Substitute the nested name specifier, if any.
348 if (SubstQualifier(D, Var))
349 return 0;
350
Mike Stump1eb44332009-09-09 15:08:12 +0000351 // If we are instantiating a static data member defined
Douglas Gregor7caa6822009-07-24 20:34:43 +0000352 // out-of-line, the instantiation will have the same lexical
353 // context (which will be a namespace scope) as the template.
354 if (D->isOutOfLine())
355 Var->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000356
John McCall46460a62010-01-20 21:53:11 +0000357 Var->setAccess(D->getAccess());
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000358
Argyrios Kyrtzidis6b6b42a2011-04-19 19:51:10 +0000359 if (!D->isStaticDataMember()) {
Douglas Gregorc070cc62010-06-17 23:14:26 +0000360 Var->setUsed(D->isUsed(false));
Argyrios Kyrtzidis6b6b42a2011-04-19 19:51:10 +0000361 Var->setReferenced(D->isReferenced());
362 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000363
Richard Smith671b3212013-02-22 04:55:39 +0000364 SemaRef.InstantiateAttrs(TemplateArgs, D, Var, LateAttrs, StartingScope);
365
366 if (Var->hasAttrs())
367 SemaRef.CheckAlignasUnderalignment(Var);
368
Mike Stump390b4cc2009-05-16 07:39:55 +0000369 // FIXME: In theory, we could have a previous declaration for variables that
370 // are not static data members.
John McCall68263142009-11-18 22:49:29 +0000371 // FIXME: having to fake up a LookupResult is dumb.
372 LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(),
Douglas Gregor449d0a82010-03-01 19:11:54 +0000373 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Douglas Gregor60c93c92010-02-09 07:26:29 +0000374 if (D->isStaticDataMember())
375 SemaRef.LookupQualifiedName(Previous, Owner, false);
Douglas Gregor9aab9c42011-12-10 01:22:52 +0000376
377 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +0000378 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
Douglas Gregor9aab9c42011-12-10 01:22:52 +0000379 SemaRef.inferObjCARCLifetime(Var))
380 Var->setInvalidDecl();
381
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +0000382 SemaRef.CheckVariableDeclaration(Var, Previous);
Mike Stump1eb44332009-09-09 15:08:12 +0000383
Douglas Gregor7caa6822009-07-24 20:34:43 +0000384 if (D->isOutOfLine()) {
Richard Smith3e9ea0b2011-12-21 00:25:33 +0000385 D->getLexicalDeclContext()->addDecl(Var);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000386 Owner->makeDeclVisibleInContext(Var);
387 } else {
388 Owner->addDecl(Var);
Douglas Gregorf7d72f52010-05-03 20:22:41 +0000389 if (Owner->isFunctionOrMethod())
390 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Var);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000391 }
Richard Smithbe507b62013-02-01 08:12:08 +0000392
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000393 // Link instantiations of static data members back to the template from
394 // which they were instantiated.
395 if (Var->isStaticDataMember())
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000396 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D,
Douglas Gregorcf3293e2009-11-01 20:32:48 +0000397 TSK_ImplicitInstantiation);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000398
Douglas Gregor60c93c92010-02-09 07:26:29 +0000399 if (Var->getAnyInitializer()) {
400 // We already have an initializer in the class.
401 } else if (D->getInit()) {
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000402 if (Var->isStaticDataMember() && !D->isOutOfLine())
Richard Smithadb1d4c2012-07-22 23:45:10 +0000403 SemaRef.PushExpressionEvaluationContext(Sema::ConstantEvaluated, D);
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000404 else
Richard Smithadb1d4c2012-07-22 23:45:10 +0000405 SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated, D);
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000406
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000407 // Instantiate the initializer.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +0000408 ExprResult Init = SemaRef.SubstInitializer(D->getInit(), TemplateArgs,
409 D->getInitStyle() == VarDecl::CallInit);
410 if (!Init.isInvalid()) {
Richard Smith34b41d92011-02-20 03:19:35 +0000411 bool TypeMayContainAuto = true;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +0000412 if (Init.get()) {
413 bool DirectInit = D->isDirectInit();
414 SemaRef.AddInitializerToDecl(Var, Init.take(), DirectInit,
415 TypeMayContainAuto);
416 } else
Eli Friedman6aeaa602012-01-05 22:34:08 +0000417 SemaRef.ActOnUninitializedDecl(Var, TypeMayContainAuto);
Douglas Gregor6eef5192009-12-14 19:27:10 +0000418 } else {
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000419 // FIXME: Not too happy about invalidating the declaration
420 // because of a bogus initializer.
421 Var->setInvalidDecl();
Douglas Gregor6eef5192009-12-14 19:27:10 +0000422 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000423
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000424 SemaRef.PopExpressionEvaluationContext();
Richard Smithad762fc2011-04-14 22:09:26 +0000425 } else if ((!Var->isStaticDataMember() || Var->isOutOfLine()) &&
426 !Var->isCXXForRangeDecl())
John McCalld226f652010-08-21 09:40:31 +0000427 SemaRef.ActOnUninitializedDecl(Var, false);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000428
Richard Smithe3499ca2011-06-21 23:42:09 +0000429 // Diagnose unused local variables with dependent types, where the diagnostic
430 // will have been deferred.
431 if (!Var->isInvalidDecl() && Owner->isFunctionOrMethod() && !Var->isUsed() &&
432 D->getType()->isDependentType())
Douglas Gregor5764f612010-05-08 23:05:03 +0000433 SemaRef.DiagnoseUnusedDecl(Var);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +0000434
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000435 return Var;
436}
437
Abramo Bagnara6206d532010-06-05 05:09:32 +0000438Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
439 AccessSpecDecl* AD
440 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
441 D->getAccessSpecifierLoc(), D->getColonLoc());
442 Owner->addHiddenDecl(AD);
443 return AD;
444}
445
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000446Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
447 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000448 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor561f8122011-07-01 01:22:09 +0000449 if (DI->getType()->isInstantiationDependentType() ||
Douglas Gregor836adf62010-05-24 17:22:01 +0000450 DI->getType()->isVariablyModifiedType()) {
John McCall07fb6be2009-10-22 23:33:21 +0000451 DI = SemaRef.SubstType(DI, TemplateArgs,
452 D->getLocation(), D->getDeclName());
453 if (!DI) {
John McCalla93c9342009-12-07 02:54:59 +0000454 DI = D->getTypeSourceInfo();
John McCall07fb6be2009-10-22 23:33:21 +0000455 Invalid = true;
456 } else if (DI->getType()->isFunctionType()) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000457 // C++ [temp.arg.type]p3:
458 // If a declaration acquires a function type through a type
459 // dependent on a template-parameter and this causes a
460 // declaration that does not use the syntactic form of a
461 // function declarator to have function type, the program is
462 // ill-formed.
463 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
John McCall07fb6be2009-10-22 23:33:21 +0000464 << DI->getType();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000465 Invalid = true;
466 }
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000467 } else {
468 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000469 }
470
471 Expr *BitWidth = D->getBitWidth();
472 if (Invalid)
473 BitWidth = 0;
474 else if (BitWidth) {
Richard Smithf6702a32011-12-20 02:08:33 +0000475 // The bit-width expression is a constant expression.
476 EnterExpressionEvaluationContext Unevaluated(SemaRef,
477 Sema::ConstantEvaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000478
John McCall60d7b3a2010-08-24 06:29:42 +0000479 ExprResult InstantiatedBitWidth
John McCallce3ff2b2009-08-25 22:02:44 +0000480 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000481 if (InstantiatedBitWidth.isInvalid()) {
482 Invalid = true;
483 BitWidth = 0;
484 } else
Anders Carlssone9146f22009-05-01 19:49:17 +0000485 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000486 }
487
John McCall07fb6be2009-10-22 23:33:21 +0000488 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
489 DI->getType(), DI,
Mike Stump1eb44332009-09-09 15:08:12 +0000490 cast<RecordDecl>(Owner),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000491 D->getLocation(),
492 D->isMutable(),
493 BitWidth,
Richard Smithca523302012-06-10 03:12:00 +0000494 D->getInClassInitStyle(),
Richard Smith703b6012012-05-23 04:22:22 +0000495 D->getInnerLocStart(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000496 D->getAccess(),
497 0);
Douglas Gregor663b5a02009-10-14 20:14:33 +0000498 if (!Field) {
499 cast<Decl>(Owner)->setInvalidDecl();
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000500 return 0;
Douglas Gregor663b5a02009-10-14 20:14:33 +0000501 }
Mike Stump1eb44332009-09-09 15:08:12 +0000502
DeLesley Hutchins23323e02012-01-20 22:50:54 +0000503 SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000504
Richard Smithbe507b62013-02-01 08:12:08 +0000505 if (Field->hasAttrs())
506 SemaRef.CheckAlignasUnderalignment(Field);
507
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000508 if (Invalid)
509 Field->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000510
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000511 if (!Field->getDeclName()) {
512 // Keep track of where this decl came from.
513 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000514 }
Douglas Gregor9901c572010-05-21 00:31:19 +0000515 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
516 if (Parent->isAnonymousStructOrUnion() &&
Sebastian Redl7a126a42010-08-31 00:36:30 +0000517 Parent->getRedeclContext()->isFunctionOrMethod())
Douglas Gregor9901c572010-05-21 00:31:19 +0000518 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000519 }
Mike Stump1eb44332009-09-09 15:08:12 +0000520
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000521 Field->setImplicit(D->isImplicit());
John McCall46460a62010-01-20 21:53:11 +0000522 Field->setAccess(D->getAccess());
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000523 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000524
525 return Field;
526}
527
Francois Pichet87c2e122010-11-21 06:08:52 +0000528Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
529 NamedDecl **NamedChain =
530 new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
531
532 int i = 0;
533 for (IndirectFieldDecl::chain_iterator PI =
534 D->chain_begin(), PE = D->chain_end();
Douglas Gregorb7107222011-03-04 19:46:35 +0000535 PI != PE; ++PI) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000536 NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), *PI,
Douglas Gregorb7107222011-03-04 19:46:35 +0000537 TemplateArgs);
538 if (!Next)
539 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000540
Douglas Gregorb7107222011-03-04 19:46:35 +0000541 NamedChain[i++] = Next;
542 }
Francois Pichet87c2e122010-11-21 06:08:52 +0000543
Francois Pichet40e17752010-12-09 10:07:54 +0000544 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
Francois Pichet87c2e122010-11-21 06:08:52 +0000545 IndirectFieldDecl* IndirectField
546 = IndirectFieldDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Francois Pichet40e17752010-12-09 10:07:54 +0000547 D->getIdentifier(), T,
Francois Pichet87c2e122010-11-21 06:08:52 +0000548 NamedChain, D->getChainingSize());
549
550
551 IndirectField->setImplicit(D->isImplicit());
552 IndirectField->setAccess(D->getAccess());
553 Owner->addDecl(IndirectField);
554 return IndirectField;
555}
556
John McCall02cace72009-08-28 07:59:38 +0000557Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
John McCall02cace72009-08-28 07:59:38 +0000558 // Handle friend type expressions by simply substituting template
Douglas Gregor06245bf2010-04-07 17:57:12 +0000559 // parameters into the pattern type and checking the result.
John McCall32f2fb52010-03-25 18:04:51 +0000560 if (TypeSourceInfo *Ty = D->getFriendType()) {
Chandler Carruth4fb86f82011-05-01 00:51:33 +0000561 TypeSourceInfo *InstTy;
562 // If this is an unsupported friend, don't bother substituting template
563 // arguments into it. The actual type referred to won't be used by any
564 // parts of Clang, and may not be valid for instantiating. Just use the
565 // same info for the instantiated friend.
566 if (D->isUnsupportedFriend()) {
567 InstTy = Ty;
568 } else {
569 InstTy = SemaRef.SubstType(Ty, TemplateArgs,
570 D->getLocation(), DeclarationName());
571 }
572 if (!InstTy)
Douglas Gregor7557a132009-12-24 20:56:24 +0000573 return 0;
John McCall02cace72009-08-28 07:59:38 +0000574
Richard Smithd6f80da2012-09-20 01:31:00 +0000575 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getLocStart(),
Abramo Bagnara0216df82011-10-29 20:52:52 +0000576 D->getFriendLoc(), InstTy);
Douglas Gregor06245bf2010-04-07 17:57:12 +0000577 if (!FD)
578 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000579
Douglas Gregor06245bf2010-04-07 17:57:12 +0000580 FD->setAccess(AS_public);
John McCall9a34edb2010-10-19 01:40:49 +0000581 FD->setUnsupportedFriend(D->isUnsupportedFriend());
Douglas Gregor06245bf2010-04-07 17:57:12 +0000582 Owner->addDecl(FD);
583 return FD;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000584 }
585
Douglas Gregor06245bf2010-04-07 17:57:12 +0000586 NamedDecl *ND = D->getFriendDecl();
587 assert(ND && "friend decl must be a decl or a type!");
588
John McCallaf2094e2010-04-08 09:05:18 +0000589 // All of the Visit implementations for the various potential friend
590 // declarations have to be carefully written to work for friend
591 // objects, with the most important detail being that the target
592 // decl should almost certainly not be placed in Owner.
593 Decl *NewND = Visit(ND);
Douglas Gregor06245bf2010-04-07 17:57:12 +0000594 if (!NewND) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000595
John McCall02cace72009-08-28 07:59:38 +0000596 FriendDecl *FD =
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000597 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor06245bf2010-04-07 17:57:12 +0000598 cast<NamedDecl>(NewND), D->getFriendLoc());
John McCall5fee1102009-08-29 03:50:18 +0000599 FD->setAccess(AS_public);
John McCall9a34edb2010-10-19 01:40:49 +0000600 FD->setUnsupportedFriend(D->isUnsupportedFriend());
John McCall02cace72009-08-28 07:59:38 +0000601 Owner->addDecl(FD);
602 return FD;
John McCallfd810b12009-08-14 02:03:10 +0000603}
604
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000605Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
606 Expr *AssertExpr = D->getAssertExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000607
Richard Smithf6702a32011-12-20 02:08:33 +0000608 // The expression in a static assertion is a constant expression.
609 EnterExpressionEvaluationContext Unevaluated(SemaRef,
610 Sema::ConstantEvaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000611
John McCall60d7b3a2010-08-24 06:29:42 +0000612 ExprResult InstantiatedAssertExpr
John McCallce3ff2b2009-08-25 22:02:44 +0000613 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000614 if (InstantiatedAssertExpr.isInvalid())
615 return 0;
616
Richard Smithe3f470a2012-07-11 22:37:56 +0000617 return SemaRef.BuildStaticAssertDeclaration(D->getLocation(),
John McCall9ae2f072010-08-23 23:25:46 +0000618 InstantiatedAssertExpr.get(),
Richard Smithe3f470a2012-07-11 22:37:56 +0000619 D->getMessage(),
620 D->getRParenLoc(),
621 D->isFailed());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000622}
623
624Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Richard Smith38f0df32012-03-26 04:58:10 +0000625 EnumDecl *PrevDecl = 0;
626 if (D->getPreviousDecl()) {
627 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
628 D->getPreviousDecl(),
629 TemplateArgs);
630 if (!Prev) return 0;
631 PrevDecl = cast<EnumDecl>(Prev);
632 }
633
Abramo Bagnaraba877ad2011-03-09 14:09:51 +0000634 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000635 D->getLocation(), D->getIdentifier(),
Richard Smith38f0df32012-03-26 04:58:10 +0000636 PrevDecl, D->isScoped(),
Abramo Bagnaraa88cefd2010-12-03 18:54:17 +0000637 D->isScopedUsingClassTag(), D->isFixed());
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000638 if (D->isFixed()) {
Richard Smithf1c66b42012-03-14 23:13:10 +0000639 if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000640 // If we have type source information for the underlying type, it means it
641 // has been explicitly set by the user. Perform substitution on it before
642 // moving on.
643 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
Richard Smithf1c66b42012-03-14 23:13:10 +0000644 TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
645 DeclarationName());
646 if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000647 Enum->setIntegerType(SemaRef.Context.IntTy);
Richard Smithf1c66b42012-03-14 23:13:10 +0000648 else
649 Enum->setIntegerTypeSourceInfo(NewTI);
650 } else {
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000651 assert(!D->getIntegerType()->isDependentType()
652 && "Dependent type without type source info");
653 Enum->setIntegerType(D->getIntegerType());
654 }
655 }
656
John McCall5b629aa2010-10-22 23:36:17 +0000657 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
658
Richard Smithf1c66b42012-03-14 23:13:10 +0000659 Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000660 Enum->setAccess(D->getAccess());
John McCallb6217662010-03-15 10:12:16 +0000661 if (SubstQualifier(D, Enum)) return 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000662 Owner->addDecl(Enum);
Richard Smithf1c66b42012-03-14 23:13:10 +0000663
Richard Smith4ca93d92012-03-26 04:08:46 +0000664 EnumDecl *Def = D->getDefinition();
665 if (Def && Def != D) {
666 // If this is an out-of-line definition of an enum member template, check
667 // that the underlying types match in the instantiation of both
668 // declarations.
669 if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
670 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
671 QualType DefnUnderlying =
672 SemaRef.SubstType(TI->getType(), TemplateArgs,
673 UnderlyingLoc, DeclarationName());
674 SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
675 DefnUnderlying, Enum);
676 }
677 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000678
Douglas Gregor96084f12010-03-01 19:00:07 +0000679 if (D->getDeclContext()->isFunctionOrMethod())
680 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000681
Richard Smithf1c66b42012-03-14 23:13:10 +0000682 // C++11 [temp.inst]p1: The implicit instantiation of a class template
683 // specialization causes the implicit instantiation of the declarations, but
684 // not the definitions of scoped member enumerations.
685 // FIXME: There appears to be no wording for what happens for an enum defined
Richard Smith38f0df32012-03-26 04:58:10 +0000686 // within a block scope, but we treat that much like a member template. Only
687 // instantiate the definition when visiting the definition in that case, since
688 // we will visit all redeclarations.
689 if (!Enum->isScoped() && Def &&
690 (!D->getDeclContext()->isFunctionOrMethod() || D->isCompleteDefinition()))
Richard Smith4ca93d92012-03-26 04:08:46 +0000691 InstantiateEnumDefinition(Enum, Def);
Richard Smithf1c66b42012-03-14 23:13:10 +0000692
693 return Enum;
694}
695
696void TemplateDeclInstantiator::InstantiateEnumDefinition(
697 EnumDecl *Enum, EnumDecl *Pattern) {
698 Enum->startDefinition();
699
Richard Smith1af83c42012-03-23 03:33:32 +0000700 // Update the location to refer to the definition.
701 Enum->setLocation(Pattern->getLocation());
702
Chris Lattner5f9e2722011-07-23 10:55:15 +0000703 SmallVector<Decl*, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000704
705 EnumConstantDecl *LastEnumConst = 0;
Richard Smithf1c66b42012-03-14 23:13:10 +0000706 for (EnumDecl::enumerator_iterator EC = Pattern->enumerator_begin(),
707 ECEnd = Pattern->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000708 EC != ECEnd; ++EC) {
709 // The specified value for the enumerator.
John McCall60d7b3a2010-08-24 06:29:42 +0000710 ExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000711 if (Expr *UninstValue = EC->getInitExpr()) {
Richard Smithf6702a32011-12-20 02:08:33 +0000712 // The enumerator's value expression is a constant expression.
Mike Stump1eb44332009-09-09 15:08:12 +0000713 EnterExpressionEvaluationContext Unevaluated(SemaRef,
Richard Smithf6702a32011-12-20 02:08:33 +0000714 Sema::ConstantEvaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000715
John McCallce3ff2b2009-08-25 22:02:44 +0000716 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000717 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000718
719 // Drop the initial value and continue.
720 bool isInvalid = false;
721 if (Value.isInvalid()) {
722 Value = SemaRef.Owned((Expr *)0);
723 isInvalid = true;
724 }
725
Mike Stump1eb44332009-09-09 15:08:12 +0000726 EnumConstantDecl *EnumConst
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000727 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
728 EC->getLocation(), EC->getIdentifier(),
John McCall9ae2f072010-08-23 23:25:46 +0000729 Value.get());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000730
731 if (isInvalid) {
732 if (EnumConst)
733 EnumConst->setInvalidDecl();
734 Enum->setInvalidDecl();
735 }
736
737 if (EnumConst) {
David Blaikie581deb32012-06-06 20:45:41 +0000738 SemaRef.InstantiateAttrs(TemplateArgs, *EC, EnumConst);
John McCall5b629aa2010-10-22 23:36:17 +0000739
John McCall3b85ecf2010-01-23 22:37:59 +0000740 EnumConst->setAccess(Enum->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000741 Enum->addDecl(EnumConst);
John McCalld226f652010-08-21 09:40:31 +0000742 Enumerators.push_back(EnumConst);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000743 LastEnumConst = EnumConst;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000744
Richard Smithf1c66b42012-03-14 23:13:10 +0000745 if (Pattern->getDeclContext()->isFunctionOrMethod() &&
746 !Enum->isScoped()) {
Douglas Gregor96084f12010-03-01 19:00:07 +0000747 // If the enumeration is within a function or method, record the enum
748 // constant as a local.
David Blaikie581deb32012-06-06 20:45:41 +0000749 SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst);
Douglas Gregor96084f12010-03-01 19:00:07 +0000750 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000751 }
752 }
Mike Stump1eb44332009-09-09 15:08:12 +0000753
Richard Smithf1c66b42012-03-14 23:13:10 +0000754 // FIXME: Fixup LBraceLoc
755 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(),
756 Enum->getRBraceLoc(), Enum,
Eli Friedmande7a0fc2010-08-15 02:27:09 +0000757 Enumerators.data(), Enumerators.size(),
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000758 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000759}
760
Douglas Gregor6477b692009-03-25 15:04:13 +0000761Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000762 llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
Douglas Gregor6477b692009-03-25 15:04:13 +0000763}
764
John McCalle29ba202009-08-20 01:44:21 +0000765Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
John McCall93ba8572010-03-25 06:39:04 +0000766 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
767
Douglas Gregor550d9b22009-10-31 17:21:17 +0000768 // Create a local instantiation scope for this class template, which
769 // will contain the instantiations of the template parameters.
John McCall2a7fb272010-08-25 05:32:35 +0000770 LocalInstantiationScope Scope(SemaRef);
John McCalle29ba202009-08-20 01:44:21 +0000771 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000772 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000773 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000774 return NULL;
John McCalle29ba202009-08-20 01:44:21 +0000775
776 CXXRecordDecl *Pattern = D->getTemplatedDecl();
John McCall93ba8572010-03-25 06:39:04 +0000777
778 // Instantiate the qualifier. We have to do this first in case
779 // we're a friend declaration, because if we are then we need to put
780 // the new declaration in the appropriate context.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000781 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
782 if (QualifierLoc) {
783 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
784 TemplateArgs);
785 if (!QualifierLoc)
786 return 0;
John McCall93ba8572010-03-25 06:39:04 +0000787 }
788
789 CXXRecordDecl *PrevDecl = 0;
790 ClassTemplateDecl *PrevClassTemplate = 0;
791
Douglas Gregoref96ee02012-01-14 16:38:05 +0000792 if (!isFriend && Pattern->getPreviousDecl()) {
Nick Lewycky37574f52010-11-08 23:29:42 +0000793 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
David Blaikie3bc93e32012-12-19 00:45:41 +0000794 if (!Found.empty()) {
795 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
Nick Lewycky37574f52010-11-08 23:29:42 +0000796 if (PrevClassTemplate)
797 PrevDecl = PrevClassTemplate->getTemplatedDecl();
798 }
799 }
800
John McCall93ba8572010-03-25 06:39:04 +0000801 // If this isn't a friend, then it's a member template, in which
802 // case we just want to build the instantiation in the
803 // specialization. If it is a friend, we want to build it in
804 // the appropriate context.
805 DeclContext *DC = Owner;
806 if (isFriend) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000807 if (QualifierLoc) {
John McCall93ba8572010-03-25 06:39:04 +0000808 CXXScopeSpec SS;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000809 SS.Adopt(QualifierLoc);
John McCall93ba8572010-03-25 06:39:04 +0000810 DC = SemaRef.computeDeclContext(SS);
811 if (!DC) return 0;
812 } else {
813 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
814 Pattern->getDeclContext(),
815 TemplateArgs);
816 }
817
818 // Look for a previous declaration of the template in the owning
819 // context.
820 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
821 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
822 SemaRef.LookupQualifiedName(R, DC);
823
824 if (R.isSingleResult()) {
825 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
826 if (PrevClassTemplate)
827 PrevDecl = PrevClassTemplate->getTemplatedDecl();
828 }
829
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000830 if (!PrevClassTemplate && QualifierLoc) {
John McCall93ba8572010-03-25 06:39:04 +0000831 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
Douglas Gregor1eabb7d2010-03-31 23:17:41 +0000832 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000833 << QualifierLoc.getSourceRange();
John McCall93ba8572010-03-25 06:39:04 +0000834 return 0;
835 }
836
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000837 bool AdoptedPreviousTemplateParams = false;
John McCall93ba8572010-03-25 06:39:04 +0000838 if (PrevClassTemplate) {
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000839 bool Complain = true;
840
841 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
842 // template for struct std::tr1::__detail::_Map_base, where the
843 // template parameters of the friend declaration don't match the
844 // template parameters of the original declaration. In this one
845 // case, we don't complain about the ill-formed friend
846 // declaration.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000847 if (isFriend && Pattern->getIdentifier() &&
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000848 Pattern->getIdentifier()->isStr("_Map_base") &&
849 DC->isNamespace() &&
850 cast<NamespaceDecl>(DC)->getIdentifier() &&
851 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
852 DeclContext *DCParent = DC->getParent();
853 if (DCParent->isNamespace() &&
854 cast<NamespaceDecl>(DCParent)->getIdentifier() &&
855 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
856 DeclContext *DCParent2 = DCParent->getParent();
857 if (DCParent2->isNamespace() &&
858 cast<NamespaceDecl>(DCParent2)->getIdentifier() &&
859 cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") &&
860 DCParent2->getParent()->isTranslationUnit())
861 Complain = false;
862 }
863 }
864
John McCall93ba8572010-03-25 06:39:04 +0000865 TemplateParameterList *PrevParams
866 = PrevClassTemplate->getTemplateParameters();
867
868 // Make sure the parameter lists match.
869 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000870 Complain,
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000871 Sema::TPL_TemplateMatch)) {
872 if (Complain)
873 return 0;
874
875 AdoptedPreviousTemplateParams = true;
876 InstParams = PrevParams;
877 }
John McCall93ba8572010-03-25 06:39:04 +0000878
879 // Do some additional validation, then merge default arguments
880 // from the existing declarations.
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000881 if (!AdoptedPreviousTemplateParams &&
882 SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
John McCall93ba8572010-03-25 06:39:04 +0000883 Sema::TPC_ClassTemplate))
884 return 0;
885 }
886 }
887
John McCalle29ba202009-08-20 01:44:21 +0000888 CXXRecordDecl *RecordInst
John McCall93ba8572010-03-25 06:39:04 +0000889 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +0000890 Pattern->getLocStart(), Pattern->getLocation(),
891 Pattern->getIdentifier(), PrevDecl,
Douglas Gregorf0510d42009-10-12 23:11:44 +0000892 /*DelayTypeCreation=*/true);
John McCalle29ba202009-08-20 01:44:21 +0000893
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000894 if (QualifierLoc)
895 RecordInst->setQualifierInfo(QualifierLoc);
John McCallb6217662010-03-15 10:12:16 +0000896
John McCalle29ba202009-08-20 01:44:21 +0000897 ClassTemplateDecl *Inst
John McCall93ba8572010-03-25 06:39:04 +0000898 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
899 D->getIdentifier(), InstParams, RecordInst,
900 PrevClassTemplate);
John McCalle29ba202009-08-20 01:44:21 +0000901 RecordInst->setDescribedClassTemplate(Inst);
John McCallea7390c2010-04-08 20:25:50 +0000902
John McCall93ba8572010-03-25 06:39:04 +0000903 if (isFriend) {
John McCallea7390c2010-04-08 20:25:50 +0000904 if (PrevClassTemplate)
905 Inst->setAccess(PrevClassTemplate->getAccess());
906 else
907 Inst->setAccess(D->getAccess());
908
John McCall93ba8572010-03-25 06:39:04 +0000909 Inst->setObjectOfFriendDecl(PrevClassTemplate != 0);
910 // TODO: do we want to track the instantiation progeny of this
911 // friend target decl?
912 } else {
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000913 Inst->setAccess(D->getAccess());
Nick Lewycky37574f52010-11-08 23:29:42 +0000914 if (!PrevClassTemplate)
915 Inst->setInstantiatedFromMemberTemplate(D);
John McCall93ba8572010-03-25 06:39:04 +0000916 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000917
Douglas Gregorf0510d42009-10-12 23:11:44 +0000918 // Trigger creation of the type for the instantiation.
John McCall3cb0ebd2010-03-10 03:28:59 +0000919 SemaRef.Context.getInjectedClassNameType(RecordInst,
Douglas Gregor24bae922010-07-08 18:37:38 +0000920 Inst->getInjectedClassNameSpecialization());
John McCallea7390c2010-04-08 20:25:50 +0000921
Douglas Gregor259571e2009-10-30 22:42:42 +0000922 // Finish handling of friends.
John McCall93ba8572010-03-25 06:39:04 +0000923 if (isFriend) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +0000924 DC->makeDeclVisibleInContext(Inst);
Abramo Bagnara4c515482011-11-26 13:33:46 +0000925 Inst->setLexicalDeclContext(Owner);
926 RecordInst->setLexicalDeclContext(Owner);
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000927 return Inst;
Douglas Gregor259571e2009-10-30 22:42:42 +0000928 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000929
Abramo Bagnara4c515482011-11-26 13:33:46 +0000930 if (D->isOutOfLine()) {
931 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
932 RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
933 }
934
John McCalle29ba202009-08-20 01:44:21 +0000935 Owner->addDecl(Inst);
Douglas Gregord65587f2010-11-10 19:44:59 +0000936
937 if (!PrevClassTemplate) {
938 // Queue up any out-of-line partial specializations of this member
939 // class template; the client will force their instantiation once
940 // the enclosing class has been instantiated.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000941 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
Douglas Gregord65587f2010-11-10 19:44:59 +0000942 D->getPartialSpecializations(PartialSpecs);
943 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
944 if (PartialSpecs[I]->isOutOfLine())
945 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
946 }
947
John McCalle29ba202009-08-20 01:44:21 +0000948 return Inst;
949}
950
Douglas Gregord60e1052009-08-27 16:57:43 +0000951Decl *
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000952TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
953 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregored9c0f92009-10-29 00:04:11 +0000954 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000955
Douglas Gregored9c0f92009-10-29 00:04:11 +0000956 // Lookup the already-instantiated declaration in the instantiation
957 // of the class template and return that.
958 DeclContext::lookup_result Found
959 = Owner->lookup(ClassTemplate->getDeclName());
David Blaikie3bc93e32012-12-19 00:45:41 +0000960 if (Found.empty())
Douglas Gregored9c0f92009-10-29 00:04:11 +0000961 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000962
Douglas Gregored9c0f92009-10-29 00:04:11 +0000963 ClassTemplateDecl *InstClassTemplate
David Blaikie3bc93e32012-12-19 00:45:41 +0000964 = dyn_cast<ClassTemplateDecl>(Found.front());
Douglas Gregored9c0f92009-10-29 00:04:11 +0000965 if (!InstClassTemplate)
966 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000967
Douglas Gregord65587f2010-11-10 19:44:59 +0000968 if (ClassTemplatePartialSpecializationDecl *Result
969 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
970 return Result;
971
972 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000973}
974
975Decl *
Douglas Gregord60e1052009-08-27 16:57:43 +0000976TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000977 // Create a local instantiation scope for this function template, which
978 // will contain the instantiations of the template parameters and then get
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000979 // merged with the local instantiation scope for the function template
Douglas Gregor550d9b22009-10-31 17:21:17 +0000980 // itself.
John McCall2a7fb272010-08-25 05:32:35 +0000981 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor895162d2010-04-30 18:55:50 +0000982
Douglas Gregord60e1052009-08-27 16:57:43 +0000983 TemplateParameterList *TempParams = D->getTemplateParameters();
984 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000985 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000986 return NULL;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000987
Douglas Gregora735b202009-10-13 14:39:41 +0000988 FunctionDecl *Instantiated = 0;
989 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000990 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
Douglas Gregora735b202009-10-13 14:39:41 +0000991 InstParams));
992 else
993 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000994 D->getTemplatedDecl(),
Douglas Gregora735b202009-10-13 14:39:41 +0000995 InstParams));
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000996
Douglas Gregora735b202009-10-13 14:39:41 +0000997 if (!Instantiated)
Douglas Gregord60e1052009-08-27 16:57:43 +0000998 return 0;
999
Mike Stump1eb44332009-09-09 15:08:12 +00001000 // Link the instantiated function template declaration to the function
Douglas Gregord60e1052009-08-27 16:57:43 +00001001 // template from which it was instantiated.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001002 FunctionTemplateDecl *InstTemplate
Douglas Gregora735b202009-10-13 14:39:41 +00001003 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregor37d681852009-10-12 22:27:17 +00001004 InstTemplate->setAccess(D->getAccess());
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001005 assert(InstTemplate &&
Douglas Gregora735b202009-10-13 14:39:41 +00001006 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCalle976ffe2009-12-14 23:19:40 +00001007
John McCallb1a56e72010-03-26 23:10:15 +00001008 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
1009
John McCalle976ffe2009-12-14 23:19:40 +00001010 // Link the instantiation back to the pattern *unless* this is a
1011 // non-definition friend declaration.
1012 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
John McCallb1a56e72010-03-26 23:10:15 +00001013 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregora735b202009-10-13 14:39:41 +00001014 InstTemplate->setInstantiatedFromMemberTemplate(D);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001015
John McCallb1a56e72010-03-26 23:10:15 +00001016 // Make declarations visible in the appropriate context.
John McCall1f2e1a92012-08-10 03:15:35 +00001017 if (!isFriend) {
Douglas Gregora735b202009-10-13 14:39:41 +00001018 Owner->addDecl(InstTemplate);
John McCall1f2e1a92012-08-10 03:15:35 +00001019 } else if (InstTemplate->getDeclContext()->isRecord() &&
1020 !D->getPreviousDecl()) {
1021 SemaRef.CheckFriendAccess(InstTemplate);
1022 }
John McCallb1a56e72010-03-26 23:10:15 +00001023
Douglas Gregord60e1052009-08-27 16:57:43 +00001024 return InstTemplate;
1025}
1026
Douglas Gregord475b8d2009-03-25 21:17:03 +00001027Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
1028 CXXRecordDecl *PrevDecl = 0;
1029 if (D->isInjectedClassName())
1030 PrevDecl = cast<CXXRecordDecl>(Owner);
Douglas Gregoref96ee02012-01-14 16:38:05 +00001031 else if (D->getPreviousDecl()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001032 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
Douglas Gregoref96ee02012-01-14 16:38:05 +00001033 D->getPreviousDecl(),
John McCall6c1c1b82009-12-15 22:29:06 +00001034 TemplateArgs);
1035 if (!Prev) return 0;
1036 PrevDecl = cast<CXXRecordDecl>(Prev);
1037 }
Douglas Gregord475b8d2009-03-25 21:17:03 +00001038
1039 CXXRecordDecl *Record
Mike Stump1eb44332009-09-09 15:08:12 +00001040 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001041 D->getLocStart(), D->getLocation(),
1042 D->getIdentifier(), PrevDecl);
John McCallb6217662010-03-15 10:12:16 +00001043
1044 // Substitute the nested name specifier, if any.
1045 if (SubstQualifier(D, Record))
1046 return 0;
1047
Douglas Gregord475b8d2009-03-25 21:17:03 +00001048 Record->setImplicit(D->isImplicit());
Eli Friedmaneaba1af2009-08-27 19:11:42 +00001049 // FIXME: Check against AS_none is an ugly hack to work around the issue that
1050 // the tag decls introduced by friend class declarations don't have an access
1051 // specifier. Remove once this area of the code gets sorted out.
1052 if (D->getAccess() != AS_none)
1053 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +00001054 if (!D->isInjectedClassName())
Douglas Gregorf6b11852009-10-08 15:14:33 +00001055 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +00001056
John McCall02cace72009-08-28 07:59:38 +00001057 // If the original function was part of a friend declaration,
1058 // inherit its namespace state.
1059 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
1060 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
1061
Douglas Gregor9901c572010-05-21 00:31:19 +00001062 // Make sure that anonymous structs and unions are recorded.
1063 if (D->isAnonymousStructOrUnion()) {
1064 Record->setAnonymousStructOrUnion(true);
Sebastian Redl7a126a42010-08-31 00:36:30 +00001065 if (Record->getDeclContext()->getRedeclContext()->isFunctionOrMethod())
Douglas Gregor9901c572010-05-21 00:31:19 +00001066 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
1067 }
Anders Carlssond8b285f2009-09-01 04:26:58 +00001068
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001069 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +00001070 return Record;
1071}
1072
Douglas Gregor71074fd2012-09-13 21:56:43 +00001073/// \brief Adjust the given function type for an instantiation of the
1074/// given declaration, to cope with modifications to the function's type that
1075/// aren't reflected in the type-source information.
1076///
1077/// \param D The declaration we're instantiating.
1078/// \param TInfo The already-instantiated type.
1079static QualType adjustFunctionTypeForInstantiation(ASTContext &Context,
1080 FunctionDecl *D,
1081 TypeSourceInfo *TInfo) {
Douglas Gregorbed51fe2012-09-13 22:01:49 +00001082 const FunctionProtoType *OrigFunc
1083 = D->getType()->castAs<FunctionProtoType>();
1084 const FunctionProtoType *NewFunc
1085 = TInfo->getType()->castAs<FunctionProtoType>();
1086 if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
1087 return TInfo->getType();
1088
1089 FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
1090 NewEPI.ExtInfo = OrigFunc->getExtInfo();
1091 return Context.getFunctionType(NewFunc->getResultType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00001092 ArrayRef<QualType>(NewFunc->arg_type_begin(),
1093 NewFunc->getNumArgs()),
Douglas Gregorbed51fe2012-09-13 22:01:49 +00001094 NewEPI);
Douglas Gregor71074fd2012-09-13 21:56:43 +00001095}
1096
John McCall02cace72009-08-28 07:59:38 +00001097/// Normal class members are of more specific types and therefore
1098/// don't make it here. This function serves two purposes:
1099/// 1) instantiating function templates
1100/// 2) substituting friend declarations
1101/// FIXME: preserve function definitions in case #2
Douglas Gregor7557a132009-12-24 20:56:24 +00001102Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
Douglas Gregora735b202009-10-13 14:39:41 +00001103 TemplateParameterList *TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +00001104 // Check whether there is already a function template specialization for
1105 // this declaration.
1106 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
John McCallb0cb0222010-03-27 05:57:59 +00001107 if (FunctionTemplate && !TemplateParams) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001108 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor24bae922010-07-08 18:37:38 +00001109 = TemplateArgs.getInnermost();
Mike Stump1eb44332009-09-09 15:08:12 +00001110
Douglas Gregor1e1e9722012-03-28 14:34:23 +00001111 void *InsertPos = 0;
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001112 FunctionDecl *SpecFunc
1113 = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
1114 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001115
Douglas Gregor127102b2009-06-29 20:59:39 +00001116 // If we already have a function template specialization, return it.
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001117 if (SpecFunc)
1118 return SpecFunc;
Douglas Gregor127102b2009-06-29 20:59:39 +00001119 }
Mike Stump1eb44332009-09-09 15:08:12 +00001120
John McCallb0cb0222010-03-27 05:57:59 +00001121 bool isFriend;
1122 if (FunctionTemplate)
1123 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1124 else
1125 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1126
Douglas Gregor79c22782010-01-16 20:21:20 +00001127 bool MergeWithParentScope = (TemplateParams != 0) ||
Douglas Gregorb212d9a2010-05-21 21:25:08 +00001128 Owner->isFunctionOrMethod() ||
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001129 !(isa<Decl>(Owner) &&
Douglas Gregor79c22782010-01-16 20:21:20 +00001130 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall2a7fb272010-08-25 05:32:35 +00001131 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +00001132
Chris Lattner5f9e2722011-07-23 10:55:15 +00001133 SmallVector<ParmVarDecl *, 4> Params;
David Blaikie64b4b432011-11-10 05:42:04 +00001134 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
John McCall21ef0fa2010-03-11 09:03:00 +00001135 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001136 return 0;
Douglas Gregor71074fd2012-09-13 21:56:43 +00001137 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
John McCallfd810b12009-08-14 02:03:10 +00001138
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001139 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1140 if (QualifierLoc) {
1141 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1142 TemplateArgs);
1143 if (!QualifierLoc)
1144 return 0;
John McCalld325daa2010-03-26 04:53:08 +00001145 }
1146
John McCall68b6b872010-02-06 01:50:47 +00001147 // If we're instantiating a local function declaration, put the result
1148 // in the owner; otherwise we need to find the instantiated context.
1149 DeclContext *DC;
1150 if (D->getDeclContext()->isFunctionOrMethod())
1151 DC = Owner;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001152 else if (isFriend && QualifierLoc) {
John McCalld325daa2010-03-26 04:53:08 +00001153 CXXScopeSpec SS;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001154 SS.Adopt(QualifierLoc);
John McCalld325daa2010-03-26 04:53:08 +00001155 DC = SemaRef.computeDeclContext(SS);
1156 if (!DC) return 0;
1157 } else {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001158 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001159 TemplateArgs);
John McCalld325daa2010-03-26 04:53:08 +00001160 }
John McCall68b6b872010-02-06 01:50:47 +00001161
John McCall02cace72009-08-28 07:59:38 +00001162 FunctionDecl *Function =
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001163 FunctionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
Abramo Bagnara635311f2012-10-04 21:40:42 +00001164 D->getNameInfo(), T, TInfo,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00001165 D->getStorageClass(),
Richard Smithaf1fc7a2011-08-15 21:04:07 +00001166 D->isInlineSpecified(), D->hasWrittenPrototype(),
Richard Smith86c3ae42012-02-13 03:54:03 +00001167 D->isConstexpr());
John McCallb6217662010-03-15 10:12:16 +00001168
Richard Smithd4497dd2013-01-25 00:08:28 +00001169 if (D->isInlined())
1170 Function->setImplicitlyInline();
1171
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001172 if (QualifierLoc)
1173 Function->setQualifierInfo(QualifierLoc);
John McCallb6217662010-03-15 10:12:16 +00001174
John McCallb1a56e72010-03-26 23:10:15 +00001175 DeclContext *LexicalDC = Owner;
1176 if (!isFriend && D->isOutOfLine()) {
1177 assert(D->getDeclContext()->isFileContext());
1178 LexicalDC = D->getDeclContext();
1179 }
1180
1181 Function->setLexicalDeclContext(LexicalDC);
Mike Stump1eb44332009-09-09 15:08:12 +00001182
Douglas Gregore53060f2009-06-25 22:08:12 +00001183 // Attach the parameters
Douglas Gregor5cbe1012011-07-05 18:30:26 +00001184 if (isa<FunctionProtoType>(Function->getType().IgnoreParens())) {
Douglas Gregor1d441ee2011-06-22 18:16:25 +00001185 // Adopt the already-instantiated parameters into our own context.
1186 for (unsigned P = 0; P < Params.size(); ++P)
1187 if (Params[P])
1188 Params[P]->setOwningFunction(Function);
1189 } else {
1190 // Since we were instantiated via a typedef of a function type, create
1191 // new parameters.
1192 const FunctionProtoType *Proto
1193 = Function->getType()->getAs<FunctionProtoType>();
1194 assert(Proto && "No function prototype in template instantiation?");
1195 for (FunctionProtoType::arg_type_iterator AI = Proto->arg_type_begin(),
1196 AE = Proto->arg_type_end(); AI != AE; ++AI) {
1197 ParmVarDecl *Param
1198 = SemaRef.BuildParmVarDeclForTypedef(Function, Function->getLocation(),
1199 *AI);
1200 Param->setScopeInfo(0, Params.size());
1201 Params.push_back(Param);
1202 }
1203 }
David Blaikie4278c652011-09-21 18:16:56 +00001204 Function->setParams(Params);
John McCall02cace72009-08-28 07:59:38 +00001205
Douglas Gregorac7c2c82010-05-17 16:38:00 +00001206 SourceLocation InstantiateAtPOI;
Douglas Gregora735b202009-10-13 14:39:41 +00001207 if (TemplateParams) {
1208 // Our resulting instantiation is actually a function template, since we
1209 // are substituting only the outer template parameters. For example, given
1210 //
1211 // template<typename T>
1212 // struct X {
1213 // template<typename U> friend void f(T, U);
1214 // };
1215 //
1216 // X<int> x;
1217 //
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001218 // We are instantiating the friend function template "f" within X<int>,
Douglas Gregora735b202009-10-13 14:39:41 +00001219 // which means substituting int for T, but leaving "f" as a friend function
1220 // template.
1221 // Build the function template itself.
John McCalld325daa2010-03-26 04:53:08 +00001222 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
Douglas Gregora735b202009-10-13 14:39:41 +00001223 Function->getLocation(),
1224 Function->getDeclName(),
1225 TemplateParams, Function);
1226 Function->setDescribedFunctionTemplate(FunctionTemplate);
John McCallb1a56e72010-03-26 23:10:15 +00001227
1228 FunctionTemplate->setLexicalDeclContext(LexicalDC);
John McCalld325daa2010-03-26 04:53:08 +00001229
1230 if (isFriend && D->isThisDeclarationADefinition()) {
1231 // TODO: should we remember this connection regardless of whether
1232 // the friend declaration provided a body?
1233 FunctionTemplate->setInstantiatedFromMemberTemplate(
1234 D->getDescribedFunctionTemplate());
1235 }
Douglas Gregor66724ea2009-11-14 01:20:54 +00001236 } else if (FunctionTemplate) {
1237 // Record this function template specialization.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001238 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor24bae922010-07-08 18:37:38 +00001239 = TemplateArgs.getInnermost();
Douglas Gregor838db382010-02-11 01:19:42 +00001240 Function->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00001241 TemplateArgumentList::CreateCopy(SemaRef.Context,
Douglas Gregor24bae922010-07-08 18:37:38 +00001242 Innermost.first,
1243 Innermost.second),
Douglas Gregor1e1e9722012-03-28 14:34:23 +00001244 /*InsertPos=*/0);
Chandler Carruth80f5b162011-08-18 09:09:59 +00001245 } else if (isFriend) {
1246 // Note, we need this connection even if the friend doesn't have a body.
1247 // Its body may exist but not have been attached yet due to deferred
1248 // parsing.
1249 // FIXME: It might be cleaner to set this when attaching the body to the
1250 // friend function declaration, however that would require finding all the
1251 // instantiations and modifying them.
John McCalld325daa2010-03-26 04:53:08 +00001252 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
John McCall02cace72009-08-28 07:59:38 +00001253 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001254
Douglas Gregore53060f2009-06-25 22:08:12 +00001255 if (InitFunctionInstantiation(Function, D))
1256 Function->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001257
John McCallaf2094e2010-04-08 09:05:18 +00001258 bool isExplicitSpecialization = false;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001259
John McCall68263142009-11-18 22:49:29 +00001260 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
1261 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
1262
John McCallaf2094e2010-04-08 09:05:18 +00001263 if (DependentFunctionTemplateSpecializationInfo *Info
1264 = D->getDependentSpecializationInfo()) {
1265 assert(isFriend && "non-friend has dependent specialization info?");
1266
1267 // This needs to be set now for future sanity.
1268 Function->setObjectOfFriendDecl(/*HasPrevious*/ true);
1269
1270 // Instantiate the explicit template arguments.
1271 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1272 Info->getRAngleLoc());
Douglas Gregore02e2622010-12-22 21:19:48 +00001273 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1274 ExplicitArgs, TemplateArgs))
1275 return 0;
John McCallaf2094e2010-04-08 09:05:18 +00001276
1277 // Map the candidate templates to their instantiations.
1278 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1279 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1280 Info->getTemplate(I),
1281 TemplateArgs);
1282 if (!Temp) return 0;
1283
1284 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1285 }
1286
1287 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1288 &ExplicitArgs,
1289 Previous))
1290 Function->setInvalidDecl();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001291
John McCallaf2094e2010-04-08 09:05:18 +00001292 isExplicitSpecialization = true;
1293
1294 } else if (TemplateParams || !FunctionTemplate) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001295 // Look only into the namespace where the friend would be declared to
1296 // find a previous declaration. This is the innermost enclosing namespace,
Douglas Gregora735b202009-10-13 14:39:41 +00001297 // as described in ActOnFriendFunctionDecl.
John McCall68263142009-11-18 22:49:29 +00001298 SemaRef.LookupQualifiedName(Previous, DC);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001299
Douglas Gregora735b202009-10-13 14:39:41 +00001300 // In C++, the previous declaration we find might be a tag type
1301 // (class or enum). In this case, the new declaration will hide the
1302 // tag type. Note that this does does not apply if we're declaring a
1303 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001304 if (Previous.isSingleTagDecl())
1305 Previous.clear();
Douglas Gregora735b202009-10-13 14:39:41 +00001306 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001307
John McCall9f54ad42009-12-10 09:41:52 +00001308 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00001309 isExplicitSpecialization);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001310
John McCall76d32642010-04-24 01:30:58 +00001311 NamedDecl *PrincipalDecl = (TemplateParams
1312 ? cast<NamedDecl>(FunctionTemplate)
1313 : Function);
1314
Douglas Gregora735b202009-10-13 14:39:41 +00001315 // If the original function was part of a friend declaration,
1316 // inherit its namespace state and add it to the owner.
John McCalld325daa2010-03-26 04:53:08 +00001317 if (isFriend) {
John McCall68263142009-11-18 22:49:29 +00001318 NamedDecl *PrevDecl;
John McCall76d32642010-04-24 01:30:58 +00001319 if (TemplateParams)
Douglas Gregoref96ee02012-01-14 16:38:05 +00001320 PrevDecl = FunctionTemplate->getPreviousDecl();
John McCall76d32642010-04-24 01:30:58 +00001321 else
Douglas Gregoref96ee02012-01-14 16:38:05 +00001322 PrevDecl = Function->getPreviousDecl();
John McCall76d32642010-04-24 01:30:58 +00001323
1324 PrincipalDecl->setObjectOfFriendDecl(PrevDecl != 0);
Richard Smith1b7f9cb2012-03-13 03:12:56 +00001325 DC->makeDeclVisibleInContext(PrincipalDecl);
Gabor Greifab297ac2010-08-30 21:10:05 +00001326
Gabor Greif77535df2010-08-30 22:25:56 +00001327 bool queuedInstantiation = false;
Gabor Greifab297ac2010-08-30 21:10:05 +00001328
Richard Smith53e53512011-10-19 00:54:10 +00001329 // C++98 [temp.friend]p5: When a function is defined in a friend function
1330 // declaration in a class template, the function is defined at each
1331 // instantiation of the class template. The function is defined even if it
1332 // is never used.
1333 // C++11 [temp.friend]p4: When a function is defined in a friend function
1334 // declaration in a class template, the function is instantiated when the
1335 // function is odr-used.
1336 //
1337 // If -Wc++98-compat is enabled, we go through the motions of checking for a
1338 // redefinition, but don't instantiate the function.
Richard Smith80ad52f2013-01-02 11:42:31 +00001339 if ((!SemaRef.getLangOpts().CPlusPlus11 ||
Richard Smith53e53512011-10-19 00:54:10 +00001340 SemaRef.Diags.getDiagnosticLevel(
1341 diag::warn_cxx98_compat_friend_redefinition,
1342 Function->getLocation())
1343 != DiagnosticsEngine::Ignored) &&
Douglas Gregor238058c2010-05-18 05:45:02 +00001344 D->isThisDeclarationADefinition()) {
1345 // Check for a function body.
1346 const FunctionDecl *Definition = 0;
Sean Hunt10620eb2011-05-06 20:44:56 +00001347 if (Function->isDefined(Definition) &&
Douglas Gregor238058c2010-05-18 05:45:02 +00001348 Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
Richard Smith53e53512011-10-19 00:54:10 +00001349 SemaRef.Diag(Function->getLocation(),
Richard Smith80ad52f2013-01-02 11:42:31 +00001350 SemaRef.getLangOpts().CPlusPlus11 ?
Richard Smith53e53512011-10-19 00:54:10 +00001351 diag::warn_cxx98_compat_friend_redefinition :
1352 diag::err_redefinition) << Function->getDeclName();
Douglas Gregor238058c2010-05-18 05:45:02 +00001353 SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
Richard Smith80ad52f2013-01-02 11:42:31 +00001354 if (!SemaRef.getLangOpts().CPlusPlus11)
Richard Smith53e53512011-10-19 00:54:10 +00001355 Function->setInvalidDecl();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001356 }
Douglas Gregor238058c2010-05-18 05:45:02 +00001357 // Check for redefinitions due to other instantiations of this or
1358 // a similar friend function.
1359 else for (FunctionDecl::redecl_iterator R = Function->redecls_begin(),
1360 REnd = Function->redecls_end();
1361 R != REnd; ++R) {
Gabor Greif13a8aff2010-08-28 15:42:30 +00001362 if (*R == Function)
1363 continue;
Gabor Greifab297ac2010-08-30 21:10:05 +00001364 switch (R->getFriendObjectKind()) {
1365 case Decl::FOK_None:
Richard Smith80ad52f2013-01-02 11:42:31 +00001366 if (!SemaRef.getLangOpts().CPlusPlus11 &&
Richard Smith53e53512011-10-19 00:54:10 +00001367 !queuedInstantiation && R->isUsed(false)) {
Gabor Greifab297ac2010-08-30 21:10:05 +00001368 if (MemberSpecializationInfo *MSInfo
1369 = Function->getMemberSpecializationInfo()) {
1370 if (MSInfo->getPointOfInstantiation().isInvalid()) {
1371 SourceLocation Loc = R->getLocation(); // FIXME
1372 MSInfo->setPointOfInstantiation(Loc);
1373 SemaRef.PendingLocalImplicitInstantiations.push_back(
1374 std::make_pair(Function, Loc));
1375 queuedInstantiation = true;
1376 }
1377 }
1378 }
1379 break;
1380 default:
Douglas Gregor238058c2010-05-18 05:45:02 +00001381 if (const FunctionDecl *RPattern
Gabor Greif6a557d82010-08-28 15:46:56 +00001382 = R->getTemplateInstantiationPattern())
Sean Hunt10620eb2011-05-06 20:44:56 +00001383 if (RPattern->isDefined(RPattern)) {
Richard Smith53e53512011-10-19 00:54:10 +00001384 SemaRef.Diag(Function->getLocation(),
Richard Smith80ad52f2013-01-02 11:42:31 +00001385 SemaRef.getLangOpts().CPlusPlus11 ?
Richard Smith53e53512011-10-19 00:54:10 +00001386 diag::warn_cxx98_compat_friend_redefinition :
1387 diag::err_redefinition)
Douglas Gregor238058c2010-05-18 05:45:02 +00001388 << Function->getDeclName();
Gabor Greif6a557d82010-08-28 15:46:56 +00001389 SemaRef.Diag(R->getLocation(), diag::note_previous_definition);
Richard Smith80ad52f2013-01-02 11:42:31 +00001390 if (!SemaRef.getLangOpts().CPlusPlus11)
Richard Smith53e53512011-10-19 00:54:10 +00001391 Function->setInvalidDecl();
Douglas Gregor238058c2010-05-18 05:45:02 +00001392 break;
1393 }
1394 }
1395 }
1396 }
Douglas Gregora735b202009-10-13 14:39:41 +00001397 }
1398
John McCall76d32642010-04-24 01:30:58 +00001399 if (Function->isOverloadedOperator() && !DC->isRecord() &&
1400 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1401 PrincipalDecl->setNonMemberOperator();
1402
Sean Hunteb88ae52011-05-23 21:07:59 +00001403 assert(!D->isDefaulted() && "only methods should be defaulted");
Douglas Gregore53060f2009-06-25 22:08:12 +00001404 return Function;
1405}
1406
Douglas Gregord60e1052009-08-27 16:57:43 +00001407Decl *
1408TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001409 TemplateParameterList *TemplateParams,
1410 bool IsClassScopeSpecialization) {
Douglas Gregor6b906862009-08-21 00:16:32 +00001411 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
Douglas Gregord60e1052009-08-27 16:57:43 +00001412 if (FunctionTemplate && !TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +00001413 // We are creating a function template specialization from a function
1414 // template. Check whether there is already a function template
Douglas Gregord60e1052009-08-27 16:57:43 +00001415 // specialization for this particular set of template arguments.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001416 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor24bae922010-07-08 18:37:38 +00001417 = TemplateArgs.getInnermost();
Mike Stump1eb44332009-09-09 15:08:12 +00001418
Douglas Gregor1e1e9722012-03-28 14:34:23 +00001419 void *InsertPos = 0;
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001420 FunctionDecl *SpecFunc
1421 = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
1422 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001423
Douglas Gregor6b906862009-08-21 00:16:32 +00001424 // If we already have a function template specialization, return it.
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001425 if (SpecFunc)
1426 return SpecFunc;
Douglas Gregor6b906862009-08-21 00:16:32 +00001427 }
1428
John McCallb0cb0222010-03-27 05:57:59 +00001429 bool isFriend;
1430 if (FunctionTemplate)
1431 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1432 else
1433 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1434
Douglas Gregor79c22782010-01-16 20:21:20 +00001435 bool MergeWithParentScope = (TemplateParams != 0) ||
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001436 !(isa<Decl>(Owner) &&
Douglas Gregor79c22782010-01-16 20:21:20 +00001437 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall2a7fb272010-08-25 05:32:35 +00001438 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Douglas Gregor48dd19b2009-05-14 21:44:34 +00001439
John McCall4eab39f2010-10-19 02:26:41 +00001440 // Instantiate enclosing template arguments for friends.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001441 SmallVector<TemplateParameterList *, 4> TempParamLists;
John McCall4eab39f2010-10-19 02:26:41 +00001442 unsigned NumTempParamLists = 0;
1443 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
1444 TempParamLists.set_size(NumTempParamLists);
1445 for (unsigned I = 0; I != NumTempParamLists; ++I) {
1446 TemplateParameterList *TempParams = D->getTemplateParameterList(I);
1447 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1448 if (!InstParams)
1449 return NULL;
1450 TempParamLists[I] = InstParams;
1451 }
1452 }
1453
Chris Lattner5f9e2722011-07-23 10:55:15 +00001454 SmallVector<ParmVarDecl *, 4> Params;
Benjamin Kramerdc370c12012-01-20 14:42:32 +00001455 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
John McCall21ef0fa2010-03-11 09:03:00 +00001456 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001457 return 0;
Douglas Gregor71074fd2012-09-13 21:56:43 +00001458 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001459
Abramo Bagnara723df242010-12-14 22:11:44 +00001460 // \brief If the type of this function, after ignoring parentheses,
1461 // is not *directly* a function type, then we're instantiating a function
1462 // that was declared via a typedef, e.g.,
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001463 //
1464 // typedef int functype(int, int);
1465 // functype func;
1466 //
1467 // In this case, we'll just go instantiate the ParmVarDecls that we
1468 // synthesized in the method declaration.
Abramo Bagnara723df242010-12-14 22:11:44 +00001469 if (!isa<FunctionProtoType>(T.IgnoreParens())) {
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001470 assert(!Params.size() && "Instantiating type could not yield parameters");
Chris Lattner5f9e2722011-07-23 10:55:15 +00001471 SmallVector<QualType, 4> ParamTypes;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001472 if (SemaRef.SubstParmTypes(D->getLocation(), D->param_begin(),
1473 D->getNumParams(), TemplateArgs, ParamTypes,
Douglas Gregor12c9c002011-01-07 16:43:16 +00001474 &Params))
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001475 return 0;
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001476 }
1477
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001478 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1479 if (QualifierLoc) {
1480 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
John McCallb0cb0222010-03-27 05:57:59 +00001481 TemplateArgs);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001482 if (!QualifierLoc)
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001483 return 0;
John McCallb0cb0222010-03-27 05:57:59 +00001484 }
1485
1486 DeclContext *DC = Owner;
1487 if (isFriend) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001488 if (QualifierLoc) {
John McCallb0cb0222010-03-27 05:57:59 +00001489 CXXScopeSpec SS;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001490 SS.Adopt(QualifierLoc);
John McCallb0cb0222010-03-27 05:57:59 +00001491 DC = SemaRef.computeDeclContext(SS);
John McCallc54d6882010-10-19 05:01:53 +00001492
1493 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
1494 return 0;
John McCallb0cb0222010-03-27 05:57:59 +00001495 } else {
1496 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1497 D->getDeclContext(),
1498 TemplateArgs);
1499 }
1500 if (!DC) return 0;
1501 }
1502
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001503 // Build the instantiated method declaration.
John McCallb0cb0222010-03-27 05:57:59 +00001504 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
Douglas Gregordec06662009-08-21 18:42:58 +00001505 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001506
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001507 SourceLocation StartLoc = D->getInnerLocStart();
Abramo Bagnara25777432010-08-11 22:01:17 +00001508 DeclarationNameInfo NameInfo
1509 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
Douglas Gregor17e32f32009-08-21 22:43:28 +00001510 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001511 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001512 StartLoc, NameInfo, T, TInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00001513 Constructor->isExplicit(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001514 Constructor->isInlineSpecified(),
Richard Smith86c3ae42012-02-13 03:54:03 +00001515 false, Constructor->isConstexpr());
Douglas Gregor17e32f32009-08-21 22:43:28 +00001516 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001517 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001518 StartLoc, NameInfo, T, TInfo,
Abramo Bagnara25777432010-08-11 22:01:17 +00001519 Destructor->isInlineSpecified(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001520 false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001521 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001522 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001523 StartLoc, NameInfo, T, TInfo,
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001524 Conversion->isInlineSpecified(),
Douglas Gregorf5251602011-03-08 17:10:18 +00001525 Conversion->isExplicit(),
Richard Smith86c3ae42012-02-13 03:54:03 +00001526 Conversion->isConstexpr(),
Richard Smith9f569cc2011-10-01 02:31:28 +00001527 Conversion->getLocEnd());
Douglas Gregordec06662009-08-21 18:42:58 +00001528 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00001529 Method = CXXMethodDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001530 StartLoc, NameInfo, T, TInfo,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00001531 D->getStorageClass(),
Douglas Gregorf5251602011-03-08 17:10:18 +00001532 D->isInlineSpecified(),
Richard Smith86c3ae42012-02-13 03:54:03 +00001533 D->isConstexpr(), D->getLocEnd());
Douglas Gregordec06662009-08-21 18:42:58 +00001534 }
Douglas Gregor6b906862009-08-21 00:16:32 +00001535
Richard Smithd4497dd2013-01-25 00:08:28 +00001536 if (D->isInlined())
1537 Method->setImplicitlyInline();
1538
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001539 if (QualifierLoc)
1540 Method->setQualifierInfo(QualifierLoc);
John McCallb6217662010-03-15 10:12:16 +00001541
Douglas Gregord60e1052009-08-27 16:57:43 +00001542 if (TemplateParams) {
1543 // Our resulting instantiation is actually a function template, since we
1544 // are substituting only the outer template parameters. For example, given
Mike Stump1eb44332009-09-09 15:08:12 +00001545 //
Douglas Gregord60e1052009-08-27 16:57:43 +00001546 // template<typename T>
1547 // struct X {
1548 // template<typename U> void f(T, U);
1549 // };
1550 //
1551 // X<int> x;
1552 //
1553 // We are instantiating the member template "f" within X<int>, which means
1554 // substituting int for T, but leaving "f" as a member function template.
1555 // Build the function template itself.
1556 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1557 Method->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001558 Method->getDeclName(),
Douglas Gregord60e1052009-08-27 16:57:43 +00001559 TemplateParams, Method);
John McCallb0cb0222010-03-27 05:57:59 +00001560 if (isFriend) {
1561 FunctionTemplate->setLexicalDeclContext(Owner);
1562 FunctionTemplate->setObjectOfFriendDecl(true);
1563 } else if (D->isOutOfLine())
Mike Stump1eb44332009-09-09 15:08:12 +00001564 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregord60e1052009-08-27 16:57:43 +00001565 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001566 } else if (FunctionTemplate) {
1567 // Record this function template specialization.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001568 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor24bae922010-07-08 18:37:38 +00001569 = TemplateArgs.getInnermost();
Douglas Gregor838db382010-02-11 01:19:42 +00001570 Method->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00001571 TemplateArgumentList::CreateCopy(SemaRef.Context,
1572 Innermost.first,
1573 Innermost.second),
Douglas Gregor1e1e9722012-03-28 14:34:23 +00001574 /*InsertPos=*/0);
John McCallb0cb0222010-03-27 05:57:59 +00001575 } else if (!isFriend) {
Douglas Gregor66724ea2009-11-14 01:20:54 +00001576 // Record that this is an instantiation of a member function.
Douglas Gregor2db32322009-10-07 23:56:10 +00001577 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001578 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001579
Mike Stump1eb44332009-09-09 15:08:12 +00001580 // If we are instantiating a member function defined
Douglas Gregor7caa6822009-07-24 20:34:43 +00001581 // out-of-line, the instantiation will have the same lexical
1582 // context (which will be a namespace scope) as the template.
John McCallb0cb0222010-03-27 05:57:59 +00001583 if (isFriend) {
John McCall4eab39f2010-10-19 02:26:41 +00001584 if (NumTempParamLists)
1585 Method->setTemplateParameterListsInfo(SemaRef.Context,
1586 NumTempParamLists,
1587 TempParamLists.data());
1588
John McCallb0cb0222010-03-27 05:57:59 +00001589 Method->setLexicalDeclContext(Owner);
1590 Method->setObjectOfFriendDecl(true);
1591 } else if (D->isOutOfLine())
Douglas Gregor7caa6822009-07-24 20:34:43 +00001592 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00001593
Douglas Gregor5545e162009-03-24 00:38:23 +00001594 // Attach the parameters
1595 for (unsigned P = 0; P < Params.size(); ++P)
1596 Params[P]->setOwningFunction(Method);
David Blaikie4278c652011-09-21 18:16:56 +00001597 Method->setParams(Params);
Douglas Gregor5545e162009-03-24 00:38:23 +00001598
1599 if (InitMethodInstantiation(Method, D))
1600 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001601
Abramo Bagnara25777432010-08-11 22:01:17 +00001602 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
1603 Sema::ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00001604
John McCallb0cb0222010-03-27 05:57:59 +00001605 if (!FunctionTemplate || TemplateParams || isFriend) {
1606 SemaRef.LookupQualifiedName(Previous, Record);
Mike Stump1eb44332009-09-09 15:08:12 +00001607
Douglas Gregordec06662009-08-21 18:42:58 +00001608 // In C++, the previous declaration we find might be a tag type
1609 // (class or enum). In this case, the new declaration will hide the
1610 // tag type. Note that this does does not apply if we're declaring a
1611 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001612 if (Previous.isSingleTagDecl())
1613 Previous.clear();
Douglas Gregordec06662009-08-21 18:42:58 +00001614 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001615
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001616 if (!IsClassScopeSpecialization)
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00001617 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001618
Douglas Gregor4ba31362009-12-01 17:24:26 +00001619 if (D->isPure())
1620 SemaRef.CheckPureMethod(Method, SourceRange());
1621
John McCall1f2e1a92012-08-10 03:15:35 +00001622 // Propagate access. For a non-friend declaration, the access is
1623 // whatever we're propagating from. For a friend, it should be the
1624 // previous declaration we just found.
1625 if (isFriend && Method->getPreviousDecl())
1626 Method->setAccess(Method->getPreviousDecl()->getAccess());
1627 else
1628 Method->setAccess(D->getAccess());
1629 if (FunctionTemplate)
1630 FunctionTemplate->setAccess(Method->getAccess());
John McCall46460a62010-01-20 21:53:11 +00001631
Anders Carlsson9eefa222011-01-20 06:52:44 +00001632 SemaRef.CheckOverrideControl(Method);
1633
Eli Friedman3bc45152011-11-15 22:39:08 +00001634 // If a function is defined as defaulted or deleted, mark it as such now.
Richard Smithac713512012-12-08 02:53:02 +00001635 if (D->isExplicitlyDefaulted())
1636 SemaRef.SetDeclDefaulted(Method, Method->getLocation());
Eli Friedman3bc45152011-11-15 22:39:08 +00001637 if (D->isDeletedAsWritten())
Richard Smithac713512012-12-08 02:53:02 +00001638 SemaRef.SetDeclDeleted(Method, Method->getLocation());
Eli Friedman3bc45152011-11-15 22:39:08 +00001639
John McCall1f2e1a92012-08-10 03:15:35 +00001640 // If there's a function template, let our caller handle it.
John McCallb0cb0222010-03-27 05:57:59 +00001641 if (FunctionTemplate) {
John McCall1f2e1a92012-08-10 03:15:35 +00001642 // do nothing
1643
1644 // Don't hide a (potentially) valid declaration with an invalid one.
John McCallb0cb0222010-03-27 05:57:59 +00001645 } else if (Method->isInvalidDecl() && !Previous.empty()) {
John McCall1f2e1a92012-08-10 03:15:35 +00001646 // do nothing
1647
1648 // Otherwise, check access to friends and make them visible.
1649 } else if (isFriend) {
1650 // We only need to re-check access for methods which we didn't
1651 // manage to match during parsing.
1652 if (!D->getPreviousDecl())
1653 SemaRef.CheckFriendAccess(Method);
1654
1655 Record->makeDeclVisibleInContext(Method);
1656
1657 // Otherwise, add the declaration. We don't need to do this for
1658 // class-scope specializations because we'll have matched them with
1659 // the appropriate template.
1660 } else if (!IsClassScopeSpecialization) {
1661 Owner->addDecl(Method);
John McCallb0cb0222010-03-27 05:57:59 +00001662 }
Sean Hunteb88ae52011-05-23 21:07:59 +00001663
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001664 return Method;
1665}
1666
Douglas Gregor615c5d42009-03-24 16:43:20 +00001667Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +00001668 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +00001669}
1670
Douglas Gregor03b2b072009-03-24 00:15:49 +00001671Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001672 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +00001673}
1674
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001675Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001676 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001677}
1678
Douglas Gregor6477b692009-03-25 15:04:13 +00001679ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
David Blaikie66874fb2013-02-21 01:47:18 +00001680 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0, None,
1681 /*ExpectParameterPack=*/ false);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001682}
1683
John McCalle29ba202009-08-20 01:44:21 +00001684Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1685 TemplateTypeParmDecl *D) {
1686 // TODO: don't always clone when decls are refcounted.
Chandler Carruth4fb86f82011-05-01 00:51:33 +00001687 assert(D->getTypeForDecl()->isTemplateTypeParmType());
Mike Stump1eb44332009-09-09 15:08:12 +00001688
John McCalle29ba202009-08-20 01:44:21 +00001689 TemplateTypeParmDecl *Inst =
Abramo Bagnara344577e2011-03-06 15:48:19 +00001690 TemplateTypeParmDecl::Create(SemaRef.Context, Owner,
1691 D->getLocStart(), D->getLocation(),
Chandler Carruth4fb86f82011-05-01 00:51:33 +00001692 D->getDepth() - TemplateArgs.getNumLevels(),
1693 D->getIndex(), D->getIdentifier(),
John McCalle29ba202009-08-20 01:44:21 +00001694 D->wasDeclaredWithTypename(),
1695 D->isParameterPack());
Douglas Gregor9a299e02011-03-04 17:52:15 +00001696 Inst->setAccess(AS_public);
John McCalle29ba202009-08-20 01:44:21 +00001697
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001698 if (D->hasDefaultArgument())
1699 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
1700
1701 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor550d9b22009-10-31 17:21:17 +00001702 // scope.
1703 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001704
John McCalle29ba202009-08-20 01:44:21 +00001705 return Inst;
1706}
1707
Douglas Gregor33642df2009-10-23 23:25:44 +00001708Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1709 NonTypeTemplateParmDecl *D) {
1710 // Substitute into the type of the non-type template parameter.
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001711 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001712 SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
1713 SmallVector<QualType, 4> ExpandedParameterPackTypes;
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001714 bool IsExpandedParameterPack = false;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001715 TypeSourceInfo *DI;
Douglas Gregor33642df2009-10-23 23:25:44 +00001716 QualType T;
Douglas Gregor33642df2009-10-23 23:25:44 +00001717 bool Invalid = false;
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001718
1719 if (D->isExpandedParameterPack()) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001720 // The non-type template parameter pack is an already-expanded pack
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001721 // expansion of types. Substitute into each of the expanded types.
1722 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
1723 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
1724 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
1725 TypeSourceInfo *NewDI =SemaRef.SubstType(D->getExpansionTypeSourceInfo(I),
1726 TemplateArgs,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001727 D->getLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001728 D->getDeclName());
1729 if (!NewDI)
1730 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001731
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001732 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1733 QualType NewT =SemaRef.CheckNonTypeTemplateParameterType(NewDI->getType(),
1734 D->getLocation());
1735 if (NewT.isNull())
1736 return 0;
1737 ExpandedParameterPackTypes.push_back(NewT);
1738 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001739
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001740 IsExpandedParameterPack = true;
1741 DI = D->getTypeSourceInfo();
1742 T = DI->getType();
Richard Smith6964b3f2012-09-07 02:06:42 +00001743 } else if (D->isPackExpansion()) {
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001744 // The non-type template parameter pack's type is a pack expansion of types.
1745 // Determine whether we need to expand this parameter pack into separate
1746 // types.
David Blaikie39e6ab42013-02-18 22:06:02 +00001747 PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>();
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001748 TypeLoc Pattern = Expansion.getPatternLoc();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001749 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001750 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001751
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001752 // Determine whether the set of unexpanded parameter packs can and should
1753 // be expanded.
1754 bool Expand = true;
1755 bool RetainExpansion = false;
David Blaikiedc84cd52013-02-20 22:23:23 +00001756 Optional<unsigned> OrigNumExpansions
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001757 = Expansion.getTypePtr()->getNumExpansions();
David Blaikiedc84cd52013-02-20 22:23:23 +00001758 Optional<unsigned> NumExpansions = OrigNumExpansions;
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001759 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
1760 Pattern.getSourceRange(),
David Blaikiea71f9d02011-09-22 02:34:54 +00001761 Unexpanded,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001762 TemplateArgs,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001763 Expand, RetainExpansion,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001764 NumExpansions))
1765 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001766
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001767 if (Expand) {
1768 for (unsigned I = 0; I != *NumExpansions; ++I) {
1769 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
1770 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001771 D->getLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001772 D->getDeclName());
1773 if (!NewDI)
1774 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001775
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001776 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1777 QualType NewT = SemaRef.CheckNonTypeTemplateParameterType(
1778 NewDI->getType(),
1779 D->getLocation());
1780 if (NewT.isNull())
1781 return 0;
1782 ExpandedParameterPackTypes.push_back(NewT);
1783 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001784
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001785 // Note that we have an expanded parameter pack. The "type" of this
1786 // expanded parameter pack is the original expansion type, but callers
1787 // will end up using the expanded parameter pack types for type-checking.
1788 IsExpandedParameterPack = true;
1789 DI = D->getTypeSourceInfo();
1790 T = DI->getType();
1791 } else {
1792 // We cannot fully expand the pack expansion now, so substitute into the
1793 // pattern and create a new pack expansion type.
1794 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
1795 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001796 D->getLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001797 D->getDeclName());
1798 if (!NewPattern)
1799 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001800
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001801 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
1802 NumExpansions);
1803 if (!DI)
1804 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001805
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001806 T = DI->getType();
1807 }
1808 } else {
1809 // Simple case: substitution into a parameter that is not a parameter pack.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001810 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001811 D->getLocation(), D->getDeclName());
1812 if (!DI)
1813 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001814
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001815 // Check that this type is acceptable for a non-type template parameter.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001816 T = SemaRef.CheckNonTypeTemplateParameterType(DI->getType(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001817 D->getLocation());
1818 if (T.isNull()) {
1819 T = SemaRef.Context.IntTy;
1820 Invalid = true;
1821 }
Douglas Gregor33642df2009-10-23 23:25:44 +00001822 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001823
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001824 NonTypeTemplateParmDecl *Param;
1825 if (IsExpandedParameterPack)
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001826 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001827 D->getInnerLocStart(),
1828 D->getLocation(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001829 D->getDepth() - TemplateArgs.getNumLevels(),
1830 D->getPosition(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001831 D->getIdentifier(), T,
1832 DI,
1833 ExpandedParameterPackTypes.data(),
1834 ExpandedParameterPackTypes.size(),
1835 ExpandedParameterPackTypesAsWritten.data());
1836 else
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001837 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001838 D->getInnerLocStart(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001839 D->getLocation(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001840 D->getDepth() - TemplateArgs.getNumLevels(),
1841 D->getPosition(),
1842 D->getIdentifier(), T,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001843 D->isParameterPack(), DI);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001844
Douglas Gregor9a299e02011-03-04 17:52:15 +00001845 Param->setAccess(AS_public);
Douglas Gregor33642df2009-10-23 23:25:44 +00001846 if (Invalid)
1847 Param->setInvalidDecl();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001848
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001849 Param->setDefaultArgument(D->getDefaultArgument(), false);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001850
1851 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor550d9b22009-10-31 17:21:17 +00001852 // scope.
1853 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor33642df2009-10-23 23:25:44 +00001854 return Param;
1855}
1856
Richard Smith6964b3f2012-09-07 02:06:42 +00001857static void collectUnexpandedParameterPacks(
1858 Sema &S,
1859 TemplateParameterList *Params,
1860 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
1861 for (TemplateParameterList::const_iterator I = Params->begin(),
1862 E = Params->end(); I != E; ++I) {
1863 if ((*I)->isTemplateParameterPack())
1864 continue;
1865 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*I))
1866 S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
1867 Unexpanded);
1868 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(*I))
1869 collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
1870 Unexpanded);
1871 }
1872}
1873
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001874Decl *
Douglas Gregor9106ef72009-11-11 16:58:32 +00001875TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1876 TemplateTemplateParmDecl *D) {
1877 // Instantiate the template parameter list of the template template parameter.
1878 TemplateParameterList *TempParams = D->getTemplateParameters();
1879 TemplateParameterList *InstParams;
Richard Smith6964b3f2012-09-07 02:06:42 +00001880 SmallVector<TemplateParameterList*, 8> ExpandedParams;
1881
1882 bool IsExpandedParameterPack = false;
1883
1884 if (D->isExpandedParameterPack()) {
1885 // The template template parameter pack is an already-expanded pack
1886 // expansion of template parameters. Substitute into each of the expanded
1887 // parameters.
1888 ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
1889 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
1890 I != N; ++I) {
1891 LocalInstantiationScope Scope(SemaRef);
1892 TemplateParameterList *Expansion =
1893 SubstTemplateParams(D->getExpansionTemplateParameters(I));
1894 if (!Expansion)
1895 return 0;
1896 ExpandedParams.push_back(Expansion);
1897 }
1898
1899 IsExpandedParameterPack = true;
1900 InstParams = TempParams;
1901 } else if (D->isPackExpansion()) {
1902 // The template template parameter pack expands to a pack of template
1903 // template parameters. Determine whether we need to expand this parameter
1904 // pack into separate parameters.
1905 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1906 collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(),
1907 Unexpanded);
1908
1909 // Determine whether the set of unexpanded parameter packs can and should
1910 // be expanded.
1911 bool Expand = true;
1912 bool RetainExpansion = false;
David Blaikiedc84cd52013-02-20 22:23:23 +00001913 Optional<unsigned> NumExpansions;
Richard Smith6964b3f2012-09-07 02:06:42 +00001914 if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(),
1915 TempParams->getSourceRange(),
1916 Unexpanded,
1917 TemplateArgs,
1918 Expand, RetainExpansion,
1919 NumExpansions))
1920 return 0;
1921
1922 if (Expand) {
1923 for (unsigned I = 0; I != *NumExpansions; ++I) {
1924 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
1925 LocalInstantiationScope Scope(SemaRef);
1926 TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
1927 if (!Expansion)
1928 return 0;
1929 ExpandedParams.push_back(Expansion);
1930 }
1931
1932 // Note that we have an expanded parameter pack. The "type" of this
1933 // expanded parameter pack is the original expansion type, but callers
1934 // will end up using the expanded parameter pack types for type-checking.
1935 IsExpandedParameterPack = true;
1936 InstParams = TempParams;
1937 } else {
1938 // We cannot fully expand the pack expansion now, so just substitute
1939 // into the pattern.
1940 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
1941
1942 LocalInstantiationScope Scope(SemaRef);
1943 InstParams = SubstTemplateParams(TempParams);
1944 if (!InstParams)
1945 return 0;
1946 }
1947 } else {
Douglas Gregor9106ef72009-11-11 16:58:32 +00001948 // Perform the actual substitution of template parameters within a new,
1949 // local instantiation scope.
John McCall2a7fb272010-08-25 05:32:35 +00001950 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor9106ef72009-11-11 16:58:32 +00001951 InstParams = SubstTemplateParams(TempParams);
1952 if (!InstParams)
Richard Smith6964b3f2012-09-07 02:06:42 +00001953 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001954 }
1955
Douglas Gregor9106ef72009-11-11 16:58:32 +00001956 // Build the template template parameter.
Richard Smith6964b3f2012-09-07 02:06:42 +00001957 TemplateTemplateParmDecl *Param;
1958 if (IsExpandedParameterPack)
1959 Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
1960 D->getLocation(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001961 D->getDepth() - TemplateArgs.getNumLevels(),
Richard Smith6964b3f2012-09-07 02:06:42 +00001962 D->getPosition(),
1963 D->getIdentifier(), InstParams,
1964 ExpandedParams);
1965 else
1966 Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
1967 D->getLocation(),
1968 D->getDepth() - TemplateArgs.getNumLevels(),
1969 D->getPosition(),
1970 D->isParameterPack(),
1971 D->getIdentifier(), InstParams);
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001972 Param->setDefaultArgument(D->getDefaultArgument(), false);
Douglas Gregor9a299e02011-03-04 17:52:15 +00001973 Param->setAccess(AS_public);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001974
1975 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor9106ef72009-11-11 16:58:32 +00001976 // scope.
1977 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001978
Douglas Gregor9106ef72009-11-11 16:58:32 +00001979 return Param;
1980}
1981
Douglas Gregor48c32a72009-11-17 06:07:40 +00001982Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregordb992412011-02-25 16:33:46 +00001983 // Using directives are never dependent (and never contain any types or
1984 // expressions), so they require no explicit instantiation work.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001985
Douglas Gregor48c32a72009-11-17 06:07:40 +00001986 UsingDirectiveDecl *Inst
1987 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001988 D->getNamespaceKeyLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00001989 D->getQualifierLoc(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001990 D->getIdentLocation(),
1991 D->getNominatedNamespace(),
Douglas Gregor48c32a72009-11-17 06:07:40 +00001992 D->getCommonAncestor());
Abramo Bagnara536afbe2012-09-05 09:55:10 +00001993
1994 // Add the using directive to its declaration context
1995 // only if this is not a function or method.
1996 if (!Owner->isFunctionOrMethod())
1997 Owner->addDecl(Inst);
1998
Douglas Gregor48c32a72009-11-17 06:07:40 +00001999 return Inst;
2000}
2001
John McCalled976492009-12-04 22:46:56 +00002002Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
Douglas Gregor1b398202010-09-29 17:58:28 +00002003
2004 // The nested name specifier may be dependent, for example
2005 // template <typename T> struct t {
2006 // struct s1 { T f1(); };
2007 // struct s2 : s1 { using s1::f1; };
2008 // };
2009 // template struct t<int>;
2010 // Here, in using s1::f1, s1 refers to t<T>::s1;
2011 // we need to substitute for t<int>::s1.
Douglas Gregor5149f372011-02-25 15:54:31 +00002012 NestedNameSpecifierLoc QualifierLoc
2013 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
2014 TemplateArgs);
2015 if (!QualifierLoc)
Douglas Gregordc355712011-02-25 00:36:19 +00002016 return 0;
Douglas Gregor1b398202010-09-29 17:58:28 +00002017
2018 // The name info is non-dependent, so no transformation
2019 // is required.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002020 DeclarationNameInfo NameInfo = D->getNameInfo();
John McCalled976492009-12-04 22:46:56 +00002021
John McCall9f54ad42009-12-10 09:41:52 +00002022 // We only need to do redeclaration lookups if we're in a class
2023 // scope (in fact, it's not really even possible in non-class
2024 // scopes).
2025 bool CheckRedeclaration = Owner->isRecord();
2026
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002027 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
2028 Sema::ForRedeclaration);
John McCall9f54ad42009-12-10 09:41:52 +00002029
John McCalled976492009-12-04 22:46:56 +00002030 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
John McCalled976492009-12-04 22:46:56 +00002031 D->getUsingLocation(),
Douglas Gregor5149f372011-02-25 15:54:31 +00002032 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002033 NameInfo,
John McCalled976492009-12-04 22:46:56 +00002034 D->isTypeName());
2035
Douglas Gregor5149f372011-02-25 15:54:31 +00002036 CXXScopeSpec SS;
2037 SS.Adopt(QualifierLoc);
John McCall9f54ad42009-12-10 09:41:52 +00002038 if (CheckRedeclaration) {
2039 Prev.setHideTags(false);
2040 SemaRef.LookupQualifiedName(Prev, Owner);
2041
2042 // Check for invalid redeclarations.
2043 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
2044 D->isTypeName(), SS,
2045 D->getLocation(), Prev))
2046 NewUD->setInvalidDecl();
2047
2048 }
2049
2050 if (!NewUD->isInvalidDecl() &&
2051 SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
John McCalled976492009-12-04 22:46:56 +00002052 D->getLocation()))
2053 NewUD->setInvalidDecl();
John McCall9f54ad42009-12-10 09:41:52 +00002054
John McCalled976492009-12-04 22:46:56 +00002055 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
2056 NewUD->setAccess(D->getAccess());
2057 Owner->addDecl(NewUD);
2058
John McCall9f54ad42009-12-10 09:41:52 +00002059 // Don't process the shadow decls for an invalid decl.
2060 if (NewUD->isInvalidDecl())
2061 return NewUD;
2062
Richard Smithc5a89a12012-04-02 01:30:27 +00002063 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
2064 if (SemaRef.CheckInheritingConstructorUsingDecl(NewUD))
2065 NewUD->setInvalidDecl();
2066 return NewUD;
2067 }
2068
John McCall323c3102009-12-22 22:26:37 +00002069 bool isFunctionScope = Owner->isFunctionOrMethod();
2070
John McCall9f54ad42009-12-10 09:41:52 +00002071 // Process the shadow decls.
2072 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
2073 I != E; ++I) {
2074 UsingShadowDecl *Shadow = *I;
2075 NamedDecl *InstTarget =
Douglas Gregorb7107222011-03-04 19:46:35 +00002076 cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
2077 Shadow->getLocation(),
2078 Shadow->getTargetDecl(),
2079 TemplateArgs));
2080 if (!InstTarget)
2081 return 0;
John McCall9f54ad42009-12-10 09:41:52 +00002082
2083 if (CheckRedeclaration &&
2084 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
2085 continue;
2086
2087 UsingShadowDecl *InstShadow
2088 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
2089 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCall323c3102009-12-22 22:26:37 +00002090
2091 if (isFunctionScope)
2092 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall9f54ad42009-12-10 09:41:52 +00002093 }
John McCalled976492009-12-04 22:46:56 +00002094
2095 return NewUD;
2096}
2097
2098Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall9f54ad42009-12-10 09:41:52 +00002099 // Ignore these; we handle them in bulk when processing the UsingDecl.
2100 return 0;
John McCalled976492009-12-04 22:46:56 +00002101}
2102
John McCall7ba107a2009-11-18 02:36:19 +00002103Decl * TemplateDeclInstantiator
2104 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Douglas Gregor5149f372011-02-25 15:54:31 +00002105 NestedNameSpecifierLoc QualifierLoc
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002106 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
Douglas Gregor5149f372011-02-25 15:54:31 +00002107 TemplateArgs);
2108 if (!QualifierLoc)
Anders Carlsson0dde18e2009-08-28 15:18:15 +00002109 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002110
Anders Carlsson0dde18e2009-08-28 15:18:15 +00002111 CXXScopeSpec SS;
Douglas Gregor5149f372011-02-25 15:54:31 +00002112 SS.Adopt(QualifierLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00002113
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002114 // Since NameInfo refers to a typename, it cannot be a C++ special name.
Benjamin Krameraccaf192012-11-14 15:08:31 +00002115 // Hence, no transformation is required for it.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002116 DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002117 NamedDecl *UD =
John McCall9488ea12009-11-17 05:59:44 +00002118 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002119 D->getUsingLoc(), SS, NameInfo, 0,
John McCall7ba107a2009-11-18 02:36:19 +00002120 /*instantiation*/ true,
2121 /*typename*/ true, D->getTypenameLoc());
Douglas Gregor4469e8a2010-05-19 17:02:24 +00002122 if (UD)
John McCalled976492009-12-04 22:46:56 +00002123 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
2124
John McCall7ba107a2009-11-18 02:36:19 +00002125 return UD;
2126}
2127
2128Decl * TemplateDeclInstantiator
2129 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregor5149f372011-02-25 15:54:31 +00002130 NestedNameSpecifierLoc QualifierLoc
2131 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), TemplateArgs);
2132 if (!QualifierLoc)
John McCall7ba107a2009-11-18 02:36:19 +00002133 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002134
John McCall7ba107a2009-11-18 02:36:19 +00002135 CXXScopeSpec SS;
Douglas Gregor5149f372011-02-25 15:54:31 +00002136 SS.Adopt(QualifierLoc);
John McCall7ba107a2009-11-18 02:36:19 +00002137
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002138 DeclarationNameInfo NameInfo
2139 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2140
John McCall7ba107a2009-11-18 02:36:19 +00002141 NamedDecl *UD =
2142 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002143 D->getUsingLoc(), SS, NameInfo, 0,
John McCall7ba107a2009-11-18 02:36:19 +00002144 /*instantiation*/ true,
2145 /*typename*/ false, SourceLocation());
Douglas Gregor4469e8a2010-05-19 17:02:24 +00002146 if (UD)
John McCalled976492009-12-04 22:46:56 +00002147 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
2148
Anders Carlsson0d8df782009-08-29 19:37:28 +00002149 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +00002150}
2151
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002152
2153Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
2154 ClassScopeFunctionSpecializationDecl *Decl) {
2155 CXXMethodDecl *OldFD = Decl->getSpecialization();
Nico Weber6b020092012-06-25 17:21:05 +00002156 CXXMethodDecl *NewFD = cast<CXXMethodDecl>(VisitCXXMethodDecl(OldFD,
2157 0, true));
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002158
2159 LookupResult Previous(SemaRef, NewFD->getNameInfo(), Sema::LookupOrdinaryName,
2160 Sema::ForRedeclaration);
2161
Nico Weber6b020092012-06-25 17:21:05 +00002162 TemplateArgumentListInfo TemplateArgs;
2163 TemplateArgumentListInfo* TemplateArgsPtr = 0;
2164 if (Decl->hasExplicitTemplateArgs()) {
2165 TemplateArgs = Decl->templateArgs();
2166 TemplateArgsPtr = &TemplateArgs;
2167 }
2168
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002169 SemaRef.LookupQualifiedName(Previous, SemaRef.CurContext);
Nico Weber6b020092012-06-25 17:21:05 +00002170 if (SemaRef.CheckFunctionTemplateSpecialization(NewFD, TemplateArgsPtr,
2171 Previous)) {
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002172 NewFD->setInvalidDecl();
2173 return NewFD;
2174 }
2175
2176 // Associate the specialization with the pattern.
2177 FunctionDecl *Specialization = cast<FunctionDecl>(Previous.getFoundDecl());
2178 assert(Specialization && "Class scope Specialization is null");
2179 SemaRef.Context.setClassScopeSpecializationPattern(Specialization, OldFD);
2180
2181 return NewFD;
2182}
2183
Alexey Bataevc6400582013-03-22 06:34:35 +00002184Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
2185 OMPThreadPrivateDecl *D) {
2186 SmallVector<DeclRefExpr *, 5> Vars;
2187 for (ArrayRef<DeclRefExpr *>::iterator I = D->varlist_begin(),
2188 E = D->varlist_end();
2189 I != E; ++I) {
2190 Expr *Var = SemaRef.SubstExpr(*I, TemplateArgs).take();
2191 assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
2192 Vars.push_back(cast<DeclRefExpr>(Var));
2193 }
2194
2195 OMPThreadPrivateDecl *TD =
2196 SemaRef.CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
2197
2198 return TD;
2199}
2200
John McCallce3ff2b2009-08-25 22:02:44 +00002201Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +00002202 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +00002203 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor2fa98002010-02-16 19:28:15 +00002204 if (D->isInvalidDecl())
2205 return 0;
2206
Douglas Gregor8dbc2692009-03-17 21:15:40 +00002207 return Instantiator.Visit(D);
2208}
2209
John McCalle29ba202009-08-20 01:44:21 +00002210/// \brief Instantiates a nested template parameter list in the current
2211/// instantiation context.
2212///
2213/// \param L The parameter list to instantiate
2214///
2215/// \returns NULL if there was an error
2216TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +00002217TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +00002218 // Get errors for all the parameters before bailing out.
2219 bool Invalid = false;
2220
2221 unsigned N = L->size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00002222 typedef SmallVector<NamedDecl *, 8> ParamVector;
John McCalle29ba202009-08-20 01:44:21 +00002223 ParamVector Params;
2224 Params.reserve(N);
2225 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
2226 PI != PE; ++PI) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002227 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCalle29ba202009-08-20 01:44:21 +00002228 Params.push_back(D);
Douglas Gregor9148c3f2009-11-11 19:13:48 +00002229 Invalid = Invalid || !D || D->isInvalidDecl();
John McCalle29ba202009-08-20 01:44:21 +00002230 }
2231
2232 // Clean up if we had an error.
Douglas Gregorff331c12010-07-25 18:17:45 +00002233 if (Invalid)
John McCalle29ba202009-08-20 01:44:21 +00002234 return NULL;
John McCalle29ba202009-08-20 01:44:21 +00002235
2236 TemplateParameterList *InstL
2237 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
2238 L->getLAngleLoc(), &Params.front(), N,
2239 L->getRAngleLoc());
2240 return InstL;
Mike Stump1eb44332009-09-09 15:08:12 +00002241}
John McCalle29ba202009-08-20 01:44:21 +00002242
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002243/// \brief Instantiate the declaration of a class template partial
Douglas Gregored9c0f92009-10-29 00:04:11 +00002244/// specialization.
2245///
2246/// \param ClassTemplate the (instantiated) class template that is partially
2247// specialized by the instantiation of \p PartialSpec.
2248///
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002249/// \param PartialSpec the (uninstantiated) class template partial
Douglas Gregored9c0f92009-10-29 00:04:11 +00002250/// specialization that we are instantiating.
2251///
Douglas Gregord65587f2010-11-10 19:44:59 +00002252/// \returns The instantiated partial specialization, if successful; otherwise,
2253/// NULL to indicate an error.
2254ClassTemplatePartialSpecializationDecl *
Douglas Gregored9c0f92009-10-29 00:04:11 +00002255TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
2256 ClassTemplateDecl *ClassTemplate,
2257 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00002258 // Create a local instantiation scope for this class template partial
2259 // specialization, which will contain the instantiations of the template
2260 // parameters.
John McCall2a7fb272010-08-25 05:32:35 +00002261 LocalInstantiationScope Scope(SemaRef);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002262
Douglas Gregored9c0f92009-10-29 00:04:11 +00002263 // Substitute into the template parameters of the class template partial
2264 // specialization.
2265 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
2266 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2267 if (!InstParams)
Douglas Gregord65587f2010-11-10 19:44:59 +00002268 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002269
Douglas Gregored9c0f92009-10-29 00:04:11 +00002270 // Substitute into the template arguments of the class template partial
2271 // specialization.
John McCalld5532b62009-11-23 01:53:49 +00002272 TemplateArgumentListInfo InstTemplateArgs; // no angle locations
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002273 if (SemaRef.Subst(PartialSpec->getTemplateArgsAsWritten(),
2274 PartialSpec->getNumTemplateArgsAsWritten(),
Douglas Gregore02e2622010-12-22 21:19:48 +00002275 InstTemplateArgs, TemplateArgs))
2276 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002277
Douglas Gregored9c0f92009-10-29 00:04:11 +00002278 // Check that the template argument list is well-formed for this
2279 // class template.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002280 SmallVector<TemplateArgument, 4> Converted;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002281 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002282 PartialSpec->getLocation(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002283 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002284 false,
2285 Converted))
Douglas Gregord65587f2010-11-10 19:44:59 +00002286 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00002287
2288 // Figure out where to insert this class template partial specialization
2289 // in the member template's set of class template partial specializations.
Douglas Gregored9c0f92009-10-29 00:04:11 +00002290 void *InsertPos = 0;
2291 ClassTemplateSpecializationDecl *PrevDecl
Douglas Gregor910f8002010-11-07 23:05:16 +00002292 = ClassTemplate->findPartialSpecialization(Converted.data(),
2293 Converted.size(), InsertPos);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002294
Douglas Gregored9c0f92009-10-29 00:04:11 +00002295 // Build the canonical type that describes the converted template
2296 // arguments of the class template partial specialization.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002297 QualType CanonType
Douglas Gregored9c0f92009-10-29 00:04:11 +00002298 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
Douglas Gregor910f8002010-11-07 23:05:16 +00002299 Converted.data(),
2300 Converted.size());
Douglas Gregored9c0f92009-10-29 00:04:11 +00002301
2302 // Build the fully-sugared type for this class template
2303 // specialization as the user wrote in the specialization
2304 // itself. This means that we'll pretty-print the type retrieved
2305 // from the specialization's declaration the way that the user
2306 // actually wrote the specialization, rather than formatting the
2307 // name based on the "canonical" representation used to store the
2308 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00002309 TypeSourceInfo *WrittenTy
2310 = SemaRef.Context.getTemplateSpecializationTypeInfo(
2311 TemplateName(ClassTemplate),
2312 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00002313 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002314 CanonType);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002315
Douglas Gregored9c0f92009-10-29 00:04:11 +00002316 if (PrevDecl) {
2317 // We've already seen a partial specialization with the same template
2318 // parameters and template arguments. This can happen, for example, when
2319 // substituting the outer template arguments ends up causing two
2320 // class template partial specializations of a member class template
2321 // to have identical forms, e.g.,
2322 //
2323 // template<typename T, typename U>
2324 // struct Outer {
2325 // template<typename X, typename Y> struct Inner;
2326 // template<typename Y> struct Inner<T, Y>;
2327 // template<typename Y> struct Inner<U, Y>;
2328 // };
2329 //
2330 // Outer<int, int> outer; // error: the partial specializations of Inner
2331 // // have the same signature.
2332 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
Douglas Gregord65587f2010-11-10 19:44:59 +00002333 << WrittenTy->getType();
Douglas Gregored9c0f92009-10-29 00:04:11 +00002334 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
2335 << SemaRef.Context.getTypeDeclType(PrevDecl);
Douglas Gregord65587f2010-11-10 19:44:59 +00002336 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00002337 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002338
2339
Douglas Gregored9c0f92009-10-29 00:04:11 +00002340 // Create the class template partial specialization declaration.
2341 ClassTemplatePartialSpecializationDecl *InstPartialSpec
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002342 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
Douglas Gregor13c85772010-05-06 00:28:52 +00002343 PartialSpec->getTagKind(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002344 Owner,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002345 PartialSpec->getLocStart(),
2346 PartialSpec->getLocation(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00002347 InstParams,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002348 ClassTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00002349 Converted.data(),
2350 Converted.size(),
John McCalld5532b62009-11-23 01:53:49 +00002351 InstTemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00002352 CanonType,
Douglas Gregordc60c1e2010-04-30 05:56:50 +00002353 0,
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00002354 ClassTemplate->getNextPartialSpecSequenceNumber());
John McCallb6217662010-03-15 10:12:16 +00002355 // Substitute the nested name specifier, if any.
2356 if (SubstQualifier(PartialSpec, InstPartialSpec))
2357 return 0;
2358
Douglas Gregored9c0f92009-10-29 00:04:11 +00002359 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
Douglas Gregor4469e8a2010-05-19 17:02:24 +00002360 InstPartialSpec->setTypeAsWritten(WrittenTy);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002361
Douglas Gregored9c0f92009-10-29 00:04:11 +00002362 // Add this partial specialization to the set of class template partial
2363 // specializations.
Douglas Gregor1e1e9722012-03-28 14:34:23 +00002364 ClassTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/0);
Douglas Gregord65587f2010-11-10 19:44:59 +00002365 return InstPartialSpec;
Douglas Gregored9c0f92009-10-29 00:04:11 +00002366}
2367
John McCall21ef0fa2010-03-11 09:03:00 +00002368TypeSourceInfo*
John McCallce3ff2b2009-08-25 22:02:44 +00002369TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002370 SmallVectorImpl<ParmVarDecl *> &Params) {
John McCall21ef0fa2010-03-11 09:03:00 +00002371 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
2372 assert(OldTInfo && "substituting function without type source info");
2373 assert(Params.empty() && "parameter vector is non-empty at start");
Douglas Gregorcefc3af2012-04-16 07:05:22 +00002374
2375 CXXRecordDecl *ThisContext = 0;
2376 unsigned ThisTypeQuals = 0;
2377 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
2378 ThisContext = Method->getParent();
2379 ThisTypeQuals = Method->getTypeQualifiers();
2380 }
2381
John McCall6cd3b9f2010-04-09 17:38:44 +00002382 TypeSourceInfo *NewTInfo
2383 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
2384 D->getTypeSpecStartLoc(),
Douglas Gregorcefc3af2012-04-16 07:05:22 +00002385 D->getDeclName(),
2386 ThisContext, ThisTypeQuals);
John McCall21ef0fa2010-03-11 09:03:00 +00002387 if (!NewTInfo)
2388 return 0;
Douglas Gregor5545e162009-03-24 00:38:23 +00002389
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00002390 if (NewTInfo != OldTInfo) {
2391 // Get parameters from the new type info.
Abramo Bagnara140a2bd2010-12-13 22:27:55 +00002392 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
David Blaikie39e6ab42013-02-18 22:06:02 +00002393 if (FunctionProtoTypeLoc OldProtoLoc =
2394 OldTL.getAs<FunctionProtoTypeLoc>()) {
Abramo Bagnara140a2bd2010-12-13 22:27:55 +00002395 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
David Blaikie39e6ab42013-02-18 22:06:02 +00002396 FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
Richard Smith500d7292012-07-18 01:29:05 +00002397 unsigned NewIdx = 0;
David Blaikie39e6ab42013-02-18 22:06:02 +00002398 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumArgs();
Douglas Gregor12c9c002011-01-07 16:43:16 +00002399 OldIdx != NumOldParams; ++OldIdx) {
David Blaikie39e6ab42013-02-18 22:06:02 +00002400 ParmVarDecl *OldParam = OldProtoLoc.getArg(OldIdx);
Richard Smith500d7292012-07-18 01:29:05 +00002401 LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
2402
David Blaikiedc84cd52013-02-20 22:23:23 +00002403 Optional<unsigned> NumArgumentsInExpansion;
Richard Smith500d7292012-07-18 01:29:05 +00002404 if (OldParam->isParameterPack())
2405 NumArgumentsInExpansion =
2406 SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
2407 TemplateArgs);
2408 if (!NumArgumentsInExpansion) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002409 // Simple case: normal parameter, or a parameter pack that's
Douglas Gregor12c9c002011-01-07 16:43:16 +00002410 // instantiated to a (still-dependent) parameter pack.
David Blaikie39e6ab42013-02-18 22:06:02 +00002411 ParmVarDecl *NewParam = NewProtoLoc.getArg(NewIdx++);
Douglas Gregor12c9c002011-01-07 16:43:16 +00002412 Params.push_back(NewParam);
Richard Smith500d7292012-07-18 01:29:05 +00002413 Scope->InstantiatedLocal(OldParam, NewParam);
2414 } else {
2415 // Parameter pack expansion: make the instantiation an argument pack.
2416 Scope->MakeInstantiatedLocalArgPack(OldParam);
2417 for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
David Blaikie39e6ab42013-02-18 22:06:02 +00002418 ParmVarDecl *NewParam = NewProtoLoc.getArg(NewIdx++);
Richard Smith500d7292012-07-18 01:29:05 +00002419 Params.push_back(NewParam);
2420 Scope->InstantiatedLocalPackArg(OldParam, NewParam);
2421 }
Douglas Gregor12c9c002011-01-07 16:43:16 +00002422 }
Douglas Gregor6920cdc2010-05-03 15:32:18 +00002423 }
Douglas Gregor895162d2010-04-30 18:55:50 +00002424 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00002425 } else {
2426 // The function type itself was not dependent and therefore no
2427 // substitution occurred. However, we still need to instantiate
2428 // the function parameters themselves.
Abramo Bagnara140a2bd2010-12-13 22:27:55 +00002429 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
David Blaikie39e6ab42013-02-18 22:06:02 +00002430 if (FunctionProtoTypeLoc OldProtoLoc =
2431 OldTL.getAs<FunctionProtoTypeLoc>()) {
2432 for (unsigned i = 0, i_end = OldProtoLoc.getNumArgs(); i != i_end; ++i) {
2433 ParmVarDecl *Parm = VisitParmVarDecl(OldProtoLoc.getArg(i));
Douglas Gregor6920cdc2010-05-03 15:32:18 +00002434 if (!Parm)
2435 return 0;
2436 Params.push_back(Parm);
2437 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00002438 }
2439 }
John McCall21ef0fa2010-03-11 09:03:00 +00002440 return NewTInfo;
Douglas Gregor5545e162009-03-24 00:38:23 +00002441}
2442
Richard Smithe6975e92012-04-17 00:58:00 +00002443/// Introduce the instantiated function parameters into the local
2444/// instantiation scope, and set the parameter names to those used
2445/// in the template.
2446static void addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function,
2447 const FunctionDecl *PatternDecl,
2448 LocalInstantiationScope &Scope,
2449 const MultiLevelTemplateArgumentList &TemplateArgs) {
2450 unsigned FParamIdx = 0;
2451 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
2452 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
2453 if (!PatternParam->isParameterPack()) {
2454 // Simple case: not a parameter pack.
2455 assert(FParamIdx < Function->getNumParams());
2456 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
2457 FunctionParam->setDeclName(PatternParam->getDeclName());
2458 Scope.InstantiatedLocal(PatternParam, FunctionParam);
2459 ++FParamIdx;
2460 continue;
2461 }
2462
2463 // Expand the parameter pack.
2464 Scope.MakeInstantiatedLocalArgPack(PatternParam);
David Blaikiedc84cd52013-02-20 22:23:23 +00002465 Optional<unsigned> NumArgumentsInExpansion
Richard Smithe6975e92012-04-17 00:58:00 +00002466 = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
Richard Smith500d7292012-07-18 01:29:05 +00002467 assert(NumArgumentsInExpansion &&
2468 "should only be called when all template arguments are known");
2469 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
Richard Smithe6975e92012-04-17 00:58:00 +00002470 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
2471 FunctionParam->setDeclName(PatternParam->getDeclName());
2472 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
2473 ++FParamIdx;
2474 }
2475 }
2476}
2477
2478static void InstantiateExceptionSpec(Sema &SemaRef, FunctionDecl *New,
2479 const FunctionProtoType *Proto,
2480 const MultiLevelTemplateArgumentList &TemplateArgs) {
Richard Smith13bffc52012-04-19 00:08:28 +00002481 assert(Proto->getExceptionSpecType() != EST_Uninstantiated);
2482
Richard Smithe6975e92012-04-17 00:58:00 +00002483 // C++11 [expr.prim.general]p3:
2484 // If a declaration declares a member function or member function
2485 // template of a class X, the expression this is a prvalue of type
2486 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
2487 // and the end of the function-definition, member-declarator, or
2488 // declarator.
2489 CXXRecordDecl *ThisContext = 0;
2490 unsigned ThisTypeQuals = 0;
2491 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(New)) {
2492 ThisContext = Method->getParent();
2493 ThisTypeQuals = Method->getTypeQualifiers();
2494 }
2495 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals,
Richard Smith80ad52f2013-01-02 11:42:31 +00002496 SemaRef.getLangOpts().CPlusPlus11);
Richard Smithe6975e92012-04-17 00:58:00 +00002497
2498 // The function has an exception specification or a "noreturn"
2499 // attribute. Substitute into each of the exception types.
2500 SmallVector<QualType, 4> Exceptions;
2501 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
2502 // FIXME: Poor location information!
2503 if (const PackExpansionType *PackExpansion
2504 = Proto->getExceptionType(I)->getAs<PackExpansionType>()) {
2505 // We have a pack expansion. Instantiate it.
2506 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2507 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
2508 Unexpanded);
2509 assert(!Unexpanded.empty() &&
2510 "Pack expansion without parameter packs?");
2511
2512 bool Expand = false;
2513 bool RetainExpansion = false;
David Blaikiedc84cd52013-02-20 22:23:23 +00002514 Optional<unsigned> NumExpansions
Richard Smithe6975e92012-04-17 00:58:00 +00002515 = PackExpansion->getNumExpansions();
2516 if (SemaRef.CheckParameterPacksForExpansion(New->getLocation(),
2517 SourceRange(),
2518 Unexpanded,
2519 TemplateArgs,
2520 Expand,
2521 RetainExpansion,
2522 NumExpansions))
2523 break;
2524
2525 if (!Expand) {
2526 // We can't expand this pack expansion into separate arguments yet;
2527 // just substitute into the pattern and create a new pack expansion
2528 // type.
2529 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2530 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2531 TemplateArgs,
2532 New->getLocation(), New->getDeclName());
2533 if (T.isNull())
2534 break;
2535
2536 T = SemaRef.Context.getPackExpansionType(T, NumExpansions);
2537 Exceptions.push_back(T);
2538 continue;
2539 }
2540
2541 // Substitute into the pack expansion pattern for each template
2542 bool Invalid = false;
2543 for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
2544 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, ArgIdx);
2545
2546 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2547 TemplateArgs,
2548 New->getLocation(), New->getDeclName());
2549 if (T.isNull()) {
2550 Invalid = true;
2551 break;
2552 }
2553
2554 Exceptions.push_back(T);
2555 }
2556
2557 if (Invalid)
2558 break;
2559
2560 continue;
2561 }
2562
2563 QualType T
2564 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
2565 New->getLocation(), New->getDeclName());
2566 if (T.isNull() ||
2567 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
2568 continue;
2569
2570 Exceptions.push_back(T);
2571 }
2572 Expr *NoexceptExpr = 0;
2573 if (Expr *OldNoexceptExpr = Proto->getNoexceptExpr()) {
2574 EnterExpressionEvaluationContext Unevaluated(SemaRef,
2575 Sema::ConstantEvaluated);
2576 ExprResult E = SemaRef.SubstExpr(OldNoexceptExpr, TemplateArgs);
2577 if (E.isUsable())
2578 E = SemaRef.CheckBooleanCondition(E.get(), E.get()->getLocStart());
2579
2580 if (E.isUsable()) {
2581 NoexceptExpr = E.take();
2582 if (!NoexceptExpr->isTypeDependent() &&
2583 !NoexceptExpr->isValueDependent())
Douglas Gregorab41fe92012-05-04 22:38:52 +00002584 NoexceptExpr
2585 = SemaRef.VerifyIntegerConstantExpression(NoexceptExpr,
2586 0, diag::err_noexcept_needs_constant_expression,
2587 /*AllowFold*/ false).take();
Richard Smithe6975e92012-04-17 00:58:00 +00002588 }
2589 }
2590
2591 // Rebuild the function type
2592 const FunctionProtoType *NewProto
2593 = New->getType()->getAs<FunctionProtoType>();
2594 assert(NewProto && "Template instantiation without function prototype?");
2595
2596 FunctionProtoType::ExtProtoInfo EPI = NewProto->getExtProtoInfo();
2597 EPI.ExceptionSpecType = Proto->getExceptionSpecType();
2598 EPI.NumExceptions = Exceptions.size();
2599 EPI.Exceptions = Exceptions.data();
2600 EPI.NoexceptExpr = NoexceptExpr;
2601
2602 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002603 ArrayRef<QualType>(NewProto->arg_type_begin(),
2604 NewProto->getNumArgs()),
Richard Smithe6975e92012-04-17 00:58:00 +00002605 EPI));
2606}
2607
2608void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
2609 FunctionDecl *Decl) {
Richard Smith13bffc52012-04-19 00:08:28 +00002610 const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
2611 if (Proto->getExceptionSpecType() != EST_Uninstantiated)
Richard Smithe6975e92012-04-17 00:58:00 +00002612 return;
2613
2614 InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
2615 InstantiatingTemplate::ExceptionSpecification());
Richard Smithb9d0b762012-07-27 04:22:15 +00002616 if (Inst) {
2617 // We hit the instantiation depth limit. Clear the exception specification
2618 // so that our callers don't have to cope with EST_Uninstantiated.
2619 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
2620 EPI.ExceptionSpecType = EST_None;
2621 Decl->setType(Context.getFunctionType(Proto->getResultType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002622 ArrayRef<QualType>(Proto->arg_type_begin(),
2623 Proto->getNumArgs()),
Richard Smithb9d0b762012-07-27 04:22:15 +00002624 EPI));
Richard Smithe6975e92012-04-17 00:58:00 +00002625 return;
Richard Smithb9d0b762012-07-27 04:22:15 +00002626 }
Richard Smithe6975e92012-04-17 00:58:00 +00002627
2628 // Enter the scope of this instantiation. We don't use
2629 // PushDeclContext because we don't have a scope.
2630 Sema::ContextRAII savedContext(*this, Decl);
2631 LocalInstantiationScope Scope(*this);
2632
2633 MultiLevelTemplateArgumentList TemplateArgs =
2634 getTemplateInstantiationArgs(Decl, 0, /*RelativeToPrimary*/true);
2635
Richard Smith13bffc52012-04-19 00:08:28 +00002636 FunctionDecl *Template = Proto->getExceptionSpecTemplate();
2637 addInstantiatedParametersToScope(*this, Decl, Template, Scope, TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +00002638
Richard Smith13bffc52012-04-19 00:08:28 +00002639 ::InstantiateExceptionSpec(*this, Decl,
2640 Template->getType()->castAs<FunctionProtoType>(),
2641 TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +00002642}
2643
Mike Stump1eb44332009-09-09 15:08:12 +00002644/// \brief Initializes the common fields of an instantiation function
Douglas Gregore53060f2009-06-25 22:08:12 +00002645/// declaration (New) from the corresponding fields of its template (Tmpl).
2646///
2647/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00002648bool
2649TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregore53060f2009-06-25 22:08:12 +00002650 FunctionDecl *Tmpl) {
David Blaikie85f485a2012-07-16 18:50:45 +00002651 if (Tmpl->isDeleted())
Sean Hunt10620eb2011-05-06 20:44:56 +00002652 New->setDeletedAsWritten();
Mike Stump1eb44332009-09-09 15:08:12 +00002653
Douglas Gregorcca9e962009-07-01 22:01:06 +00002654 // If we are performing substituting explicitly-specified template arguments
2655 // or deduced template arguments into a function template and we reach this
2656 // point, we are now past the point where SFINAE applies and have committed
Mike Stump1eb44332009-09-09 15:08:12 +00002657 // to keeping the new function template specialization. We therefore
2658 // convert the active template instantiation for the function template
Douglas Gregorcca9e962009-07-01 22:01:06 +00002659 // into a template instantiation for this specific function template
2660 // specialization, which is not a SFINAE context, so that we diagnose any
2661 // further errors in the declaration itself.
2662 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
2663 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
2664 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
2665 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump1eb44332009-09-09 15:08:12 +00002666 if (FunctionTemplateDecl *FunTmpl
Nick Lewycky4a9e60f2012-11-16 08:40:59 +00002667 = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002668 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorcca9e962009-07-01 22:01:06 +00002669 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +00002670 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +00002671 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
Nick Lewycky4a9e60f2012-11-16 08:40:59 +00002672 ActiveInst.Entity = New;
Douglas Gregorcca9e962009-07-01 22:01:06 +00002673 }
2674 }
Mike Stump1eb44332009-09-09 15:08:12 +00002675
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002676 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
2677 assert(Proto && "Function template without prototype?");
2678
Sebastian Redl60618fa2011-03-12 11:50:43 +00002679 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
John McCalle23cf432010-12-14 08:05:40 +00002680 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
John McCalle23cf432010-12-14 08:05:40 +00002681
Richard Smithe6975e92012-04-17 00:58:00 +00002682 // DR1330: In C++11, defer instantiation of a non-trivial
2683 // exception specification.
Richard Smith80ad52f2013-01-02 11:42:31 +00002684 if (SemaRef.getLangOpts().CPlusPlus11 &&
Richard Smithe6975e92012-04-17 00:58:00 +00002685 EPI.ExceptionSpecType != EST_None &&
2686 EPI.ExceptionSpecType != EST_DynamicNone &&
2687 EPI.ExceptionSpecType != EST_BasicNoexcept) {
Richard Smith13bffc52012-04-19 00:08:28 +00002688 FunctionDecl *ExceptionSpecTemplate = Tmpl;
2689 if (EPI.ExceptionSpecType == EST_Uninstantiated)
2690 ExceptionSpecTemplate = EPI.ExceptionSpecTemplate;
Richard Smithb9d0b762012-07-27 04:22:15 +00002691 assert(EPI.ExceptionSpecType != EST_Unevaluated &&
2692 "instantiating implicitly-declared special member");
Richard Smith13bffc52012-04-19 00:08:28 +00002693
Richard Smithe6975e92012-04-17 00:58:00 +00002694 // Mark the function has having an uninstantiated exception specification.
2695 const FunctionProtoType *NewProto
2696 = New->getType()->getAs<FunctionProtoType>();
2697 assert(NewProto && "Template instantiation without function prototype?");
2698 EPI = NewProto->getExtProtoInfo();
2699 EPI.ExceptionSpecType = EST_Uninstantiated;
2700 EPI.ExceptionSpecDecl = New;
Richard Smith13bffc52012-04-19 00:08:28 +00002701 EPI.ExceptionSpecTemplate = ExceptionSpecTemplate;
Richard Smithe6975e92012-04-17 00:58:00 +00002702 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002703 ArrayRef<QualType>(NewProto->arg_type_begin(),
2704 NewProto->getNumArgs()),
Richard Smithe6975e92012-04-17 00:58:00 +00002705 EPI));
2706 } else {
2707 ::InstantiateExceptionSpec(SemaRef, New, Proto, TemplateArgs);
2708 }
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002709 }
2710
Rafael Espindola19f74ac2011-07-06 15:46:09 +00002711 // Get the definition. Leaves the variable unchanged if undefined.
Richard Smithe6975e92012-04-17 00:58:00 +00002712 const FunctionDecl *Definition = Tmpl;
Rafael Espindola19f74ac2011-07-06 15:46:09 +00002713 Tmpl->isDefined(Definition);
2714
DeLesley Hutchins23323e02012-01-20 22:50:54 +00002715 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
2716 LateAttrs, StartingScope);
Douglas Gregor7cf84d62010-06-15 17:05:35 +00002717
Douglas Gregore53060f2009-06-25 22:08:12 +00002718 return false;
2719}
2720
Douglas Gregor5545e162009-03-24 00:38:23 +00002721/// \brief Initializes common fields of an instantiated method
2722/// declaration (New) from the corresponding fields of its template
2723/// (Tmpl).
2724///
2725/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00002726bool
2727TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor5545e162009-03-24 00:38:23 +00002728 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +00002729 if (InitFunctionInstantiation(New, Tmpl))
2730 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002731
Douglas Gregor5545e162009-03-24 00:38:23 +00002732 New->setAccess(Tmpl->getAccess());
Fariborz Jahaniane7184df2009-12-03 18:44:40 +00002733 if (Tmpl->isVirtualAsWritten())
Douglas Gregor85606eb2010-09-28 20:50:54 +00002734 New->setVirtualAsWritten(true);
Douglas Gregor5545e162009-03-24 00:38:23 +00002735
2736 // FIXME: attributes
2737 // FIXME: New needs a pointer to Tmpl
2738 return false;
2739}
Douglas Gregora58861f2009-05-13 20:28:22 +00002740
2741/// \brief Instantiate the definition of the given function from its
2742/// template.
2743///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002744/// \param PointOfInstantiation the point at which the instantiation was
2745/// required. Note that this is not precisely a "point of instantiation"
2746/// for the function, but it's close.
2747///
Douglas Gregora58861f2009-05-13 20:28:22 +00002748/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002749/// function template specialization or member function of a class template
2750/// specialization.
2751///
2752/// \param Recursive if true, recursively instantiates any functions that
2753/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002754///
2755/// \param DefinitionRequired if true, then we are performing an explicit
2756/// instantiation where the body of the function is required. Complain if
2757/// there is no such body.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002758void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002759 FunctionDecl *Function,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002760 bool Recursive,
2761 bool DefinitionRequired) {
Sean Hunt10620eb2011-05-06 20:44:56 +00002762 if (Function->isInvalidDecl() || Function->isDefined())
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002763 return;
2764
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002765 // Never instantiate an explicit specialization except if it is a class scope
2766 // explicit specialization.
2767 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
2768 !Function->getClassScopeSpecializationPattern())
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002769 return;
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00002770
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002771 // Find the function body that we'll be substituting.
Douglas Gregor3b846b62009-10-27 20:53:28 +00002772 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Sean Huntf996e052011-05-27 20:00:14 +00002773 assert(PatternDecl && "instantiating a non-template");
2774
2775 Stmt *Pattern = PatternDecl->getBody(PatternDecl);
2776 assert(PatternDecl && "template definition is not a template");
2777 if (!Pattern) {
2778 // Try to find a defaulted definition
2779 PatternDecl->isDefined(PatternDecl);
Sean Huntdfab8542011-05-25 22:02:25 +00002780 }
Sean Huntf996e052011-05-27 20:00:14 +00002781 assert(PatternDecl && "template definition is not a template");
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002782
Francois Pichet8387e2a2011-04-22 22:18:13 +00002783 // Postpone late parsed template instantiations.
Sean Huntf996e052011-05-27 20:00:14 +00002784 if (PatternDecl->isLateTemplateParsed() &&
Nick Lewycky8a29bc02011-05-12 03:51:24 +00002785 !LateTemplateParser) {
Francois Pichet8387e2a2011-04-22 22:18:13 +00002786 PendingInstantiations.push_back(
2787 std::make_pair(Function, PointOfInstantiation));
2788 return;
2789 }
2790
2791 // Call the LateTemplateParser callback if there a need to late parse
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002792 // a templated function definition.
Sean Huntf996e052011-05-27 20:00:14 +00002793 if (!Pattern && PatternDecl->isLateTemplateParsed() &&
Francois Pichet8387e2a2011-04-22 22:18:13 +00002794 LateTemplateParser) {
Francois Pichet4a47e8d2011-04-23 11:52:20 +00002795 LateTemplateParser(OpaqueParser, PatternDecl);
Francois Pichet8387e2a2011-04-22 22:18:13 +00002796 Pattern = PatternDecl->getBody(PatternDecl);
2797 }
2798
Sean Huntf996e052011-05-27 20:00:14 +00002799 if (!Pattern && !PatternDecl->isDefaulted()) {
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002800 if (DefinitionRequired) {
2801 if (Function->getPrimaryTemplate())
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002802 Diag(PointOfInstantiation,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002803 diag::err_explicit_instantiation_undefined_func_template)
2804 << Function->getPrimaryTemplate();
2805 else
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002806 Diag(PointOfInstantiation,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002807 diag::err_explicit_instantiation_undefined_member)
2808 << 1 << Function->getDeclName() << Function->getDeclContext();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002809
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002810 if (PatternDecl)
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002811 Diag(PatternDecl->getLocation(),
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002812 diag::note_explicit_instantiation_here);
Douglas Gregorcfe833b2010-05-17 17:57:54 +00002813 Function->setInvalidDecl();
Chandler Carruth58e390e2010-08-25 08:27:02 +00002814 } else if (Function->getTemplateSpecializationKind()
2815 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00002816 PendingInstantiations.push_back(
Chandler Carruth58e390e2010-08-25 08:27:02 +00002817 std::make_pair(Function, PointOfInstantiation));
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002818 }
Chandler Carruth58e390e2010-08-25 08:27:02 +00002819
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002820 return;
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002821 }
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002822
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002823 // C++0x [temp.explicit]p9:
2824 // Except for inline functions, other explicit instantiation declarations
Mike Stump1eb44332009-09-09 15:08:12 +00002825 // have the effect of suppressing the implicit instantiation of the entity
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002826 // to which they refer.
Mike Stump1eb44332009-09-09 15:08:12 +00002827 if (Function->getTemplateSpecializationKind()
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002828 == TSK_ExplicitInstantiationDeclaration &&
Douglas Gregor7ced9c82009-10-27 21:11:48 +00002829 !PatternDecl->isInlined())
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002830 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002831
Richard Smithd4497dd2013-01-25 00:08:28 +00002832 if (PatternDecl->isInlined())
2833 Function->setImplicitlyInline();
2834
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002835 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
2836 if (Inst)
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002837 return;
2838
Abramo Bagnarae9946242011-11-18 08:08:52 +00002839 // Copy the inner loc start from the pattern.
2840 Function->setInnerLocStart(PatternDecl->getInnerLocStart());
2841
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002842 // If we're performing recursive template instantiation, create our own
2843 // queue of pending implicit instantiations that we will instantiate later,
2844 // while we're still within our own instantiation context.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002845 SmallVector<VTableUse, 16> SavedVTableUses;
Chandler Carruth62c78d52010-08-25 08:44:16 +00002846 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002847 if (Recursive) {
2848 VTableUses.swap(SavedVTableUses);
Chandler Carruth62c78d52010-08-25 08:44:16 +00002849 PendingInstantiations.swap(SavedPendingInstantiations);
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002850 }
Mike Stump1eb44332009-09-09 15:08:12 +00002851
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002852 EnterExpressionEvaluationContext EvalContext(*this,
John McCallf312b1e2010-08-26 23:41:50 +00002853 Sema::PotentiallyEvaluated);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002854
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002855 // Introduce a new scope where local variable instantiations will be
Douglas Gregor60406be2010-01-16 22:29:39 +00002856 // recorded, unless we're actually a member function within a local
2857 // class, in which case we need to merge our results with the parent
2858 // scope (of the enclosing function).
2859 bool MergeWithParentScope = false;
2860 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
2861 MergeWithParentScope = Rec->isLocalClass();
2862
2863 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +00002864
Richard Smith1d28caf2012-12-11 01:14:52 +00002865 if (PatternDecl->isDefaulted())
Sean Huntcd10dec2011-05-23 23:14:04 +00002866 SetDeclDefaulted(Function, PatternDecl->getLocation());
Richard Smith1d28caf2012-12-11 01:14:52 +00002867 else {
2868 ActOnStartOfFunctionDef(0, Function);
2869
2870 // Enter the scope of this instantiation. We don't use
2871 // PushDeclContext because we don't have a scope.
2872 Sema::ContextRAII savedContext(*this, Function);
2873
2874 MultiLevelTemplateArgumentList TemplateArgs =
2875 getTemplateInstantiationArgs(Function, 0, false, PatternDecl);
2876
2877 addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope,
2878 TemplateArgs);
2879
Sean Huntcd10dec2011-05-23 23:14:04 +00002880 // If this is a constructor, instantiate the member initializers.
2881 if (const CXXConstructorDecl *Ctor =
2882 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
2883 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
2884 TemplateArgs);
2885 }
2886
2887 // Instantiate the function body.
2888 StmtResult Body = SubstStmt(Pattern, TemplateArgs);
2889
2890 if (Body.isInvalid())
2891 Function->setInvalidDecl();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002892
Sean Huntcd10dec2011-05-23 23:14:04 +00002893 ActOnFinishFunctionBody(Function, Body.get(),
2894 /*IsInstantiation=*/true);
Richard Smith1d28caf2012-12-11 01:14:52 +00002895
2896 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
2897
2898 savedContext.pop();
Mike Stump1eb44332009-09-09 15:08:12 +00002899 }
2900
Douglas Gregoraba43bb2009-05-26 20:50:29 +00002901 DeclGroupRef DG(Function);
2902 Consumer.HandleTopLevelDecl(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00002903
Douglas Gregor60406be2010-01-16 22:29:39 +00002904 // This class may have local implicit instantiations that need to be
2905 // instantiation within this scope.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002906 PerformPendingInstantiations(/*LocalOnly=*/true);
Douglas Gregor60406be2010-01-16 22:29:39 +00002907 Scope.Exit();
2908
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002909 if (Recursive) {
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002910 // Define any pending vtables.
2911 DefineUsedVTables();
2912
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002913 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002914 // instantiation of this template.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002915 PerformPendingInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002916
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002917 // Restore the set of pending vtables.
Nick Lewycky81559102011-05-31 07:58:42 +00002918 assert(VTableUses.empty() &&
2919 "VTableUses should be empty before it is discarded.");
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002920 VTableUses.swap(SavedVTableUses);
2921
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002922 // Restore the set of pending implicit instantiations.
Nick Lewycky81559102011-05-31 07:58:42 +00002923 assert(PendingInstantiations.empty() &&
2924 "PendingInstantiations should be empty before it is discarded.");
Chandler Carruth62c78d52010-08-25 08:44:16 +00002925 PendingInstantiations.swap(SavedPendingInstantiations);
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002926 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002927}
2928
2929/// \brief Instantiate the definition of the given variable from its
2930/// template.
2931///
Douglas Gregor7caa6822009-07-24 20:34:43 +00002932/// \param PointOfInstantiation the point at which the instantiation was
2933/// required. Note that this is not precisely a "point of instantiation"
2934/// for the function, but it's close.
2935///
2936/// \param Var the already-instantiated declaration of a static member
2937/// variable of a class template specialization.
2938///
2939/// \param Recursive if true, recursively instantiates any functions that
2940/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002941///
2942/// \param DefinitionRequired if true, then we are performing an explicit
2943/// instantiation where an out-of-line definition of the member variable
2944/// is required. Complain if there is no such definition.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002945void Sema::InstantiateStaticDataMemberDefinition(
2946 SourceLocation PointOfInstantiation,
2947 VarDecl *Var,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002948 bool Recursive,
2949 bool DefinitionRequired) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002950 if (Var->isInvalidDecl())
2951 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002952
Douglas Gregor7caa6822009-07-24 20:34:43 +00002953 // Find the out-of-line definition of this static data member.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002954 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregor7caa6822009-07-24 20:34:43 +00002955 assert(Def && "This data member was not instantiated from a template?");
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002956 assert(Def->isStaticDataMember() && "Not a static data member?");
Douglas Gregor0d035142009-10-27 18:42:08 +00002957 Def = Def->getOutOfLineDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00002958
Douglas Gregor0d035142009-10-27 18:42:08 +00002959 if (!Def) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002960 // We did not find an out-of-line definition of this static data member,
2961 // so we won't perform any instantiation. Rather, we rely on the user to
Mike Stump1eb44332009-09-09 15:08:12 +00002962 // instantiate this definition (or provide a specialization for it) in
2963 // another translation unit.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002964 if (DefinitionRequired) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002965 Def = Var->getInstantiatedFromStaticDataMember();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002966 Diag(PointOfInstantiation,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002967 diag::err_explicit_instantiation_undefined_member)
2968 << 2 << Var->getDeclName() << Var->getDeclContext();
2969 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
Chandler Carruth58e390e2010-08-25 08:27:02 +00002970 } else if (Var->getTemplateSpecializationKind()
2971 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00002972 PendingInstantiations.push_back(
Chandler Carruth58e390e2010-08-25 08:27:02 +00002973 std::make_pair(Var, PointOfInstantiation));
2974 }
2975
Douglas Gregor7caa6822009-07-24 20:34:43 +00002976 return;
2977 }
2978
Rafael Espindola234fe652012-03-05 10:54:55 +00002979 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
2980
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002981 // Never instantiate an explicit specialization.
Rafael Espindola234fe652012-03-05 10:54:55 +00002982 if (TSK == TSK_ExplicitSpecialization)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002983 return;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002984
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002985 // C++0x [temp.explicit]p9:
2986 // Except for inline functions, other explicit instantiation declarations
2987 // have the effect of suppressing the implicit instantiation of the entity
2988 // to which they refer.
Rafael Espindola234fe652012-03-05 10:54:55 +00002989 if (TSK == TSK_ExplicitInstantiationDeclaration)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002990 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002991
Argyrios Kyrtzidisafda9052013-02-24 00:05:01 +00002992 // Make sure to pass the instantiated variable to the consumer at the end.
2993 struct PassToConsumerRAII {
2994 ASTConsumer &Consumer;
2995 VarDecl *Var;
2996
2997 PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
2998 : Consumer(Consumer), Var(Var) { }
2999
3000 ~PassToConsumerRAII() {
3001 Consumer.HandleCXXStaticMemberVarInstantiation(Var);
3002 }
3003 } PassToConsumerRAII(Consumer, Var);
Rafael Espindola02503932012-03-08 15:51:03 +00003004
Douglas Gregorf15748a2011-06-03 03:35:07 +00003005 // If we already have a definition, we're done.
Nick Lewycky95e38722012-04-04 02:38:36 +00003006 if (VarDecl *Def = Var->getDefinition()) {
3007 // We may be explicitly instantiating something we've already implicitly
3008 // instantiated.
3009 Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
3010 PointOfInstantiation);
Douglas Gregorf15748a2011-06-03 03:35:07 +00003011 return;
Nick Lewycky95e38722012-04-04 02:38:36 +00003012 }
Douglas Gregorf15748a2011-06-03 03:35:07 +00003013
Douglas Gregor7caa6822009-07-24 20:34:43 +00003014 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
3015 if (Inst)
3016 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003017
Douglas Gregor7caa6822009-07-24 20:34:43 +00003018 // If we're performing recursive template instantiation, create our own
3019 // queue of pending implicit instantiations that we will instantiate later,
3020 // while we're still within our own instantiation context.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003021 SmallVector<VTableUse, 16> SavedVTableUses;
Chandler Carruth62c78d52010-08-25 08:44:16 +00003022 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
Nick Lewycky81559102011-05-31 07:58:42 +00003023 if (Recursive) {
3024 VTableUses.swap(SavedVTableUses);
Chandler Carruth62c78d52010-08-25 08:44:16 +00003025 PendingInstantiations.swap(SavedPendingInstantiations);
Nick Lewycky81559102011-05-31 07:58:42 +00003026 }
Mike Stump1eb44332009-09-09 15:08:12 +00003027
Douglas Gregor7caa6822009-07-24 20:34:43 +00003028 // Enter the scope of this instantiation. We don't use
3029 // PushDeclContext because we don't have a scope.
John McCallf5ba7e02011-02-14 20:37:25 +00003030 ContextRAII previousContext(*this, Var->getDeclContext());
Douglas Gregor7bdc1522012-02-16 21:36:18 +00003031 LocalInstantiationScope Local(*this);
3032
Douglas Gregor1028c9f2009-10-14 21:29:40 +00003033 VarDecl *OldVar = Var;
John McCallce3ff2b2009-08-25 22:02:44 +00003034 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Nico Weber6bb4dcb2010-11-28 22:53:37 +00003035 getTemplateInstantiationArgs(Var)));
John McCallf5ba7e02011-02-14 20:37:25 +00003036
3037 previousContext.pop();
Douglas Gregor7caa6822009-07-24 20:34:43 +00003038
3039 if (Var) {
Argyrios Kyrtzidisafda9052013-02-24 00:05:01 +00003040 PassToConsumerRAII.Var = Var;
Douglas Gregor583f33b2009-10-15 18:07:02 +00003041 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
3042 assert(MSInfo && "Missing member specialization information?");
3043 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
3044 MSInfo->getPointOfInstantiation());
Douglas Gregor7caa6822009-07-24 20:34:43 +00003045 }
Douglas Gregor7bdc1522012-02-16 21:36:18 +00003046 Local.Exit();
3047
Douglas Gregor7caa6822009-07-24 20:34:43 +00003048 if (Recursive) {
Nick Lewycky81559102011-05-31 07:58:42 +00003049 // Define any newly required vtables.
3050 DefineUsedVTables();
3051
Douglas Gregor7caa6822009-07-24 20:34:43 +00003052 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00003053 // instantiation of this template.
Chandler Carruth62c78d52010-08-25 08:44:16 +00003054 PerformPendingInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00003055
Nick Lewycky81559102011-05-31 07:58:42 +00003056 // Restore the set of pending vtables.
3057 assert(VTableUses.empty() &&
3058 "VTableUses should be empty before it is discarded, "
3059 "while instantiating static data member.");
3060 VTableUses.swap(SavedVTableUses);
3061
Douglas Gregor7caa6822009-07-24 20:34:43 +00003062 // Restore the set of pending implicit instantiations.
Nick Lewycky81559102011-05-31 07:58:42 +00003063 assert(PendingInstantiations.empty() &&
3064 "PendingInstantiations should be empty before it is discarded, "
3065 "while instantiating static data member.");
Chandler Carruth62c78d52010-08-25 08:44:16 +00003066 PendingInstantiations.swap(SavedPendingInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00003067 }
Douglas Gregora58861f2009-05-13 20:28:22 +00003068}
Douglas Gregor815215d2009-05-27 05:35:12 +00003069
Anders Carlsson09025312009-08-29 05:16:22 +00003070void
3071Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
3072 const CXXConstructorDecl *Tmpl,
3073 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00003074
Richard Trieu90ab75b2011-09-09 03:18:59 +00003075 SmallVector<CXXCtorInitializer*, 4> NewInits;
Richard Smith54b3ba82012-09-25 00:23:05 +00003076 bool AnyErrors = Tmpl->isInvalidDecl();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003077
Anders Carlsson09025312009-08-29 05:16:22 +00003078 // Instantiate all the initializers.
3079 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00003080 InitsEnd = Tmpl->init_end();
3081 Inits != InitsEnd; ++Inits) {
Sean Huntcbb67482011-01-08 20:30:50 +00003082 CXXCtorInitializer *Init = *Inits;
Anders Carlsson09025312009-08-29 05:16:22 +00003083
Chandler Carruth030ef472010-09-03 21:54:20 +00003084 // Only instantiate written initializers, let Sema re-construct implicit
3085 // ones.
3086 if (!Init->isWritten())
3087 continue;
3088
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003089 SourceLocation EllipsisLoc;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003090
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003091 if (Init->isPackExpansion()) {
3092 // This is a pack expansion. We should expand it now.
Douglas Gregor76852c22011-11-01 01:16:03 +00003093 TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003094 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003095 collectUnexpandedParameterPacks(BaseTL, Unexpanded);
3096 bool ShouldExpand = false;
Douglas Gregord3731192011-01-10 07:32:04 +00003097 bool RetainExpansion = false;
David Blaikiedc84cd52013-02-20 22:23:23 +00003098 Optional<unsigned> NumExpansions;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003099 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003100 BaseTL.getSourceRange(),
David Blaikiea71f9d02011-09-22 02:34:54 +00003101 Unexpanded,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003102 TemplateArgs, ShouldExpand,
Douglas Gregord3731192011-01-10 07:32:04 +00003103 RetainExpansion,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003104 NumExpansions)) {
3105 AnyErrors = true;
3106 New->setInvalidDecl();
3107 continue;
3108 }
3109 assert(ShouldExpand && "Partial instantiation of base initializer?");
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003110
3111 // Loop over all of the arguments in the argument pack(s),
Douglas Gregorcded4f62011-01-14 17:04:44 +00003112 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003113 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
3114
3115 // Instantiate the initializer.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003116 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
3117 /*CXXDirectInit=*/true);
3118 if (TempInit.isInvalid()) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003119 AnyErrors = true;
3120 break;
3121 }
3122
3123 // Instantiate the base type.
Douglas Gregor76852c22011-11-01 01:16:03 +00003124 TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003125 TemplateArgs,
3126 Init->getSourceLocation(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003127 New->getDeclName());
3128 if (!BaseTInfo) {
3129 AnyErrors = true;
3130 break;
3131 }
3132
3133 // Build the initializer.
Sebastian Redl6df65482011-09-24 17:48:25 +00003134 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003135 BaseTInfo, TempInit.take(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003136 New->getParent(),
3137 SourceLocation());
3138 if (NewInit.isInvalid()) {
3139 AnyErrors = true;
3140 break;
3141 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003142
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003143 NewInits.push_back(NewInit.get());
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003144 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003145
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003146 continue;
3147 }
3148
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00003149 // Instantiate the initializer.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003150 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
3151 /*CXXDirectInit=*/true);
3152 if (TempInit.isInvalid()) {
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00003153 AnyErrors = true;
3154 continue;
Anders Carlsson09025312009-08-29 05:16:22 +00003155 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003156
Anders Carlsson09025312009-08-29 05:16:22 +00003157 MemInitResult NewInit;
Douglas Gregor76852c22011-11-01 01:16:03 +00003158 if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
3159 TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
3160 TemplateArgs,
3161 Init->getSourceLocation(),
3162 New->getDeclName());
3163 if (!TInfo) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003164 AnyErrors = true;
Douglas Gregor802ab452009-12-02 22:36:29 +00003165 New->setInvalidDecl();
3166 continue;
3167 }
Sebastian Redl6df65482011-09-24 17:48:25 +00003168
Douglas Gregor76852c22011-11-01 01:16:03 +00003169 if (Init->isBaseInitializer())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003170 NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.take(),
Douglas Gregor76852c22011-11-01 01:16:03 +00003171 New->getParent(), EllipsisLoc);
3172 else
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003173 NewInit = BuildDelegatingInitializer(TInfo, TempInit.take(),
Douglas Gregor76852c22011-11-01 01:16:03 +00003174 cast<CXXRecordDecl>(CurContext->getParent()));
Anders Carlsson09025312009-08-29 05:16:22 +00003175 } else if (Init->isMemberInitializer()) {
Douglas Gregorb7107222011-03-04 19:46:35 +00003176 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
Francois Pichet00eb3f92010-12-04 09:14:42 +00003177 Init->getMemberLocation(),
3178 Init->getMember(),
3179 TemplateArgs));
Douglas Gregorb7107222011-03-04 19:46:35 +00003180 if (!Member) {
3181 AnyErrors = true;
3182 New->setInvalidDecl();
3183 continue;
3184 }
Mike Stump1eb44332009-09-09 15:08:12 +00003185
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003186 NewInit = BuildMemberInitializer(Member, TempInit.take(),
Sebastian Redl6df65482011-09-24 17:48:25 +00003187 Init->getSourceLocation());
Francois Pichet00eb3f92010-12-04 09:14:42 +00003188 } else if (Init->isIndirectMemberInitializer()) {
3189 IndirectFieldDecl *IndirectMember =
Douglas Gregorb7107222011-03-04 19:46:35 +00003190 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
Francois Pichet00eb3f92010-12-04 09:14:42 +00003191 Init->getMemberLocation(),
3192 Init->getIndirectMember(), TemplateArgs));
3193
Douglas Gregorb7107222011-03-04 19:46:35 +00003194 if (!IndirectMember) {
3195 AnyErrors = true;
3196 New->setInvalidDecl();
Sebastian Redl6df65482011-09-24 17:48:25 +00003197 continue;
Douglas Gregorb7107222011-03-04 19:46:35 +00003198 }
Sebastian Redl6df65482011-09-24 17:48:25 +00003199
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003200 NewInit = BuildMemberInitializer(IndirectMember, TempInit.take(),
Sebastian Redl6df65482011-09-24 17:48:25 +00003201 Init->getSourceLocation());
Anders Carlsson09025312009-08-29 05:16:22 +00003202 }
3203
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003204 if (NewInit.isInvalid()) {
3205 AnyErrors = true;
Anders Carlsson09025312009-08-29 05:16:22 +00003206 New->setInvalidDecl();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003207 } else {
Richard Trieu90ab75b2011-09-09 03:18:59 +00003208 NewInits.push_back(NewInit.get());
Anders Carlsson09025312009-08-29 05:16:22 +00003209 }
3210 }
Mike Stump1eb44332009-09-09 15:08:12 +00003211
Anders Carlsson09025312009-08-29 05:16:22 +00003212 // Assign all the initializers to the new constructor.
John McCalld226f652010-08-21 09:40:31 +00003213 ActOnMemInitializers(New,
Anders Carlsson09025312009-08-29 05:16:22 +00003214 /*FIXME: ColonLoc */
3215 SourceLocation(),
David Blaikie93c86172013-01-17 05:26:25 +00003216 NewInits,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003217 AnyErrors);
Anders Carlsson09025312009-08-29 05:16:22 +00003218}
3219
John McCall52a575a2009-08-29 08:11:13 +00003220// TODO: this could be templated if the various decl types used the
3221// same method name.
3222static bool isInstantiationOf(ClassTemplateDecl *Pattern,
3223 ClassTemplateDecl *Instance) {
3224 Pattern = Pattern->getCanonicalDecl();
3225
3226 do {
3227 Instance = Instance->getCanonicalDecl();
3228 if (Pattern == Instance) return true;
3229 Instance = Instance->getInstantiatedFromMemberTemplate();
3230 } while (Instance);
3231
3232 return false;
3233}
3234
Douglas Gregor0d696532009-09-28 06:34:35 +00003235static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
3236 FunctionTemplateDecl *Instance) {
3237 Pattern = Pattern->getCanonicalDecl();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003238
Douglas Gregor0d696532009-09-28 06:34:35 +00003239 do {
3240 Instance = Instance->getCanonicalDecl();
3241 if (Pattern == Instance) return true;
3242 Instance = Instance->getInstantiatedFromMemberTemplate();
3243 } while (Instance);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003244
Douglas Gregor0d696532009-09-28 06:34:35 +00003245 return false;
3246}
3247
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003248static bool
Douglas Gregored9c0f92009-10-29 00:04:11 +00003249isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
3250 ClassTemplatePartialSpecializationDecl *Instance) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003251 Pattern
Douglas Gregored9c0f92009-10-29 00:04:11 +00003252 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
3253 do {
3254 Instance = cast<ClassTemplatePartialSpecializationDecl>(
3255 Instance->getCanonicalDecl());
3256 if (Pattern == Instance)
3257 return true;
3258 Instance = Instance->getInstantiatedFromMember();
3259 } while (Instance);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003260
Douglas Gregored9c0f92009-10-29 00:04:11 +00003261 return false;
3262}
3263
John McCall52a575a2009-08-29 08:11:13 +00003264static bool isInstantiationOf(CXXRecordDecl *Pattern,
3265 CXXRecordDecl *Instance) {
3266 Pattern = Pattern->getCanonicalDecl();
3267
3268 do {
3269 Instance = Instance->getCanonicalDecl();
3270 if (Pattern == Instance) return true;
3271 Instance = Instance->getInstantiatedFromMemberClass();
3272 } while (Instance);
3273
3274 return false;
3275}
3276
3277static bool isInstantiationOf(FunctionDecl *Pattern,
3278 FunctionDecl *Instance) {
3279 Pattern = Pattern->getCanonicalDecl();
3280
3281 do {
3282 Instance = Instance->getCanonicalDecl();
3283 if (Pattern == Instance) return true;
3284 Instance = Instance->getInstantiatedFromMemberFunction();
3285 } while (Instance);
3286
3287 return false;
3288}
3289
3290static bool isInstantiationOf(EnumDecl *Pattern,
3291 EnumDecl *Instance) {
3292 Pattern = Pattern->getCanonicalDecl();
3293
3294 do {
3295 Instance = Instance->getCanonicalDecl();
3296 if (Pattern == Instance) return true;
3297 Instance = Instance->getInstantiatedFromMemberEnum();
3298 } while (Instance);
3299
3300 return false;
3301}
3302
John McCalled976492009-12-04 22:46:56 +00003303static bool isInstantiationOf(UsingShadowDecl *Pattern,
3304 UsingShadowDecl *Instance,
3305 ASTContext &C) {
3306 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
3307}
3308
3309static bool isInstantiationOf(UsingDecl *Pattern,
3310 UsingDecl *Instance,
3311 ASTContext &C) {
3312 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
3313}
3314
John McCall7ba107a2009-11-18 02:36:19 +00003315static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
3316 UsingDecl *Instance,
3317 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00003318 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCall7ba107a2009-11-18 02:36:19 +00003319}
3320
3321static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson0d8df782009-08-29 19:37:28 +00003322 UsingDecl *Instance,
3323 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00003324 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00003325}
3326
John McCall52a575a2009-08-29 08:11:13 +00003327static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
3328 VarDecl *Instance) {
3329 assert(Instance->isStaticDataMember());
3330
3331 Pattern = Pattern->getCanonicalDecl();
3332
3333 do {
3334 Instance = Instance->getCanonicalDecl();
3335 if (Pattern == Instance) return true;
3336 Instance = Instance->getInstantiatedFromStaticDataMember();
3337 } while (Instance);
3338
3339 return false;
3340}
3341
John McCalled976492009-12-04 22:46:56 +00003342// Other is the prospective instantiation
3343// D is the prospective pattern
Douglas Gregor815215d2009-05-27 05:35:12 +00003344static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00003345 if (D->getKind() != Other->getKind()) {
John McCall7ba107a2009-11-18 02:36:19 +00003346 if (UnresolvedUsingTypenameDecl *UUD
3347 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3348 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
3349 return isInstantiationOf(UUD, UD, Ctx);
3350 }
3351 }
3352
3353 if (UnresolvedUsingValueDecl *UUD
3354 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00003355 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
3356 return isInstantiationOf(UUD, UD, Ctx);
3357 }
3358 }
Douglas Gregor815215d2009-05-27 05:35:12 +00003359
Anders Carlsson0d8df782009-08-29 19:37:28 +00003360 return false;
3361 }
Mike Stump1eb44332009-09-09 15:08:12 +00003362
John McCall52a575a2009-08-29 08:11:13 +00003363 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
3364 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00003365
John McCall52a575a2009-08-29 08:11:13 +00003366 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
3367 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00003368
John McCall52a575a2009-08-29 08:11:13 +00003369 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
3370 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00003371
Douglas Gregor7caa6822009-07-24 20:34:43 +00003372 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00003373 if (Var->isStaticDataMember())
3374 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
3375
3376 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
3377 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00003378
Douglas Gregor0d696532009-09-28 06:34:35 +00003379 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
3380 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
3381
Douglas Gregored9c0f92009-10-29 00:04:11 +00003382 if (ClassTemplatePartialSpecializationDecl *PartialSpec
3383 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
3384 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
3385 PartialSpec);
3386
Anders Carlssond8b285f2009-09-01 04:26:58 +00003387 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
3388 if (!Field->getDeclName()) {
3389 // This is an unnamed field.
Mike Stump1eb44332009-09-09 15:08:12 +00003390 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlssond8b285f2009-09-01 04:26:58 +00003391 cast<FieldDecl>(D);
3392 }
3393 }
Mike Stump1eb44332009-09-09 15:08:12 +00003394
John McCalled976492009-12-04 22:46:56 +00003395 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
3396 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
3397
3398 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
3399 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
3400
Douglas Gregor815215d2009-05-27 05:35:12 +00003401 return D->getDeclName() && isa<NamedDecl>(Other) &&
3402 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
3403}
3404
3405template<typename ForwardIterator>
Mike Stump1eb44332009-09-09 15:08:12 +00003406static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor815215d2009-05-27 05:35:12 +00003407 NamedDecl *D,
3408 ForwardIterator first,
3409 ForwardIterator last) {
3410 for (; first != last; ++first)
3411 if (isInstantiationOf(Ctx, D, *first))
3412 return cast<NamedDecl>(*first);
3413
3414 return 0;
3415}
3416
John McCall02cace72009-08-28 07:59:38 +00003417/// \brief Finds the instantiation of the given declaration context
3418/// within the current instantiation.
3419///
3420/// \returns NULL if there was an error
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003421DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
Douglas Gregore95b4092009-09-16 18:34:49 +00003422 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCall02cace72009-08-28 07:59:38 +00003423 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003424 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +00003425 return cast_or_null<DeclContext>(ID);
3426 } else return DC;
3427}
3428
Douglas Gregored961e72009-05-27 17:54:46 +00003429/// \brief Find the instantiation of the given declaration within the
3430/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00003431///
3432/// This routine is intended to be used when \p D is a declaration
3433/// referenced from within a template, that needs to mapped into the
3434/// corresponding declaration within an instantiation. For example,
3435/// given:
3436///
3437/// \code
3438/// template<typename T>
3439/// struct X {
3440/// enum Kind {
3441/// KnownValue = sizeof(T)
3442/// };
3443///
3444/// bool getKind() const { return KnownValue; }
3445/// };
3446///
3447/// template struct X<int>;
3448/// \endcode
3449///
3450/// In the instantiation of X<int>::getKind(), we need to map the
3451/// EnumConstantDecl for KnownValue (which refers to
James Dennettf198d122012-06-17 03:36:08 +00003452/// X<T>::\<Kind>\::KnownValue) to its instantiation
James Dennettef2b5b32012-06-15 22:23:43 +00003453/// (X<int>::\<Kind>\::KnownValue). InstantiateCurrentDeclRef() performs
Douglas Gregored961e72009-05-27 17:54:46 +00003454/// this mapping from within the instantiation of X<int>.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003455NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
Douglas Gregore95b4092009-09-16 18:34:49 +00003456 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor815215d2009-05-27 05:35:12 +00003457 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor550d9b22009-10-31 17:21:17 +00003458 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
Douglas Gregor6d3e6272010-02-05 19:54:12 +00003459 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
Douglas Gregor7bdc1522012-02-16 21:36:18 +00003460 (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext()) ||
3461 (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) {
Douglas Gregor2bba76b2009-05-27 17:07:49 +00003462 // D is a local of some kind. Look into the map of local
3463 // declarations to their instantiations.
Chris Lattnerd8e54992011-02-17 19:47:42 +00003464 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
3465 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
3466 = CurrentInstantiationScope->findInstantiationOf(D);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003467
Chris Lattner57ad3782011-02-17 20:34:02 +00003468 if (Found) {
3469 if (Decl *FD = Found->dyn_cast<Decl *>())
3470 return cast<NamedDecl>(FD);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003471
Richard Smith9a4db032012-09-12 00:56:43 +00003472 int PackIdx = ArgumentPackSubstitutionIndex;
3473 assert(PackIdx != -1 && "found declaration pack but not pack expanding");
Chris Lattner57ad3782011-02-17 20:34:02 +00003474 return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
3475 }
3476
3477 // If we didn't find the decl, then we must have a label decl that hasn't
3478 // been found yet. Lazily instantiate it and return it now.
3479 assert(isa<LabelDecl>(D));
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003480
Chris Lattner57ad3782011-02-17 20:34:02 +00003481 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
3482 assert(Inst && "Failed to instantiate label??");
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003483
Chris Lattner57ad3782011-02-17 20:34:02 +00003484 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
3485 return cast<LabelDecl>(Inst);
Douglas Gregor2bba76b2009-05-27 17:07:49 +00003486 }
Douglas Gregor815215d2009-05-27 05:35:12 +00003487
Douglas Gregore95b4092009-09-16 18:34:49 +00003488 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
3489 if (!Record->isDependentContext())
3490 return D;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003491
Douglas Gregor2c1227c2011-11-07 17:43:18 +00003492 // Determine whether this record is the "templated" declaration describing
3493 // a class template or class template partial specialization.
Douglas Gregore95b4092009-09-16 18:34:49 +00003494 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
Douglas Gregor2c1227c2011-11-07 17:43:18 +00003495 if (ClassTemplate)
3496 ClassTemplate = ClassTemplate->getCanonicalDecl();
3497 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
3498 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
3499 ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
3500
3501 // Walk the current context to find either the record or an instantiation of
3502 // it.
3503 DeclContext *DC = CurContext;
3504 while (!DC->isFileContext()) {
3505 // If we're performing substitution while we're inside the template
3506 // definition, we'll find our own context. We're done.
3507 if (DC->Equals(Record))
3508 return Record;
3509
3510 if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
3511 // Check whether we're in the process of instantiating a class template
3512 // specialization of the template we're mapping.
3513 if (ClassTemplateSpecializationDecl *InstSpec
3514 = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
3515 ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
3516 if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
3517 return InstRecord;
3518 }
3519
3520 // Check whether we're in the process of instantiating a member class.
3521 if (isInstantiationOf(Record, InstRecord))
3522 return InstRecord;
Douglas Gregore95b4092009-09-16 18:34:49 +00003523 }
Douglas Gregor2c1227c2011-11-07 17:43:18 +00003524
3525
3526 // Move to the outer template scope.
3527 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
3528 if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){
3529 DC = FD->getLexicalDeclContext();
3530 continue;
3531 }
John McCall52a575a2009-08-29 08:11:13 +00003532 }
Douglas Gregor2c1227c2011-11-07 17:43:18 +00003533
3534 DC = DC->getParent();
John McCall52a575a2009-08-29 08:11:13 +00003535 }
Douglas Gregor8b013bd2010-02-05 22:40:03 +00003536
Douglas Gregore95b4092009-09-16 18:34:49 +00003537 // Fall through to deal with other dependent record types (e.g.,
3538 // anonymous unions in class templates).
3539 }
John McCall52a575a2009-08-29 08:11:13 +00003540
Douglas Gregore95b4092009-09-16 18:34:49 +00003541 if (!ParentDC->isDependentContext())
3542 return D;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003543
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003544 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00003545 if (!ParentDC)
Douglas Gregor44c73842009-09-01 17:53:10 +00003546 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003547
Douglas Gregor815215d2009-05-27 05:35:12 +00003548 if (ParentDC != D->getDeclContext()) {
3549 // We performed some kind of instantiation in the parent context,
3550 // so now we need to look into the instantiated parent context to
3551 // find the instantiation of the declaration D.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003552
John McCall3cb0ebd2010-03-10 03:28:59 +00003553 // If our context used to be dependent, we may need to instantiate
3554 // it before performing lookup into that context.
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00003555 bool IsBeingInstantiated = false;
John McCall3cb0ebd2010-03-10 03:28:59 +00003556 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003557 if (!Spec->isDependentContext()) {
3558 QualType T = Context.getTypeDeclType(Spec);
John McCall3cb0ebd2010-03-10 03:28:59 +00003559 const RecordType *Tag = T->getAs<RecordType>();
3560 assert(Tag && "type of non-dependent record is not a RecordType");
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00003561 if (Tag->isBeingDefined())
3562 IsBeingInstantiated = true;
John McCall3cb0ebd2010-03-10 03:28:59 +00003563 if (!Tag->isBeingDefined() &&
3564 RequireCompleteType(Loc, T, diag::err_incomplete_type))
3565 return 0;
Douglas Gregora43064c2010-11-05 23:22:45 +00003566
3567 ParentDC = Tag->getDecl();
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003568 }
3569 }
3570
Douglas Gregor815215d2009-05-27 05:35:12 +00003571 NamedDecl *Result = 0;
3572 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003573 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
David Blaikie3bc93e32012-12-19 00:45:41 +00003574 Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
Douglas Gregor815215d2009-05-27 05:35:12 +00003575 } else {
3576 // Since we don't have a name for the entity we're looking for,
3577 // our only option is to walk through all of the declarations to
3578 // find that name. This will occur in a few cases:
3579 //
3580 // - anonymous struct/union within a template
3581 // - unnamed class/struct/union/enum within a template
3582 //
3583 // FIXME: Find a better way to find these instantiations!
Mike Stump1eb44332009-09-09 15:08:12 +00003584 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003585 ParentDC->decls_begin(),
3586 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00003587 }
Mike Stump1eb44332009-09-09 15:08:12 +00003588
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00003589 if (!Result) {
3590 if (isa<UsingShadowDecl>(D)) {
3591 // UsingShadowDecls can instantiate to nothing because of using hiding.
3592 } else if (Diags.hasErrorOccurred()) {
3593 // We've already complained about something, so most likely this
3594 // declaration failed to instantiate. There's no point in complaining
3595 // further, since this is normal in invalid code.
3596 } else if (IsBeingInstantiated) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003597 // The class in which this member exists is currently being
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00003598 // instantiated, and we haven't gotten around to instantiating this
3599 // member yet. This can happen when the code uses forward declarations
3600 // of member classes, and introduces ordering dependencies via
3601 // template instantiation.
3602 Diag(Loc, diag::err_member_not_yet_instantiated)
3603 << D->getDeclName()
3604 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
3605 Diag(D->getLocation(), diag::note_non_instantiated_member_here);
Richard Smith0724b7c2012-03-26 20:28:16 +00003606 } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
3607 // This enumeration constant was found when the template was defined,
3608 // but can't be found in the instantiation. This can happen if an
3609 // unscoped enumeration member is explicitly specialized.
3610 EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
3611 EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
3612 TemplateArgs));
3613 assert(Spec->getTemplateSpecializationKind() ==
3614 TSK_ExplicitSpecialization);
3615 Diag(Loc, diag::err_enumerator_does_not_exist)
3616 << D->getDeclName()
3617 << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
3618 Diag(Spec->getLocation(), diag::note_enum_specialized_here)
3619 << Context.getTypeDeclType(Spec);
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00003620 } else {
3621 // We should have found something, but didn't.
3622 llvm_unreachable("Unable to find instantiation of declaration!");
3623 }
3624 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003625
Douglas Gregor815215d2009-05-27 05:35:12 +00003626 D = Result;
3627 }
3628
Douglas Gregor815215d2009-05-27 05:35:12 +00003629 return D;
3630}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003631
Mike Stump1eb44332009-09-09 15:08:12 +00003632/// \brief Performs template instantiation for all implicit template
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003633/// instantiations we have seen until this point.
Nick Lewycky81559102011-05-31 07:58:42 +00003634void Sema::PerformPendingInstantiations(bool LocalOnly) {
Douglas Gregor6e4a3f52011-07-28 19:49:54 +00003635 // Load pending instantiations from the external source.
3636 if (!LocalOnly && ExternalSource) {
Richard Smithb9d0b762012-07-27 04:22:15 +00003637 SmallVector<PendingImplicitInstantiation, 4> Pending;
Douglas Gregor6e4a3f52011-07-28 19:49:54 +00003638 ExternalSource->ReadPendingInstantiations(Pending);
3639 PendingInstantiations.insert(PendingInstantiations.begin(),
3640 Pending.begin(), Pending.end());
3641 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003642
Douglas Gregor60406be2010-01-16 22:29:39 +00003643 while (!PendingLocalImplicitInstantiations.empty() ||
Chandler Carruth62c78d52010-08-25 08:44:16 +00003644 (!LocalOnly && !PendingInstantiations.empty())) {
Douglas Gregor60406be2010-01-16 22:29:39 +00003645 PendingImplicitInstantiation Inst;
3646
3647 if (PendingLocalImplicitInstantiations.empty()) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00003648 Inst = PendingInstantiations.front();
3649 PendingInstantiations.pop_front();
Douglas Gregor60406be2010-01-16 22:29:39 +00003650 } else {
3651 Inst = PendingLocalImplicitInstantiations.front();
3652 PendingLocalImplicitInstantiations.pop_front();
3653 }
Mike Stump1eb44332009-09-09 15:08:12 +00003654
Douglas Gregor7caa6822009-07-24 20:34:43 +00003655 // Instantiate function definitions
3656 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
John McCallf312b1e2010-08-26 23:41:50 +00003657 PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(),
3658 "instantiating function definition");
Chandler Carruth58e390e2010-08-25 08:27:02 +00003659 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
3660 TSK_ExplicitInstantiationDefinition;
3661 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true,
3662 DefinitionRequired);
Douglas Gregor7caa6822009-07-24 20:34:43 +00003663 continue;
3664 }
Mike Stump1eb44332009-09-09 15:08:12 +00003665
Douglas Gregor7caa6822009-07-24 20:34:43 +00003666 // Instantiate static data member definitions.
3667 VarDecl *Var = cast<VarDecl>(Inst.first);
3668 assert(Var->isStaticDataMember() && "Not a static data member?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00003669
Chandler Carruth291b4412010-02-13 10:17:50 +00003670 // Don't try to instantiate declarations if the most recent redeclaration
3671 // is invalid.
Douglas Gregoref96ee02012-01-14 16:38:05 +00003672 if (Var->getMostRecentDecl()->isInvalidDecl())
Chandler Carruth291b4412010-02-13 10:17:50 +00003673 continue;
3674
3675 // Check if the most recent declaration has changed the specialization kind
3676 // and removed the need for implicit instantiation.
Douglas Gregoref96ee02012-01-14 16:38:05 +00003677 switch (Var->getMostRecentDecl()->getTemplateSpecializationKind()) {
Chandler Carruth291b4412010-02-13 10:17:50 +00003678 case TSK_Undeclared:
David Blaikieb219cfc2011-09-23 05:06:16 +00003679 llvm_unreachable("Cannot instantitiate an undeclared specialization.");
Chandler Carruth291b4412010-02-13 10:17:50 +00003680 case TSK_ExplicitInstantiationDeclaration:
Chandler Carruth291b4412010-02-13 10:17:50 +00003681 case TSK_ExplicitSpecialization:
Chandler Carruth58e390e2010-08-25 08:27:02 +00003682 continue; // No longer need to instantiate this type.
3683 case TSK_ExplicitInstantiationDefinition:
3684 // We only need an instantiation if the pending instantiation *is* the
3685 // explicit instantiation.
Douglas Gregoref96ee02012-01-14 16:38:05 +00003686 if (Var != Var->getMostRecentDecl()) continue;
Chandler Carruth291b4412010-02-13 10:17:50 +00003687 case TSK_ImplicitInstantiation:
3688 break;
3689 }
3690
John McCallf312b1e2010-08-26 23:41:50 +00003691 PrettyDeclStackTraceEntry CrashInfo(*this, Var, Var->getLocation(),
3692 "instantiating static data member "
3693 "definition");
Mike Stump1eb44332009-09-09 15:08:12 +00003694
Chandler Carruth58e390e2010-08-25 08:27:02 +00003695 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
3696 TSK_ExplicitInstantiationDefinition;
3697 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true,
3698 DefinitionRequired);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003699 }
3700}
John McCall0c01d182010-03-24 05:22:00 +00003701
3702void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
3703 const MultiLevelTemplateArgumentList &TemplateArgs) {
3704 for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(),
3705 E = Pattern->ddiag_end(); I != E; ++I) {
3706 DependentDiagnostic *DD = *I;
3707
3708 switch (DD->getKind()) {
3709 case DependentDiagnostic::Access:
3710 HandleDependentAccessCheck(*DD, TemplateArgs);
3711 break;
3712 }
3713 }
3714}