blob: 688a7360ad73244a25032e686c32ad3296d0d36a [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());
Richard Smith38afbc72013-04-13 02:43:54 +0000342 Var->setTLSKind(D->getTLSKind());
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
John McCall76da55d2013-04-16 07:28:30 +0000528Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) {
529 bool Invalid = false;
530 TypeSourceInfo *DI = D->getTypeSourceInfo();
531
532 if (DI->getType()->isVariablyModifiedType()) {
533 SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified)
534 << D->getName();
535 Invalid = true;
536 } else if (DI->getType()->isInstantiationDependentType()) {
537 DI = SemaRef.SubstType(DI, TemplateArgs,
538 D->getLocation(), D->getDeclName());
539 if (!DI) {
540 DI = D->getTypeSourceInfo();
541 Invalid = true;
542 } else if (DI->getType()->isFunctionType()) {
543 // C++ [temp.arg.type]p3:
544 // If a declaration acquires a function type through a type
545 // dependent on a template-parameter and this causes a
546 // declaration that does not use the syntactic form of a
547 // function declarator to have function type, the program is
548 // ill-formed.
549 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
550 << DI->getType();
551 Invalid = true;
552 }
553 } else {
554 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
555 }
556
557 MSPropertyDecl *Property = new (SemaRef.Context)
558 MSPropertyDecl(Owner, D->getLocation(),
559 D->getDeclName(), DI->getType(), DI,
560 D->getLocStart(),
561 D->getGetterId(), D->getSetterId());
562
563 SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs,
564 StartingScope);
565
566 if (Invalid)
567 Property->setInvalidDecl();
568
569 Property->setAccess(D->getAccess());
570 Owner->addDecl(Property);
571
572 return Property;
573}
574
Francois Pichet87c2e122010-11-21 06:08:52 +0000575Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
576 NamedDecl **NamedChain =
577 new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
578
579 int i = 0;
580 for (IndirectFieldDecl::chain_iterator PI =
581 D->chain_begin(), PE = D->chain_end();
Douglas Gregorb7107222011-03-04 19:46:35 +0000582 PI != PE; ++PI) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000583 NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), *PI,
Douglas Gregorb7107222011-03-04 19:46:35 +0000584 TemplateArgs);
585 if (!Next)
586 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000587
Douglas Gregorb7107222011-03-04 19:46:35 +0000588 NamedChain[i++] = Next;
589 }
Francois Pichet87c2e122010-11-21 06:08:52 +0000590
Francois Pichet40e17752010-12-09 10:07:54 +0000591 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
Francois Pichet87c2e122010-11-21 06:08:52 +0000592 IndirectFieldDecl* IndirectField
593 = IndirectFieldDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Francois Pichet40e17752010-12-09 10:07:54 +0000594 D->getIdentifier(), T,
Francois Pichet87c2e122010-11-21 06:08:52 +0000595 NamedChain, D->getChainingSize());
596
597
598 IndirectField->setImplicit(D->isImplicit());
599 IndirectField->setAccess(D->getAccess());
600 Owner->addDecl(IndirectField);
601 return IndirectField;
602}
603
John McCall02cace72009-08-28 07:59:38 +0000604Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
John McCall02cace72009-08-28 07:59:38 +0000605 // Handle friend type expressions by simply substituting template
Douglas Gregor06245bf2010-04-07 17:57:12 +0000606 // parameters into the pattern type and checking the result.
John McCall32f2fb52010-03-25 18:04:51 +0000607 if (TypeSourceInfo *Ty = D->getFriendType()) {
Chandler Carruth4fb86f82011-05-01 00:51:33 +0000608 TypeSourceInfo *InstTy;
609 // If this is an unsupported friend, don't bother substituting template
610 // arguments into it. The actual type referred to won't be used by any
611 // parts of Clang, and may not be valid for instantiating. Just use the
612 // same info for the instantiated friend.
613 if (D->isUnsupportedFriend()) {
614 InstTy = Ty;
615 } else {
616 InstTy = SemaRef.SubstType(Ty, TemplateArgs,
617 D->getLocation(), DeclarationName());
618 }
619 if (!InstTy)
Douglas Gregor7557a132009-12-24 20:56:24 +0000620 return 0;
John McCall02cace72009-08-28 07:59:38 +0000621
Richard Smithd6f80da2012-09-20 01:31:00 +0000622 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getLocStart(),
Abramo Bagnara0216df82011-10-29 20:52:52 +0000623 D->getFriendLoc(), InstTy);
Douglas Gregor06245bf2010-04-07 17:57:12 +0000624 if (!FD)
625 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000626
Douglas Gregor06245bf2010-04-07 17:57:12 +0000627 FD->setAccess(AS_public);
John McCall9a34edb2010-10-19 01:40:49 +0000628 FD->setUnsupportedFriend(D->isUnsupportedFriend());
Douglas Gregor06245bf2010-04-07 17:57:12 +0000629 Owner->addDecl(FD);
630 return FD;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000631 }
632
Douglas Gregor06245bf2010-04-07 17:57:12 +0000633 NamedDecl *ND = D->getFriendDecl();
634 assert(ND && "friend decl must be a decl or a type!");
635
John McCallaf2094e2010-04-08 09:05:18 +0000636 // All of the Visit implementations for the various potential friend
637 // declarations have to be carefully written to work for friend
638 // objects, with the most important detail being that the target
639 // decl should almost certainly not be placed in Owner.
640 Decl *NewND = Visit(ND);
Douglas Gregor06245bf2010-04-07 17:57:12 +0000641 if (!NewND) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000642
John McCall02cace72009-08-28 07:59:38 +0000643 FriendDecl *FD =
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000644 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor06245bf2010-04-07 17:57:12 +0000645 cast<NamedDecl>(NewND), D->getFriendLoc());
John McCall5fee1102009-08-29 03:50:18 +0000646 FD->setAccess(AS_public);
John McCall9a34edb2010-10-19 01:40:49 +0000647 FD->setUnsupportedFriend(D->isUnsupportedFriend());
John McCall02cace72009-08-28 07:59:38 +0000648 Owner->addDecl(FD);
649 return FD;
John McCallfd810b12009-08-14 02:03:10 +0000650}
651
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000652Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
653 Expr *AssertExpr = D->getAssertExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000654
Richard Smithf6702a32011-12-20 02:08:33 +0000655 // The expression in a static assertion is a constant expression.
656 EnterExpressionEvaluationContext Unevaluated(SemaRef,
657 Sema::ConstantEvaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000658
John McCall60d7b3a2010-08-24 06:29:42 +0000659 ExprResult InstantiatedAssertExpr
John McCallce3ff2b2009-08-25 22:02:44 +0000660 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000661 if (InstantiatedAssertExpr.isInvalid())
662 return 0;
663
Richard Smithe3f470a2012-07-11 22:37:56 +0000664 return SemaRef.BuildStaticAssertDeclaration(D->getLocation(),
John McCall9ae2f072010-08-23 23:25:46 +0000665 InstantiatedAssertExpr.get(),
Richard Smithe3f470a2012-07-11 22:37:56 +0000666 D->getMessage(),
667 D->getRParenLoc(),
668 D->isFailed());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000669}
670
671Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Richard Smith38f0df32012-03-26 04:58:10 +0000672 EnumDecl *PrevDecl = 0;
673 if (D->getPreviousDecl()) {
674 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
675 D->getPreviousDecl(),
676 TemplateArgs);
677 if (!Prev) return 0;
678 PrevDecl = cast<EnumDecl>(Prev);
679 }
680
Abramo Bagnaraba877ad2011-03-09 14:09:51 +0000681 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000682 D->getLocation(), D->getIdentifier(),
Richard Smith38f0df32012-03-26 04:58:10 +0000683 PrevDecl, D->isScoped(),
Abramo Bagnaraa88cefd2010-12-03 18:54:17 +0000684 D->isScopedUsingClassTag(), D->isFixed());
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000685 if (D->isFixed()) {
Richard Smithf1c66b42012-03-14 23:13:10 +0000686 if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000687 // If we have type source information for the underlying type, it means it
688 // has been explicitly set by the user. Perform substitution on it before
689 // moving on.
690 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
Richard Smithf1c66b42012-03-14 23:13:10 +0000691 TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
692 DeclarationName());
693 if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000694 Enum->setIntegerType(SemaRef.Context.IntTy);
Richard Smithf1c66b42012-03-14 23:13:10 +0000695 else
696 Enum->setIntegerTypeSourceInfo(NewTI);
697 } else {
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000698 assert(!D->getIntegerType()->isDependentType()
699 && "Dependent type without type source info");
700 Enum->setIntegerType(D->getIntegerType());
701 }
702 }
703
John McCall5b629aa2010-10-22 23:36:17 +0000704 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
705
Richard Smithf1c66b42012-03-14 23:13:10 +0000706 Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000707 Enum->setAccess(D->getAccess());
John McCallb6217662010-03-15 10:12:16 +0000708 if (SubstQualifier(D, Enum)) return 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000709 Owner->addDecl(Enum);
Richard Smithf1c66b42012-03-14 23:13:10 +0000710
Richard Smith4ca93d92012-03-26 04:08:46 +0000711 EnumDecl *Def = D->getDefinition();
712 if (Def && Def != D) {
713 // If this is an out-of-line definition of an enum member template, check
714 // that the underlying types match in the instantiation of both
715 // declarations.
716 if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
717 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
718 QualType DefnUnderlying =
719 SemaRef.SubstType(TI->getType(), TemplateArgs,
720 UnderlyingLoc, DeclarationName());
721 SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
722 DefnUnderlying, Enum);
723 }
724 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000725
Douglas Gregor96084f12010-03-01 19:00:07 +0000726 if (D->getDeclContext()->isFunctionOrMethod())
727 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000728
Richard Smithf1c66b42012-03-14 23:13:10 +0000729 // C++11 [temp.inst]p1: The implicit instantiation of a class template
730 // specialization causes the implicit instantiation of the declarations, but
731 // not the definitions of scoped member enumerations.
732 // FIXME: There appears to be no wording for what happens for an enum defined
Richard Smith38f0df32012-03-26 04:58:10 +0000733 // within a block scope, but we treat that much like a member template. Only
734 // instantiate the definition when visiting the definition in that case, since
735 // we will visit all redeclarations.
736 if (!Enum->isScoped() && Def &&
737 (!D->getDeclContext()->isFunctionOrMethod() || D->isCompleteDefinition()))
Richard Smith4ca93d92012-03-26 04:08:46 +0000738 InstantiateEnumDefinition(Enum, Def);
Richard Smithf1c66b42012-03-14 23:13:10 +0000739
740 return Enum;
741}
742
743void TemplateDeclInstantiator::InstantiateEnumDefinition(
744 EnumDecl *Enum, EnumDecl *Pattern) {
745 Enum->startDefinition();
746
Richard Smith1af83c42012-03-23 03:33:32 +0000747 // Update the location to refer to the definition.
748 Enum->setLocation(Pattern->getLocation());
749
Chris Lattner5f9e2722011-07-23 10:55:15 +0000750 SmallVector<Decl*, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000751
752 EnumConstantDecl *LastEnumConst = 0;
Richard Smithf1c66b42012-03-14 23:13:10 +0000753 for (EnumDecl::enumerator_iterator EC = Pattern->enumerator_begin(),
754 ECEnd = Pattern->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000755 EC != ECEnd; ++EC) {
756 // The specified value for the enumerator.
John McCall60d7b3a2010-08-24 06:29:42 +0000757 ExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000758 if (Expr *UninstValue = EC->getInitExpr()) {
Richard Smithf6702a32011-12-20 02:08:33 +0000759 // The enumerator's value expression is a constant expression.
Mike Stump1eb44332009-09-09 15:08:12 +0000760 EnterExpressionEvaluationContext Unevaluated(SemaRef,
Richard Smithf6702a32011-12-20 02:08:33 +0000761 Sema::ConstantEvaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000762
John McCallce3ff2b2009-08-25 22:02:44 +0000763 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000764 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000765
766 // Drop the initial value and continue.
767 bool isInvalid = false;
768 if (Value.isInvalid()) {
769 Value = SemaRef.Owned((Expr *)0);
770 isInvalid = true;
771 }
772
Mike Stump1eb44332009-09-09 15:08:12 +0000773 EnumConstantDecl *EnumConst
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000774 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
775 EC->getLocation(), EC->getIdentifier(),
John McCall9ae2f072010-08-23 23:25:46 +0000776 Value.get());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000777
778 if (isInvalid) {
779 if (EnumConst)
780 EnumConst->setInvalidDecl();
781 Enum->setInvalidDecl();
782 }
783
784 if (EnumConst) {
David Blaikie581deb32012-06-06 20:45:41 +0000785 SemaRef.InstantiateAttrs(TemplateArgs, *EC, EnumConst);
John McCall5b629aa2010-10-22 23:36:17 +0000786
John McCall3b85ecf2010-01-23 22:37:59 +0000787 EnumConst->setAccess(Enum->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000788 Enum->addDecl(EnumConst);
John McCalld226f652010-08-21 09:40:31 +0000789 Enumerators.push_back(EnumConst);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000790 LastEnumConst = EnumConst;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000791
Richard Smithf1c66b42012-03-14 23:13:10 +0000792 if (Pattern->getDeclContext()->isFunctionOrMethod() &&
793 !Enum->isScoped()) {
Douglas Gregor96084f12010-03-01 19:00:07 +0000794 // If the enumeration is within a function or method, record the enum
795 // constant as a local.
David Blaikie581deb32012-06-06 20:45:41 +0000796 SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst);
Douglas Gregor96084f12010-03-01 19:00:07 +0000797 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000798 }
799 }
Mike Stump1eb44332009-09-09 15:08:12 +0000800
Richard Smithf1c66b42012-03-14 23:13:10 +0000801 // FIXME: Fixup LBraceLoc
802 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(),
803 Enum->getRBraceLoc(), Enum,
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +0000804 Enumerators,
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000805 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000806}
807
Douglas Gregor6477b692009-03-25 15:04:13 +0000808Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000809 llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
Douglas Gregor6477b692009-03-25 15:04:13 +0000810}
811
John McCalle29ba202009-08-20 01:44:21 +0000812Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
John McCall93ba8572010-03-25 06:39:04 +0000813 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
814
Douglas Gregor550d9b22009-10-31 17:21:17 +0000815 // Create a local instantiation scope for this class template, which
816 // will contain the instantiations of the template parameters.
John McCall2a7fb272010-08-25 05:32:35 +0000817 LocalInstantiationScope Scope(SemaRef);
John McCalle29ba202009-08-20 01:44:21 +0000818 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000819 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000820 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000821 return NULL;
John McCalle29ba202009-08-20 01:44:21 +0000822
823 CXXRecordDecl *Pattern = D->getTemplatedDecl();
John McCall93ba8572010-03-25 06:39:04 +0000824
825 // Instantiate the qualifier. We have to do this first in case
826 // we're a friend declaration, because if we are then we need to put
827 // the new declaration in the appropriate context.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000828 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
829 if (QualifierLoc) {
830 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
831 TemplateArgs);
832 if (!QualifierLoc)
833 return 0;
John McCall93ba8572010-03-25 06:39:04 +0000834 }
835
836 CXXRecordDecl *PrevDecl = 0;
837 ClassTemplateDecl *PrevClassTemplate = 0;
838
Douglas Gregoref96ee02012-01-14 16:38:05 +0000839 if (!isFriend && Pattern->getPreviousDecl()) {
Nick Lewycky37574f52010-11-08 23:29:42 +0000840 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
David Blaikie3bc93e32012-12-19 00:45:41 +0000841 if (!Found.empty()) {
842 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
Nick Lewycky37574f52010-11-08 23:29:42 +0000843 if (PrevClassTemplate)
844 PrevDecl = PrevClassTemplate->getTemplatedDecl();
845 }
846 }
847
John McCall93ba8572010-03-25 06:39:04 +0000848 // If this isn't a friend, then it's a member template, in which
849 // case we just want to build the instantiation in the
850 // specialization. If it is a friend, we want to build it in
851 // the appropriate context.
852 DeclContext *DC = Owner;
853 if (isFriend) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000854 if (QualifierLoc) {
John McCall93ba8572010-03-25 06:39:04 +0000855 CXXScopeSpec SS;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000856 SS.Adopt(QualifierLoc);
John McCall93ba8572010-03-25 06:39:04 +0000857 DC = SemaRef.computeDeclContext(SS);
858 if (!DC) return 0;
859 } else {
860 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
861 Pattern->getDeclContext(),
862 TemplateArgs);
863 }
864
865 // Look for a previous declaration of the template in the owning
866 // context.
867 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
868 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
869 SemaRef.LookupQualifiedName(R, DC);
870
871 if (R.isSingleResult()) {
872 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
873 if (PrevClassTemplate)
874 PrevDecl = PrevClassTemplate->getTemplatedDecl();
875 }
876
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000877 if (!PrevClassTemplate && QualifierLoc) {
John McCall93ba8572010-03-25 06:39:04 +0000878 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
Douglas Gregor1eabb7d2010-03-31 23:17:41 +0000879 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000880 << QualifierLoc.getSourceRange();
John McCall93ba8572010-03-25 06:39:04 +0000881 return 0;
882 }
883
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000884 bool AdoptedPreviousTemplateParams = false;
John McCall93ba8572010-03-25 06:39:04 +0000885 if (PrevClassTemplate) {
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000886 bool Complain = true;
887
888 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
889 // template for struct std::tr1::__detail::_Map_base, where the
890 // template parameters of the friend declaration don't match the
891 // template parameters of the original declaration. In this one
892 // case, we don't complain about the ill-formed friend
893 // declaration.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000894 if (isFriend && Pattern->getIdentifier() &&
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000895 Pattern->getIdentifier()->isStr("_Map_base") &&
896 DC->isNamespace() &&
897 cast<NamespaceDecl>(DC)->getIdentifier() &&
898 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
899 DeclContext *DCParent = DC->getParent();
900 if (DCParent->isNamespace() &&
901 cast<NamespaceDecl>(DCParent)->getIdentifier() &&
902 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
903 DeclContext *DCParent2 = DCParent->getParent();
904 if (DCParent2->isNamespace() &&
905 cast<NamespaceDecl>(DCParent2)->getIdentifier() &&
906 cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") &&
907 DCParent2->getParent()->isTranslationUnit())
908 Complain = false;
909 }
910 }
911
John McCall93ba8572010-03-25 06:39:04 +0000912 TemplateParameterList *PrevParams
913 = PrevClassTemplate->getTemplateParameters();
914
915 // Make sure the parameter lists match.
916 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000917 Complain,
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000918 Sema::TPL_TemplateMatch)) {
919 if (Complain)
920 return 0;
921
922 AdoptedPreviousTemplateParams = true;
923 InstParams = PrevParams;
924 }
John McCall93ba8572010-03-25 06:39:04 +0000925
926 // Do some additional validation, then merge default arguments
927 // from the existing declarations.
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000928 if (!AdoptedPreviousTemplateParams &&
929 SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
John McCall93ba8572010-03-25 06:39:04 +0000930 Sema::TPC_ClassTemplate))
931 return 0;
932 }
933 }
934
John McCalle29ba202009-08-20 01:44:21 +0000935 CXXRecordDecl *RecordInst
John McCall93ba8572010-03-25 06:39:04 +0000936 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +0000937 Pattern->getLocStart(), Pattern->getLocation(),
938 Pattern->getIdentifier(), PrevDecl,
Douglas Gregorf0510d42009-10-12 23:11:44 +0000939 /*DelayTypeCreation=*/true);
John McCalle29ba202009-08-20 01:44:21 +0000940
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000941 if (QualifierLoc)
942 RecordInst->setQualifierInfo(QualifierLoc);
John McCallb6217662010-03-15 10:12:16 +0000943
John McCalle29ba202009-08-20 01:44:21 +0000944 ClassTemplateDecl *Inst
John McCall93ba8572010-03-25 06:39:04 +0000945 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
946 D->getIdentifier(), InstParams, RecordInst,
947 PrevClassTemplate);
John McCalle29ba202009-08-20 01:44:21 +0000948 RecordInst->setDescribedClassTemplate(Inst);
John McCallea7390c2010-04-08 20:25:50 +0000949
John McCall93ba8572010-03-25 06:39:04 +0000950 if (isFriend) {
John McCallea7390c2010-04-08 20:25:50 +0000951 if (PrevClassTemplate)
952 Inst->setAccess(PrevClassTemplate->getAccess());
953 else
954 Inst->setAccess(D->getAccess());
955
John McCall93ba8572010-03-25 06:39:04 +0000956 Inst->setObjectOfFriendDecl(PrevClassTemplate != 0);
957 // TODO: do we want to track the instantiation progeny of this
958 // friend target decl?
959 } else {
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000960 Inst->setAccess(D->getAccess());
Nick Lewycky37574f52010-11-08 23:29:42 +0000961 if (!PrevClassTemplate)
962 Inst->setInstantiatedFromMemberTemplate(D);
John McCall93ba8572010-03-25 06:39:04 +0000963 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000964
Douglas Gregorf0510d42009-10-12 23:11:44 +0000965 // Trigger creation of the type for the instantiation.
John McCall3cb0ebd2010-03-10 03:28:59 +0000966 SemaRef.Context.getInjectedClassNameType(RecordInst,
Douglas Gregor24bae922010-07-08 18:37:38 +0000967 Inst->getInjectedClassNameSpecialization());
John McCallea7390c2010-04-08 20:25:50 +0000968
Douglas Gregor259571e2009-10-30 22:42:42 +0000969 // Finish handling of friends.
John McCall93ba8572010-03-25 06:39:04 +0000970 if (isFriend) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +0000971 DC->makeDeclVisibleInContext(Inst);
Abramo Bagnara4c515482011-11-26 13:33:46 +0000972 Inst->setLexicalDeclContext(Owner);
973 RecordInst->setLexicalDeclContext(Owner);
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000974 return Inst;
Douglas Gregor259571e2009-10-30 22:42:42 +0000975 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000976
Abramo Bagnara4c515482011-11-26 13:33:46 +0000977 if (D->isOutOfLine()) {
978 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
979 RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
980 }
981
John McCalle29ba202009-08-20 01:44:21 +0000982 Owner->addDecl(Inst);
Douglas Gregord65587f2010-11-10 19:44:59 +0000983
984 if (!PrevClassTemplate) {
985 // Queue up any out-of-line partial specializations of this member
986 // class template; the client will force their instantiation once
987 // the enclosing class has been instantiated.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000988 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
Douglas Gregord65587f2010-11-10 19:44:59 +0000989 D->getPartialSpecializations(PartialSpecs);
990 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
991 if (PartialSpecs[I]->isOutOfLine())
992 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
993 }
994
John McCalle29ba202009-08-20 01:44:21 +0000995 return Inst;
996}
997
Douglas Gregord60e1052009-08-27 16:57:43 +0000998Decl *
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000999TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
1000 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregored9c0f92009-10-29 00:04:11 +00001001 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001002
Douglas Gregored9c0f92009-10-29 00:04:11 +00001003 // Lookup the already-instantiated declaration in the instantiation
1004 // of the class template and return that.
1005 DeclContext::lookup_result Found
1006 = Owner->lookup(ClassTemplate->getDeclName());
David Blaikie3bc93e32012-12-19 00:45:41 +00001007 if (Found.empty())
Douglas Gregored9c0f92009-10-29 00:04:11 +00001008 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001009
Douglas Gregored9c0f92009-10-29 00:04:11 +00001010 ClassTemplateDecl *InstClassTemplate
David Blaikie3bc93e32012-12-19 00:45:41 +00001011 = dyn_cast<ClassTemplateDecl>(Found.front());
Douglas Gregored9c0f92009-10-29 00:04:11 +00001012 if (!InstClassTemplate)
1013 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001014
Douglas Gregord65587f2010-11-10 19:44:59 +00001015 if (ClassTemplatePartialSpecializationDecl *Result
1016 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
1017 return Result;
1018
1019 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
Douglas Gregor7974c3b2009-10-07 17:21:34 +00001020}
1021
1022Decl *
Douglas Gregord60e1052009-08-27 16:57:43 +00001023TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00001024 // Create a local instantiation scope for this function template, which
1025 // will contain the instantiations of the template parameters and then get
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001026 // merged with the local instantiation scope for the function template
Douglas Gregor550d9b22009-10-31 17:21:17 +00001027 // itself.
John McCall2a7fb272010-08-25 05:32:35 +00001028 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor895162d2010-04-30 18:55:50 +00001029
Douglas Gregord60e1052009-08-27 16:57:43 +00001030 TemplateParameterList *TempParams = D->getTemplateParameters();
1031 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +00001032 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +00001033 return NULL;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001034
Douglas Gregora735b202009-10-13 14:39:41 +00001035 FunctionDecl *Instantiated = 0;
1036 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001037 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
Douglas Gregora735b202009-10-13 14:39:41 +00001038 InstParams));
1039 else
1040 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001041 D->getTemplatedDecl(),
Douglas Gregora735b202009-10-13 14:39:41 +00001042 InstParams));
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001043
Douglas Gregora735b202009-10-13 14:39:41 +00001044 if (!Instantiated)
Douglas Gregord60e1052009-08-27 16:57:43 +00001045 return 0;
1046
Mike Stump1eb44332009-09-09 15:08:12 +00001047 // Link the instantiated function template declaration to the function
Douglas Gregord60e1052009-08-27 16:57:43 +00001048 // template from which it was instantiated.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001049 FunctionTemplateDecl *InstTemplate
Douglas Gregora735b202009-10-13 14:39:41 +00001050 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregor37d681852009-10-12 22:27:17 +00001051 InstTemplate->setAccess(D->getAccess());
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001052 assert(InstTemplate &&
Douglas Gregora735b202009-10-13 14:39:41 +00001053 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCalle976ffe2009-12-14 23:19:40 +00001054
John McCallb1a56e72010-03-26 23:10:15 +00001055 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
1056
John McCalle976ffe2009-12-14 23:19:40 +00001057 // Link the instantiation back to the pattern *unless* this is a
1058 // non-definition friend declaration.
1059 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
John McCallb1a56e72010-03-26 23:10:15 +00001060 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregora735b202009-10-13 14:39:41 +00001061 InstTemplate->setInstantiatedFromMemberTemplate(D);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001062
John McCallb1a56e72010-03-26 23:10:15 +00001063 // Make declarations visible in the appropriate context.
John McCall1f2e1a92012-08-10 03:15:35 +00001064 if (!isFriend) {
Douglas Gregora735b202009-10-13 14:39:41 +00001065 Owner->addDecl(InstTemplate);
John McCall1f2e1a92012-08-10 03:15:35 +00001066 } else if (InstTemplate->getDeclContext()->isRecord() &&
1067 !D->getPreviousDecl()) {
1068 SemaRef.CheckFriendAccess(InstTemplate);
1069 }
John McCallb1a56e72010-03-26 23:10:15 +00001070
Douglas Gregord60e1052009-08-27 16:57:43 +00001071 return InstTemplate;
1072}
1073
Douglas Gregord475b8d2009-03-25 21:17:03 +00001074Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
1075 CXXRecordDecl *PrevDecl = 0;
1076 if (D->isInjectedClassName())
1077 PrevDecl = cast<CXXRecordDecl>(Owner);
Douglas Gregoref96ee02012-01-14 16:38:05 +00001078 else if (D->getPreviousDecl()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001079 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
Douglas Gregoref96ee02012-01-14 16:38:05 +00001080 D->getPreviousDecl(),
John McCall6c1c1b82009-12-15 22:29:06 +00001081 TemplateArgs);
1082 if (!Prev) return 0;
1083 PrevDecl = cast<CXXRecordDecl>(Prev);
1084 }
Douglas Gregord475b8d2009-03-25 21:17:03 +00001085
1086 CXXRecordDecl *Record
Mike Stump1eb44332009-09-09 15:08:12 +00001087 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001088 D->getLocStart(), D->getLocation(),
1089 D->getIdentifier(), PrevDecl);
John McCallb6217662010-03-15 10:12:16 +00001090
1091 // Substitute the nested name specifier, if any.
1092 if (SubstQualifier(D, Record))
1093 return 0;
1094
Douglas Gregord475b8d2009-03-25 21:17:03 +00001095 Record->setImplicit(D->isImplicit());
Eli Friedmaneaba1af2009-08-27 19:11:42 +00001096 // FIXME: Check against AS_none is an ugly hack to work around the issue that
1097 // the tag decls introduced by friend class declarations don't have an access
1098 // specifier. Remove once this area of the code gets sorted out.
1099 if (D->getAccess() != AS_none)
1100 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +00001101 if (!D->isInjectedClassName())
Douglas Gregorf6b11852009-10-08 15:14:33 +00001102 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +00001103
John McCall02cace72009-08-28 07:59:38 +00001104 // If the original function was part of a friend declaration,
1105 // inherit its namespace state.
1106 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
1107 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
1108
Douglas Gregor9901c572010-05-21 00:31:19 +00001109 // Make sure that anonymous structs and unions are recorded.
1110 if (D->isAnonymousStructOrUnion()) {
1111 Record->setAnonymousStructOrUnion(true);
Sebastian Redl7a126a42010-08-31 00:36:30 +00001112 if (Record->getDeclContext()->getRedeclContext()->isFunctionOrMethod())
Douglas Gregor9901c572010-05-21 00:31:19 +00001113 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
1114 }
Anders Carlssond8b285f2009-09-01 04:26:58 +00001115
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001116 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +00001117 return Record;
1118}
1119
Douglas Gregor71074fd2012-09-13 21:56:43 +00001120/// \brief Adjust the given function type for an instantiation of the
1121/// given declaration, to cope with modifications to the function's type that
1122/// aren't reflected in the type-source information.
1123///
1124/// \param D The declaration we're instantiating.
1125/// \param TInfo The already-instantiated type.
1126static QualType adjustFunctionTypeForInstantiation(ASTContext &Context,
1127 FunctionDecl *D,
1128 TypeSourceInfo *TInfo) {
Douglas Gregorbed51fe2012-09-13 22:01:49 +00001129 const FunctionProtoType *OrigFunc
1130 = D->getType()->castAs<FunctionProtoType>();
1131 const FunctionProtoType *NewFunc
1132 = TInfo->getType()->castAs<FunctionProtoType>();
1133 if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
1134 return TInfo->getType();
1135
1136 FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
1137 NewEPI.ExtInfo = OrigFunc->getExtInfo();
1138 return Context.getFunctionType(NewFunc->getResultType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00001139 ArrayRef<QualType>(NewFunc->arg_type_begin(),
1140 NewFunc->getNumArgs()),
Douglas Gregorbed51fe2012-09-13 22:01:49 +00001141 NewEPI);
Douglas Gregor71074fd2012-09-13 21:56:43 +00001142}
1143
John McCall02cace72009-08-28 07:59:38 +00001144/// Normal class members are of more specific types and therefore
1145/// don't make it here. This function serves two purposes:
1146/// 1) instantiating function templates
1147/// 2) substituting friend declarations
1148/// FIXME: preserve function definitions in case #2
Douglas Gregor7557a132009-12-24 20:56:24 +00001149Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
Douglas Gregora735b202009-10-13 14:39:41 +00001150 TemplateParameterList *TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +00001151 // Check whether there is already a function template specialization for
1152 // this declaration.
1153 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
John McCallb0cb0222010-03-27 05:57:59 +00001154 if (FunctionTemplate && !TemplateParams) {
Richard Smithc95d4132013-05-03 23:46:09 +00001155 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Mike Stump1eb44332009-09-09 15:08:12 +00001156
Douglas Gregor1e1e9722012-03-28 14:34:23 +00001157 void *InsertPos = 0;
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001158 FunctionDecl *SpecFunc
Richard Smithc95d4132013-05-03 23:46:09 +00001159 = FunctionTemplate->findSpecialization(Innermost.begin(), Innermost.size(),
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001160 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001161
Douglas Gregor127102b2009-06-29 20:59:39 +00001162 // If we already have a function template specialization, return it.
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001163 if (SpecFunc)
1164 return SpecFunc;
Douglas Gregor127102b2009-06-29 20:59:39 +00001165 }
Mike Stump1eb44332009-09-09 15:08:12 +00001166
John McCallb0cb0222010-03-27 05:57:59 +00001167 bool isFriend;
1168 if (FunctionTemplate)
1169 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1170 else
1171 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1172
Douglas Gregor79c22782010-01-16 20:21:20 +00001173 bool MergeWithParentScope = (TemplateParams != 0) ||
Douglas Gregorb212d9a2010-05-21 21:25:08 +00001174 Owner->isFunctionOrMethod() ||
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001175 !(isa<Decl>(Owner) &&
Douglas Gregor79c22782010-01-16 20:21:20 +00001176 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall2a7fb272010-08-25 05:32:35 +00001177 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +00001178
Chris Lattner5f9e2722011-07-23 10:55:15 +00001179 SmallVector<ParmVarDecl *, 4> Params;
David Blaikie64b4b432011-11-10 05:42:04 +00001180 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
John McCall21ef0fa2010-03-11 09:03:00 +00001181 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001182 return 0;
Douglas Gregor71074fd2012-09-13 21:56:43 +00001183 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
John McCallfd810b12009-08-14 02:03:10 +00001184
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001185 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1186 if (QualifierLoc) {
1187 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1188 TemplateArgs);
1189 if (!QualifierLoc)
1190 return 0;
John McCalld325daa2010-03-26 04:53:08 +00001191 }
1192
John McCall68b6b872010-02-06 01:50:47 +00001193 // If we're instantiating a local function declaration, put the result
1194 // in the owner; otherwise we need to find the instantiated context.
1195 DeclContext *DC;
1196 if (D->getDeclContext()->isFunctionOrMethod())
1197 DC = Owner;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001198 else if (isFriend && QualifierLoc) {
John McCalld325daa2010-03-26 04:53:08 +00001199 CXXScopeSpec SS;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001200 SS.Adopt(QualifierLoc);
John McCalld325daa2010-03-26 04:53:08 +00001201 DC = SemaRef.computeDeclContext(SS);
1202 if (!DC) return 0;
1203 } else {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001204 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001205 TemplateArgs);
John McCalld325daa2010-03-26 04:53:08 +00001206 }
John McCall68b6b872010-02-06 01:50:47 +00001207
John McCall02cace72009-08-28 07:59:38 +00001208 FunctionDecl *Function =
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001209 FunctionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
Abramo Bagnara635311f2012-10-04 21:40:42 +00001210 D->getNameInfo(), T, TInfo,
Rafael Espindola459ef032013-04-16 02:29:15 +00001211 D->getCanonicalDecl()->getStorageClass(),
Richard Smithaf1fc7a2011-08-15 21:04:07 +00001212 D->isInlineSpecified(), D->hasWrittenPrototype(),
Richard Smith86c3ae42012-02-13 03:54:03 +00001213 D->isConstexpr());
John McCallb6217662010-03-15 10:12:16 +00001214
Richard Smithd4497dd2013-01-25 00:08:28 +00001215 if (D->isInlined())
1216 Function->setImplicitlyInline();
1217
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001218 if (QualifierLoc)
1219 Function->setQualifierInfo(QualifierLoc);
John McCallb6217662010-03-15 10:12:16 +00001220
John McCallb1a56e72010-03-26 23:10:15 +00001221 DeclContext *LexicalDC = Owner;
1222 if (!isFriend && D->isOutOfLine()) {
1223 assert(D->getDeclContext()->isFileContext());
1224 LexicalDC = D->getDeclContext();
1225 }
1226
1227 Function->setLexicalDeclContext(LexicalDC);
Mike Stump1eb44332009-09-09 15:08:12 +00001228
Douglas Gregore53060f2009-06-25 22:08:12 +00001229 // Attach the parameters
Douglas Gregor5cbe1012011-07-05 18:30:26 +00001230 if (isa<FunctionProtoType>(Function->getType().IgnoreParens())) {
Douglas Gregor1d441ee2011-06-22 18:16:25 +00001231 // Adopt the already-instantiated parameters into our own context.
1232 for (unsigned P = 0; P < Params.size(); ++P)
1233 if (Params[P])
1234 Params[P]->setOwningFunction(Function);
1235 } else {
1236 // Since we were instantiated via a typedef of a function type, create
1237 // new parameters.
1238 const FunctionProtoType *Proto
1239 = Function->getType()->getAs<FunctionProtoType>();
1240 assert(Proto && "No function prototype in template instantiation?");
1241 for (FunctionProtoType::arg_type_iterator AI = Proto->arg_type_begin(),
1242 AE = Proto->arg_type_end(); AI != AE; ++AI) {
1243 ParmVarDecl *Param
1244 = SemaRef.BuildParmVarDeclForTypedef(Function, Function->getLocation(),
1245 *AI);
1246 Param->setScopeInfo(0, Params.size());
1247 Params.push_back(Param);
1248 }
1249 }
David Blaikie4278c652011-09-21 18:16:56 +00001250 Function->setParams(Params);
John McCall02cace72009-08-28 07:59:38 +00001251
Douglas Gregorac7c2c82010-05-17 16:38:00 +00001252 SourceLocation InstantiateAtPOI;
Douglas Gregora735b202009-10-13 14:39:41 +00001253 if (TemplateParams) {
1254 // Our resulting instantiation is actually a function template, since we
1255 // are substituting only the outer template parameters. For example, given
1256 //
1257 // template<typename T>
1258 // struct X {
1259 // template<typename U> friend void f(T, U);
1260 // };
1261 //
1262 // X<int> x;
1263 //
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001264 // We are instantiating the friend function template "f" within X<int>,
Douglas Gregora735b202009-10-13 14:39:41 +00001265 // which means substituting int for T, but leaving "f" as a friend function
1266 // template.
1267 // Build the function template itself.
John McCalld325daa2010-03-26 04:53:08 +00001268 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
Douglas Gregora735b202009-10-13 14:39:41 +00001269 Function->getLocation(),
1270 Function->getDeclName(),
1271 TemplateParams, Function);
1272 Function->setDescribedFunctionTemplate(FunctionTemplate);
John McCallb1a56e72010-03-26 23:10:15 +00001273
1274 FunctionTemplate->setLexicalDeclContext(LexicalDC);
John McCalld325daa2010-03-26 04:53:08 +00001275
1276 if (isFriend && D->isThisDeclarationADefinition()) {
1277 // TODO: should we remember this connection regardless of whether
1278 // the friend declaration provided a body?
1279 FunctionTemplate->setInstantiatedFromMemberTemplate(
1280 D->getDescribedFunctionTemplate());
1281 }
Douglas Gregor66724ea2009-11-14 01:20:54 +00001282 } else if (FunctionTemplate) {
1283 // Record this function template specialization.
Richard Smithc95d4132013-05-03 23:46:09 +00001284 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Douglas Gregor838db382010-02-11 01:19:42 +00001285 Function->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00001286 TemplateArgumentList::CreateCopy(SemaRef.Context,
Richard Smithc95d4132013-05-03 23:46:09 +00001287 Innermost.begin(),
1288 Innermost.size()),
Douglas Gregor1e1e9722012-03-28 14:34:23 +00001289 /*InsertPos=*/0);
Chandler Carruth80f5b162011-08-18 09:09:59 +00001290 } else if (isFriend) {
1291 // Note, we need this connection even if the friend doesn't have a body.
1292 // Its body may exist but not have been attached yet due to deferred
1293 // parsing.
1294 // FIXME: It might be cleaner to set this when attaching the body to the
1295 // friend function declaration, however that would require finding all the
1296 // instantiations and modifying them.
John McCalld325daa2010-03-26 04:53:08 +00001297 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
John McCall02cace72009-08-28 07:59:38 +00001298 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001299
Douglas Gregore53060f2009-06-25 22:08:12 +00001300 if (InitFunctionInstantiation(Function, D))
1301 Function->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001302
John McCallaf2094e2010-04-08 09:05:18 +00001303 bool isExplicitSpecialization = false;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001304
John McCall68263142009-11-18 22:49:29 +00001305 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
1306 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
1307
John McCallaf2094e2010-04-08 09:05:18 +00001308 if (DependentFunctionTemplateSpecializationInfo *Info
1309 = D->getDependentSpecializationInfo()) {
1310 assert(isFriend && "non-friend has dependent specialization info?");
1311
1312 // This needs to be set now for future sanity.
1313 Function->setObjectOfFriendDecl(/*HasPrevious*/ true);
1314
1315 // Instantiate the explicit template arguments.
1316 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1317 Info->getRAngleLoc());
Douglas Gregore02e2622010-12-22 21:19:48 +00001318 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1319 ExplicitArgs, TemplateArgs))
1320 return 0;
John McCallaf2094e2010-04-08 09:05:18 +00001321
1322 // Map the candidate templates to their instantiations.
1323 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1324 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1325 Info->getTemplate(I),
1326 TemplateArgs);
1327 if (!Temp) return 0;
1328
1329 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1330 }
1331
1332 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1333 &ExplicitArgs,
1334 Previous))
1335 Function->setInvalidDecl();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001336
John McCallaf2094e2010-04-08 09:05:18 +00001337 isExplicitSpecialization = true;
1338
1339 } else if (TemplateParams || !FunctionTemplate) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001340 // Look only into the namespace where the friend would be declared to
1341 // find a previous declaration. This is the innermost enclosing namespace,
Douglas Gregora735b202009-10-13 14:39:41 +00001342 // as described in ActOnFriendFunctionDecl.
John McCall68263142009-11-18 22:49:29 +00001343 SemaRef.LookupQualifiedName(Previous, DC);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001344
Douglas Gregora735b202009-10-13 14:39:41 +00001345 // In C++, the previous declaration we find might be a tag type
1346 // (class or enum). In this case, the new declaration will hide the
1347 // tag type. Note that this does does not apply if we're declaring a
1348 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001349 if (Previous.isSingleTagDecl())
1350 Previous.clear();
Douglas Gregora735b202009-10-13 14:39:41 +00001351 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001352
John McCall9f54ad42009-12-10 09:41:52 +00001353 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00001354 isExplicitSpecialization);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001355
John McCall76d32642010-04-24 01:30:58 +00001356 NamedDecl *PrincipalDecl = (TemplateParams
1357 ? cast<NamedDecl>(FunctionTemplate)
1358 : Function);
1359
Douglas Gregora735b202009-10-13 14:39:41 +00001360 // If the original function was part of a friend declaration,
1361 // inherit its namespace state and add it to the owner.
John McCalld325daa2010-03-26 04:53:08 +00001362 if (isFriend) {
John McCall68263142009-11-18 22:49:29 +00001363 NamedDecl *PrevDecl;
John McCall76d32642010-04-24 01:30:58 +00001364 if (TemplateParams)
Douglas Gregoref96ee02012-01-14 16:38:05 +00001365 PrevDecl = FunctionTemplate->getPreviousDecl();
John McCall76d32642010-04-24 01:30:58 +00001366 else
Douglas Gregoref96ee02012-01-14 16:38:05 +00001367 PrevDecl = Function->getPreviousDecl();
John McCall76d32642010-04-24 01:30:58 +00001368
1369 PrincipalDecl->setObjectOfFriendDecl(PrevDecl != 0);
Richard Smith1b7f9cb2012-03-13 03:12:56 +00001370 DC->makeDeclVisibleInContext(PrincipalDecl);
Gabor Greifab297ac2010-08-30 21:10:05 +00001371
Gabor Greif77535df2010-08-30 22:25:56 +00001372 bool queuedInstantiation = false;
Gabor Greifab297ac2010-08-30 21:10:05 +00001373
Richard Smith53e53512011-10-19 00:54:10 +00001374 // C++98 [temp.friend]p5: When a function is defined in a friend function
1375 // declaration in a class template, the function is defined at each
1376 // instantiation of the class template. The function is defined even if it
1377 // is never used.
1378 // C++11 [temp.friend]p4: When a function is defined in a friend function
1379 // declaration in a class template, the function is instantiated when the
1380 // function is odr-used.
1381 //
1382 // If -Wc++98-compat is enabled, we go through the motions of checking for a
1383 // redefinition, but don't instantiate the function.
Richard Smith80ad52f2013-01-02 11:42:31 +00001384 if ((!SemaRef.getLangOpts().CPlusPlus11 ||
Richard Smith53e53512011-10-19 00:54:10 +00001385 SemaRef.Diags.getDiagnosticLevel(
1386 diag::warn_cxx98_compat_friend_redefinition,
1387 Function->getLocation())
1388 != DiagnosticsEngine::Ignored) &&
Douglas Gregor238058c2010-05-18 05:45:02 +00001389 D->isThisDeclarationADefinition()) {
1390 // Check for a function body.
1391 const FunctionDecl *Definition = 0;
Sean Hunt10620eb2011-05-06 20:44:56 +00001392 if (Function->isDefined(Definition) &&
Douglas Gregor238058c2010-05-18 05:45:02 +00001393 Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
Richard Smith53e53512011-10-19 00:54:10 +00001394 SemaRef.Diag(Function->getLocation(),
Richard Smith80ad52f2013-01-02 11:42:31 +00001395 SemaRef.getLangOpts().CPlusPlus11 ?
Richard Smith53e53512011-10-19 00:54:10 +00001396 diag::warn_cxx98_compat_friend_redefinition :
1397 diag::err_redefinition) << Function->getDeclName();
Douglas Gregor238058c2010-05-18 05:45:02 +00001398 SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
Richard Smith80ad52f2013-01-02 11:42:31 +00001399 if (!SemaRef.getLangOpts().CPlusPlus11)
Richard Smith53e53512011-10-19 00:54:10 +00001400 Function->setInvalidDecl();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001401 }
Douglas Gregor238058c2010-05-18 05:45:02 +00001402 // Check for redefinitions due to other instantiations of this or
1403 // a similar friend function.
1404 else for (FunctionDecl::redecl_iterator R = Function->redecls_begin(),
1405 REnd = Function->redecls_end();
1406 R != REnd; ++R) {
Gabor Greif13a8aff2010-08-28 15:42:30 +00001407 if (*R == Function)
1408 continue;
Gabor Greifab297ac2010-08-30 21:10:05 +00001409 switch (R->getFriendObjectKind()) {
1410 case Decl::FOK_None:
Richard Smith80ad52f2013-01-02 11:42:31 +00001411 if (!SemaRef.getLangOpts().CPlusPlus11 &&
Richard Smith53e53512011-10-19 00:54:10 +00001412 !queuedInstantiation && R->isUsed(false)) {
Gabor Greifab297ac2010-08-30 21:10:05 +00001413 if (MemberSpecializationInfo *MSInfo
1414 = Function->getMemberSpecializationInfo()) {
1415 if (MSInfo->getPointOfInstantiation().isInvalid()) {
1416 SourceLocation Loc = R->getLocation(); // FIXME
1417 MSInfo->setPointOfInstantiation(Loc);
1418 SemaRef.PendingLocalImplicitInstantiations.push_back(
1419 std::make_pair(Function, Loc));
1420 queuedInstantiation = true;
1421 }
1422 }
1423 }
1424 break;
1425 default:
Douglas Gregor238058c2010-05-18 05:45:02 +00001426 if (const FunctionDecl *RPattern
Gabor Greif6a557d82010-08-28 15:46:56 +00001427 = R->getTemplateInstantiationPattern())
Sean Hunt10620eb2011-05-06 20:44:56 +00001428 if (RPattern->isDefined(RPattern)) {
Richard Smith53e53512011-10-19 00:54:10 +00001429 SemaRef.Diag(Function->getLocation(),
Richard Smith80ad52f2013-01-02 11:42:31 +00001430 SemaRef.getLangOpts().CPlusPlus11 ?
Richard Smith53e53512011-10-19 00:54:10 +00001431 diag::warn_cxx98_compat_friend_redefinition :
1432 diag::err_redefinition)
Douglas Gregor238058c2010-05-18 05:45:02 +00001433 << Function->getDeclName();
Gabor Greif6a557d82010-08-28 15:46:56 +00001434 SemaRef.Diag(R->getLocation(), diag::note_previous_definition);
Richard Smith80ad52f2013-01-02 11:42:31 +00001435 if (!SemaRef.getLangOpts().CPlusPlus11)
Richard Smith53e53512011-10-19 00:54:10 +00001436 Function->setInvalidDecl();
Douglas Gregor238058c2010-05-18 05:45:02 +00001437 break;
1438 }
1439 }
1440 }
1441 }
Douglas Gregora735b202009-10-13 14:39:41 +00001442 }
1443
John McCall76d32642010-04-24 01:30:58 +00001444 if (Function->isOverloadedOperator() && !DC->isRecord() &&
1445 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1446 PrincipalDecl->setNonMemberOperator();
1447
Sean Hunteb88ae52011-05-23 21:07:59 +00001448 assert(!D->isDefaulted() && "only methods should be defaulted");
Douglas Gregore53060f2009-06-25 22:08:12 +00001449 return Function;
1450}
1451
Douglas Gregord60e1052009-08-27 16:57:43 +00001452Decl *
1453TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001454 TemplateParameterList *TemplateParams,
1455 bool IsClassScopeSpecialization) {
Douglas Gregor6b906862009-08-21 00:16:32 +00001456 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
Douglas Gregord60e1052009-08-27 16:57:43 +00001457 if (FunctionTemplate && !TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +00001458 // We are creating a function template specialization from a function
1459 // template. Check whether there is already a function template
Douglas Gregord60e1052009-08-27 16:57:43 +00001460 // specialization for this particular set of template arguments.
Richard Smithc95d4132013-05-03 23:46:09 +00001461 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Mike Stump1eb44332009-09-09 15:08:12 +00001462
Douglas Gregor1e1e9722012-03-28 14:34:23 +00001463 void *InsertPos = 0;
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001464 FunctionDecl *SpecFunc
Richard Smithc95d4132013-05-03 23:46:09 +00001465 = FunctionTemplate->findSpecialization(Innermost.begin(),
1466 Innermost.size(),
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001467 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001468
Douglas Gregor6b906862009-08-21 00:16:32 +00001469 // If we already have a function template specialization, return it.
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001470 if (SpecFunc)
1471 return SpecFunc;
Douglas Gregor6b906862009-08-21 00:16:32 +00001472 }
1473
John McCallb0cb0222010-03-27 05:57:59 +00001474 bool isFriend;
1475 if (FunctionTemplate)
1476 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1477 else
1478 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1479
Douglas Gregor79c22782010-01-16 20:21:20 +00001480 bool MergeWithParentScope = (TemplateParams != 0) ||
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001481 !(isa<Decl>(Owner) &&
Douglas Gregor79c22782010-01-16 20:21:20 +00001482 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall2a7fb272010-08-25 05:32:35 +00001483 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Douglas Gregor48dd19b2009-05-14 21:44:34 +00001484
John McCall4eab39f2010-10-19 02:26:41 +00001485 // Instantiate enclosing template arguments for friends.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001486 SmallVector<TemplateParameterList *, 4> TempParamLists;
John McCall4eab39f2010-10-19 02:26:41 +00001487 unsigned NumTempParamLists = 0;
1488 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
1489 TempParamLists.set_size(NumTempParamLists);
1490 for (unsigned I = 0; I != NumTempParamLists; ++I) {
1491 TemplateParameterList *TempParams = D->getTemplateParameterList(I);
1492 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1493 if (!InstParams)
1494 return NULL;
1495 TempParamLists[I] = InstParams;
1496 }
1497 }
1498
Chris Lattner5f9e2722011-07-23 10:55:15 +00001499 SmallVector<ParmVarDecl *, 4> Params;
Benjamin Kramerdc370c12012-01-20 14:42:32 +00001500 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
John McCall21ef0fa2010-03-11 09:03:00 +00001501 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001502 return 0;
Douglas Gregor71074fd2012-09-13 21:56:43 +00001503 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001504
Abramo Bagnara723df242010-12-14 22:11:44 +00001505 // \brief If the type of this function, after ignoring parentheses,
1506 // is not *directly* a function type, then we're instantiating a function
1507 // that was declared via a typedef, e.g.,
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001508 //
1509 // typedef int functype(int, int);
1510 // functype func;
1511 //
1512 // In this case, we'll just go instantiate the ParmVarDecls that we
1513 // synthesized in the method declaration.
Abramo Bagnara723df242010-12-14 22:11:44 +00001514 if (!isa<FunctionProtoType>(T.IgnoreParens())) {
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001515 assert(!Params.size() && "Instantiating type could not yield parameters");
Chris Lattner5f9e2722011-07-23 10:55:15 +00001516 SmallVector<QualType, 4> ParamTypes;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001517 if (SemaRef.SubstParmTypes(D->getLocation(), D->param_begin(),
1518 D->getNumParams(), TemplateArgs, ParamTypes,
Douglas Gregor12c9c002011-01-07 16:43:16 +00001519 &Params))
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001520 return 0;
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001521 }
1522
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001523 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1524 if (QualifierLoc) {
1525 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
John McCallb0cb0222010-03-27 05:57:59 +00001526 TemplateArgs);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001527 if (!QualifierLoc)
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001528 return 0;
John McCallb0cb0222010-03-27 05:57:59 +00001529 }
1530
1531 DeclContext *DC = Owner;
1532 if (isFriend) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001533 if (QualifierLoc) {
John McCallb0cb0222010-03-27 05:57:59 +00001534 CXXScopeSpec SS;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001535 SS.Adopt(QualifierLoc);
John McCallb0cb0222010-03-27 05:57:59 +00001536 DC = SemaRef.computeDeclContext(SS);
John McCallc54d6882010-10-19 05:01:53 +00001537
1538 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
1539 return 0;
John McCallb0cb0222010-03-27 05:57:59 +00001540 } else {
1541 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1542 D->getDeclContext(),
1543 TemplateArgs);
1544 }
1545 if (!DC) return 0;
1546 }
1547
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001548 // Build the instantiated method declaration.
John McCallb0cb0222010-03-27 05:57:59 +00001549 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
Douglas Gregordec06662009-08-21 18:42:58 +00001550 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001551
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001552 SourceLocation StartLoc = D->getInnerLocStart();
Abramo Bagnara25777432010-08-11 22:01:17 +00001553 DeclarationNameInfo NameInfo
1554 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
Douglas Gregor17e32f32009-08-21 22:43:28 +00001555 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001556 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001557 StartLoc, NameInfo, T, TInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00001558 Constructor->isExplicit(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001559 Constructor->isInlineSpecified(),
Richard Smith86c3ae42012-02-13 03:54:03 +00001560 false, Constructor->isConstexpr());
Richard Smith4841ca52013-04-10 05:48:59 +00001561 // Claim that the instantiation of a constructor or constructor template
1562 // inherits the same constructor that the template does.
1563 if (const CXXConstructorDecl *Inh = Constructor->getInheritedConstructor())
1564 cast<CXXConstructorDecl>(Method)->setInheritedConstructor(Inh);
Douglas Gregor17e32f32009-08-21 22:43:28 +00001565 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001566 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001567 StartLoc, NameInfo, T, TInfo,
Abramo Bagnara25777432010-08-11 22:01:17 +00001568 Destructor->isInlineSpecified(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001569 false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001570 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001571 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001572 StartLoc, NameInfo, T, TInfo,
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001573 Conversion->isInlineSpecified(),
Douglas Gregorf5251602011-03-08 17:10:18 +00001574 Conversion->isExplicit(),
Richard Smith86c3ae42012-02-13 03:54:03 +00001575 Conversion->isConstexpr(),
Richard Smith9f569cc2011-10-01 02:31:28 +00001576 Conversion->getLocEnd());
Douglas Gregordec06662009-08-21 18:42:58 +00001577 } else {
Rafael Espindola72fdc892013-04-15 12:38:20 +00001578 StorageClass SC = D->isStatic() ? SC_Static : SC_None;
Abramo Bagnara25777432010-08-11 22:01:17 +00001579 Method = CXXMethodDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001580 StartLoc, NameInfo, T, TInfo,
Rafael Espindola72fdc892013-04-15 12:38:20 +00001581 SC, D->isInlineSpecified(),
Richard Smith86c3ae42012-02-13 03:54:03 +00001582 D->isConstexpr(), D->getLocEnd());
Douglas Gregordec06662009-08-21 18:42:58 +00001583 }
Douglas Gregor6b906862009-08-21 00:16:32 +00001584
Richard Smithd4497dd2013-01-25 00:08:28 +00001585 if (D->isInlined())
1586 Method->setImplicitlyInline();
1587
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001588 if (QualifierLoc)
1589 Method->setQualifierInfo(QualifierLoc);
John McCallb6217662010-03-15 10:12:16 +00001590
Douglas Gregord60e1052009-08-27 16:57:43 +00001591 if (TemplateParams) {
1592 // Our resulting instantiation is actually a function template, since we
1593 // are substituting only the outer template parameters. For example, given
Mike Stump1eb44332009-09-09 15:08:12 +00001594 //
Douglas Gregord60e1052009-08-27 16:57:43 +00001595 // template<typename T>
1596 // struct X {
1597 // template<typename U> void f(T, U);
1598 // };
1599 //
1600 // X<int> x;
1601 //
1602 // We are instantiating the member template "f" within X<int>, which means
1603 // substituting int for T, but leaving "f" as a member function template.
1604 // Build the function template itself.
1605 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1606 Method->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001607 Method->getDeclName(),
Douglas Gregord60e1052009-08-27 16:57:43 +00001608 TemplateParams, Method);
John McCallb0cb0222010-03-27 05:57:59 +00001609 if (isFriend) {
1610 FunctionTemplate->setLexicalDeclContext(Owner);
1611 FunctionTemplate->setObjectOfFriendDecl(true);
1612 } else if (D->isOutOfLine())
Mike Stump1eb44332009-09-09 15:08:12 +00001613 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregord60e1052009-08-27 16:57:43 +00001614 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001615 } else if (FunctionTemplate) {
1616 // Record this function template specialization.
Richard Smithc95d4132013-05-03 23:46:09 +00001617 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Douglas Gregor838db382010-02-11 01:19:42 +00001618 Method->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00001619 TemplateArgumentList::CreateCopy(SemaRef.Context,
Richard Smithc95d4132013-05-03 23:46:09 +00001620 Innermost.begin(),
1621 Innermost.size()),
Douglas Gregor1e1e9722012-03-28 14:34:23 +00001622 /*InsertPos=*/0);
John McCallb0cb0222010-03-27 05:57:59 +00001623 } else if (!isFriend) {
Douglas Gregor66724ea2009-11-14 01:20:54 +00001624 // Record that this is an instantiation of a member function.
Douglas Gregor2db32322009-10-07 23:56:10 +00001625 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001626 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001627
Mike Stump1eb44332009-09-09 15:08:12 +00001628 // If we are instantiating a member function defined
Douglas Gregor7caa6822009-07-24 20:34:43 +00001629 // out-of-line, the instantiation will have the same lexical
1630 // context (which will be a namespace scope) as the template.
John McCallb0cb0222010-03-27 05:57:59 +00001631 if (isFriend) {
John McCall4eab39f2010-10-19 02:26:41 +00001632 if (NumTempParamLists)
1633 Method->setTemplateParameterListsInfo(SemaRef.Context,
1634 NumTempParamLists,
1635 TempParamLists.data());
1636
John McCallb0cb0222010-03-27 05:57:59 +00001637 Method->setLexicalDeclContext(Owner);
1638 Method->setObjectOfFriendDecl(true);
1639 } else if (D->isOutOfLine())
Douglas Gregor7caa6822009-07-24 20:34:43 +00001640 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00001641
Douglas Gregor5545e162009-03-24 00:38:23 +00001642 // Attach the parameters
1643 for (unsigned P = 0; P < Params.size(); ++P)
1644 Params[P]->setOwningFunction(Method);
David Blaikie4278c652011-09-21 18:16:56 +00001645 Method->setParams(Params);
Douglas Gregor5545e162009-03-24 00:38:23 +00001646
1647 if (InitMethodInstantiation(Method, D))
1648 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001649
Abramo Bagnara25777432010-08-11 22:01:17 +00001650 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
1651 Sema::ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00001652
John McCallb0cb0222010-03-27 05:57:59 +00001653 if (!FunctionTemplate || TemplateParams || isFriend) {
1654 SemaRef.LookupQualifiedName(Previous, Record);
Mike Stump1eb44332009-09-09 15:08:12 +00001655
Douglas Gregordec06662009-08-21 18:42:58 +00001656 // In C++, the previous declaration we find might be a tag type
1657 // (class or enum). In this case, the new declaration will hide the
1658 // tag type. Note that this does does not apply if we're declaring a
1659 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001660 if (Previous.isSingleTagDecl())
1661 Previous.clear();
Douglas Gregordec06662009-08-21 18:42:58 +00001662 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001663
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001664 if (!IsClassScopeSpecialization)
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00001665 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001666
Douglas Gregor4ba31362009-12-01 17:24:26 +00001667 if (D->isPure())
1668 SemaRef.CheckPureMethod(Method, SourceRange());
1669
John McCall1f2e1a92012-08-10 03:15:35 +00001670 // Propagate access. For a non-friend declaration, the access is
1671 // whatever we're propagating from. For a friend, it should be the
1672 // previous declaration we just found.
1673 if (isFriend && Method->getPreviousDecl())
1674 Method->setAccess(Method->getPreviousDecl()->getAccess());
1675 else
1676 Method->setAccess(D->getAccess());
1677 if (FunctionTemplate)
1678 FunctionTemplate->setAccess(Method->getAccess());
John McCall46460a62010-01-20 21:53:11 +00001679
Anders Carlsson9eefa222011-01-20 06:52:44 +00001680 SemaRef.CheckOverrideControl(Method);
1681
Eli Friedman3bc45152011-11-15 22:39:08 +00001682 // If a function is defined as defaulted or deleted, mark it as such now.
Richard Smithac713512012-12-08 02:53:02 +00001683 if (D->isExplicitlyDefaulted())
1684 SemaRef.SetDeclDefaulted(Method, Method->getLocation());
Eli Friedman3bc45152011-11-15 22:39:08 +00001685 if (D->isDeletedAsWritten())
Richard Smithac713512012-12-08 02:53:02 +00001686 SemaRef.SetDeclDeleted(Method, Method->getLocation());
Eli Friedman3bc45152011-11-15 22:39:08 +00001687
John McCall1f2e1a92012-08-10 03:15:35 +00001688 // If there's a function template, let our caller handle it.
John McCallb0cb0222010-03-27 05:57:59 +00001689 if (FunctionTemplate) {
John McCall1f2e1a92012-08-10 03:15:35 +00001690 // do nothing
1691
1692 // Don't hide a (potentially) valid declaration with an invalid one.
John McCallb0cb0222010-03-27 05:57:59 +00001693 } else if (Method->isInvalidDecl() && !Previous.empty()) {
John McCall1f2e1a92012-08-10 03:15:35 +00001694 // do nothing
1695
1696 // Otherwise, check access to friends and make them visible.
1697 } else if (isFriend) {
1698 // We only need to re-check access for methods which we didn't
1699 // manage to match during parsing.
1700 if (!D->getPreviousDecl())
1701 SemaRef.CheckFriendAccess(Method);
1702
1703 Record->makeDeclVisibleInContext(Method);
1704
1705 // Otherwise, add the declaration. We don't need to do this for
1706 // class-scope specializations because we'll have matched them with
1707 // the appropriate template.
1708 } else if (!IsClassScopeSpecialization) {
1709 Owner->addDecl(Method);
John McCallb0cb0222010-03-27 05:57:59 +00001710 }
Sean Hunteb88ae52011-05-23 21:07:59 +00001711
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001712 return Method;
1713}
1714
Douglas Gregor615c5d42009-03-24 16:43:20 +00001715Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +00001716 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +00001717}
1718
Douglas Gregor03b2b072009-03-24 00:15:49 +00001719Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001720 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +00001721}
1722
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001723Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001724 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001725}
1726
Douglas Gregor6477b692009-03-25 15:04:13 +00001727ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
David Blaikie66874fb2013-02-21 01:47:18 +00001728 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0, None,
1729 /*ExpectParameterPack=*/ false);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001730}
1731
John McCalle29ba202009-08-20 01:44:21 +00001732Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1733 TemplateTypeParmDecl *D) {
1734 // TODO: don't always clone when decls are refcounted.
Chandler Carruth4fb86f82011-05-01 00:51:33 +00001735 assert(D->getTypeForDecl()->isTemplateTypeParmType());
Mike Stump1eb44332009-09-09 15:08:12 +00001736
John McCalle29ba202009-08-20 01:44:21 +00001737 TemplateTypeParmDecl *Inst =
Abramo Bagnara344577e2011-03-06 15:48:19 +00001738 TemplateTypeParmDecl::Create(SemaRef.Context, Owner,
1739 D->getLocStart(), D->getLocation(),
Chandler Carruth4fb86f82011-05-01 00:51:33 +00001740 D->getDepth() - TemplateArgs.getNumLevels(),
1741 D->getIndex(), D->getIdentifier(),
John McCalle29ba202009-08-20 01:44:21 +00001742 D->wasDeclaredWithTypename(),
1743 D->isParameterPack());
Douglas Gregor9a299e02011-03-04 17:52:15 +00001744 Inst->setAccess(AS_public);
John McCalle29ba202009-08-20 01:44:21 +00001745
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001746 if (D->hasDefaultArgument())
1747 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
1748
1749 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor550d9b22009-10-31 17:21:17 +00001750 // scope.
1751 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001752
John McCalle29ba202009-08-20 01:44:21 +00001753 return Inst;
1754}
1755
Douglas Gregor33642df2009-10-23 23:25:44 +00001756Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1757 NonTypeTemplateParmDecl *D) {
1758 // Substitute into the type of the non-type template parameter.
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001759 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001760 SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
1761 SmallVector<QualType, 4> ExpandedParameterPackTypes;
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001762 bool IsExpandedParameterPack = false;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001763 TypeSourceInfo *DI;
Douglas Gregor33642df2009-10-23 23:25:44 +00001764 QualType T;
Douglas Gregor33642df2009-10-23 23:25:44 +00001765 bool Invalid = false;
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001766
1767 if (D->isExpandedParameterPack()) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001768 // The non-type template parameter pack is an already-expanded pack
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001769 // expansion of types. Substitute into each of the expanded types.
1770 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
1771 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
1772 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
1773 TypeSourceInfo *NewDI =SemaRef.SubstType(D->getExpansionTypeSourceInfo(I),
1774 TemplateArgs,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001775 D->getLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001776 D->getDeclName());
1777 if (!NewDI)
1778 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001779
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001780 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1781 QualType NewT =SemaRef.CheckNonTypeTemplateParameterType(NewDI->getType(),
1782 D->getLocation());
1783 if (NewT.isNull())
1784 return 0;
1785 ExpandedParameterPackTypes.push_back(NewT);
1786 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001787
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001788 IsExpandedParameterPack = true;
1789 DI = D->getTypeSourceInfo();
1790 T = DI->getType();
Richard Smith6964b3f2012-09-07 02:06:42 +00001791 } else if (D->isPackExpansion()) {
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001792 // The non-type template parameter pack's type is a pack expansion of types.
1793 // Determine whether we need to expand this parameter pack into separate
1794 // types.
David Blaikie39e6ab42013-02-18 22:06:02 +00001795 PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>();
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001796 TypeLoc Pattern = Expansion.getPatternLoc();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001797 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001798 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001799
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001800 // Determine whether the set of unexpanded parameter packs can and should
1801 // be expanded.
1802 bool Expand = true;
1803 bool RetainExpansion = false;
David Blaikiedc84cd52013-02-20 22:23:23 +00001804 Optional<unsigned> OrigNumExpansions
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001805 = Expansion.getTypePtr()->getNumExpansions();
David Blaikiedc84cd52013-02-20 22:23:23 +00001806 Optional<unsigned> NumExpansions = OrigNumExpansions;
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001807 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
1808 Pattern.getSourceRange(),
David Blaikiea71f9d02011-09-22 02:34:54 +00001809 Unexpanded,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001810 TemplateArgs,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001811 Expand, RetainExpansion,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001812 NumExpansions))
1813 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001814
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001815 if (Expand) {
1816 for (unsigned I = 0; I != *NumExpansions; ++I) {
1817 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
1818 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001819 D->getLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001820 D->getDeclName());
1821 if (!NewDI)
1822 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001823
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001824 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1825 QualType NewT = SemaRef.CheckNonTypeTemplateParameterType(
1826 NewDI->getType(),
1827 D->getLocation());
1828 if (NewT.isNull())
1829 return 0;
1830 ExpandedParameterPackTypes.push_back(NewT);
1831 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001832
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001833 // Note that we have an expanded parameter pack. The "type" of this
1834 // expanded parameter pack is the original expansion type, but callers
1835 // will end up using the expanded parameter pack types for type-checking.
1836 IsExpandedParameterPack = true;
1837 DI = D->getTypeSourceInfo();
1838 T = DI->getType();
1839 } else {
1840 // We cannot fully expand the pack expansion now, so substitute into the
1841 // pattern and create a new pack expansion type.
1842 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
1843 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001844 D->getLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001845 D->getDeclName());
1846 if (!NewPattern)
1847 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001848
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001849 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
1850 NumExpansions);
1851 if (!DI)
1852 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001853
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001854 T = DI->getType();
1855 }
1856 } else {
1857 // Simple case: substitution into a parameter that is not a parameter pack.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001858 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001859 D->getLocation(), D->getDeclName());
1860 if (!DI)
1861 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001862
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001863 // Check that this type is acceptable for a non-type template parameter.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001864 T = SemaRef.CheckNonTypeTemplateParameterType(DI->getType(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001865 D->getLocation());
1866 if (T.isNull()) {
1867 T = SemaRef.Context.IntTy;
1868 Invalid = true;
1869 }
Douglas Gregor33642df2009-10-23 23:25:44 +00001870 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001871
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001872 NonTypeTemplateParmDecl *Param;
1873 if (IsExpandedParameterPack)
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001874 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001875 D->getInnerLocStart(),
1876 D->getLocation(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001877 D->getDepth() - TemplateArgs.getNumLevels(),
1878 D->getPosition(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001879 D->getIdentifier(), T,
1880 DI,
1881 ExpandedParameterPackTypes.data(),
1882 ExpandedParameterPackTypes.size(),
1883 ExpandedParameterPackTypesAsWritten.data());
1884 else
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001885 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001886 D->getInnerLocStart(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001887 D->getLocation(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001888 D->getDepth() - TemplateArgs.getNumLevels(),
1889 D->getPosition(),
1890 D->getIdentifier(), T,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001891 D->isParameterPack(), DI);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001892
Douglas Gregor9a299e02011-03-04 17:52:15 +00001893 Param->setAccess(AS_public);
Douglas Gregor33642df2009-10-23 23:25:44 +00001894 if (Invalid)
1895 Param->setInvalidDecl();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001896
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001897 Param->setDefaultArgument(D->getDefaultArgument(), false);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001898
1899 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor550d9b22009-10-31 17:21:17 +00001900 // scope.
1901 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor33642df2009-10-23 23:25:44 +00001902 return Param;
1903}
1904
Richard Smith6964b3f2012-09-07 02:06:42 +00001905static void collectUnexpandedParameterPacks(
1906 Sema &S,
1907 TemplateParameterList *Params,
1908 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
1909 for (TemplateParameterList::const_iterator I = Params->begin(),
1910 E = Params->end(); I != E; ++I) {
1911 if ((*I)->isTemplateParameterPack())
1912 continue;
1913 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*I))
1914 S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
1915 Unexpanded);
1916 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(*I))
1917 collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
1918 Unexpanded);
1919 }
1920}
1921
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001922Decl *
Douglas Gregor9106ef72009-11-11 16:58:32 +00001923TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1924 TemplateTemplateParmDecl *D) {
1925 // Instantiate the template parameter list of the template template parameter.
1926 TemplateParameterList *TempParams = D->getTemplateParameters();
1927 TemplateParameterList *InstParams;
Richard Smith6964b3f2012-09-07 02:06:42 +00001928 SmallVector<TemplateParameterList*, 8> ExpandedParams;
1929
1930 bool IsExpandedParameterPack = false;
1931
1932 if (D->isExpandedParameterPack()) {
1933 // The template template parameter pack is an already-expanded pack
1934 // expansion of template parameters. Substitute into each of the expanded
1935 // parameters.
1936 ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
1937 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
1938 I != N; ++I) {
1939 LocalInstantiationScope Scope(SemaRef);
1940 TemplateParameterList *Expansion =
1941 SubstTemplateParams(D->getExpansionTemplateParameters(I));
1942 if (!Expansion)
1943 return 0;
1944 ExpandedParams.push_back(Expansion);
1945 }
1946
1947 IsExpandedParameterPack = true;
1948 InstParams = TempParams;
1949 } else if (D->isPackExpansion()) {
1950 // The template template parameter pack expands to a pack of template
1951 // template parameters. Determine whether we need to expand this parameter
1952 // pack into separate parameters.
1953 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1954 collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(),
1955 Unexpanded);
1956
1957 // Determine whether the set of unexpanded parameter packs can and should
1958 // be expanded.
1959 bool Expand = true;
1960 bool RetainExpansion = false;
David Blaikiedc84cd52013-02-20 22:23:23 +00001961 Optional<unsigned> NumExpansions;
Richard Smith6964b3f2012-09-07 02:06:42 +00001962 if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(),
1963 TempParams->getSourceRange(),
1964 Unexpanded,
1965 TemplateArgs,
1966 Expand, RetainExpansion,
1967 NumExpansions))
1968 return 0;
1969
1970 if (Expand) {
1971 for (unsigned I = 0; I != *NumExpansions; ++I) {
1972 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
1973 LocalInstantiationScope Scope(SemaRef);
1974 TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
1975 if (!Expansion)
1976 return 0;
1977 ExpandedParams.push_back(Expansion);
1978 }
1979
1980 // Note that we have an expanded parameter pack. The "type" of this
1981 // expanded parameter pack is the original expansion type, but callers
1982 // will end up using the expanded parameter pack types for type-checking.
1983 IsExpandedParameterPack = true;
1984 InstParams = TempParams;
1985 } else {
1986 // We cannot fully expand the pack expansion now, so just substitute
1987 // into the pattern.
1988 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
1989
1990 LocalInstantiationScope Scope(SemaRef);
1991 InstParams = SubstTemplateParams(TempParams);
1992 if (!InstParams)
1993 return 0;
1994 }
1995 } else {
Douglas Gregor9106ef72009-11-11 16:58:32 +00001996 // Perform the actual substitution of template parameters within a new,
1997 // local instantiation scope.
John McCall2a7fb272010-08-25 05:32:35 +00001998 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor9106ef72009-11-11 16:58:32 +00001999 InstParams = SubstTemplateParams(TempParams);
2000 if (!InstParams)
Richard Smith6964b3f2012-09-07 02:06:42 +00002001 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002002 }
2003
Douglas Gregor9106ef72009-11-11 16:58:32 +00002004 // Build the template template parameter.
Richard Smith6964b3f2012-09-07 02:06:42 +00002005 TemplateTemplateParmDecl *Param;
2006 if (IsExpandedParameterPack)
2007 Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
2008 D->getLocation(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002009 D->getDepth() - TemplateArgs.getNumLevels(),
Richard Smith6964b3f2012-09-07 02:06:42 +00002010 D->getPosition(),
2011 D->getIdentifier(), InstParams,
2012 ExpandedParams);
2013 else
2014 Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
2015 D->getLocation(),
2016 D->getDepth() - TemplateArgs.getNumLevels(),
2017 D->getPosition(),
2018 D->isParameterPack(),
2019 D->getIdentifier(), InstParams);
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00002020 Param->setDefaultArgument(D->getDefaultArgument(), false);
Douglas Gregor9a299e02011-03-04 17:52:15 +00002021 Param->setAccess(AS_public);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002022
2023 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor9106ef72009-11-11 16:58:32 +00002024 // scope.
2025 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002026
Douglas Gregor9106ef72009-11-11 16:58:32 +00002027 return Param;
2028}
2029
Douglas Gregor48c32a72009-11-17 06:07:40 +00002030Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregordb992412011-02-25 16:33:46 +00002031 // Using directives are never dependent (and never contain any types or
2032 // expressions), so they require no explicit instantiation work.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002033
Douglas Gregor48c32a72009-11-17 06:07:40 +00002034 UsingDirectiveDecl *Inst
2035 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002036 D->getNamespaceKeyLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00002037 D->getQualifierLoc(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002038 D->getIdentLocation(),
2039 D->getNominatedNamespace(),
Douglas Gregor48c32a72009-11-17 06:07:40 +00002040 D->getCommonAncestor());
Abramo Bagnara536afbe2012-09-05 09:55:10 +00002041
2042 // Add the using directive to its declaration context
2043 // only if this is not a function or method.
2044 if (!Owner->isFunctionOrMethod())
2045 Owner->addDecl(Inst);
2046
Douglas Gregor48c32a72009-11-17 06:07:40 +00002047 return Inst;
2048}
2049
John McCalled976492009-12-04 22:46:56 +00002050Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
Douglas Gregor1b398202010-09-29 17:58:28 +00002051
2052 // The nested name specifier may be dependent, for example
2053 // template <typename T> struct t {
2054 // struct s1 { T f1(); };
2055 // struct s2 : s1 { using s1::f1; };
2056 // };
2057 // template struct t<int>;
2058 // Here, in using s1::f1, s1 refers to t<T>::s1;
2059 // we need to substitute for t<int>::s1.
Douglas Gregor5149f372011-02-25 15:54:31 +00002060 NestedNameSpecifierLoc QualifierLoc
2061 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
2062 TemplateArgs);
2063 if (!QualifierLoc)
Douglas Gregordc355712011-02-25 00:36:19 +00002064 return 0;
Douglas Gregor1b398202010-09-29 17:58:28 +00002065
2066 // The name info is non-dependent, so no transformation
2067 // is required.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002068 DeclarationNameInfo NameInfo = D->getNameInfo();
John McCalled976492009-12-04 22:46:56 +00002069
John McCall9f54ad42009-12-10 09:41:52 +00002070 // We only need to do redeclaration lookups if we're in a class
2071 // scope (in fact, it's not really even possible in non-class
2072 // scopes).
2073 bool CheckRedeclaration = Owner->isRecord();
2074
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002075 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
2076 Sema::ForRedeclaration);
John McCall9f54ad42009-12-10 09:41:52 +00002077
John McCalled976492009-12-04 22:46:56 +00002078 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
John McCalled976492009-12-04 22:46:56 +00002079 D->getUsingLocation(),
Douglas Gregor5149f372011-02-25 15:54:31 +00002080 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002081 NameInfo,
John McCalled976492009-12-04 22:46:56 +00002082 D->isTypeName());
2083
Douglas Gregor5149f372011-02-25 15:54:31 +00002084 CXXScopeSpec SS;
2085 SS.Adopt(QualifierLoc);
John McCall9f54ad42009-12-10 09:41:52 +00002086 if (CheckRedeclaration) {
2087 Prev.setHideTags(false);
2088 SemaRef.LookupQualifiedName(Prev, Owner);
2089
2090 // Check for invalid redeclarations.
2091 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
2092 D->isTypeName(), SS,
2093 D->getLocation(), Prev))
2094 NewUD->setInvalidDecl();
2095
2096 }
2097
2098 if (!NewUD->isInvalidDecl() &&
2099 SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
John McCalled976492009-12-04 22:46:56 +00002100 D->getLocation()))
2101 NewUD->setInvalidDecl();
John McCall9f54ad42009-12-10 09:41:52 +00002102
John McCalled976492009-12-04 22:46:56 +00002103 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
2104 NewUD->setAccess(D->getAccess());
2105 Owner->addDecl(NewUD);
2106
John McCall9f54ad42009-12-10 09:41:52 +00002107 // Don't process the shadow decls for an invalid decl.
2108 if (NewUD->isInvalidDecl())
2109 return NewUD;
2110
Richard Smithc5a89a12012-04-02 01:30:27 +00002111 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
2112 if (SemaRef.CheckInheritingConstructorUsingDecl(NewUD))
2113 NewUD->setInvalidDecl();
2114 return NewUD;
2115 }
2116
John McCall323c3102009-12-22 22:26:37 +00002117 bool isFunctionScope = Owner->isFunctionOrMethod();
2118
John McCall9f54ad42009-12-10 09:41:52 +00002119 // Process the shadow decls.
2120 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
2121 I != E; ++I) {
2122 UsingShadowDecl *Shadow = *I;
2123 NamedDecl *InstTarget =
Douglas Gregorb7107222011-03-04 19:46:35 +00002124 cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
2125 Shadow->getLocation(),
2126 Shadow->getTargetDecl(),
2127 TemplateArgs));
2128 if (!InstTarget)
2129 return 0;
John McCall9f54ad42009-12-10 09:41:52 +00002130
2131 if (CheckRedeclaration &&
2132 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
2133 continue;
2134
2135 UsingShadowDecl *InstShadow
2136 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
2137 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCall323c3102009-12-22 22:26:37 +00002138
2139 if (isFunctionScope)
2140 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall9f54ad42009-12-10 09:41:52 +00002141 }
John McCalled976492009-12-04 22:46:56 +00002142
2143 return NewUD;
2144}
2145
2146Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall9f54ad42009-12-10 09:41:52 +00002147 // Ignore these; we handle them in bulk when processing the UsingDecl.
2148 return 0;
John McCalled976492009-12-04 22:46:56 +00002149}
2150
John McCall7ba107a2009-11-18 02:36:19 +00002151Decl * TemplateDeclInstantiator
2152 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Douglas Gregor5149f372011-02-25 15:54:31 +00002153 NestedNameSpecifierLoc QualifierLoc
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002154 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
Douglas Gregor5149f372011-02-25 15:54:31 +00002155 TemplateArgs);
2156 if (!QualifierLoc)
Anders Carlsson0dde18e2009-08-28 15:18:15 +00002157 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002158
Anders Carlsson0dde18e2009-08-28 15:18:15 +00002159 CXXScopeSpec SS;
Douglas Gregor5149f372011-02-25 15:54:31 +00002160 SS.Adopt(QualifierLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00002161
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002162 // Since NameInfo refers to a typename, it cannot be a C++ special name.
Benjamin Krameraccaf192012-11-14 15:08:31 +00002163 // Hence, no transformation is required for it.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002164 DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002165 NamedDecl *UD =
John McCall9488ea12009-11-17 05:59:44 +00002166 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002167 D->getUsingLoc(), SS, NameInfo, 0,
John McCall7ba107a2009-11-18 02:36:19 +00002168 /*instantiation*/ true,
2169 /*typename*/ true, D->getTypenameLoc());
Douglas Gregor4469e8a2010-05-19 17:02:24 +00002170 if (UD)
John McCalled976492009-12-04 22:46:56 +00002171 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
2172
John McCall7ba107a2009-11-18 02:36:19 +00002173 return UD;
2174}
2175
2176Decl * TemplateDeclInstantiator
2177 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregor5149f372011-02-25 15:54:31 +00002178 NestedNameSpecifierLoc QualifierLoc
2179 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), TemplateArgs);
2180 if (!QualifierLoc)
John McCall7ba107a2009-11-18 02:36:19 +00002181 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002182
John McCall7ba107a2009-11-18 02:36:19 +00002183 CXXScopeSpec SS;
Douglas Gregor5149f372011-02-25 15:54:31 +00002184 SS.Adopt(QualifierLoc);
John McCall7ba107a2009-11-18 02:36:19 +00002185
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002186 DeclarationNameInfo NameInfo
2187 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2188
John McCall7ba107a2009-11-18 02:36:19 +00002189 NamedDecl *UD =
2190 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002191 D->getUsingLoc(), SS, NameInfo, 0,
John McCall7ba107a2009-11-18 02:36:19 +00002192 /*instantiation*/ true,
2193 /*typename*/ false, SourceLocation());
Douglas Gregor4469e8a2010-05-19 17:02:24 +00002194 if (UD)
John McCalled976492009-12-04 22:46:56 +00002195 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
2196
Anders Carlsson0d8df782009-08-29 19:37:28 +00002197 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +00002198}
2199
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002200
2201Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
2202 ClassScopeFunctionSpecializationDecl *Decl) {
2203 CXXMethodDecl *OldFD = Decl->getSpecialization();
Nico Weber6b020092012-06-25 17:21:05 +00002204 CXXMethodDecl *NewFD = cast<CXXMethodDecl>(VisitCXXMethodDecl(OldFD,
2205 0, true));
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002206
2207 LookupResult Previous(SemaRef, NewFD->getNameInfo(), Sema::LookupOrdinaryName,
2208 Sema::ForRedeclaration);
2209
Nico Weber6b020092012-06-25 17:21:05 +00002210 TemplateArgumentListInfo TemplateArgs;
2211 TemplateArgumentListInfo* TemplateArgsPtr = 0;
2212 if (Decl->hasExplicitTemplateArgs()) {
2213 TemplateArgs = Decl->templateArgs();
2214 TemplateArgsPtr = &TemplateArgs;
2215 }
2216
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002217 SemaRef.LookupQualifiedName(Previous, SemaRef.CurContext);
Nico Weber6b020092012-06-25 17:21:05 +00002218 if (SemaRef.CheckFunctionTemplateSpecialization(NewFD, TemplateArgsPtr,
2219 Previous)) {
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002220 NewFD->setInvalidDecl();
2221 return NewFD;
2222 }
2223
2224 // Associate the specialization with the pattern.
2225 FunctionDecl *Specialization = cast<FunctionDecl>(Previous.getFoundDecl());
2226 assert(Specialization && "Class scope Specialization is null");
2227 SemaRef.Context.setClassScopeSpecializationPattern(Specialization, OldFD);
2228
2229 return NewFD;
2230}
2231
Alexey Bataevc6400582013-03-22 06:34:35 +00002232Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
2233 OMPThreadPrivateDecl *D) {
2234 SmallVector<DeclRefExpr *, 5> Vars;
2235 for (ArrayRef<DeclRefExpr *>::iterator I = D->varlist_begin(),
2236 E = D->varlist_end();
2237 I != E; ++I) {
2238 Expr *Var = SemaRef.SubstExpr(*I, TemplateArgs).take();
2239 assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
2240 Vars.push_back(cast<DeclRefExpr>(Var));
2241 }
2242
2243 OMPThreadPrivateDecl *TD =
2244 SemaRef.CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
2245
2246 return TD;
2247}
2248
John McCallce3ff2b2009-08-25 22:02:44 +00002249Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +00002250 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +00002251 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor2fa98002010-02-16 19:28:15 +00002252 if (D->isInvalidDecl())
2253 return 0;
2254
Douglas Gregor8dbc2692009-03-17 21:15:40 +00002255 return Instantiator.Visit(D);
2256}
2257
John McCalle29ba202009-08-20 01:44:21 +00002258/// \brief Instantiates a nested template parameter list in the current
2259/// instantiation context.
2260///
2261/// \param L The parameter list to instantiate
2262///
2263/// \returns NULL if there was an error
2264TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +00002265TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +00002266 // Get errors for all the parameters before bailing out.
2267 bool Invalid = false;
2268
2269 unsigned N = L->size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00002270 typedef SmallVector<NamedDecl *, 8> ParamVector;
John McCalle29ba202009-08-20 01:44:21 +00002271 ParamVector Params;
2272 Params.reserve(N);
2273 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
2274 PI != PE; ++PI) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002275 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCalle29ba202009-08-20 01:44:21 +00002276 Params.push_back(D);
Douglas Gregor9148c3f2009-11-11 19:13:48 +00002277 Invalid = Invalid || !D || D->isInvalidDecl();
John McCalle29ba202009-08-20 01:44:21 +00002278 }
2279
2280 // Clean up if we had an error.
Douglas Gregorff331c12010-07-25 18:17:45 +00002281 if (Invalid)
John McCalle29ba202009-08-20 01:44:21 +00002282 return NULL;
John McCalle29ba202009-08-20 01:44:21 +00002283
2284 TemplateParameterList *InstL
2285 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
2286 L->getLAngleLoc(), &Params.front(), N,
2287 L->getRAngleLoc());
2288 return InstL;
Mike Stump1eb44332009-09-09 15:08:12 +00002289}
John McCalle29ba202009-08-20 01:44:21 +00002290
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002291/// \brief Instantiate the declaration of a class template partial
Douglas Gregored9c0f92009-10-29 00:04:11 +00002292/// specialization.
2293///
2294/// \param ClassTemplate the (instantiated) class template that is partially
2295// specialized by the instantiation of \p PartialSpec.
2296///
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002297/// \param PartialSpec the (uninstantiated) class template partial
Douglas Gregored9c0f92009-10-29 00:04:11 +00002298/// specialization that we are instantiating.
2299///
Douglas Gregord65587f2010-11-10 19:44:59 +00002300/// \returns The instantiated partial specialization, if successful; otherwise,
2301/// NULL to indicate an error.
2302ClassTemplatePartialSpecializationDecl *
Douglas Gregored9c0f92009-10-29 00:04:11 +00002303TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
2304 ClassTemplateDecl *ClassTemplate,
2305 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00002306 // Create a local instantiation scope for this class template partial
2307 // specialization, which will contain the instantiations of the template
2308 // parameters.
John McCall2a7fb272010-08-25 05:32:35 +00002309 LocalInstantiationScope Scope(SemaRef);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002310
Douglas Gregored9c0f92009-10-29 00:04:11 +00002311 // Substitute into the template parameters of the class template partial
2312 // specialization.
2313 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
2314 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2315 if (!InstParams)
Douglas Gregord65587f2010-11-10 19:44:59 +00002316 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002317
Douglas Gregored9c0f92009-10-29 00:04:11 +00002318 // Substitute into the template arguments of the class template partial
2319 // specialization.
John McCalld5532b62009-11-23 01:53:49 +00002320 TemplateArgumentListInfo InstTemplateArgs; // no angle locations
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002321 if (SemaRef.Subst(PartialSpec->getTemplateArgsAsWritten(),
2322 PartialSpec->getNumTemplateArgsAsWritten(),
Douglas Gregore02e2622010-12-22 21:19:48 +00002323 InstTemplateArgs, TemplateArgs))
2324 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002325
Douglas Gregored9c0f92009-10-29 00:04:11 +00002326 // Check that the template argument list is well-formed for this
2327 // class template.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002328 SmallVector<TemplateArgument, 4> Converted;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002329 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002330 PartialSpec->getLocation(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002331 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002332 false,
2333 Converted))
Douglas Gregord65587f2010-11-10 19:44:59 +00002334 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00002335
2336 // Figure out where to insert this class template partial specialization
2337 // in the member template's set of class template partial specializations.
Douglas Gregored9c0f92009-10-29 00:04:11 +00002338 void *InsertPos = 0;
2339 ClassTemplateSpecializationDecl *PrevDecl
Douglas Gregor910f8002010-11-07 23:05:16 +00002340 = ClassTemplate->findPartialSpecialization(Converted.data(),
2341 Converted.size(), InsertPos);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002342
Douglas Gregored9c0f92009-10-29 00:04:11 +00002343 // Build the canonical type that describes the converted template
2344 // arguments of the class template partial specialization.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002345 QualType CanonType
Douglas Gregored9c0f92009-10-29 00:04:11 +00002346 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
Douglas Gregor910f8002010-11-07 23:05:16 +00002347 Converted.data(),
2348 Converted.size());
Douglas Gregored9c0f92009-10-29 00:04:11 +00002349
2350 // Build the fully-sugared type for this class template
2351 // specialization as the user wrote in the specialization
2352 // itself. This means that we'll pretty-print the type retrieved
2353 // from the specialization's declaration the way that the user
2354 // actually wrote the specialization, rather than formatting the
2355 // name based on the "canonical" representation used to store the
2356 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00002357 TypeSourceInfo *WrittenTy
2358 = SemaRef.Context.getTemplateSpecializationTypeInfo(
2359 TemplateName(ClassTemplate),
2360 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00002361 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002362 CanonType);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002363
Douglas Gregored9c0f92009-10-29 00:04:11 +00002364 if (PrevDecl) {
2365 // We've already seen a partial specialization with the same template
2366 // parameters and template arguments. This can happen, for example, when
2367 // substituting the outer template arguments ends up causing two
2368 // class template partial specializations of a member class template
2369 // to have identical forms, e.g.,
2370 //
2371 // template<typename T, typename U>
2372 // struct Outer {
2373 // template<typename X, typename Y> struct Inner;
2374 // template<typename Y> struct Inner<T, Y>;
2375 // template<typename Y> struct Inner<U, Y>;
2376 // };
2377 //
2378 // Outer<int, int> outer; // error: the partial specializations of Inner
2379 // // have the same signature.
2380 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
Douglas Gregord65587f2010-11-10 19:44:59 +00002381 << WrittenTy->getType();
Douglas Gregored9c0f92009-10-29 00:04:11 +00002382 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
2383 << SemaRef.Context.getTypeDeclType(PrevDecl);
Douglas Gregord65587f2010-11-10 19:44:59 +00002384 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00002385 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002386
2387
Douglas Gregored9c0f92009-10-29 00:04:11 +00002388 // Create the class template partial specialization declaration.
2389 ClassTemplatePartialSpecializationDecl *InstPartialSpec
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002390 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
Douglas Gregor13c85772010-05-06 00:28:52 +00002391 PartialSpec->getTagKind(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002392 Owner,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002393 PartialSpec->getLocStart(),
2394 PartialSpec->getLocation(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00002395 InstParams,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002396 ClassTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00002397 Converted.data(),
2398 Converted.size(),
John McCalld5532b62009-11-23 01:53:49 +00002399 InstTemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00002400 CanonType,
Douglas Gregordc60c1e2010-04-30 05:56:50 +00002401 0,
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00002402 ClassTemplate->getNextPartialSpecSequenceNumber());
John McCallb6217662010-03-15 10:12:16 +00002403 // Substitute the nested name specifier, if any.
2404 if (SubstQualifier(PartialSpec, InstPartialSpec))
2405 return 0;
2406
Douglas Gregored9c0f92009-10-29 00:04:11 +00002407 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
Douglas Gregor4469e8a2010-05-19 17:02:24 +00002408 InstPartialSpec->setTypeAsWritten(WrittenTy);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002409
Douglas Gregored9c0f92009-10-29 00:04:11 +00002410 // Add this partial specialization to the set of class template partial
2411 // specializations.
Douglas Gregor1e1e9722012-03-28 14:34:23 +00002412 ClassTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/0);
Douglas Gregord65587f2010-11-10 19:44:59 +00002413 return InstPartialSpec;
Douglas Gregored9c0f92009-10-29 00:04:11 +00002414}
2415
John McCall21ef0fa2010-03-11 09:03:00 +00002416TypeSourceInfo*
John McCallce3ff2b2009-08-25 22:02:44 +00002417TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002418 SmallVectorImpl<ParmVarDecl *> &Params) {
John McCall21ef0fa2010-03-11 09:03:00 +00002419 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
2420 assert(OldTInfo && "substituting function without type source info");
2421 assert(Params.empty() && "parameter vector is non-empty at start");
Douglas Gregorcefc3af2012-04-16 07:05:22 +00002422
2423 CXXRecordDecl *ThisContext = 0;
2424 unsigned ThisTypeQuals = 0;
2425 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
2426 ThisContext = Method->getParent();
2427 ThisTypeQuals = Method->getTypeQualifiers();
2428 }
2429
John McCall6cd3b9f2010-04-09 17:38:44 +00002430 TypeSourceInfo *NewTInfo
2431 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
2432 D->getTypeSpecStartLoc(),
Douglas Gregorcefc3af2012-04-16 07:05:22 +00002433 D->getDeclName(),
2434 ThisContext, ThisTypeQuals);
John McCall21ef0fa2010-03-11 09:03:00 +00002435 if (!NewTInfo)
2436 return 0;
Douglas Gregor5545e162009-03-24 00:38:23 +00002437
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00002438 if (NewTInfo != OldTInfo) {
2439 // Get parameters from the new type info.
Abramo Bagnara140a2bd2010-12-13 22:27:55 +00002440 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
David Blaikie39e6ab42013-02-18 22:06:02 +00002441 if (FunctionProtoTypeLoc OldProtoLoc =
2442 OldTL.getAs<FunctionProtoTypeLoc>()) {
Abramo Bagnara140a2bd2010-12-13 22:27:55 +00002443 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
David Blaikie39e6ab42013-02-18 22:06:02 +00002444 FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
Richard Smith500d7292012-07-18 01:29:05 +00002445 unsigned NewIdx = 0;
David Blaikie39e6ab42013-02-18 22:06:02 +00002446 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumArgs();
Douglas Gregor12c9c002011-01-07 16:43:16 +00002447 OldIdx != NumOldParams; ++OldIdx) {
David Blaikie39e6ab42013-02-18 22:06:02 +00002448 ParmVarDecl *OldParam = OldProtoLoc.getArg(OldIdx);
Richard Smith500d7292012-07-18 01:29:05 +00002449 LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
2450
David Blaikiedc84cd52013-02-20 22:23:23 +00002451 Optional<unsigned> NumArgumentsInExpansion;
Richard Smith500d7292012-07-18 01:29:05 +00002452 if (OldParam->isParameterPack())
2453 NumArgumentsInExpansion =
2454 SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
2455 TemplateArgs);
2456 if (!NumArgumentsInExpansion) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002457 // Simple case: normal parameter, or a parameter pack that's
Douglas Gregor12c9c002011-01-07 16:43:16 +00002458 // instantiated to a (still-dependent) parameter pack.
David Blaikie39e6ab42013-02-18 22:06:02 +00002459 ParmVarDecl *NewParam = NewProtoLoc.getArg(NewIdx++);
Douglas Gregor12c9c002011-01-07 16:43:16 +00002460 Params.push_back(NewParam);
Richard Smith500d7292012-07-18 01:29:05 +00002461 Scope->InstantiatedLocal(OldParam, NewParam);
2462 } else {
2463 // Parameter pack expansion: make the instantiation an argument pack.
2464 Scope->MakeInstantiatedLocalArgPack(OldParam);
2465 for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
David Blaikie39e6ab42013-02-18 22:06:02 +00002466 ParmVarDecl *NewParam = NewProtoLoc.getArg(NewIdx++);
Richard Smith500d7292012-07-18 01:29:05 +00002467 Params.push_back(NewParam);
2468 Scope->InstantiatedLocalPackArg(OldParam, NewParam);
2469 }
Douglas Gregor12c9c002011-01-07 16:43:16 +00002470 }
Douglas Gregor6920cdc2010-05-03 15:32:18 +00002471 }
Douglas Gregor895162d2010-04-30 18:55:50 +00002472 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00002473 } else {
2474 // The function type itself was not dependent and therefore no
2475 // substitution occurred. However, we still need to instantiate
2476 // the function parameters themselves.
Abramo Bagnara140a2bd2010-12-13 22:27:55 +00002477 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
David Blaikie39e6ab42013-02-18 22:06:02 +00002478 if (FunctionProtoTypeLoc OldProtoLoc =
2479 OldTL.getAs<FunctionProtoTypeLoc>()) {
2480 for (unsigned i = 0, i_end = OldProtoLoc.getNumArgs(); i != i_end; ++i) {
2481 ParmVarDecl *Parm = VisitParmVarDecl(OldProtoLoc.getArg(i));
Douglas Gregor6920cdc2010-05-03 15:32:18 +00002482 if (!Parm)
2483 return 0;
2484 Params.push_back(Parm);
2485 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00002486 }
2487 }
John McCall21ef0fa2010-03-11 09:03:00 +00002488 return NewTInfo;
Douglas Gregor5545e162009-03-24 00:38:23 +00002489}
2490
Richard Smithe6975e92012-04-17 00:58:00 +00002491/// Introduce the instantiated function parameters into the local
2492/// instantiation scope, and set the parameter names to those used
2493/// in the template.
2494static void addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function,
2495 const FunctionDecl *PatternDecl,
2496 LocalInstantiationScope &Scope,
2497 const MultiLevelTemplateArgumentList &TemplateArgs) {
2498 unsigned FParamIdx = 0;
2499 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
2500 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
2501 if (!PatternParam->isParameterPack()) {
2502 // Simple case: not a parameter pack.
2503 assert(FParamIdx < Function->getNumParams());
2504 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
2505 FunctionParam->setDeclName(PatternParam->getDeclName());
2506 Scope.InstantiatedLocal(PatternParam, FunctionParam);
2507 ++FParamIdx;
2508 continue;
2509 }
2510
2511 // Expand the parameter pack.
2512 Scope.MakeInstantiatedLocalArgPack(PatternParam);
David Blaikiedc84cd52013-02-20 22:23:23 +00002513 Optional<unsigned> NumArgumentsInExpansion
Richard Smithe6975e92012-04-17 00:58:00 +00002514 = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
Richard Smith500d7292012-07-18 01:29:05 +00002515 assert(NumArgumentsInExpansion &&
2516 "should only be called when all template arguments are known");
2517 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
Richard Smithe6975e92012-04-17 00:58:00 +00002518 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
2519 FunctionParam->setDeclName(PatternParam->getDeclName());
2520 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
2521 ++FParamIdx;
2522 }
2523 }
2524}
2525
2526static void InstantiateExceptionSpec(Sema &SemaRef, FunctionDecl *New,
2527 const FunctionProtoType *Proto,
2528 const MultiLevelTemplateArgumentList &TemplateArgs) {
Richard Smith13bffc52012-04-19 00:08:28 +00002529 assert(Proto->getExceptionSpecType() != EST_Uninstantiated);
2530
Richard Smithe6975e92012-04-17 00:58:00 +00002531 // C++11 [expr.prim.general]p3:
2532 // If a declaration declares a member function or member function
2533 // template of a class X, the expression this is a prvalue of type
2534 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
2535 // and the end of the function-definition, member-declarator, or
2536 // declarator.
2537 CXXRecordDecl *ThisContext = 0;
2538 unsigned ThisTypeQuals = 0;
2539 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(New)) {
2540 ThisContext = Method->getParent();
2541 ThisTypeQuals = Method->getTypeQualifiers();
2542 }
2543 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals,
Richard Smith80ad52f2013-01-02 11:42:31 +00002544 SemaRef.getLangOpts().CPlusPlus11);
Richard Smithe6975e92012-04-17 00:58:00 +00002545
2546 // The function has an exception specification or a "noreturn"
2547 // attribute. Substitute into each of the exception types.
2548 SmallVector<QualType, 4> Exceptions;
2549 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
2550 // FIXME: Poor location information!
2551 if (const PackExpansionType *PackExpansion
2552 = Proto->getExceptionType(I)->getAs<PackExpansionType>()) {
2553 // We have a pack expansion. Instantiate it.
2554 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2555 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
2556 Unexpanded);
2557 assert(!Unexpanded.empty() &&
2558 "Pack expansion without parameter packs?");
2559
2560 bool Expand = false;
2561 bool RetainExpansion = false;
David Blaikiedc84cd52013-02-20 22:23:23 +00002562 Optional<unsigned> NumExpansions
Richard Smithe6975e92012-04-17 00:58:00 +00002563 = PackExpansion->getNumExpansions();
2564 if (SemaRef.CheckParameterPacksForExpansion(New->getLocation(),
2565 SourceRange(),
2566 Unexpanded,
2567 TemplateArgs,
2568 Expand,
2569 RetainExpansion,
2570 NumExpansions))
2571 break;
2572
2573 if (!Expand) {
2574 // We can't expand this pack expansion into separate arguments yet;
2575 // just substitute into the pattern and create a new pack expansion
2576 // type.
2577 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2578 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2579 TemplateArgs,
2580 New->getLocation(), New->getDeclName());
2581 if (T.isNull())
2582 break;
2583
2584 T = SemaRef.Context.getPackExpansionType(T, NumExpansions);
2585 Exceptions.push_back(T);
2586 continue;
2587 }
2588
2589 // Substitute into the pack expansion pattern for each template
2590 bool Invalid = false;
2591 for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
2592 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, ArgIdx);
2593
2594 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2595 TemplateArgs,
2596 New->getLocation(), New->getDeclName());
2597 if (T.isNull()) {
2598 Invalid = true;
2599 break;
2600 }
2601
2602 Exceptions.push_back(T);
2603 }
2604
2605 if (Invalid)
2606 break;
2607
2608 continue;
2609 }
2610
2611 QualType T
2612 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
2613 New->getLocation(), New->getDeclName());
2614 if (T.isNull() ||
2615 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
2616 continue;
2617
2618 Exceptions.push_back(T);
2619 }
2620 Expr *NoexceptExpr = 0;
2621 if (Expr *OldNoexceptExpr = Proto->getNoexceptExpr()) {
2622 EnterExpressionEvaluationContext Unevaluated(SemaRef,
2623 Sema::ConstantEvaluated);
2624 ExprResult E = SemaRef.SubstExpr(OldNoexceptExpr, TemplateArgs);
2625 if (E.isUsable())
2626 E = SemaRef.CheckBooleanCondition(E.get(), E.get()->getLocStart());
2627
2628 if (E.isUsable()) {
2629 NoexceptExpr = E.take();
2630 if (!NoexceptExpr->isTypeDependent() &&
2631 !NoexceptExpr->isValueDependent())
Douglas Gregorab41fe92012-05-04 22:38:52 +00002632 NoexceptExpr
2633 = SemaRef.VerifyIntegerConstantExpression(NoexceptExpr,
2634 0, diag::err_noexcept_needs_constant_expression,
2635 /*AllowFold*/ false).take();
Richard Smithe6975e92012-04-17 00:58:00 +00002636 }
2637 }
2638
2639 // Rebuild the function type
2640 const FunctionProtoType *NewProto
2641 = New->getType()->getAs<FunctionProtoType>();
2642 assert(NewProto && "Template instantiation without function prototype?");
2643
2644 FunctionProtoType::ExtProtoInfo EPI = NewProto->getExtProtoInfo();
2645 EPI.ExceptionSpecType = Proto->getExceptionSpecType();
2646 EPI.NumExceptions = Exceptions.size();
2647 EPI.Exceptions = Exceptions.data();
2648 EPI.NoexceptExpr = NoexceptExpr;
2649
2650 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002651 ArrayRef<QualType>(NewProto->arg_type_begin(),
2652 NewProto->getNumArgs()),
Richard Smithe6975e92012-04-17 00:58:00 +00002653 EPI));
2654}
2655
2656void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
2657 FunctionDecl *Decl) {
Richard Smith13bffc52012-04-19 00:08:28 +00002658 const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
2659 if (Proto->getExceptionSpecType() != EST_Uninstantiated)
Richard Smithe6975e92012-04-17 00:58:00 +00002660 return;
2661
2662 InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
2663 InstantiatingTemplate::ExceptionSpecification());
Richard Smithb9d0b762012-07-27 04:22:15 +00002664 if (Inst) {
2665 // We hit the instantiation depth limit. Clear the exception specification
2666 // so that our callers don't have to cope with EST_Uninstantiated.
2667 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
2668 EPI.ExceptionSpecType = EST_None;
2669 Decl->setType(Context.getFunctionType(Proto->getResultType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002670 ArrayRef<QualType>(Proto->arg_type_begin(),
2671 Proto->getNumArgs()),
Richard Smithb9d0b762012-07-27 04:22:15 +00002672 EPI));
Richard Smithe6975e92012-04-17 00:58:00 +00002673 return;
Richard Smithb9d0b762012-07-27 04:22:15 +00002674 }
Richard Smithe6975e92012-04-17 00:58:00 +00002675
2676 // Enter the scope of this instantiation. We don't use
2677 // PushDeclContext because we don't have a scope.
2678 Sema::ContextRAII savedContext(*this, Decl);
2679 LocalInstantiationScope Scope(*this);
2680
2681 MultiLevelTemplateArgumentList TemplateArgs =
2682 getTemplateInstantiationArgs(Decl, 0, /*RelativeToPrimary*/true);
2683
Richard Smith13bffc52012-04-19 00:08:28 +00002684 FunctionDecl *Template = Proto->getExceptionSpecTemplate();
2685 addInstantiatedParametersToScope(*this, Decl, Template, Scope, TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +00002686
Richard Smith13bffc52012-04-19 00:08:28 +00002687 ::InstantiateExceptionSpec(*this, Decl,
2688 Template->getType()->castAs<FunctionProtoType>(),
2689 TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +00002690}
2691
Mike Stump1eb44332009-09-09 15:08:12 +00002692/// \brief Initializes the common fields of an instantiation function
Douglas Gregore53060f2009-06-25 22:08:12 +00002693/// declaration (New) from the corresponding fields of its template (Tmpl).
2694///
2695/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00002696bool
2697TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregore53060f2009-06-25 22:08:12 +00002698 FunctionDecl *Tmpl) {
David Blaikie85f485a2012-07-16 18:50:45 +00002699 if (Tmpl->isDeleted())
Sean Hunt10620eb2011-05-06 20:44:56 +00002700 New->setDeletedAsWritten();
Mike Stump1eb44332009-09-09 15:08:12 +00002701
Douglas Gregorcca9e962009-07-01 22:01:06 +00002702 // If we are performing substituting explicitly-specified template arguments
2703 // or deduced template arguments into a function template and we reach this
2704 // point, we are now past the point where SFINAE applies and have committed
Mike Stump1eb44332009-09-09 15:08:12 +00002705 // to keeping the new function template specialization. We therefore
2706 // convert the active template instantiation for the function template
Douglas Gregorcca9e962009-07-01 22:01:06 +00002707 // into a template instantiation for this specific function template
2708 // specialization, which is not a SFINAE context, so that we diagnose any
2709 // further errors in the declaration itself.
2710 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
2711 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
2712 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
2713 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump1eb44332009-09-09 15:08:12 +00002714 if (FunctionTemplateDecl *FunTmpl
Nick Lewycky4a9e60f2012-11-16 08:40:59 +00002715 = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002716 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorcca9e962009-07-01 22:01:06 +00002717 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +00002718 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +00002719 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
Nick Lewycky4a9e60f2012-11-16 08:40:59 +00002720 ActiveInst.Entity = New;
Douglas Gregorcca9e962009-07-01 22:01:06 +00002721 }
2722 }
Mike Stump1eb44332009-09-09 15:08:12 +00002723
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002724 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
2725 assert(Proto && "Function template without prototype?");
2726
Sebastian Redl60618fa2011-03-12 11:50:43 +00002727 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
John McCalle23cf432010-12-14 08:05:40 +00002728 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
John McCalle23cf432010-12-14 08:05:40 +00002729
Richard Smithe6975e92012-04-17 00:58:00 +00002730 // DR1330: In C++11, defer instantiation of a non-trivial
2731 // exception specification.
Richard Smith80ad52f2013-01-02 11:42:31 +00002732 if (SemaRef.getLangOpts().CPlusPlus11 &&
Richard Smithe6975e92012-04-17 00:58:00 +00002733 EPI.ExceptionSpecType != EST_None &&
2734 EPI.ExceptionSpecType != EST_DynamicNone &&
2735 EPI.ExceptionSpecType != EST_BasicNoexcept) {
Richard Smith13bffc52012-04-19 00:08:28 +00002736 FunctionDecl *ExceptionSpecTemplate = Tmpl;
2737 if (EPI.ExceptionSpecType == EST_Uninstantiated)
2738 ExceptionSpecTemplate = EPI.ExceptionSpecTemplate;
Richard Smith4841ca52013-04-10 05:48:59 +00002739 ExceptionSpecificationType NewEST = EST_Uninstantiated;
2740 if (EPI.ExceptionSpecType == EST_Unevaluated)
2741 NewEST = EST_Unevaluated;
Richard Smith13bffc52012-04-19 00:08:28 +00002742
Richard Smithe6975e92012-04-17 00:58:00 +00002743 // Mark the function has having an uninstantiated exception specification.
2744 const FunctionProtoType *NewProto
2745 = New->getType()->getAs<FunctionProtoType>();
2746 assert(NewProto && "Template instantiation without function prototype?");
2747 EPI = NewProto->getExtProtoInfo();
Richard Smith4841ca52013-04-10 05:48:59 +00002748 EPI.ExceptionSpecType = NewEST;
Richard Smithe6975e92012-04-17 00:58:00 +00002749 EPI.ExceptionSpecDecl = New;
Richard Smith13bffc52012-04-19 00:08:28 +00002750 EPI.ExceptionSpecTemplate = ExceptionSpecTemplate;
Richard Smithe6975e92012-04-17 00:58:00 +00002751 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002752 ArrayRef<QualType>(NewProto->arg_type_begin(),
2753 NewProto->getNumArgs()),
Richard Smithe6975e92012-04-17 00:58:00 +00002754 EPI));
2755 } else {
2756 ::InstantiateExceptionSpec(SemaRef, New, Proto, TemplateArgs);
2757 }
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002758 }
2759
Rafael Espindola19f74ac2011-07-06 15:46:09 +00002760 // Get the definition. Leaves the variable unchanged if undefined.
Richard Smithe6975e92012-04-17 00:58:00 +00002761 const FunctionDecl *Definition = Tmpl;
Rafael Espindola19f74ac2011-07-06 15:46:09 +00002762 Tmpl->isDefined(Definition);
2763
DeLesley Hutchins23323e02012-01-20 22:50:54 +00002764 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
2765 LateAttrs, StartingScope);
Douglas Gregor7cf84d62010-06-15 17:05:35 +00002766
Douglas Gregore53060f2009-06-25 22:08:12 +00002767 return false;
2768}
2769
Douglas Gregor5545e162009-03-24 00:38:23 +00002770/// \brief Initializes common fields of an instantiated method
2771/// declaration (New) from the corresponding fields of its template
2772/// (Tmpl).
2773///
2774/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00002775bool
2776TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor5545e162009-03-24 00:38:23 +00002777 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +00002778 if (InitFunctionInstantiation(New, Tmpl))
2779 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002780
Douglas Gregor5545e162009-03-24 00:38:23 +00002781 New->setAccess(Tmpl->getAccess());
Fariborz Jahaniane7184df2009-12-03 18:44:40 +00002782 if (Tmpl->isVirtualAsWritten())
Douglas Gregor85606eb2010-09-28 20:50:54 +00002783 New->setVirtualAsWritten(true);
Douglas Gregor5545e162009-03-24 00:38:23 +00002784
Douglas Gregor5545e162009-03-24 00:38:23 +00002785 // FIXME: New needs a pointer to Tmpl
2786 return false;
2787}
Douglas Gregora58861f2009-05-13 20:28:22 +00002788
2789/// \brief Instantiate the definition of the given function from its
2790/// template.
2791///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002792/// \param PointOfInstantiation the point at which the instantiation was
2793/// required. Note that this is not precisely a "point of instantiation"
2794/// for the function, but it's close.
2795///
Douglas Gregora58861f2009-05-13 20:28:22 +00002796/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002797/// function template specialization or member function of a class template
2798/// specialization.
2799///
2800/// \param Recursive if true, recursively instantiates any functions that
2801/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002802///
2803/// \param DefinitionRequired if true, then we are performing an explicit
2804/// instantiation where the body of the function is required. Complain if
2805/// there is no such body.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002806void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002807 FunctionDecl *Function,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002808 bool Recursive,
2809 bool DefinitionRequired) {
Sean Hunt10620eb2011-05-06 20:44:56 +00002810 if (Function->isInvalidDecl() || Function->isDefined())
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002811 return;
2812
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002813 // Never instantiate an explicit specialization except if it is a class scope
2814 // explicit specialization.
2815 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
2816 !Function->getClassScopeSpecializationPattern())
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002817 return;
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00002818
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002819 // Find the function body that we'll be substituting.
Douglas Gregor3b846b62009-10-27 20:53:28 +00002820 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Sean Huntf996e052011-05-27 20:00:14 +00002821 assert(PatternDecl && "instantiating a non-template");
2822
2823 Stmt *Pattern = PatternDecl->getBody(PatternDecl);
2824 assert(PatternDecl && "template definition is not a template");
2825 if (!Pattern) {
2826 // Try to find a defaulted definition
2827 PatternDecl->isDefined(PatternDecl);
Sean Huntdfab8542011-05-25 22:02:25 +00002828 }
Sean Huntf996e052011-05-27 20:00:14 +00002829 assert(PatternDecl && "template definition is not a template");
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002830
Francois Pichet8387e2a2011-04-22 22:18:13 +00002831 // Postpone late parsed template instantiations.
Sean Huntf996e052011-05-27 20:00:14 +00002832 if (PatternDecl->isLateTemplateParsed() &&
Nick Lewycky8a29bc02011-05-12 03:51:24 +00002833 !LateTemplateParser) {
Francois Pichet8387e2a2011-04-22 22:18:13 +00002834 PendingInstantiations.push_back(
2835 std::make_pair(Function, PointOfInstantiation));
2836 return;
2837 }
2838
2839 // Call the LateTemplateParser callback if there a need to late parse
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002840 // a templated function definition.
Sean Huntf996e052011-05-27 20:00:14 +00002841 if (!Pattern && PatternDecl->isLateTemplateParsed() &&
Francois Pichet8387e2a2011-04-22 22:18:13 +00002842 LateTemplateParser) {
Francois Pichet4a47e8d2011-04-23 11:52:20 +00002843 LateTemplateParser(OpaqueParser, PatternDecl);
Francois Pichet8387e2a2011-04-22 22:18:13 +00002844 Pattern = PatternDecl->getBody(PatternDecl);
2845 }
2846
Sean Huntf996e052011-05-27 20:00:14 +00002847 if (!Pattern && !PatternDecl->isDefaulted()) {
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002848 if (DefinitionRequired) {
2849 if (Function->getPrimaryTemplate())
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002850 Diag(PointOfInstantiation,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002851 diag::err_explicit_instantiation_undefined_func_template)
2852 << Function->getPrimaryTemplate();
2853 else
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002854 Diag(PointOfInstantiation,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002855 diag::err_explicit_instantiation_undefined_member)
2856 << 1 << Function->getDeclName() << Function->getDeclContext();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002857
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002858 if (PatternDecl)
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002859 Diag(PatternDecl->getLocation(),
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002860 diag::note_explicit_instantiation_here);
Douglas Gregorcfe833b2010-05-17 17:57:54 +00002861 Function->setInvalidDecl();
Chandler Carruth58e390e2010-08-25 08:27:02 +00002862 } else if (Function->getTemplateSpecializationKind()
2863 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00002864 PendingInstantiations.push_back(
Chandler Carruth58e390e2010-08-25 08:27:02 +00002865 std::make_pair(Function, PointOfInstantiation));
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002866 }
Chandler Carruth58e390e2010-08-25 08:27:02 +00002867
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002868 return;
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002869 }
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002870
Richard Smith60e141e2013-05-04 07:00:32 +00002871 // C++1y [temp.explicit]p10:
2872 // Except for inline functions, declarations with types deduced from their
2873 // initializer or return value, and class template specializations, other
2874 // explicit instantiation declarations have the effect of suppressing the
2875 // implicit instantiation of the entity to which they refer.
Mike Stump1eb44332009-09-09 15:08:12 +00002876 if (Function->getTemplateSpecializationKind()
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002877 == TSK_ExplicitInstantiationDeclaration &&
Richard Smith60e141e2013-05-04 07:00:32 +00002878 !PatternDecl->isInlined() &&
2879 !PatternDecl->getResultType()->isUndeducedType())
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002880 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002881
Richard Smithd4497dd2013-01-25 00:08:28 +00002882 if (PatternDecl->isInlined())
2883 Function->setImplicitlyInline();
2884
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002885 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
2886 if (Inst)
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002887 return;
2888
Abramo Bagnarae9946242011-11-18 08:08:52 +00002889 // Copy the inner loc start from the pattern.
2890 Function->setInnerLocStart(PatternDecl->getInnerLocStart());
2891
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002892 // If we're performing recursive template instantiation, create our own
2893 // queue of pending implicit instantiations that we will instantiate later,
2894 // while we're still within our own instantiation context.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002895 SmallVector<VTableUse, 16> SavedVTableUses;
Chandler Carruth62c78d52010-08-25 08:44:16 +00002896 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002897 if (Recursive) {
2898 VTableUses.swap(SavedVTableUses);
Chandler Carruth62c78d52010-08-25 08:44:16 +00002899 PendingInstantiations.swap(SavedPendingInstantiations);
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002900 }
Mike Stump1eb44332009-09-09 15:08:12 +00002901
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002902 EnterExpressionEvaluationContext EvalContext(*this,
John McCallf312b1e2010-08-26 23:41:50 +00002903 Sema::PotentiallyEvaluated);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002904
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002905 // Introduce a new scope where local variable instantiations will be
Douglas Gregor60406be2010-01-16 22:29:39 +00002906 // recorded, unless we're actually a member function within a local
2907 // class, in which case we need to merge our results with the parent
2908 // scope (of the enclosing function).
2909 bool MergeWithParentScope = false;
2910 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
2911 MergeWithParentScope = Rec->isLocalClass();
2912
2913 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +00002914
Richard Smith1d28caf2012-12-11 01:14:52 +00002915 if (PatternDecl->isDefaulted())
Sean Huntcd10dec2011-05-23 23:14:04 +00002916 SetDeclDefaulted(Function, PatternDecl->getLocation());
Richard Smith1d28caf2012-12-11 01:14:52 +00002917 else {
2918 ActOnStartOfFunctionDef(0, Function);
2919
2920 // Enter the scope of this instantiation. We don't use
2921 // PushDeclContext because we don't have a scope.
2922 Sema::ContextRAII savedContext(*this, Function);
2923
2924 MultiLevelTemplateArgumentList TemplateArgs =
2925 getTemplateInstantiationArgs(Function, 0, false, PatternDecl);
2926
2927 addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope,
2928 TemplateArgs);
2929
Sean Huntcd10dec2011-05-23 23:14:04 +00002930 // If this is a constructor, instantiate the member initializers.
2931 if (const CXXConstructorDecl *Ctor =
2932 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
2933 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
2934 TemplateArgs);
2935 }
2936
2937 // Instantiate the function body.
2938 StmtResult Body = SubstStmt(Pattern, TemplateArgs);
2939
2940 if (Body.isInvalid())
2941 Function->setInvalidDecl();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002942
Sean Huntcd10dec2011-05-23 23:14:04 +00002943 ActOnFinishFunctionBody(Function, Body.get(),
2944 /*IsInstantiation=*/true);
Richard Smith1d28caf2012-12-11 01:14:52 +00002945
2946 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
2947
2948 savedContext.pop();
Mike Stump1eb44332009-09-09 15:08:12 +00002949 }
2950
Douglas Gregoraba43bb2009-05-26 20:50:29 +00002951 DeclGroupRef DG(Function);
2952 Consumer.HandleTopLevelDecl(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00002953
Douglas Gregor60406be2010-01-16 22:29:39 +00002954 // This class may have local implicit instantiations that need to be
2955 // instantiation within this scope.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002956 PerformPendingInstantiations(/*LocalOnly=*/true);
Douglas Gregor60406be2010-01-16 22:29:39 +00002957 Scope.Exit();
2958
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002959 if (Recursive) {
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002960 // Define any pending vtables.
2961 DefineUsedVTables();
2962
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002963 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002964 // instantiation of this template.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002965 PerformPendingInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002966
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002967 // Restore the set of pending vtables.
Nick Lewycky81559102011-05-31 07:58:42 +00002968 assert(VTableUses.empty() &&
2969 "VTableUses should be empty before it is discarded.");
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002970 VTableUses.swap(SavedVTableUses);
2971
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002972 // Restore the set of pending implicit instantiations.
Nick Lewycky81559102011-05-31 07:58:42 +00002973 assert(PendingInstantiations.empty() &&
2974 "PendingInstantiations should be empty before it is discarded.");
Chandler Carruth62c78d52010-08-25 08:44:16 +00002975 PendingInstantiations.swap(SavedPendingInstantiations);
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002976 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002977}
2978
2979/// \brief Instantiate the definition of the given variable from its
2980/// template.
2981///
Douglas Gregor7caa6822009-07-24 20:34:43 +00002982/// \param PointOfInstantiation the point at which the instantiation was
2983/// required. Note that this is not precisely a "point of instantiation"
2984/// for the function, but it's close.
2985///
2986/// \param Var the already-instantiated declaration of a static member
2987/// variable of a class template specialization.
2988///
2989/// \param Recursive if true, recursively instantiates any functions that
2990/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002991///
2992/// \param DefinitionRequired if true, then we are performing an explicit
2993/// instantiation where an out-of-line definition of the member variable
2994/// is required. Complain if there is no such definition.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002995void Sema::InstantiateStaticDataMemberDefinition(
2996 SourceLocation PointOfInstantiation,
2997 VarDecl *Var,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002998 bool Recursive,
2999 bool DefinitionRequired) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00003000 if (Var->isInvalidDecl())
3001 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003002
Douglas Gregor7caa6822009-07-24 20:34:43 +00003003 // Find the out-of-line definition of this static data member.
Douglas Gregor7caa6822009-07-24 20:34:43 +00003004 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregor7caa6822009-07-24 20:34:43 +00003005 assert(Def && "This data member was not instantiated from a template?");
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003006 assert(Def->isStaticDataMember() && "Not a static data member?");
Douglas Gregor0d035142009-10-27 18:42:08 +00003007 Def = Def->getOutOfLineDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00003008
Douglas Gregor0d035142009-10-27 18:42:08 +00003009 if (!Def) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00003010 // We did not find an out-of-line definition of this static data member,
3011 // so we won't perform any instantiation. Rather, we rely on the user to
Mike Stump1eb44332009-09-09 15:08:12 +00003012 // instantiate this definition (or provide a specialization for it) in
3013 // another translation unit.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00003014 if (DefinitionRequired) {
Douglas Gregor0d035142009-10-27 18:42:08 +00003015 Def = Var->getInstantiatedFromStaticDataMember();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003016 Diag(PointOfInstantiation,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00003017 diag::err_explicit_instantiation_undefined_member)
3018 << 2 << Var->getDeclName() << Var->getDeclContext();
3019 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
Chandler Carruth58e390e2010-08-25 08:27:02 +00003020 } else if (Var->getTemplateSpecializationKind()
3021 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00003022 PendingInstantiations.push_back(
Chandler Carruth58e390e2010-08-25 08:27:02 +00003023 std::make_pair(Var, PointOfInstantiation));
3024 }
3025
Douglas Gregor7caa6822009-07-24 20:34:43 +00003026 return;
3027 }
3028
Rafael Espindola234fe652012-03-05 10:54:55 +00003029 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
3030
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003031 // Never instantiate an explicit specialization.
Rafael Espindola234fe652012-03-05 10:54:55 +00003032 if (TSK == TSK_ExplicitSpecialization)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003033 return;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003034
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003035 // C++0x [temp.explicit]p9:
3036 // Except for inline functions, other explicit instantiation declarations
3037 // have the effect of suppressing the implicit instantiation of the entity
3038 // to which they refer.
Rafael Espindola234fe652012-03-05 10:54:55 +00003039 if (TSK == TSK_ExplicitInstantiationDeclaration)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003040 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003041
Argyrios Kyrtzidisafda9052013-02-24 00:05:01 +00003042 // Make sure to pass the instantiated variable to the consumer at the end.
3043 struct PassToConsumerRAII {
3044 ASTConsumer &Consumer;
3045 VarDecl *Var;
3046
3047 PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
3048 : Consumer(Consumer), Var(Var) { }
3049
3050 ~PassToConsumerRAII() {
3051 Consumer.HandleCXXStaticMemberVarInstantiation(Var);
3052 }
3053 } PassToConsumerRAII(Consumer, Var);
Rafael Espindola02503932012-03-08 15:51:03 +00003054
Douglas Gregorf15748a2011-06-03 03:35:07 +00003055 // If we already have a definition, we're done.
Nick Lewycky95e38722012-04-04 02:38:36 +00003056 if (VarDecl *Def = Var->getDefinition()) {
3057 // We may be explicitly instantiating something we've already implicitly
3058 // instantiated.
3059 Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
3060 PointOfInstantiation);
Douglas Gregorf15748a2011-06-03 03:35:07 +00003061 return;
Nick Lewycky95e38722012-04-04 02:38:36 +00003062 }
Douglas Gregorf15748a2011-06-03 03:35:07 +00003063
Douglas Gregor7caa6822009-07-24 20:34:43 +00003064 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
3065 if (Inst)
3066 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003067
Douglas Gregor7caa6822009-07-24 20:34:43 +00003068 // If we're performing recursive template instantiation, create our own
3069 // queue of pending implicit instantiations that we will instantiate later,
3070 // while we're still within our own instantiation context.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003071 SmallVector<VTableUse, 16> SavedVTableUses;
Chandler Carruth62c78d52010-08-25 08:44:16 +00003072 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
Nick Lewycky81559102011-05-31 07:58:42 +00003073 if (Recursive) {
3074 VTableUses.swap(SavedVTableUses);
Chandler Carruth62c78d52010-08-25 08:44:16 +00003075 PendingInstantiations.swap(SavedPendingInstantiations);
Nick Lewycky81559102011-05-31 07:58:42 +00003076 }
Mike Stump1eb44332009-09-09 15:08:12 +00003077
Douglas Gregor7caa6822009-07-24 20:34:43 +00003078 // Enter the scope of this instantiation. We don't use
3079 // PushDeclContext because we don't have a scope.
John McCallf5ba7e02011-02-14 20:37:25 +00003080 ContextRAII previousContext(*this, Var->getDeclContext());
Douglas Gregor7bdc1522012-02-16 21:36:18 +00003081 LocalInstantiationScope Local(*this);
3082
Douglas Gregor1028c9f2009-10-14 21:29:40 +00003083 VarDecl *OldVar = Var;
John McCallce3ff2b2009-08-25 22:02:44 +00003084 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Nico Weber6bb4dcb2010-11-28 22:53:37 +00003085 getTemplateInstantiationArgs(Var)));
John McCallf5ba7e02011-02-14 20:37:25 +00003086
3087 previousContext.pop();
Douglas Gregor7caa6822009-07-24 20:34:43 +00003088
3089 if (Var) {
Argyrios Kyrtzidisafda9052013-02-24 00:05:01 +00003090 PassToConsumerRAII.Var = Var;
Douglas Gregor583f33b2009-10-15 18:07:02 +00003091 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
3092 assert(MSInfo && "Missing member specialization information?");
3093 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
3094 MSInfo->getPointOfInstantiation());
Douglas Gregor7caa6822009-07-24 20:34:43 +00003095 }
Douglas Gregor7bdc1522012-02-16 21:36:18 +00003096 Local.Exit();
3097
Douglas Gregor7caa6822009-07-24 20:34:43 +00003098 if (Recursive) {
Nick Lewycky81559102011-05-31 07:58:42 +00003099 // Define any newly required vtables.
3100 DefineUsedVTables();
3101
Douglas Gregor7caa6822009-07-24 20:34:43 +00003102 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00003103 // instantiation of this template.
Chandler Carruth62c78d52010-08-25 08:44:16 +00003104 PerformPendingInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00003105
Nick Lewycky81559102011-05-31 07:58:42 +00003106 // Restore the set of pending vtables.
3107 assert(VTableUses.empty() &&
3108 "VTableUses should be empty before it is discarded, "
3109 "while instantiating static data member.");
3110 VTableUses.swap(SavedVTableUses);
3111
Douglas Gregor7caa6822009-07-24 20:34:43 +00003112 // Restore the set of pending implicit instantiations.
Nick Lewycky81559102011-05-31 07:58:42 +00003113 assert(PendingInstantiations.empty() &&
3114 "PendingInstantiations should be empty before it is discarded, "
3115 "while instantiating static data member.");
Chandler Carruth62c78d52010-08-25 08:44:16 +00003116 PendingInstantiations.swap(SavedPendingInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00003117 }
Douglas Gregora58861f2009-05-13 20:28:22 +00003118}
Douglas Gregor815215d2009-05-27 05:35:12 +00003119
Anders Carlsson09025312009-08-29 05:16:22 +00003120void
3121Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
3122 const CXXConstructorDecl *Tmpl,
3123 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00003124
Richard Trieu90ab75b2011-09-09 03:18:59 +00003125 SmallVector<CXXCtorInitializer*, 4> NewInits;
Richard Smith54b3ba82012-09-25 00:23:05 +00003126 bool AnyErrors = Tmpl->isInvalidDecl();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003127
Anders Carlsson09025312009-08-29 05:16:22 +00003128 // Instantiate all the initializers.
3129 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00003130 InitsEnd = Tmpl->init_end();
3131 Inits != InitsEnd; ++Inits) {
Sean Huntcbb67482011-01-08 20:30:50 +00003132 CXXCtorInitializer *Init = *Inits;
Anders Carlsson09025312009-08-29 05:16:22 +00003133
Chandler Carruth030ef472010-09-03 21:54:20 +00003134 // Only instantiate written initializers, let Sema re-construct implicit
3135 // ones.
3136 if (!Init->isWritten())
3137 continue;
3138
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003139 SourceLocation EllipsisLoc;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003140
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003141 if (Init->isPackExpansion()) {
3142 // This is a pack expansion. We should expand it now.
Douglas Gregor76852c22011-11-01 01:16:03 +00003143 TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003144 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003145 collectUnexpandedParameterPacks(BaseTL, Unexpanded);
3146 bool ShouldExpand = false;
Douglas Gregord3731192011-01-10 07:32:04 +00003147 bool RetainExpansion = false;
David Blaikiedc84cd52013-02-20 22:23:23 +00003148 Optional<unsigned> NumExpansions;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003149 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003150 BaseTL.getSourceRange(),
David Blaikiea71f9d02011-09-22 02:34:54 +00003151 Unexpanded,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003152 TemplateArgs, ShouldExpand,
Douglas Gregord3731192011-01-10 07:32:04 +00003153 RetainExpansion,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003154 NumExpansions)) {
3155 AnyErrors = true;
3156 New->setInvalidDecl();
3157 continue;
3158 }
3159 assert(ShouldExpand && "Partial instantiation of base initializer?");
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003160
3161 // Loop over all of the arguments in the argument pack(s),
Douglas Gregorcded4f62011-01-14 17:04:44 +00003162 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003163 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
3164
3165 // Instantiate the initializer.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003166 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
3167 /*CXXDirectInit=*/true);
3168 if (TempInit.isInvalid()) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003169 AnyErrors = true;
3170 break;
3171 }
3172
3173 // Instantiate the base type.
Douglas Gregor76852c22011-11-01 01:16:03 +00003174 TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003175 TemplateArgs,
3176 Init->getSourceLocation(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003177 New->getDeclName());
3178 if (!BaseTInfo) {
3179 AnyErrors = true;
3180 break;
3181 }
3182
3183 // Build the initializer.
Sebastian Redl6df65482011-09-24 17:48:25 +00003184 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003185 BaseTInfo, TempInit.take(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003186 New->getParent(),
3187 SourceLocation());
3188 if (NewInit.isInvalid()) {
3189 AnyErrors = true;
3190 break;
3191 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003192
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003193 NewInits.push_back(NewInit.get());
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003194 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003195
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003196 continue;
3197 }
3198
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00003199 // Instantiate the initializer.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003200 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
3201 /*CXXDirectInit=*/true);
3202 if (TempInit.isInvalid()) {
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00003203 AnyErrors = true;
3204 continue;
Anders Carlsson09025312009-08-29 05:16:22 +00003205 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003206
Anders Carlsson09025312009-08-29 05:16:22 +00003207 MemInitResult NewInit;
Douglas Gregor76852c22011-11-01 01:16:03 +00003208 if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
3209 TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
3210 TemplateArgs,
3211 Init->getSourceLocation(),
3212 New->getDeclName());
3213 if (!TInfo) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003214 AnyErrors = true;
Douglas Gregor802ab452009-12-02 22:36:29 +00003215 New->setInvalidDecl();
3216 continue;
3217 }
Sebastian Redl6df65482011-09-24 17:48:25 +00003218
Douglas Gregor76852c22011-11-01 01:16:03 +00003219 if (Init->isBaseInitializer())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003220 NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.take(),
Douglas Gregor76852c22011-11-01 01:16:03 +00003221 New->getParent(), EllipsisLoc);
3222 else
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003223 NewInit = BuildDelegatingInitializer(TInfo, TempInit.take(),
Douglas Gregor76852c22011-11-01 01:16:03 +00003224 cast<CXXRecordDecl>(CurContext->getParent()));
Anders Carlsson09025312009-08-29 05:16:22 +00003225 } else if (Init->isMemberInitializer()) {
Douglas Gregorb7107222011-03-04 19:46:35 +00003226 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
Francois Pichet00eb3f92010-12-04 09:14:42 +00003227 Init->getMemberLocation(),
3228 Init->getMember(),
3229 TemplateArgs));
Douglas Gregorb7107222011-03-04 19:46:35 +00003230 if (!Member) {
3231 AnyErrors = true;
3232 New->setInvalidDecl();
3233 continue;
3234 }
Mike Stump1eb44332009-09-09 15:08:12 +00003235
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003236 NewInit = BuildMemberInitializer(Member, TempInit.take(),
Sebastian Redl6df65482011-09-24 17:48:25 +00003237 Init->getSourceLocation());
Francois Pichet00eb3f92010-12-04 09:14:42 +00003238 } else if (Init->isIndirectMemberInitializer()) {
3239 IndirectFieldDecl *IndirectMember =
Douglas Gregorb7107222011-03-04 19:46:35 +00003240 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
Francois Pichet00eb3f92010-12-04 09:14:42 +00003241 Init->getMemberLocation(),
3242 Init->getIndirectMember(), TemplateArgs));
3243
Douglas Gregorb7107222011-03-04 19:46:35 +00003244 if (!IndirectMember) {
3245 AnyErrors = true;
3246 New->setInvalidDecl();
Sebastian Redl6df65482011-09-24 17:48:25 +00003247 continue;
Douglas Gregorb7107222011-03-04 19:46:35 +00003248 }
Sebastian Redl6df65482011-09-24 17:48:25 +00003249
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003250 NewInit = BuildMemberInitializer(IndirectMember, TempInit.take(),
Sebastian Redl6df65482011-09-24 17:48:25 +00003251 Init->getSourceLocation());
Anders Carlsson09025312009-08-29 05:16:22 +00003252 }
3253
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003254 if (NewInit.isInvalid()) {
3255 AnyErrors = true;
Anders Carlsson09025312009-08-29 05:16:22 +00003256 New->setInvalidDecl();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003257 } else {
Richard Trieu90ab75b2011-09-09 03:18:59 +00003258 NewInits.push_back(NewInit.get());
Anders Carlsson09025312009-08-29 05:16:22 +00003259 }
3260 }
Mike Stump1eb44332009-09-09 15:08:12 +00003261
Anders Carlsson09025312009-08-29 05:16:22 +00003262 // Assign all the initializers to the new constructor.
John McCalld226f652010-08-21 09:40:31 +00003263 ActOnMemInitializers(New,
Anders Carlsson09025312009-08-29 05:16:22 +00003264 /*FIXME: ColonLoc */
3265 SourceLocation(),
David Blaikie93c86172013-01-17 05:26:25 +00003266 NewInits,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003267 AnyErrors);
Anders Carlsson09025312009-08-29 05:16:22 +00003268}
3269
John McCall52a575a2009-08-29 08:11:13 +00003270// TODO: this could be templated if the various decl types used the
3271// same method name.
3272static bool isInstantiationOf(ClassTemplateDecl *Pattern,
3273 ClassTemplateDecl *Instance) {
3274 Pattern = Pattern->getCanonicalDecl();
3275
3276 do {
3277 Instance = Instance->getCanonicalDecl();
3278 if (Pattern == Instance) return true;
3279 Instance = Instance->getInstantiatedFromMemberTemplate();
3280 } while (Instance);
3281
3282 return false;
3283}
3284
Douglas Gregor0d696532009-09-28 06:34:35 +00003285static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
3286 FunctionTemplateDecl *Instance) {
3287 Pattern = Pattern->getCanonicalDecl();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003288
Douglas Gregor0d696532009-09-28 06:34:35 +00003289 do {
3290 Instance = Instance->getCanonicalDecl();
3291 if (Pattern == Instance) return true;
3292 Instance = Instance->getInstantiatedFromMemberTemplate();
3293 } while (Instance);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003294
Douglas Gregor0d696532009-09-28 06:34:35 +00003295 return false;
3296}
3297
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003298static bool
Douglas Gregored9c0f92009-10-29 00:04:11 +00003299isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
3300 ClassTemplatePartialSpecializationDecl *Instance) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003301 Pattern
Douglas Gregored9c0f92009-10-29 00:04:11 +00003302 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
3303 do {
3304 Instance = cast<ClassTemplatePartialSpecializationDecl>(
3305 Instance->getCanonicalDecl());
3306 if (Pattern == Instance)
3307 return true;
3308 Instance = Instance->getInstantiatedFromMember();
3309 } while (Instance);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003310
Douglas Gregored9c0f92009-10-29 00:04:11 +00003311 return false;
3312}
3313
John McCall52a575a2009-08-29 08:11:13 +00003314static bool isInstantiationOf(CXXRecordDecl *Pattern,
3315 CXXRecordDecl *Instance) {
3316 Pattern = Pattern->getCanonicalDecl();
3317
3318 do {
3319 Instance = Instance->getCanonicalDecl();
3320 if (Pattern == Instance) return true;
3321 Instance = Instance->getInstantiatedFromMemberClass();
3322 } while (Instance);
3323
3324 return false;
3325}
3326
3327static bool isInstantiationOf(FunctionDecl *Pattern,
3328 FunctionDecl *Instance) {
3329 Pattern = Pattern->getCanonicalDecl();
3330
3331 do {
3332 Instance = Instance->getCanonicalDecl();
3333 if (Pattern == Instance) return true;
3334 Instance = Instance->getInstantiatedFromMemberFunction();
3335 } while (Instance);
3336
3337 return false;
3338}
3339
3340static bool isInstantiationOf(EnumDecl *Pattern,
3341 EnumDecl *Instance) {
3342 Pattern = Pattern->getCanonicalDecl();
3343
3344 do {
3345 Instance = Instance->getCanonicalDecl();
3346 if (Pattern == Instance) return true;
3347 Instance = Instance->getInstantiatedFromMemberEnum();
3348 } while (Instance);
3349
3350 return false;
3351}
3352
John McCalled976492009-12-04 22:46:56 +00003353static bool isInstantiationOf(UsingShadowDecl *Pattern,
3354 UsingShadowDecl *Instance,
3355 ASTContext &C) {
3356 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
3357}
3358
3359static bool isInstantiationOf(UsingDecl *Pattern,
3360 UsingDecl *Instance,
3361 ASTContext &C) {
3362 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
3363}
3364
John McCall7ba107a2009-11-18 02:36:19 +00003365static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
3366 UsingDecl *Instance,
3367 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00003368 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCall7ba107a2009-11-18 02:36:19 +00003369}
3370
3371static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson0d8df782009-08-29 19:37:28 +00003372 UsingDecl *Instance,
3373 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00003374 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00003375}
3376
John McCall52a575a2009-08-29 08:11:13 +00003377static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
3378 VarDecl *Instance) {
3379 assert(Instance->isStaticDataMember());
3380
3381 Pattern = Pattern->getCanonicalDecl();
3382
3383 do {
3384 Instance = Instance->getCanonicalDecl();
3385 if (Pattern == Instance) return true;
3386 Instance = Instance->getInstantiatedFromStaticDataMember();
3387 } while (Instance);
3388
3389 return false;
3390}
3391
John McCalled976492009-12-04 22:46:56 +00003392// Other is the prospective instantiation
3393// D is the prospective pattern
Douglas Gregor815215d2009-05-27 05:35:12 +00003394static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00003395 if (D->getKind() != Other->getKind()) {
John McCall7ba107a2009-11-18 02:36:19 +00003396 if (UnresolvedUsingTypenameDecl *UUD
3397 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3398 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
3399 return isInstantiationOf(UUD, UD, Ctx);
3400 }
3401 }
3402
3403 if (UnresolvedUsingValueDecl *UUD
3404 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00003405 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
3406 return isInstantiationOf(UUD, UD, Ctx);
3407 }
3408 }
Douglas Gregor815215d2009-05-27 05:35:12 +00003409
Anders Carlsson0d8df782009-08-29 19:37:28 +00003410 return false;
3411 }
Mike Stump1eb44332009-09-09 15:08:12 +00003412
John McCall52a575a2009-08-29 08:11:13 +00003413 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
3414 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00003415
John McCall52a575a2009-08-29 08:11:13 +00003416 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
3417 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00003418
John McCall52a575a2009-08-29 08:11:13 +00003419 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
3420 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00003421
Douglas Gregor7caa6822009-07-24 20:34:43 +00003422 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00003423 if (Var->isStaticDataMember())
3424 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
3425
3426 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
3427 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00003428
Douglas Gregor0d696532009-09-28 06:34:35 +00003429 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
3430 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
3431
Douglas Gregored9c0f92009-10-29 00:04:11 +00003432 if (ClassTemplatePartialSpecializationDecl *PartialSpec
3433 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
3434 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
3435 PartialSpec);
3436
Anders Carlssond8b285f2009-09-01 04:26:58 +00003437 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
3438 if (!Field->getDeclName()) {
3439 // This is an unnamed field.
Mike Stump1eb44332009-09-09 15:08:12 +00003440 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlssond8b285f2009-09-01 04:26:58 +00003441 cast<FieldDecl>(D);
3442 }
3443 }
Mike Stump1eb44332009-09-09 15:08:12 +00003444
John McCalled976492009-12-04 22:46:56 +00003445 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
3446 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
3447
3448 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
3449 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
3450
Douglas Gregor815215d2009-05-27 05:35:12 +00003451 return D->getDeclName() && isa<NamedDecl>(Other) &&
3452 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
3453}
3454
3455template<typename ForwardIterator>
Mike Stump1eb44332009-09-09 15:08:12 +00003456static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor815215d2009-05-27 05:35:12 +00003457 NamedDecl *D,
3458 ForwardIterator first,
3459 ForwardIterator last) {
3460 for (; first != last; ++first)
3461 if (isInstantiationOf(Ctx, D, *first))
3462 return cast<NamedDecl>(*first);
3463
3464 return 0;
3465}
3466
John McCall02cace72009-08-28 07:59:38 +00003467/// \brief Finds the instantiation of the given declaration context
3468/// within the current instantiation.
3469///
3470/// \returns NULL if there was an error
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003471DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
Douglas Gregore95b4092009-09-16 18:34:49 +00003472 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCall02cace72009-08-28 07:59:38 +00003473 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003474 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +00003475 return cast_or_null<DeclContext>(ID);
3476 } else return DC;
3477}
3478
Douglas Gregored961e72009-05-27 17:54:46 +00003479/// \brief Find the instantiation of the given declaration within the
3480/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00003481///
3482/// This routine is intended to be used when \p D is a declaration
3483/// referenced from within a template, that needs to mapped into the
3484/// corresponding declaration within an instantiation. For example,
3485/// given:
3486///
3487/// \code
3488/// template<typename T>
3489/// struct X {
3490/// enum Kind {
3491/// KnownValue = sizeof(T)
3492/// };
3493///
3494/// bool getKind() const { return KnownValue; }
3495/// };
3496///
3497/// template struct X<int>;
3498/// \endcode
3499///
3500/// In the instantiation of X<int>::getKind(), we need to map the
3501/// EnumConstantDecl for KnownValue (which refers to
James Dennettf198d122012-06-17 03:36:08 +00003502/// X<T>::\<Kind>\::KnownValue) to its instantiation
James Dennettef2b5b32012-06-15 22:23:43 +00003503/// (X<int>::\<Kind>\::KnownValue). InstantiateCurrentDeclRef() performs
Douglas Gregored961e72009-05-27 17:54:46 +00003504/// this mapping from within the instantiation of X<int>.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003505NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
Douglas Gregore95b4092009-09-16 18:34:49 +00003506 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor815215d2009-05-27 05:35:12 +00003507 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor550d9b22009-10-31 17:21:17 +00003508 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
Douglas Gregor6d3e6272010-02-05 19:54:12 +00003509 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
Douglas Gregor7bdc1522012-02-16 21:36:18 +00003510 (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext()) ||
3511 (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) {
Douglas Gregor2bba76b2009-05-27 17:07:49 +00003512 // D is a local of some kind. Look into the map of local
3513 // declarations to their instantiations.
Chris Lattnerd8e54992011-02-17 19:47:42 +00003514 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
3515 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
3516 = CurrentInstantiationScope->findInstantiationOf(D);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003517
Chris Lattner57ad3782011-02-17 20:34:02 +00003518 if (Found) {
3519 if (Decl *FD = Found->dyn_cast<Decl *>())
3520 return cast<NamedDecl>(FD);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003521
Richard Smith9a4db032012-09-12 00:56:43 +00003522 int PackIdx = ArgumentPackSubstitutionIndex;
3523 assert(PackIdx != -1 && "found declaration pack but not pack expanding");
Chris Lattner57ad3782011-02-17 20:34:02 +00003524 return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
3525 }
3526
3527 // If we didn't find the decl, then we must have a label decl that hasn't
3528 // been found yet. Lazily instantiate it and return it now.
3529 assert(isa<LabelDecl>(D));
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003530
Chris Lattner57ad3782011-02-17 20:34:02 +00003531 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
3532 assert(Inst && "Failed to instantiate label??");
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003533
Chris Lattner57ad3782011-02-17 20:34:02 +00003534 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
3535 return cast<LabelDecl>(Inst);
Douglas Gregor2bba76b2009-05-27 17:07:49 +00003536 }
Douglas Gregor815215d2009-05-27 05:35:12 +00003537
Douglas Gregore95b4092009-09-16 18:34:49 +00003538 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
3539 if (!Record->isDependentContext())
3540 return D;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003541
Douglas Gregor2c1227c2011-11-07 17:43:18 +00003542 // Determine whether this record is the "templated" declaration describing
3543 // a class template or class template partial specialization.
Douglas Gregore95b4092009-09-16 18:34:49 +00003544 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
Douglas Gregor2c1227c2011-11-07 17:43:18 +00003545 if (ClassTemplate)
3546 ClassTemplate = ClassTemplate->getCanonicalDecl();
3547 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
3548 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
3549 ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
3550
3551 // Walk the current context to find either the record or an instantiation of
3552 // it.
3553 DeclContext *DC = CurContext;
3554 while (!DC->isFileContext()) {
3555 // If we're performing substitution while we're inside the template
3556 // definition, we'll find our own context. We're done.
3557 if (DC->Equals(Record))
3558 return Record;
3559
3560 if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
3561 // Check whether we're in the process of instantiating a class template
3562 // specialization of the template we're mapping.
3563 if (ClassTemplateSpecializationDecl *InstSpec
3564 = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
3565 ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
3566 if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
3567 return InstRecord;
3568 }
3569
3570 // Check whether we're in the process of instantiating a member class.
3571 if (isInstantiationOf(Record, InstRecord))
3572 return InstRecord;
Douglas Gregore95b4092009-09-16 18:34:49 +00003573 }
Douglas Gregor2c1227c2011-11-07 17:43:18 +00003574
3575
3576 // Move to the outer template scope.
3577 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
3578 if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){
3579 DC = FD->getLexicalDeclContext();
3580 continue;
3581 }
John McCall52a575a2009-08-29 08:11:13 +00003582 }
Douglas Gregor2c1227c2011-11-07 17:43:18 +00003583
3584 DC = DC->getParent();
John McCall52a575a2009-08-29 08:11:13 +00003585 }
Douglas Gregor8b013bd2010-02-05 22:40:03 +00003586
Douglas Gregore95b4092009-09-16 18:34:49 +00003587 // Fall through to deal with other dependent record types (e.g.,
3588 // anonymous unions in class templates).
3589 }
John McCall52a575a2009-08-29 08:11:13 +00003590
Douglas Gregore95b4092009-09-16 18:34:49 +00003591 if (!ParentDC->isDependentContext())
3592 return D;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003593
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003594 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00003595 if (!ParentDC)
Douglas Gregor44c73842009-09-01 17:53:10 +00003596 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003597
Douglas Gregor815215d2009-05-27 05:35:12 +00003598 if (ParentDC != D->getDeclContext()) {
3599 // We performed some kind of instantiation in the parent context,
3600 // so now we need to look into the instantiated parent context to
3601 // find the instantiation of the declaration D.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003602
John McCall3cb0ebd2010-03-10 03:28:59 +00003603 // If our context used to be dependent, we may need to instantiate
3604 // it before performing lookup into that context.
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00003605 bool IsBeingInstantiated = false;
John McCall3cb0ebd2010-03-10 03:28:59 +00003606 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003607 if (!Spec->isDependentContext()) {
3608 QualType T = Context.getTypeDeclType(Spec);
John McCall3cb0ebd2010-03-10 03:28:59 +00003609 const RecordType *Tag = T->getAs<RecordType>();
3610 assert(Tag && "type of non-dependent record is not a RecordType");
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00003611 if (Tag->isBeingDefined())
3612 IsBeingInstantiated = true;
John McCall3cb0ebd2010-03-10 03:28:59 +00003613 if (!Tag->isBeingDefined() &&
3614 RequireCompleteType(Loc, T, diag::err_incomplete_type))
3615 return 0;
Douglas Gregora43064c2010-11-05 23:22:45 +00003616
3617 ParentDC = Tag->getDecl();
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003618 }
3619 }
3620
Douglas Gregor815215d2009-05-27 05:35:12 +00003621 NamedDecl *Result = 0;
3622 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003623 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
David Blaikie3bc93e32012-12-19 00:45:41 +00003624 Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
Douglas Gregor815215d2009-05-27 05:35:12 +00003625 } else {
3626 // Since we don't have a name for the entity we're looking for,
3627 // our only option is to walk through all of the declarations to
3628 // find that name. This will occur in a few cases:
3629 //
3630 // - anonymous struct/union within a template
3631 // - unnamed class/struct/union/enum within a template
3632 //
3633 // FIXME: Find a better way to find these instantiations!
Mike Stump1eb44332009-09-09 15:08:12 +00003634 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003635 ParentDC->decls_begin(),
3636 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00003637 }
Mike Stump1eb44332009-09-09 15:08:12 +00003638
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00003639 if (!Result) {
3640 if (isa<UsingShadowDecl>(D)) {
3641 // UsingShadowDecls can instantiate to nothing because of using hiding.
3642 } else if (Diags.hasErrorOccurred()) {
3643 // We've already complained about something, so most likely this
3644 // declaration failed to instantiate. There's no point in complaining
3645 // further, since this is normal in invalid code.
3646 } else if (IsBeingInstantiated) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003647 // The class in which this member exists is currently being
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00003648 // instantiated, and we haven't gotten around to instantiating this
3649 // member yet. This can happen when the code uses forward declarations
3650 // of member classes, and introduces ordering dependencies via
3651 // template instantiation.
3652 Diag(Loc, diag::err_member_not_yet_instantiated)
3653 << D->getDeclName()
3654 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
3655 Diag(D->getLocation(), diag::note_non_instantiated_member_here);
Richard Smith0724b7c2012-03-26 20:28:16 +00003656 } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
3657 // This enumeration constant was found when the template was defined,
3658 // but can't be found in the instantiation. This can happen if an
3659 // unscoped enumeration member is explicitly specialized.
3660 EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
3661 EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
3662 TemplateArgs));
3663 assert(Spec->getTemplateSpecializationKind() ==
3664 TSK_ExplicitSpecialization);
3665 Diag(Loc, diag::err_enumerator_does_not_exist)
3666 << D->getDeclName()
3667 << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
3668 Diag(Spec->getLocation(), diag::note_enum_specialized_here)
3669 << Context.getTypeDeclType(Spec);
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00003670 } else {
3671 // We should have found something, but didn't.
3672 llvm_unreachable("Unable to find instantiation of declaration!");
3673 }
3674 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003675
Douglas Gregor815215d2009-05-27 05:35:12 +00003676 D = Result;
3677 }
3678
Douglas Gregor815215d2009-05-27 05:35:12 +00003679 return D;
3680}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003681
Mike Stump1eb44332009-09-09 15:08:12 +00003682/// \brief Performs template instantiation for all implicit template
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003683/// instantiations we have seen until this point.
Nick Lewycky81559102011-05-31 07:58:42 +00003684void Sema::PerformPendingInstantiations(bool LocalOnly) {
Douglas Gregor6e4a3f52011-07-28 19:49:54 +00003685 // Load pending instantiations from the external source.
3686 if (!LocalOnly && ExternalSource) {
Richard Smithb9d0b762012-07-27 04:22:15 +00003687 SmallVector<PendingImplicitInstantiation, 4> Pending;
Douglas Gregor6e4a3f52011-07-28 19:49:54 +00003688 ExternalSource->ReadPendingInstantiations(Pending);
3689 PendingInstantiations.insert(PendingInstantiations.begin(),
3690 Pending.begin(), Pending.end());
3691 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003692
Douglas Gregor60406be2010-01-16 22:29:39 +00003693 while (!PendingLocalImplicitInstantiations.empty() ||
Chandler Carruth62c78d52010-08-25 08:44:16 +00003694 (!LocalOnly && !PendingInstantiations.empty())) {
Douglas Gregor60406be2010-01-16 22:29:39 +00003695 PendingImplicitInstantiation Inst;
3696
3697 if (PendingLocalImplicitInstantiations.empty()) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00003698 Inst = PendingInstantiations.front();
3699 PendingInstantiations.pop_front();
Douglas Gregor60406be2010-01-16 22:29:39 +00003700 } else {
3701 Inst = PendingLocalImplicitInstantiations.front();
3702 PendingLocalImplicitInstantiations.pop_front();
3703 }
Mike Stump1eb44332009-09-09 15:08:12 +00003704
Douglas Gregor7caa6822009-07-24 20:34:43 +00003705 // Instantiate function definitions
3706 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
John McCallf312b1e2010-08-26 23:41:50 +00003707 PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(),
3708 "instantiating function definition");
Chandler Carruth58e390e2010-08-25 08:27:02 +00003709 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
3710 TSK_ExplicitInstantiationDefinition;
3711 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true,
3712 DefinitionRequired);
Douglas Gregor7caa6822009-07-24 20:34:43 +00003713 continue;
3714 }
Mike Stump1eb44332009-09-09 15:08:12 +00003715
Douglas Gregor7caa6822009-07-24 20:34:43 +00003716 // Instantiate static data member definitions.
3717 VarDecl *Var = cast<VarDecl>(Inst.first);
3718 assert(Var->isStaticDataMember() && "Not a static data member?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00003719
Chandler Carruth291b4412010-02-13 10:17:50 +00003720 // Don't try to instantiate declarations if the most recent redeclaration
3721 // is invalid.
Douglas Gregoref96ee02012-01-14 16:38:05 +00003722 if (Var->getMostRecentDecl()->isInvalidDecl())
Chandler Carruth291b4412010-02-13 10:17:50 +00003723 continue;
3724
3725 // Check if the most recent declaration has changed the specialization kind
3726 // and removed the need for implicit instantiation.
Douglas Gregoref96ee02012-01-14 16:38:05 +00003727 switch (Var->getMostRecentDecl()->getTemplateSpecializationKind()) {
Chandler Carruth291b4412010-02-13 10:17:50 +00003728 case TSK_Undeclared:
David Blaikieb219cfc2011-09-23 05:06:16 +00003729 llvm_unreachable("Cannot instantitiate an undeclared specialization.");
Chandler Carruth291b4412010-02-13 10:17:50 +00003730 case TSK_ExplicitInstantiationDeclaration:
Chandler Carruth291b4412010-02-13 10:17:50 +00003731 case TSK_ExplicitSpecialization:
Chandler Carruth58e390e2010-08-25 08:27:02 +00003732 continue; // No longer need to instantiate this type.
3733 case TSK_ExplicitInstantiationDefinition:
3734 // We only need an instantiation if the pending instantiation *is* the
3735 // explicit instantiation.
Douglas Gregoref96ee02012-01-14 16:38:05 +00003736 if (Var != Var->getMostRecentDecl()) continue;
Chandler Carruth291b4412010-02-13 10:17:50 +00003737 case TSK_ImplicitInstantiation:
3738 break;
3739 }
3740
John McCallf312b1e2010-08-26 23:41:50 +00003741 PrettyDeclStackTraceEntry CrashInfo(*this, Var, Var->getLocation(),
3742 "instantiating static data member "
3743 "definition");
Mike Stump1eb44332009-09-09 15:08:12 +00003744
Chandler Carruth58e390e2010-08-25 08:27:02 +00003745 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
3746 TSK_ExplicitInstantiationDefinition;
3747 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true,
3748 DefinitionRequired);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003749 }
3750}
John McCall0c01d182010-03-24 05:22:00 +00003751
3752void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
3753 const MultiLevelTemplateArgumentList &TemplateArgs) {
3754 for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(),
3755 E = Pattern->ddiag_end(); I != E; ++I) {
3756 DependentDiagnostic *DD = *I;
3757
3758 switch (DD->getKind()) {
3759 case DependentDiagnostic::Access:
3760 HandleDependentAccessCheck(*DD, TemplateArgs);
3761 break;
3762 }
3763 }
3764}