blob: 5636647cda50ca044591a9a3ea14c7d369bb2283 [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 Gregore737f502010-08-12 20:07:10 +000013#include "clang/Sema/Lookup.h"
John McCallf312b1e2010-08-26 23:41:50 +000014#include "clang/Sema/PrettyDeclStackTrace.h"
John McCall7cd088e2010-08-24 07:21:54 +000015#include "clang/Sema/Template.h"
Douglas Gregoraba43bb2009-05-26 20:50:29 +000016#include "clang/AST/ASTConsumer.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000017#include "clang/AST/ASTContext.h"
18#include "clang/AST/DeclTemplate.h"
19#include "clang/AST/DeclVisitor.h"
John McCall0c01d182010-03-24 05:22:00 +000020#include "clang/AST/DependentDiagnostic.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000021#include "clang/AST/Expr.h"
Douglas Gregora88cfbf2009-12-12 18:16:41 +000022#include "clang/AST/ExprCXX.h"
John McCall21ef0fa2010-03-11 09:03:00 +000023#include "clang/AST/TypeLoc.h"
Douglas Gregor83ddad32009-08-26 21:14:46 +000024#include "clang/Lex/Preprocessor.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000025
26using namespace clang;
27
28namespace {
Benjamin Kramer85b45212009-11-28 19:45:26 +000029 class TemplateDeclInstantiator
Chris Lattnerb28317a2009-03-28 19:18:32 +000030 : public DeclVisitor<TemplateDeclInstantiator, Decl *> {
Douglas Gregor8dbc2692009-03-17 21:15:40 +000031 Sema &SemaRef;
32 DeclContext *Owner;
Douglas Gregord6350ae2009-08-28 20:31:08 +000033 const MultiLevelTemplateArgumentList &TemplateArgs;
Mike Stump1eb44332009-09-09 15:08:12 +000034
Douglas Gregor8dbc2692009-03-17 21:15:40 +000035 public:
Douglas Gregor8dbc2692009-03-17 21:15:40 +000036 TemplateDeclInstantiator(Sema &SemaRef, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +000037 const MultiLevelTemplateArgumentList &TemplateArgs)
Douglas Gregor7e063902009-05-11 23:53:27 +000038 : SemaRef(SemaRef), Owner(Owner), TemplateArgs(TemplateArgs) { }
Mike Stump1eb44332009-09-09 15:08:12 +000039
Mike Stump390b4cc2009-05-16 07:39:55 +000040 // FIXME: Once we get closer to completion, replace these manually-written
41 // declarations with automatically-generated ones from
Sean Hunt9a555912010-05-30 07:21:58 +000042 // clang/AST/DeclNodes.inc.
Douglas Gregor4f722be2009-03-25 15:45:12 +000043 Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D);
44 Decl *VisitNamespaceDecl(NamespaceDecl *D);
John McCall3dbd3d52010-02-16 06:53:13 +000045 Decl *VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000046 Decl *VisitTypedefDecl(TypedefDecl *D);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +000047 Decl *VisitVarDecl(VarDecl *D);
Abramo Bagnara6206d532010-06-05 05:09:32 +000048 Decl *VisitAccessSpecDecl(AccessSpecDecl *D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000049 Decl *VisitFieldDecl(FieldDecl *D);
50 Decl *VisitStaticAssertDecl(StaticAssertDecl *D);
51 Decl *VisitEnumDecl(EnumDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000052 Decl *VisitEnumConstantDecl(EnumConstantDecl *D);
John McCall02cace72009-08-28 07:59:38 +000053 Decl *VisitFriendDecl(FriendDecl *D);
Douglas Gregora735b202009-10-13 14:39:41 +000054 Decl *VisitFunctionDecl(FunctionDecl *D,
55 TemplateParameterList *TemplateParams = 0);
Douglas Gregord475b8d2009-03-25 21:17:03 +000056 Decl *VisitCXXRecordDecl(CXXRecordDecl *D);
Douglas Gregord60e1052009-08-27 16:57:43 +000057 Decl *VisitCXXMethodDecl(CXXMethodDecl *D,
58 TemplateParameterList *TemplateParams = 0);
Douglas Gregor615c5d42009-03-24 16:43:20 +000059 Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
Douglas Gregor03b2b072009-03-24 00:15:49 +000060 Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +000061 Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000062 ParmVarDecl *VisitParmVarDecl(ParmVarDecl *D);
John McCalle29ba202009-08-20 01:44:21 +000063 Decl *VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor7974c3b2009-10-07 17:21:34 +000064 Decl *VisitClassTemplatePartialSpecializationDecl(
65 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregord60e1052009-08-27 16:57:43 +000066 Decl *VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
John McCalle29ba202009-08-20 01:44:21 +000067 Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Douglas Gregor33642df2009-10-23 23:25:44 +000068 Decl *VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregor9106ef72009-11-11 16:58:32 +000069 Decl *VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Douglas Gregor48c32a72009-11-17 06:07:40 +000070 Decl *VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
John McCalled976492009-12-04 22:46:56 +000071 Decl *VisitUsingDecl(UsingDecl *D);
72 Decl *VisitUsingShadowDecl(UsingShadowDecl *D);
John McCall7ba107a2009-11-18 02:36:19 +000073 Decl *VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
74 Decl *VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Mike Stump1eb44332009-09-09 15:08:12 +000075
Douglas Gregor8dbc2692009-03-17 21:15:40 +000076 // Base case. FIXME: Remove once we can instantiate everything.
Douglas Gregor48c32a72009-11-17 06:07:40 +000077 Decl *VisitDecl(Decl *D) {
78 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
79 Diagnostic::Error,
80 "cannot instantiate %0 yet");
81 SemaRef.Diag(D->getLocation(), DiagID)
82 << D->getDeclKindName();
83
Douglas Gregor8dbc2692009-03-17 21:15:40 +000084 return 0;
85 }
Douglas Gregor5545e162009-03-24 00:38:23 +000086
87 // Helper functions for instantiating methods.
John McCall21ef0fa2010-03-11 09:03:00 +000088 TypeSourceInfo *SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +000089 llvm::SmallVectorImpl<ParmVarDecl *> &Params);
Douglas Gregore53060f2009-06-25 22:08:12 +000090 bool InitFunctionInstantiation(FunctionDecl *New, FunctionDecl *Tmpl);
Douglas Gregor5545e162009-03-24 00:38:23 +000091 bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl);
John McCalle29ba202009-08-20 01:44:21 +000092
93 TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +000094 SubstTemplateParams(TemplateParameterList *List);
John McCallb6217662010-03-15 10:12:16 +000095
96 bool SubstQualifier(const DeclaratorDecl *OldDecl,
97 DeclaratorDecl *NewDecl);
98 bool SubstQualifier(const TagDecl *OldDecl,
99 TagDecl *NewDecl);
Douglas Gregored9c0f92009-10-29 00:04:11 +0000100
101 bool InstantiateClassTemplatePartialSpecialization(
102 ClassTemplateDecl *ClassTemplate,
103 ClassTemplatePartialSpecializationDecl *PartialSpec);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000104 };
105}
106
John McCallb6217662010-03-15 10:12:16 +0000107bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
108 DeclaratorDecl *NewDecl) {
109 NestedNameSpecifier *OldQual = OldDecl->getQualifier();
110 if (!OldQual) return false;
111
112 SourceRange QualRange = OldDecl->getQualifierRange();
113
114 NestedNameSpecifier *NewQual
115 = SemaRef.SubstNestedNameSpecifier(OldQual, QualRange, TemplateArgs);
116 if (!NewQual)
117 return true;
118
119 NewDecl->setQualifierInfo(NewQual, QualRange);
120 return false;
121}
122
123bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
124 TagDecl *NewDecl) {
125 NestedNameSpecifier *OldQual = OldDecl->getQualifier();
126 if (!OldQual) return false;
127
128 SourceRange QualRange = OldDecl->getQualifierRange();
129
130 NestedNameSpecifier *NewQual
131 = SemaRef.SubstNestedNameSpecifier(OldQual, QualRange, TemplateArgs);
132 if (!NewQual)
133 return true;
134
135 NewDecl->setQualifierInfo(NewQual, QualRange);
136 return false;
137}
138
Chandler Carruth4ced79f2010-06-25 03:22:07 +0000139// FIXME: Is this still too simple?
John McCall1d8d1cc2010-08-01 02:01:53 +0000140void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
141 Decl *Tmpl, Decl *New) {
Sean Huntcf807c42010-08-18 23:23:40 +0000142 for (AttrVec::const_iterator i = Tmpl->attr_begin(), e = Tmpl->attr_end();
143 i != e; ++i) {
144 const Attr *TmplAttr = *i;
Chandler Carruth4ced79f2010-06-25 03:22:07 +0000145 // FIXME: This should be generalized to more than just the AlignedAttr.
146 if (const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr)) {
Sean Huntcf807c42010-08-18 23:23:40 +0000147 if (Aligned->isAlignmentDependent()) {
Chandler Carruth4ced79f2010-06-25 03:22:07 +0000148 // The alignment expression is not potentially evaluated.
John McCall1d8d1cc2010-08-01 02:01:53 +0000149 EnterExpressionEvaluationContext Unevaluated(*this,
John McCallf312b1e2010-08-26 23:41:50 +0000150 Sema::Unevaluated);
Chandler Carruth4ced79f2010-06-25 03:22:07 +0000151
Sean Huntcf807c42010-08-18 23:23:40 +0000152 if (Aligned->isAlignmentExpr()) {
John McCall60d7b3a2010-08-24 06:29:42 +0000153 ExprResult Result = SubstExpr(Aligned->getAlignmentExpr(),
Sean Huntcf807c42010-08-18 23:23:40 +0000154 TemplateArgs);
155 if (!Result.isInvalid())
156 AddAlignedAttr(Aligned->getLocation(), New, Result.takeAs<Expr>());
157 }
158 else {
159 TypeSourceInfo *Result = SubstType(Aligned->getAlignmentType(),
160 TemplateArgs,
161 Aligned->getLocation(),
162 DeclarationName());
163 if (Result)
164 AddAlignedAttr(Aligned->getLocation(), New, Result);
165 }
Chandler Carruth4ced79f2010-06-25 03:22:07 +0000166 continue;
167 }
168 }
169
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000170 // FIXME: Is cloning correct for all attributes?
John McCall1d8d1cc2010-08-01 02:01:53 +0000171 Attr *NewAttr = TmplAttr->clone(Context);
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000172 New->addAttr(NewAttr);
173 }
174}
175
Douglas Gregor4f722be2009-03-25 15:45:12 +0000176Decl *
177TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
178 assert(false && "Translation units cannot be instantiated");
179 return D;
180}
181
182Decl *
183TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
184 assert(false && "Namespaces cannot be instantiated");
185 return D;
186}
187
John McCall3dbd3d52010-02-16 06:53:13 +0000188Decl *
189TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
190 NamespaceAliasDecl *Inst
191 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
192 D->getNamespaceLoc(),
193 D->getAliasLoc(),
194 D->getNamespace()->getIdentifier(),
195 D->getQualifierRange(),
196 D->getQualifier(),
197 D->getTargetNameLoc(),
198 D->getNamespace());
199 Owner->addDecl(Inst);
200 return Inst;
201}
202
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000203Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
204 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000205 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor836adf62010-05-24 17:22:01 +0000206 if (DI->getType()->isDependentType() ||
207 DI->getType()->isVariablyModifiedType()) {
John McCallba6a9bd2009-10-24 08:00:42 +0000208 DI = SemaRef.SubstType(DI, TemplateArgs,
209 D->getLocation(), D->getDeclName());
210 if (!DI) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000211 Invalid = true;
John McCalla93c9342009-12-07 02:54:59 +0000212 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000213 }
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000214 } else {
215 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000216 }
Mike Stump1eb44332009-09-09 15:08:12 +0000217
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000218 // Create the new typedef
219 TypedefDecl *Typedef
220 = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(),
John McCallba6a9bd2009-10-24 08:00:42 +0000221 D->getIdentifier(), DI);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000222 if (Invalid)
223 Typedef->setInvalidDecl();
224
Douglas Gregord57a38e2010-04-23 16:25:07 +0000225 if (const TagType *TT = DI->getType()->getAs<TagType>()) {
226 TagDecl *TD = TT->getDecl();
227
228 // If the TagDecl that the TypedefDecl points to is an anonymous decl
229 // keep track of the TypedefDecl.
230 if (!TD->getIdentifier() && !TD->getTypedefForAnonDecl())
231 TD->setTypedefForAnonDecl(Typedef);
232 }
233
John McCall5126fd02009-12-30 00:31:22 +0000234 if (TypedefDecl *Prev = D->getPreviousDeclaration()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000235 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
236 TemplateArgs);
John McCall5126fd02009-12-30 00:31:22 +0000237 Typedef->setPreviousDeclaration(cast<TypedefDecl>(InstPrev));
238 }
239
John McCall1d8d1cc2010-08-01 02:01:53 +0000240 SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
Douglas Gregord57a38e2010-04-23 16:25:07 +0000241
John McCall46460a62010-01-20 21:53:11 +0000242 Typedef->setAccess(D->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000243 Owner->addDecl(Typedef);
Mike Stump1eb44332009-09-09 15:08:12 +0000244
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000245 return Typedef;
246}
247
Douglas Gregor6eef5192009-12-14 19:27:10 +0000248/// \brief Instantiate the arguments provided as part of initialization.
249///
250/// \returns true if an error occurred, false otherwise.
251static bool InstantiateInitializationArguments(Sema &SemaRef,
252 Expr **Args, unsigned NumArgs,
253 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCallca0408f2010-08-23 06:44:23 +0000254 ASTOwningVector<Expr*> &InitArgs) {
Douglas Gregor6eef5192009-12-14 19:27:10 +0000255 for (unsigned I = 0; I != NumArgs; ++I) {
256 // When we hit the first defaulted argument, break out of the loop:
257 // we don't pass those default arguments on.
258 if (Args[I]->isDefaultArgument())
259 break;
260
John McCall60d7b3a2010-08-24 06:29:42 +0000261 ExprResult Arg = SemaRef.SubstExpr(Args[I], TemplateArgs);
Douglas Gregor6eef5192009-12-14 19:27:10 +0000262 if (Arg.isInvalid())
263 return true;
264
Douglas Gregor6eef5192009-12-14 19:27:10 +0000265 InitArgs.push_back(Arg.release());
Douglas Gregor6eef5192009-12-14 19:27:10 +0000266 }
267
268 return false;
269}
270
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000271/// \brief Instantiate an initializer, breaking it into separate
272/// initialization arguments.
273///
274/// \param S The semantic analysis object.
275///
276/// \param Init The initializer to instantiate.
277///
278/// \param TemplateArgs Template arguments to be substituted into the
279/// initializer.
280///
281/// \param NewArgs Will be filled in with the instantiation arguments.
282///
283/// \returns true if an error occurred, false otherwise
284static bool InstantiateInitializer(Sema &S, Expr *Init,
285 const MultiLevelTemplateArgumentList &TemplateArgs,
286 SourceLocation &LParenLoc,
John McCallca0408f2010-08-23 06:44:23 +0000287 ASTOwningVector<Expr*> &NewArgs,
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000288 SourceLocation &RParenLoc) {
289 NewArgs.clear();
290 LParenLoc = SourceLocation();
291 RParenLoc = SourceLocation();
292
293 if (!Init)
294 return false;
295
296 if (CXXExprWithTemporaries *ExprTemp = dyn_cast<CXXExprWithTemporaries>(Init))
297 Init = ExprTemp->getSubExpr();
298
299 while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
300 Init = Binder->getSubExpr();
301
302 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
303 Init = ICE->getSubExprAsWritten();
304
305 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
306 LParenLoc = ParenList->getLParenLoc();
307 RParenLoc = ParenList->getRParenLoc();
308 return InstantiateInitializationArguments(S, ParenList->getExprs(),
309 ParenList->getNumExprs(),
Douglas Gregora1a04782010-09-09 16:33:13 +0000310 TemplateArgs, NewArgs);
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000311 }
312
313 if (CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init)) {
Douglas Gregor28329e52010-03-24 21:22:47 +0000314 if (!isa<CXXTemporaryObjectExpr>(Construct)) {
315 if (InstantiateInitializationArguments(S,
316 Construct->getArgs(),
317 Construct->getNumArgs(),
Douglas Gregora1a04782010-09-09 16:33:13 +0000318 TemplateArgs, NewArgs))
Douglas Gregor28329e52010-03-24 21:22:47 +0000319 return true;
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000320
Douglas Gregor28329e52010-03-24 21:22:47 +0000321 // FIXME: Fake locations!
322 LParenLoc = S.PP.getLocForEndOfToken(Init->getLocStart());
Douglas Gregora1a04782010-09-09 16:33:13 +0000323 RParenLoc = LParenLoc;
Douglas Gregor28329e52010-03-24 21:22:47 +0000324 return false;
325 }
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000326 }
327
John McCall60d7b3a2010-08-24 06:29:42 +0000328 ExprResult Result = S.SubstExpr(Init, TemplateArgs);
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000329 if (Result.isInvalid())
330 return true;
331
332 NewArgs.push_back(Result.takeAs<Expr>());
333 return false;
334}
335
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000336Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
Douglas Gregor9901c572010-05-21 00:31:19 +0000337 // If this is the variable for an anonymous struct or union,
338 // instantiate the anonymous struct/union type first.
339 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
340 if (RecordTy->getDecl()->isAnonymousStructOrUnion())
341 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
342 return 0;
343
John McCallce3ff2b2009-08-25 22:02:44 +0000344 // Do substitution on the type of the declaration
John McCalla93c9342009-12-07 02:54:59 +0000345 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
John McCall0a5fa062009-10-21 02:39:02 +0000346 TemplateArgs,
347 D->getTypeSpecStartLoc(),
348 D->getDeclName());
349 if (!DI)
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000350 return 0;
351
Douglas Gregorc6dbc3f2010-09-12 07:37:24 +0000352 if (DI->getType()->isFunctionType()) {
353 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
354 << D->isStaticDataMember() << DI->getType();
355 return 0;
356 }
357
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000358 // Build the instantiated declaration
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000359 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
360 D->getLocation(), D->getIdentifier(),
John McCall0a5fa062009-10-21 02:39:02 +0000361 DI->getType(), DI,
Douglas Gregor16573fa2010-04-19 22:54:31 +0000362 D->getStorageClass(),
363 D->getStorageClassAsWritten());
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000364 Var->setThreadSpecified(D->isThreadSpecified());
365 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
Mike Stump1eb44332009-09-09 15:08:12 +0000366
John McCallb6217662010-03-15 10:12:16 +0000367 // Substitute the nested name specifier, if any.
368 if (SubstQualifier(D, Var))
369 return 0;
370
Mike Stump1eb44332009-09-09 15:08:12 +0000371 // If we are instantiating a static data member defined
Douglas Gregor7caa6822009-07-24 20:34:43 +0000372 // out-of-line, the instantiation will have the same lexical
373 // context (which will be a namespace scope) as the template.
374 if (D->isOutOfLine())
375 Var->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000376
John McCall46460a62010-01-20 21:53:11 +0000377 Var->setAccess(D->getAccess());
Douglas Gregorc070cc62010-06-17 23:14:26 +0000378
379 if (!D->isStaticDataMember())
380 Var->setUsed(D->isUsed(false));
Douglas Gregor4469e8a2010-05-19 17:02:24 +0000381
Mike Stump390b4cc2009-05-16 07:39:55 +0000382 // FIXME: In theory, we could have a previous declaration for variables that
383 // are not static data members.
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000384 bool Redeclaration = false;
John McCall68263142009-11-18 22:49:29 +0000385 // FIXME: having to fake up a LookupResult is dumb.
386 LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(),
Douglas Gregor449d0a82010-03-01 19:11:54 +0000387 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Douglas Gregor60c93c92010-02-09 07:26:29 +0000388 if (D->isStaticDataMember())
389 SemaRef.LookupQualifiedName(Previous, Owner, false);
John McCall68263142009-11-18 22:49:29 +0000390 SemaRef.CheckVariableDeclaration(Var, Previous, Redeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +0000391
Douglas Gregor7caa6822009-07-24 20:34:43 +0000392 if (D->isOutOfLine()) {
Abramo Bagnaraea7b4882010-06-04 09:35:39 +0000393 if (!D->isStaticDataMember())
394 D->getLexicalDeclContext()->addDecl(Var);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000395 Owner->makeDeclVisibleInContext(Var);
396 } else {
397 Owner->addDecl(Var);
Douglas Gregorf7d72f52010-05-03 20:22:41 +0000398 if (Owner->isFunctionOrMethod())
399 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Var);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000400 }
John McCall1d8d1cc2010-08-01 02:01:53 +0000401 SemaRef.InstantiateAttrs(TemplateArgs, D, Var);
Fariborz Jahanian8dd0c562010-07-13 00:16:40 +0000402
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000403 // Link instantiations of static data members back to the template from
404 // which they were instantiated.
405 if (Var->isStaticDataMember())
406 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D,
Douglas Gregorcf3293e2009-11-01 20:32:48 +0000407 TSK_ImplicitInstantiation);
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000408
Douglas Gregor60c93c92010-02-09 07:26:29 +0000409 if (Var->getAnyInitializer()) {
410 // We already have an initializer in the class.
411 } else if (D->getInit()) {
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000412 if (Var->isStaticDataMember() && !D->isOutOfLine())
413 SemaRef.PushExpressionEvaluationContext(Sema::Unevaluated);
414 else
415 SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
416
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000417 // Instantiate the initializer.
418 SourceLocation LParenLoc, RParenLoc;
John McCallca0408f2010-08-23 06:44:23 +0000419 ASTOwningVector<Expr*> InitArgs(SemaRef);
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000420 if (!InstantiateInitializer(SemaRef, D->getInit(), TemplateArgs, LParenLoc,
Douglas Gregora1a04782010-09-09 16:33:13 +0000421 InitArgs, RParenLoc)) {
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000422 // Attach the initializer to the declaration.
423 if (D->hasCXXDirectInitializer()) {
Douglas Gregor6eef5192009-12-14 19:27:10 +0000424 // Add the direct initializer to the declaration.
John McCalld226f652010-08-21 09:40:31 +0000425 SemaRef.AddCXXDirectInitializerToDecl(Var,
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000426 LParenLoc,
Douglas Gregor6eef5192009-12-14 19:27:10 +0000427 move_arg(InitArgs),
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000428 RParenLoc);
429 } else if (InitArgs.size() == 1) {
John McCall9ae2f072010-08-23 23:25:46 +0000430 Expr *Init = InitArgs.take()[0];
431 SemaRef.AddInitializerToDecl(Var, Init, false);
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000432 } else {
433 assert(InitArgs.size() == 0);
John McCalld226f652010-08-21 09:40:31 +0000434 SemaRef.ActOnUninitializedDecl(Var, false);
Douglas Gregor6eef5192009-12-14 19:27:10 +0000435 }
Douglas Gregor6eef5192009-12-14 19:27:10 +0000436 } else {
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000437 // FIXME: Not too happy about invalidating the declaration
438 // because of a bogus initializer.
439 Var->setInvalidDecl();
Douglas Gregor6eef5192009-12-14 19:27:10 +0000440 }
441
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000442 SemaRef.PopExpressionEvaluationContext();
Douglas Gregor65b90052009-07-27 17:43:39 +0000443 } else if (!Var->isStaticDataMember() || Var->isOutOfLine())
John McCalld226f652010-08-21 09:40:31 +0000444 SemaRef.ActOnUninitializedDecl(Var, false);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000445
Douglas Gregor5764f612010-05-08 23:05:03 +0000446 // Diagnose unused local variables.
447 if (!Var->isInvalidDecl() && Owner->isFunctionOrMethod() && !Var->isUsed())
448 SemaRef.DiagnoseUnusedDecl(Var);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +0000449
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000450 return Var;
451}
452
Abramo Bagnara6206d532010-06-05 05:09:32 +0000453Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
454 AccessSpecDecl* AD
455 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
456 D->getAccessSpecifierLoc(), D->getColonLoc());
457 Owner->addHiddenDecl(AD);
458 return AD;
459}
460
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000461Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
462 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000463 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor836adf62010-05-24 17:22:01 +0000464 if (DI->getType()->isDependentType() ||
465 DI->getType()->isVariablyModifiedType()) {
John McCall07fb6be2009-10-22 23:33:21 +0000466 DI = SemaRef.SubstType(DI, TemplateArgs,
467 D->getLocation(), D->getDeclName());
468 if (!DI) {
John McCalla93c9342009-12-07 02:54:59 +0000469 DI = D->getTypeSourceInfo();
John McCall07fb6be2009-10-22 23:33:21 +0000470 Invalid = true;
471 } else if (DI->getType()->isFunctionType()) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000472 // C++ [temp.arg.type]p3:
473 // If a declaration acquires a function type through a type
474 // dependent on a template-parameter and this causes a
475 // declaration that does not use the syntactic form of a
476 // function declarator to have function type, the program is
477 // ill-formed.
478 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
John McCall07fb6be2009-10-22 23:33:21 +0000479 << DI->getType();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000480 Invalid = true;
481 }
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000482 } else {
483 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000484 }
485
486 Expr *BitWidth = D->getBitWidth();
487 if (Invalid)
488 BitWidth = 0;
489 else if (BitWidth) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000490 // The bit-width expression is not potentially evaluated.
John McCallf312b1e2010-08-26 23:41:50 +0000491 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000492
John McCall60d7b3a2010-08-24 06:29:42 +0000493 ExprResult InstantiatedBitWidth
John McCallce3ff2b2009-08-25 22:02:44 +0000494 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000495 if (InstantiatedBitWidth.isInvalid()) {
496 Invalid = true;
497 BitWidth = 0;
498 } else
Anders Carlssone9146f22009-05-01 19:49:17 +0000499 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000500 }
501
John McCall07fb6be2009-10-22 23:33:21 +0000502 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
503 DI->getType(), DI,
Mike Stump1eb44332009-09-09 15:08:12 +0000504 cast<RecordDecl>(Owner),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000505 D->getLocation(),
506 D->isMutable(),
507 BitWidth,
Steve Naroffea218b82009-07-14 14:58:18 +0000508 D->getTypeSpecStartLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000509 D->getAccess(),
510 0);
Douglas Gregor663b5a02009-10-14 20:14:33 +0000511 if (!Field) {
512 cast<Decl>(Owner)->setInvalidDecl();
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000513 return 0;
Douglas Gregor663b5a02009-10-14 20:14:33 +0000514 }
Mike Stump1eb44332009-09-09 15:08:12 +0000515
John McCall1d8d1cc2010-08-01 02:01:53 +0000516 SemaRef.InstantiateAttrs(TemplateArgs, D, Field);
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000517
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000518 if (Invalid)
519 Field->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000520
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000521 if (!Field->getDeclName()) {
522 // Keep track of where this decl came from.
523 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
Douglas Gregor9901c572010-05-21 00:31:19 +0000524 }
525 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
526 if (Parent->isAnonymousStructOrUnion() &&
Sebastian Redl7a126a42010-08-31 00:36:30 +0000527 Parent->getRedeclContext()->isFunctionOrMethod())
Douglas Gregor9901c572010-05-21 00:31:19 +0000528 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000529 }
Mike Stump1eb44332009-09-09 15:08:12 +0000530
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000531 Field->setImplicit(D->isImplicit());
John McCall46460a62010-01-20 21:53:11 +0000532 Field->setAccess(D->getAccess());
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000533 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000534
535 return Field;
536}
537
John McCall02cace72009-08-28 07:59:38 +0000538Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
John McCall02cace72009-08-28 07:59:38 +0000539 // Handle friend type expressions by simply substituting template
Douglas Gregor06245bf2010-04-07 17:57:12 +0000540 // parameters into the pattern type and checking the result.
John McCall32f2fb52010-03-25 18:04:51 +0000541 if (TypeSourceInfo *Ty = D->getFriendType()) {
542 TypeSourceInfo *InstTy =
543 SemaRef.SubstType(Ty, TemplateArgs,
544 D->getLocation(), DeclarationName());
Douglas Gregor06245bf2010-04-07 17:57:12 +0000545 if (!InstTy)
Douglas Gregor7557a132009-12-24 20:56:24 +0000546 return 0;
John McCall02cace72009-08-28 07:59:38 +0000547
Douglas Gregor06245bf2010-04-07 17:57:12 +0000548 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getFriendLoc(), InstTy);
549 if (!FD)
550 return 0;
551
552 FD->setAccess(AS_public);
John McCall9a34edb2010-10-19 01:40:49 +0000553 FD->setUnsupportedFriend(D->isUnsupportedFriend());
Douglas Gregor06245bf2010-04-07 17:57:12 +0000554 Owner->addDecl(FD);
555 return FD;
556 }
557
558 NamedDecl *ND = D->getFriendDecl();
559 assert(ND && "friend decl must be a decl or a type!");
560
John McCallaf2094e2010-04-08 09:05:18 +0000561 // All of the Visit implementations for the various potential friend
562 // declarations have to be carefully written to work for friend
563 // objects, with the most important detail being that the target
564 // decl should almost certainly not be placed in Owner.
565 Decl *NewND = Visit(ND);
Douglas Gregor06245bf2010-04-07 17:57:12 +0000566 if (!NewND) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000567
John McCall02cace72009-08-28 07:59:38 +0000568 FriendDecl *FD =
Douglas Gregor06245bf2010-04-07 17:57:12 +0000569 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
570 cast<NamedDecl>(NewND), D->getFriendLoc());
John McCall5fee1102009-08-29 03:50:18 +0000571 FD->setAccess(AS_public);
John McCall9a34edb2010-10-19 01:40:49 +0000572 FD->setUnsupportedFriend(D->isUnsupportedFriend());
John McCall02cace72009-08-28 07:59:38 +0000573 Owner->addDecl(FD);
574 return FD;
John McCallfd810b12009-08-14 02:03:10 +0000575}
576
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000577Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
578 Expr *AssertExpr = D->getAssertExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000579
Douglas Gregorac7610d2009-06-22 20:57:11 +0000580 // The expression in a static assertion is not potentially evaluated.
John McCallf312b1e2010-08-26 23:41:50 +0000581 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000582
John McCall60d7b3a2010-08-24 06:29:42 +0000583 ExprResult InstantiatedAssertExpr
John McCallce3ff2b2009-08-25 22:02:44 +0000584 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000585 if (InstantiatedAssertExpr.isInvalid())
586 return 0;
587
John McCall60d7b3a2010-08-24 06:29:42 +0000588 ExprResult Message(D->getMessage());
Douglas Gregor43d9d922009-08-08 01:41:12 +0000589 D->getMessage()->Retain();
John McCalld226f652010-08-21 09:40:31 +0000590 return SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
John McCall9ae2f072010-08-23 23:25:46 +0000591 InstantiatedAssertExpr.get(),
592 Message.get());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000593}
594
595Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +0000596 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000597 D->getLocation(), D->getIdentifier(),
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000598 D->getTagKeywordLoc(),
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000599 /*PrevDecl=*/0,
600 D->isScoped(), D->isFixed());
601 if (D->isFixed()) {
602 if (TypeSourceInfo* TI = D->getIntegerTypeSourceInfo()) {
603 // If we have type source information for the underlying type, it means it
604 // has been explicitly set by the user. Perform substitution on it before
605 // moving on.
606 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
607 Enum->setIntegerTypeSourceInfo(SemaRef.SubstType(TI,
608 TemplateArgs,
609 UnderlyingLoc,
610 DeclarationName()));
611
612 if (!Enum->getIntegerTypeSourceInfo())
613 Enum->setIntegerType(SemaRef.Context.IntTy);
614 }
615 else {
616 assert(!D->getIntegerType()->isDependentType()
617 && "Dependent type without type source info");
618 Enum->setIntegerType(D->getIntegerType());
619 }
620 }
621
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000622 Enum->setInstantiationOfMemberEnum(D);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000623 Enum->setAccess(D->getAccess());
John McCallb6217662010-03-15 10:12:16 +0000624 if (SubstQualifier(D, Enum)) return 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000625 Owner->addDecl(Enum);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000626 Enum->startDefinition();
627
Douglas Gregor96084f12010-03-01 19:00:07 +0000628 if (D->getDeclContext()->isFunctionOrMethod())
629 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
630
John McCalld226f652010-08-21 09:40:31 +0000631 llvm::SmallVector<Decl*, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000632
633 EnumConstantDecl *LastEnumConst = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000634 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
635 ECEnd = D->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000636 EC != ECEnd; ++EC) {
637 // The specified value for the enumerator.
John McCall60d7b3a2010-08-24 06:29:42 +0000638 ExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000639 if (Expr *UninstValue = EC->getInitExpr()) {
640 // The enumerator's value expression is not potentially evaluated.
Mike Stump1eb44332009-09-09 15:08:12 +0000641 EnterExpressionEvaluationContext Unevaluated(SemaRef,
John McCallf312b1e2010-08-26 23:41:50 +0000642 Sema::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000643
John McCallce3ff2b2009-08-25 22:02:44 +0000644 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000645 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000646
647 // Drop the initial value and continue.
648 bool isInvalid = false;
649 if (Value.isInvalid()) {
650 Value = SemaRef.Owned((Expr *)0);
651 isInvalid = true;
652 }
653
Mike Stump1eb44332009-09-09 15:08:12 +0000654 EnumConstantDecl *EnumConst
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000655 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
656 EC->getLocation(), EC->getIdentifier(),
John McCall9ae2f072010-08-23 23:25:46 +0000657 Value.get());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000658
659 if (isInvalid) {
660 if (EnumConst)
661 EnumConst->setInvalidDecl();
662 Enum->setInvalidDecl();
663 }
664
665 if (EnumConst) {
John McCall3b85ecf2010-01-23 22:37:59 +0000666 EnumConst->setAccess(Enum->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000667 Enum->addDecl(EnumConst);
John McCalld226f652010-08-21 09:40:31 +0000668 Enumerators.push_back(EnumConst);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000669 LastEnumConst = EnumConst;
Douglas Gregor96084f12010-03-01 19:00:07 +0000670
671 if (D->getDeclContext()->isFunctionOrMethod()) {
672 // If the enumeration is within a function or method, record the enum
673 // constant as a local.
674 SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst);
675 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000676 }
677 }
Mike Stump1eb44332009-09-09 15:08:12 +0000678
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000679 // FIXME: Fixup LBraceLoc and RBraceLoc
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000680 // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000681 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
John McCalld226f652010-08-21 09:40:31 +0000682 Enum,
Eli Friedmande7a0fc2010-08-15 02:27:09 +0000683 Enumerators.data(), Enumerators.size(),
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000684 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000685
686 return Enum;
687}
688
Douglas Gregor6477b692009-03-25 15:04:13 +0000689Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
690 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
691 return 0;
692}
693
John McCalle29ba202009-08-20 01:44:21 +0000694Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
John McCall93ba8572010-03-25 06:39:04 +0000695 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
696
Douglas Gregor550d9b22009-10-31 17:21:17 +0000697 // Create a local instantiation scope for this class template, which
698 // will contain the instantiations of the template parameters.
John McCall2a7fb272010-08-25 05:32:35 +0000699 LocalInstantiationScope Scope(SemaRef);
John McCalle29ba202009-08-20 01:44:21 +0000700 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000701 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000702 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000703 return NULL;
John McCalle29ba202009-08-20 01:44:21 +0000704
705 CXXRecordDecl *Pattern = D->getTemplatedDecl();
John McCall93ba8572010-03-25 06:39:04 +0000706
707 // Instantiate the qualifier. We have to do this first in case
708 // we're a friend declaration, because if we are then we need to put
709 // the new declaration in the appropriate context.
710 NestedNameSpecifier *Qualifier = Pattern->getQualifier();
711 if (Qualifier) {
712 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
713 Pattern->getQualifierRange(),
714 TemplateArgs);
715 if (!Qualifier) return 0;
716 }
717
718 CXXRecordDecl *PrevDecl = 0;
719 ClassTemplateDecl *PrevClassTemplate = 0;
720
721 // If this isn't a friend, then it's a member template, in which
722 // case we just want to build the instantiation in the
723 // specialization. If it is a friend, we want to build it in
724 // the appropriate context.
725 DeclContext *DC = Owner;
726 if (isFriend) {
727 if (Qualifier) {
728 CXXScopeSpec SS;
729 SS.setScopeRep(Qualifier);
730 SS.setRange(Pattern->getQualifierRange());
731 DC = SemaRef.computeDeclContext(SS);
732 if (!DC) return 0;
733 } else {
734 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
735 Pattern->getDeclContext(),
736 TemplateArgs);
737 }
738
739 // Look for a previous declaration of the template in the owning
740 // context.
741 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
742 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
743 SemaRef.LookupQualifiedName(R, DC);
744
745 if (R.isSingleResult()) {
746 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
747 if (PrevClassTemplate)
748 PrevDecl = PrevClassTemplate->getTemplatedDecl();
749 }
750
751 if (!PrevClassTemplate && Qualifier) {
752 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
Douglas Gregor1eabb7d2010-03-31 23:17:41 +0000753 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
754 << Pattern->getQualifierRange();
John McCall93ba8572010-03-25 06:39:04 +0000755 return 0;
756 }
757
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000758 bool AdoptedPreviousTemplateParams = false;
John McCall93ba8572010-03-25 06:39:04 +0000759 if (PrevClassTemplate) {
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000760 bool Complain = true;
761
762 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
763 // template for struct std::tr1::__detail::_Map_base, where the
764 // template parameters of the friend declaration don't match the
765 // template parameters of the original declaration. In this one
766 // case, we don't complain about the ill-formed friend
767 // declaration.
768 if (isFriend && Pattern->getIdentifier() &&
769 Pattern->getIdentifier()->isStr("_Map_base") &&
770 DC->isNamespace() &&
771 cast<NamespaceDecl>(DC)->getIdentifier() &&
772 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
773 DeclContext *DCParent = DC->getParent();
774 if (DCParent->isNamespace() &&
775 cast<NamespaceDecl>(DCParent)->getIdentifier() &&
776 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
777 DeclContext *DCParent2 = DCParent->getParent();
778 if (DCParent2->isNamespace() &&
779 cast<NamespaceDecl>(DCParent2)->getIdentifier() &&
780 cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") &&
781 DCParent2->getParent()->isTranslationUnit())
782 Complain = false;
783 }
784 }
785
John McCall93ba8572010-03-25 06:39:04 +0000786 TemplateParameterList *PrevParams
787 = PrevClassTemplate->getTemplateParameters();
788
789 // Make sure the parameter lists match.
790 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000791 Complain,
792 Sema::TPL_TemplateMatch)) {
793 if (Complain)
794 return 0;
795
796 AdoptedPreviousTemplateParams = true;
797 InstParams = PrevParams;
798 }
John McCall93ba8572010-03-25 06:39:04 +0000799
800 // Do some additional validation, then merge default arguments
801 // from the existing declarations.
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000802 if (!AdoptedPreviousTemplateParams &&
803 SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
John McCall93ba8572010-03-25 06:39:04 +0000804 Sema::TPC_ClassTemplate))
805 return 0;
806 }
807 }
808
John McCalle29ba202009-08-20 01:44:21 +0000809 CXXRecordDecl *RecordInst
John McCall93ba8572010-03-25 06:39:04 +0000810 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
John McCalle29ba202009-08-20 01:44:21 +0000811 Pattern->getLocation(), Pattern->getIdentifier(),
John McCall93ba8572010-03-25 06:39:04 +0000812 Pattern->getTagKeywordLoc(), PrevDecl,
Douglas Gregorf0510d42009-10-12 23:11:44 +0000813 /*DelayTypeCreation=*/true);
John McCalle29ba202009-08-20 01:44:21 +0000814
John McCall93ba8572010-03-25 06:39:04 +0000815 if (Qualifier)
816 RecordInst->setQualifierInfo(Qualifier, Pattern->getQualifierRange());
John McCallb6217662010-03-15 10:12:16 +0000817
John McCalle29ba202009-08-20 01:44:21 +0000818 ClassTemplateDecl *Inst
John McCall93ba8572010-03-25 06:39:04 +0000819 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
820 D->getIdentifier(), InstParams, RecordInst,
821 PrevClassTemplate);
John McCalle29ba202009-08-20 01:44:21 +0000822 RecordInst->setDescribedClassTemplate(Inst);
John McCallea7390c2010-04-08 20:25:50 +0000823
John McCall93ba8572010-03-25 06:39:04 +0000824 if (isFriend) {
John McCallea7390c2010-04-08 20:25:50 +0000825 if (PrevClassTemplate)
826 Inst->setAccess(PrevClassTemplate->getAccess());
827 else
828 Inst->setAccess(D->getAccess());
829
John McCall93ba8572010-03-25 06:39:04 +0000830 Inst->setObjectOfFriendDecl(PrevClassTemplate != 0);
831 // TODO: do we want to track the instantiation progeny of this
832 // friend target decl?
833 } else {
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000834 Inst->setAccess(D->getAccess());
John McCall93ba8572010-03-25 06:39:04 +0000835 Inst->setInstantiatedFromMemberTemplate(D);
836 }
Douglas Gregorf0510d42009-10-12 23:11:44 +0000837
838 // Trigger creation of the type for the instantiation.
John McCall3cb0ebd2010-03-10 03:28:59 +0000839 SemaRef.Context.getInjectedClassNameType(RecordInst,
Douglas Gregor24bae922010-07-08 18:37:38 +0000840 Inst->getInjectedClassNameSpecialization());
John McCallea7390c2010-04-08 20:25:50 +0000841
Douglas Gregor259571e2009-10-30 22:42:42 +0000842 // Finish handling of friends.
John McCall93ba8572010-03-25 06:39:04 +0000843 if (isFriend) {
844 DC->makeDeclVisibleInContext(Inst, /*Recoverable*/ false);
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000845 return Inst;
Douglas Gregor259571e2009-10-30 22:42:42 +0000846 }
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000847
John McCalle29ba202009-08-20 01:44:21 +0000848 Owner->addDecl(Inst);
Douglas Gregored9c0f92009-10-29 00:04:11 +0000849
Douglas Gregored9c0f92009-10-29 00:04:11 +0000850 // Instantiate all of the partial specializations of this member class
851 // template.
Douglas Gregordc60c1e2010-04-30 05:56:50 +0000852 llvm::SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
853 D->getPartialSpecializations(PartialSpecs);
Douglas Gregored9c0f92009-10-29 00:04:11 +0000854 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
855 InstantiateClassTemplatePartialSpecialization(Inst, PartialSpecs[I]);
856
John McCalle29ba202009-08-20 01:44:21 +0000857 return Inst;
858}
859
Douglas Gregord60e1052009-08-27 16:57:43 +0000860Decl *
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000861TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
862 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregored9c0f92009-10-29 00:04:11 +0000863 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
864
865 // Lookup the already-instantiated declaration in the instantiation
866 // of the class template and return that.
867 DeclContext::lookup_result Found
868 = Owner->lookup(ClassTemplate->getDeclName());
869 if (Found.first == Found.second)
870 return 0;
871
872 ClassTemplateDecl *InstClassTemplate
873 = dyn_cast<ClassTemplateDecl>(*Found.first);
874 if (!InstClassTemplate)
875 return 0;
876
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +0000877 return InstClassTemplate->findPartialSpecInstantiatedFromMember(D);
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000878}
879
880Decl *
Douglas Gregord60e1052009-08-27 16:57:43 +0000881TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000882 // Create a local instantiation scope for this function template, which
883 // will contain the instantiations of the template parameters and then get
884 // merged with the local instantiation scope for the function template
885 // itself.
John McCall2a7fb272010-08-25 05:32:35 +0000886 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor895162d2010-04-30 18:55:50 +0000887
Douglas Gregord60e1052009-08-27 16:57:43 +0000888 TemplateParameterList *TempParams = D->getTemplateParameters();
889 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000890 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000891 return NULL;
Douglas Gregored9c0f92009-10-29 00:04:11 +0000892
Douglas Gregora735b202009-10-13 14:39:41 +0000893 FunctionDecl *Instantiated = 0;
894 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
895 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
896 InstParams));
897 else
898 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
899 D->getTemplatedDecl(),
900 InstParams));
901
902 if (!Instantiated)
Douglas Gregord60e1052009-08-27 16:57:43 +0000903 return 0;
904
John McCall46460a62010-01-20 21:53:11 +0000905 Instantiated->setAccess(D->getAccess());
906
Mike Stump1eb44332009-09-09 15:08:12 +0000907 // Link the instantiated function template declaration to the function
Douglas Gregord60e1052009-08-27 16:57:43 +0000908 // template from which it was instantiated.
Douglas Gregor37d681852009-10-12 22:27:17 +0000909 FunctionTemplateDecl *InstTemplate
Douglas Gregora735b202009-10-13 14:39:41 +0000910 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregor37d681852009-10-12 22:27:17 +0000911 InstTemplate->setAccess(D->getAccess());
Douglas Gregora735b202009-10-13 14:39:41 +0000912 assert(InstTemplate &&
913 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCalle976ffe2009-12-14 23:19:40 +0000914
John McCallb1a56e72010-03-26 23:10:15 +0000915 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
916
John McCalle976ffe2009-12-14 23:19:40 +0000917 // Link the instantiation back to the pattern *unless* this is a
918 // non-definition friend declaration.
919 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
John McCallb1a56e72010-03-26 23:10:15 +0000920 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregora735b202009-10-13 14:39:41 +0000921 InstTemplate->setInstantiatedFromMemberTemplate(D);
922
John McCallb1a56e72010-03-26 23:10:15 +0000923 // Make declarations visible in the appropriate context.
924 if (!isFriend)
Douglas Gregora735b202009-10-13 14:39:41 +0000925 Owner->addDecl(InstTemplate);
John McCallb1a56e72010-03-26 23:10:15 +0000926
Douglas Gregord60e1052009-08-27 16:57:43 +0000927 return InstTemplate;
928}
929
Douglas Gregord475b8d2009-03-25 21:17:03 +0000930Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
931 CXXRecordDecl *PrevDecl = 0;
932 if (D->isInjectedClassName())
933 PrevDecl = cast<CXXRecordDecl>(Owner);
John McCall6c1c1b82009-12-15 22:29:06 +0000934 else if (D->getPreviousDeclaration()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000935 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
936 D->getPreviousDeclaration(),
John McCall6c1c1b82009-12-15 22:29:06 +0000937 TemplateArgs);
938 if (!Prev) return 0;
939 PrevDecl = cast<CXXRecordDecl>(Prev);
940 }
Douglas Gregord475b8d2009-03-25 21:17:03 +0000941
942 CXXRecordDecl *Record
Mike Stump1eb44332009-09-09 15:08:12 +0000943 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000944 D->getLocation(), D->getIdentifier(),
945 D->getTagKeywordLoc(), PrevDecl);
John McCallb6217662010-03-15 10:12:16 +0000946
947 // Substitute the nested name specifier, if any.
948 if (SubstQualifier(D, Record))
949 return 0;
950
Douglas Gregord475b8d2009-03-25 21:17:03 +0000951 Record->setImplicit(D->isImplicit());
Eli Friedmaneaba1af2009-08-27 19:11:42 +0000952 // FIXME: Check against AS_none is an ugly hack to work around the issue that
953 // the tag decls introduced by friend class declarations don't have an access
954 // specifier. Remove once this area of the code gets sorted out.
955 if (D->getAccess() != AS_none)
956 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000957 if (!D->isInjectedClassName())
Douglas Gregorf6b11852009-10-08 15:14:33 +0000958 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000959
John McCall02cace72009-08-28 07:59:38 +0000960 // If the original function was part of a friend declaration,
961 // inherit its namespace state.
962 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
963 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
964
Douglas Gregor9901c572010-05-21 00:31:19 +0000965 // Make sure that anonymous structs and unions are recorded.
966 if (D->isAnonymousStructOrUnion()) {
967 Record->setAnonymousStructOrUnion(true);
Sebastian Redl7a126a42010-08-31 00:36:30 +0000968 if (Record->getDeclContext()->getRedeclContext()->isFunctionOrMethod())
Douglas Gregor9901c572010-05-21 00:31:19 +0000969 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
970 }
Anders Carlssond8b285f2009-09-01 04:26:58 +0000971
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000972 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000973 return Record;
974}
975
John McCall02cace72009-08-28 07:59:38 +0000976/// Normal class members are of more specific types and therefore
977/// don't make it here. This function serves two purposes:
978/// 1) instantiating function templates
979/// 2) substituting friend declarations
980/// FIXME: preserve function definitions in case #2
Douglas Gregor7557a132009-12-24 20:56:24 +0000981Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
Douglas Gregora735b202009-10-13 14:39:41 +0000982 TemplateParameterList *TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000983 // Check whether there is already a function template specialization for
984 // this declaration.
985 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
986 void *InsertPos = 0;
John McCallb0cb0222010-03-27 05:57:59 +0000987 if (FunctionTemplate && !TemplateParams) {
Douglas Gregor24bae922010-07-08 18:37:38 +0000988 std::pair<const TemplateArgument *, unsigned> Innermost
989 = TemplateArgs.getInnermost();
Mike Stump1eb44332009-09-09 15:08:12 +0000990
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +0000991 FunctionDecl *SpecFunc
992 = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
993 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000994
Douglas Gregor127102b2009-06-29 20:59:39 +0000995 // If we already have a function template specialization, return it.
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +0000996 if (SpecFunc)
997 return SpecFunc;
Douglas Gregor127102b2009-06-29 20:59:39 +0000998 }
Mike Stump1eb44332009-09-09 15:08:12 +0000999
John McCallb0cb0222010-03-27 05:57:59 +00001000 bool isFriend;
1001 if (FunctionTemplate)
1002 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1003 else
1004 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1005
Douglas Gregor79c22782010-01-16 20:21:20 +00001006 bool MergeWithParentScope = (TemplateParams != 0) ||
Douglas Gregorb212d9a2010-05-21 21:25:08 +00001007 Owner->isFunctionOrMethod() ||
Douglas Gregor79c22782010-01-16 20:21:20 +00001008 !(isa<Decl>(Owner) &&
1009 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall2a7fb272010-08-25 05:32:35 +00001010 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +00001011
Douglas Gregore53060f2009-06-25 22:08:12 +00001012 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall21ef0fa2010-03-11 09:03:00 +00001013 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
1014 TInfo = SubstFunctionType(D, Params);
1015 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001016 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +00001017 QualType T = TInfo->getType();
John McCallfd810b12009-08-14 02:03:10 +00001018
John McCalld325daa2010-03-26 04:53:08 +00001019 NestedNameSpecifier *Qualifier = D->getQualifier();
1020 if (Qualifier) {
1021 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
1022 D->getQualifierRange(),
1023 TemplateArgs);
1024 if (!Qualifier) return 0;
1025 }
1026
John McCall68b6b872010-02-06 01:50:47 +00001027 // If we're instantiating a local function declaration, put the result
1028 // in the owner; otherwise we need to find the instantiated context.
1029 DeclContext *DC;
1030 if (D->getDeclContext()->isFunctionOrMethod())
1031 DC = Owner;
John McCalld325daa2010-03-26 04:53:08 +00001032 else if (isFriend && Qualifier) {
1033 CXXScopeSpec SS;
1034 SS.setScopeRep(Qualifier);
1035 SS.setRange(D->getQualifierRange());
1036 DC = SemaRef.computeDeclContext(SS);
1037 if (!DC) return 0;
1038 } else {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001039 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
1040 TemplateArgs);
John McCalld325daa2010-03-26 04:53:08 +00001041 }
John McCall68b6b872010-02-06 01:50:47 +00001042
John McCall02cace72009-08-28 07:59:38 +00001043 FunctionDecl *Function =
Mike Stump1eb44332009-09-09 15:08:12 +00001044 FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
John McCall21ef0fa2010-03-11 09:03:00 +00001045 D->getDeclName(), T, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001046 D->getStorageClass(), D->getStorageClassAsWritten(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001047 D->isInlineSpecified(), D->hasWrittenPrototype());
John McCallb6217662010-03-15 10:12:16 +00001048
John McCalld325daa2010-03-26 04:53:08 +00001049 if (Qualifier)
1050 Function->setQualifierInfo(Qualifier, D->getQualifierRange());
John McCallb6217662010-03-15 10:12:16 +00001051
John McCallb1a56e72010-03-26 23:10:15 +00001052 DeclContext *LexicalDC = Owner;
1053 if (!isFriend && D->isOutOfLine()) {
1054 assert(D->getDeclContext()->isFileContext());
1055 LexicalDC = D->getDeclContext();
1056 }
1057
1058 Function->setLexicalDeclContext(LexicalDC);
Mike Stump1eb44332009-09-09 15:08:12 +00001059
Douglas Gregore53060f2009-06-25 22:08:12 +00001060 // Attach the parameters
1061 for (unsigned P = 0; P < Params.size(); ++P)
John McCall3019c442010-09-17 00:50:28 +00001062 if (Params[P])
1063 Params[P]->setOwningFunction(Function);
Douglas Gregor838db382010-02-11 01:19:42 +00001064 Function->setParams(Params.data(), Params.size());
John McCall02cace72009-08-28 07:59:38 +00001065
Douglas Gregorac7c2c82010-05-17 16:38:00 +00001066 SourceLocation InstantiateAtPOI;
Douglas Gregora735b202009-10-13 14:39:41 +00001067 if (TemplateParams) {
1068 // Our resulting instantiation is actually a function template, since we
1069 // are substituting only the outer template parameters. For example, given
1070 //
1071 // template<typename T>
1072 // struct X {
1073 // template<typename U> friend void f(T, U);
1074 // };
1075 //
1076 // X<int> x;
1077 //
1078 // We are instantiating the friend function template "f" within X<int>,
1079 // which means substituting int for T, but leaving "f" as a friend function
1080 // template.
1081 // Build the function template itself.
John McCalld325daa2010-03-26 04:53:08 +00001082 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
Douglas Gregora735b202009-10-13 14:39:41 +00001083 Function->getLocation(),
1084 Function->getDeclName(),
1085 TemplateParams, Function);
1086 Function->setDescribedFunctionTemplate(FunctionTemplate);
John McCallb1a56e72010-03-26 23:10:15 +00001087
1088 FunctionTemplate->setLexicalDeclContext(LexicalDC);
John McCalld325daa2010-03-26 04:53:08 +00001089
1090 if (isFriend && D->isThisDeclarationADefinition()) {
1091 // TODO: should we remember this connection regardless of whether
1092 // the friend declaration provided a body?
1093 FunctionTemplate->setInstantiatedFromMemberTemplate(
1094 D->getDescribedFunctionTemplate());
1095 }
Douglas Gregor66724ea2009-11-14 01:20:54 +00001096 } else if (FunctionTemplate) {
1097 // Record this function template specialization.
Douglas Gregor24bae922010-07-08 18:37:38 +00001098 std::pair<const TemplateArgument *, unsigned> Innermost
1099 = TemplateArgs.getInnermost();
Douglas Gregor838db382010-02-11 01:19:42 +00001100 Function->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor24bae922010-07-08 18:37:38 +00001101 new (SemaRef.Context) TemplateArgumentList(SemaRef.Context,
1102 Innermost.first,
1103 Innermost.second),
Douglas Gregor66724ea2009-11-14 01:20:54 +00001104 InsertPos);
John McCalld325daa2010-03-26 04:53:08 +00001105 } else if (isFriend && D->isThisDeclarationADefinition()) {
1106 // TODO: should we remember this connection regardless of whether
1107 // the friend declaration provided a body?
1108 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
John McCall02cace72009-08-28 07:59:38 +00001109 }
Douglas Gregora735b202009-10-13 14:39:41 +00001110
Douglas Gregore53060f2009-06-25 22:08:12 +00001111 if (InitFunctionInstantiation(Function, D))
1112 Function->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001113
Douglas Gregore53060f2009-06-25 22:08:12 +00001114 bool Redeclaration = false;
1115 bool OverloadableAttrRequired = false;
John McCallaf2094e2010-04-08 09:05:18 +00001116 bool isExplicitSpecialization = false;
Douglas Gregora735b202009-10-13 14:39:41 +00001117
John McCall68263142009-11-18 22:49:29 +00001118 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
1119 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
1120
John McCallaf2094e2010-04-08 09:05:18 +00001121 if (DependentFunctionTemplateSpecializationInfo *Info
1122 = D->getDependentSpecializationInfo()) {
1123 assert(isFriend && "non-friend has dependent specialization info?");
1124
1125 // This needs to be set now for future sanity.
1126 Function->setObjectOfFriendDecl(/*HasPrevious*/ true);
1127
1128 // Instantiate the explicit template arguments.
1129 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1130 Info->getRAngleLoc());
1131 for (unsigned I = 0, E = Info->getNumTemplateArgs(); I != E; ++I) {
1132 TemplateArgumentLoc Loc;
1133 if (SemaRef.Subst(Info->getTemplateArg(I), Loc, TemplateArgs))
1134 return 0;
1135
1136 ExplicitArgs.addArgument(Loc);
1137 }
1138
1139 // Map the candidate templates to their instantiations.
1140 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1141 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1142 Info->getTemplate(I),
1143 TemplateArgs);
1144 if (!Temp) return 0;
1145
1146 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1147 }
1148
1149 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1150 &ExplicitArgs,
1151 Previous))
1152 Function->setInvalidDecl();
1153
1154 isExplicitSpecialization = true;
1155
1156 } else if (TemplateParams || !FunctionTemplate) {
Douglas Gregora735b202009-10-13 14:39:41 +00001157 // Look only into the namespace where the friend would be declared to
1158 // find a previous declaration. This is the innermost enclosing namespace,
1159 // as described in ActOnFriendFunctionDecl.
John McCall68263142009-11-18 22:49:29 +00001160 SemaRef.LookupQualifiedName(Previous, DC);
Douglas Gregora735b202009-10-13 14:39:41 +00001161
Douglas Gregora735b202009-10-13 14:39:41 +00001162 // In C++, the previous declaration we find might be a tag type
1163 // (class or enum). In this case, the new declaration will hide the
1164 // tag type. Note that this does does not apply if we're declaring a
1165 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001166 if (Previous.isSingleTagDecl())
1167 Previous.clear();
Douglas Gregora735b202009-10-13 14:39:41 +00001168 }
1169
John McCall9f54ad42009-12-10 09:41:52 +00001170 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
John McCallaf2094e2010-04-08 09:05:18 +00001171 isExplicitSpecialization, Redeclaration,
Douglas Gregore53060f2009-06-25 22:08:12 +00001172 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001173
John McCall76d32642010-04-24 01:30:58 +00001174 NamedDecl *PrincipalDecl = (TemplateParams
1175 ? cast<NamedDecl>(FunctionTemplate)
1176 : Function);
1177
Douglas Gregora735b202009-10-13 14:39:41 +00001178 // If the original function was part of a friend declaration,
1179 // inherit its namespace state and add it to the owner.
John McCalld325daa2010-03-26 04:53:08 +00001180 if (isFriend) {
John McCall68263142009-11-18 22:49:29 +00001181 NamedDecl *PrevDecl;
John McCall76d32642010-04-24 01:30:58 +00001182 if (TemplateParams)
Douglas Gregora735b202009-10-13 14:39:41 +00001183 PrevDecl = FunctionTemplate->getPreviousDeclaration();
John McCall76d32642010-04-24 01:30:58 +00001184 else
Douglas Gregora735b202009-10-13 14:39:41 +00001185 PrevDecl = Function->getPreviousDeclaration();
John McCall76d32642010-04-24 01:30:58 +00001186
1187 PrincipalDecl->setObjectOfFriendDecl(PrevDecl != 0);
1188 DC->makeDeclVisibleInContext(PrincipalDecl, /*Recoverable=*/ false);
Gabor Greifab297ac2010-08-30 21:10:05 +00001189
Gabor Greif77535df2010-08-30 22:25:56 +00001190 bool queuedInstantiation = false;
Gabor Greifab297ac2010-08-30 21:10:05 +00001191
Douglas Gregor238058c2010-05-18 05:45:02 +00001192 if (!SemaRef.getLangOptions().CPlusPlus0x &&
1193 D->isThisDeclarationADefinition()) {
1194 // Check for a function body.
1195 const FunctionDecl *Definition = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001196 if (Function->hasBody(Definition) &&
Douglas Gregor238058c2010-05-18 05:45:02 +00001197 Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
1198 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1199 << Function->getDeclName();
1200 SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
1201 Function->setInvalidDecl();
1202 }
1203 // Check for redefinitions due to other instantiations of this or
1204 // a similar friend function.
1205 else for (FunctionDecl::redecl_iterator R = Function->redecls_begin(),
1206 REnd = Function->redecls_end();
1207 R != REnd; ++R) {
Gabor Greif13a8aff2010-08-28 15:42:30 +00001208 if (*R == Function)
1209 continue;
Gabor Greifab297ac2010-08-30 21:10:05 +00001210 switch (R->getFriendObjectKind()) {
1211 case Decl::FOK_None:
1212 if (!queuedInstantiation && R->isUsed(false)) {
1213 if (MemberSpecializationInfo *MSInfo
1214 = Function->getMemberSpecializationInfo()) {
1215 if (MSInfo->getPointOfInstantiation().isInvalid()) {
1216 SourceLocation Loc = R->getLocation(); // FIXME
1217 MSInfo->setPointOfInstantiation(Loc);
1218 SemaRef.PendingLocalImplicitInstantiations.push_back(
1219 std::make_pair(Function, Loc));
1220 queuedInstantiation = true;
1221 }
1222 }
1223 }
1224 break;
1225 default:
Douglas Gregor238058c2010-05-18 05:45:02 +00001226 if (const FunctionDecl *RPattern
Gabor Greif6a557d82010-08-28 15:46:56 +00001227 = R->getTemplateInstantiationPattern())
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001228 if (RPattern->hasBody(RPattern)) {
Douglas Gregor238058c2010-05-18 05:45:02 +00001229 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1230 << Function->getDeclName();
Gabor Greif6a557d82010-08-28 15:46:56 +00001231 SemaRef.Diag(R->getLocation(), diag::note_previous_definition);
Douglas Gregor238058c2010-05-18 05:45:02 +00001232 Function->setInvalidDecl();
1233 break;
1234 }
1235 }
1236 }
1237 }
Douglas Gregora735b202009-10-13 14:39:41 +00001238 }
1239
John McCall76d32642010-04-24 01:30:58 +00001240 if (Function->isOverloadedOperator() && !DC->isRecord() &&
1241 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1242 PrincipalDecl->setNonMemberOperator();
1243
Douglas Gregore53060f2009-06-25 22:08:12 +00001244 return Function;
1245}
1246
Douglas Gregord60e1052009-08-27 16:57:43 +00001247Decl *
1248TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
1249 TemplateParameterList *TemplateParams) {
Douglas Gregor6b906862009-08-21 00:16:32 +00001250 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1251 void *InsertPos = 0;
Douglas Gregord60e1052009-08-27 16:57:43 +00001252 if (FunctionTemplate && !TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +00001253 // We are creating a function template specialization from a function
1254 // template. Check whether there is already a function template
Douglas Gregord60e1052009-08-27 16:57:43 +00001255 // specialization for this particular set of template arguments.
Douglas Gregor24bae922010-07-08 18:37:38 +00001256 std::pair<const TemplateArgument *, unsigned> Innermost
1257 = TemplateArgs.getInnermost();
Mike Stump1eb44332009-09-09 15:08:12 +00001258
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001259 FunctionDecl *SpecFunc
1260 = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
1261 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001262
Douglas Gregor6b906862009-08-21 00:16:32 +00001263 // If we already have a function template specialization, return it.
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001264 if (SpecFunc)
1265 return SpecFunc;
Douglas Gregor6b906862009-08-21 00:16:32 +00001266 }
1267
John McCallb0cb0222010-03-27 05:57:59 +00001268 bool isFriend;
1269 if (FunctionTemplate)
1270 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1271 else
1272 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1273
Douglas Gregor79c22782010-01-16 20:21:20 +00001274 bool MergeWithParentScope = (TemplateParams != 0) ||
1275 !(isa<Decl>(Owner) &&
1276 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall2a7fb272010-08-25 05:32:35 +00001277 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Douglas Gregor48dd19b2009-05-14 21:44:34 +00001278
John McCall4eab39f2010-10-19 02:26:41 +00001279 // Instantiate enclosing template arguments for friends.
1280 llvm::SmallVector<TemplateParameterList *, 4> TempParamLists;
1281 unsigned NumTempParamLists = 0;
1282 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
1283 TempParamLists.set_size(NumTempParamLists);
1284 for (unsigned I = 0; I != NumTempParamLists; ++I) {
1285 TemplateParameterList *TempParams = D->getTemplateParameterList(I);
1286 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1287 if (!InstParams)
1288 return NULL;
1289 TempParamLists[I] = InstParams;
1290 }
1291 }
1292
Douglas Gregor0ca20ac2009-05-29 18:27:38 +00001293 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall21ef0fa2010-03-11 09:03:00 +00001294 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
1295 TInfo = SubstFunctionType(D, Params);
1296 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001297 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +00001298 QualType T = TInfo->getType();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001299
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001300 // \brief If the type of this function is not *directly* a function
1301 // type, then we're instantiating the a function that was declared
1302 // via a typedef, e.g.,
1303 //
1304 // typedef int functype(int, int);
1305 // functype func;
1306 //
1307 // In this case, we'll just go instantiate the ParmVarDecls that we
1308 // synthesized in the method declaration.
1309 if (!isa<FunctionProtoType>(T)) {
1310 assert(!Params.size() && "Instantiating type could not yield parameters");
1311 for (unsigned I = 0, N = D->getNumParams(); I != N; ++I) {
1312 ParmVarDecl *P = SemaRef.SubstParmVarDecl(D->getParamDecl(I),
1313 TemplateArgs);
1314 if (!P)
1315 return 0;
1316
1317 Params.push_back(P);
1318 }
1319 }
1320
John McCallb0cb0222010-03-27 05:57:59 +00001321 NestedNameSpecifier *Qualifier = D->getQualifier();
1322 if (Qualifier) {
1323 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
1324 D->getQualifierRange(),
1325 TemplateArgs);
1326 if (!Qualifier) return 0;
1327 }
1328
1329 DeclContext *DC = Owner;
1330 if (isFriend) {
1331 if (Qualifier) {
1332 CXXScopeSpec SS;
1333 SS.setScopeRep(Qualifier);
1334 SS.setRange(D->getQualifierRange());
1335 DC = SemaRef.computeDeclContext(SS);
1336 } else {
1337 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1338 D->getDeclContext(),
1339 TemplateArgs);
1340 }
1341 if (!DC) return 0;
1342 }
1343
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001344 // Build the instantiated method declaration.
John McCallb0cb0222010-03-27 05:57:59 +00001345 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
Douglas Gregordec06662009-08-21 18:42:58 +00001346 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001347
Abramo Bagnara25777432010-08-11 22:01:17 +00001348 DeclarationNameInfo NameInfo
1349 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
Douglas Gregor17e32f32009-08-21 22:43:28 +00001350 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001351 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnara25777432010-08-11 22:01:17 +00001352 NameInfo, T, TInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00001353 Constructor->isExplicit(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001354 Constructor->isInlineSpecified(),
1355 false);
Douglas Gregor17e32f32009-08-21 22:43:28 +00001356 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001357 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnara25777432010-08-11 22:01:17 +00001358 NameInfo, T,
1359 Destructor->isInlineSpecified(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001360 false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001361 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001362 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
Abramo Bagnara25777432010-08-11 22:01:17 +00001363 NameInfo, T, TInfo,
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001364 Conversion->isInlineSpecified(),
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001365 Conversion->isExplicit());
Douglas Gregordec06662009-08-21 18:42:58 +00001366 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00001367 Method = CXXMethodDecl::Create(SemaRef.Context, Record,
1368 NameInfo, T, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001369 D->isStatic(),
1370 D->getStorageClassAsWritten(),
1371 D->isInlineSpecified());
Douglas Gregordec06662009-08-21 18:42:58 +00001372 }
Douglas Gregor6b906862009-08-21 00:16:32 +00001373
John McCallb0cb0222010-03-27 05:57:59 +00001374 if (Qualifier)
1375 Method->setQualifierInfo(Qualifier, D->getQualifierRange());
John McCallb6217662010-03-15 10:12:16 +00001376
Douglas Gregord60e1052009-08-27 16:57:43 +00001377 if (TemplateParams) {
1378 // Our resulting instantiation is actually a function template, since we
1379 // are substituting only the outer template parameters. For example, given
Mike Stump1eb44332009-09-09 15:08:12 +00001380 //
Douglas Gregord60e1052009-08-27 16:57:43 +00001381 // template<typename T>
1382 // struct X {
1383 // template<typename U> void f(T, U);
1384 // };
1385 //
1386 // X<int> x;
1387 //
1388 // We are instantiating the member template "f" within X<int>, which means
1389 // substituting int for T, but leaving "f" as a member function template.
1390 // Build the function template itself.
1391 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1392 Method->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001393 Method->getDeclName(),
Douglas Gregord60e1052009-08-27 16:57:43 +00001394 TemplateParams, Method);
John McCallb0cb0222010-03-27 05:57:59 +00001395 if (isFriend) {
1396 FunctionTemplate->setLexicalDeclContext(Owner);
1397 FunctionTemplate->setObjectOfFriendDecl(true);
1398 } else if (D->isOutOfLine())
Mike Stump1eb44332009-09-09 15:08:12 +00001399 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregord60e1052009-08-27 16:57:43 +00001400 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001401 } else if (FunctionTemplate) {
1402 // Record this function template specialization.
Douglas Gregor24bae922010-07-08 18:37:38 +00001403 std::pair<const TemplateArgument *, unsigned> Innermost
1404 = TemplateArgs.getInnermost();
Douglas Gregor838db382010-02-11 01:19:42 +00001405 Method->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor24bae922010-07-08 18:37:38 +00001406 new (SemaRef.Context) TemplateArgumentList(SemaRef.Context,
1407 Innermost.first,
1408 Innermost.second),
Douglas Gregor66724ea2009-11-14 01:20:54 +00001409 InsertPos);
John McCallb0cb0222010-03-27 05:57:59 +00001410 } else if (!isFriend) {
Douglas Gregor66724ea2009-11-14 01:20:54 +00001411 // Record that this is an instantiation of a member function.
Douglas Gregor2db32322009-10-07 23:56:10 +00001412 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001413 }
1414
Mike Stump1eb44332009-09-09 15:08:12 +00001415 // If we are instantiating a member function defined
Douglas Gregor7caa6822009-07-24 20:34:43 +00001416 // out-of-line, the instantiation will have the same lexical
1417 // context (which will be a namespace scope) as the template.
John McCallb0cb0222010-03-27 05:57:59 +00001418 if (isFriend) {
John McCall4eab39f2010-10-19 02:26:41 +00001419 if (NumTempParamLists)
1420 Method->setTemplateParameterListsInfo(SemaRef.Context,
1421 NumTempParamLists,
1422 TempParamLists.data());
1423
John McCallb0cb0222010-03-27 05:57:59 +00001424 Method->setLexicalDeclContext(Owner);
1425 Method->setObjectOfFriendDecl(true);
1426 } else if (D->isOutOfLine())
Douglas Gregor7caa6822009-07-24 20:34:43 +00001427 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00001428
Douglas Gregor5545e162009-03-24 00:38:23 +00001429 // Attach the parameters
1430 for (unsigned P = 0; P < Params.size(); ++P)
1431 Params[P]->setOwningFunction(Method);
Douglas Gregor838db382010-02-11 01:19:42 +00001432 Method->setParams(Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +00001433
1434 if (InitMethodInstantiation(Method, D))
1435 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001436
Abramo Bagnara25777432010-08-11 22:01:17 +00001437 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
1438 Sema::ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00001439
John McCallb0cb0222010-03-27 05:57:59 +00001440 if (!FunctionTemplate || TemplateParams || isFriend) {
1441 SemaRef.LookupQualifiedName(Previous, Record);
Mike Stump1eb44332009-09-09 15:08:12 +00001442
Douglas Gregordec06662009-08-21 18:42:58 +00001443 // In C++, the previous declaration we find might be a tag type
1444 // (class or enum). In this case, the new declaration will hide the
1445 // tag type. Note that this does does not apply if we're declaring a
1446 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001447 if (Previous.isSingleTagDecl())
1448 Previous.clear();
Douglas Gregordec06662009-08-21 18:42:58 +00001449 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001450
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001451 bool Redeclaration = false;
1452 bool OverloadableAttrRequired = false;
John McCall9f54ad42009-12-10 09:41:52 +00001453 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false, Redeclaration,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001454 /*FIXME:*/OverloadableAttrRequired);
1455
Douglas Gregor4ba31362009-12-01 17:24:26 +00001456 if (D->isPure())
1457 SemaRef.CheckPureMethod(Method, SourceRange());
1458
John McCall46460a62010-01-20 21:53:11 +00001459 Method->setAccess(D->getAccess());
1460
John McCallb0cb0222010-03-27 05:57:59 +00001461 if (FunctionTemplate) {
1462 // If there's a function template, let our caller handle it.
1463 } else if (Method->isInvalidDecl() && !Previous.empty()) {
1464 // Don't hide a (potentially) valid declaration with an invalid one.
1465 } else {
1466 NamedDecl *DeclToAdd = (TemplateParams
1467 ? cast<NamedDecl>(FunctionTemplate)
1468 : Method);
1469 if (isFriend)
1470 Record->makeDeclVisibleInContext(DeclToAdd);
1471 else
1472 Owner->addDecl(DeclToAdd);
1473 }
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001474
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001475 return Method;
1476}
1477
Douglas Gregor615c5d42009-03-24 16:43:20 +00001478Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +00001479 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +00001480}
1481
Douglas Gregor03b2b072009-03-24 00:15:49 +00001482Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001483 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +00001484}
1485
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001486Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001487 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001488}
1489
Douglas Gregor6477b692009-03-25 15:04:13 +00001490ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001491 return SemaRef.SubstParmVarDecl(D, TemplateArgs);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001492}
1493
John McCalle29ba202009-08-20 01:44:21 +00001494Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1495 TemplateTypeParmDecl *D) {
1496 // TODO: don't always clone when decls are refcounted.
Douglas Gregorefed5c82010-06-16 15:23:05 +00001497 const Type* T = D->getTypeForDecl();
1498 assert(T->isTemplateTypeParmType());
1499 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001500
John McCalle29ba202009-08-20 01:44:21 +00001501 TemplateTypeParmDecl *Inst =
1502 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor71b87e42010-08-30 23:23:59 +00001503 TTPT->getDepth() - TemplateArgs.getNumLevels(),
1504 TTPT->getIndex(),TTPT->getName(),
John McCalle29ba202009-08-20 01:44:21 +00001505 D->wasDeclaredWithTypename(),
1506 D->isParameterPack());
1507
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001508 if (D->hasDefaultArgument())
1509 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
John McCalle29ba202009-08-20 01:44:21 +00001510
Douglas Gregor550d9b22009-10-31 17:21:17 +00001511 // Introduce this template parameter's instantiation into the instantiation
1512 // scope.
1513 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1514
John McCalle29ba202009-08-20 01:44:21 +00001515 return Inst;
1516}
1517
Douglas Gregor33642df2009-10-23 23:25:44 +00001518Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1519 NonTypeTemplateParmDecl *D) {
1520 // Substitute into the type of the non-type template parameter.
1521 QualType T;
John McCalla93c9342009-12-07 02:54:59 +00001522 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor33642df2009-10-23 23:25:44 +00001523 if (DI) {
1524 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
1525 D->getDeclName());
1526 if (DI) T = DI->getType();
1527 } else {
1528 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
1529 D->getDeclName());
1530 DI = 0;
1531 }
1532 if (T.isNull())
1533 return 0;
1534
1535 // Check that this type is acceptable for a non-type template parameter.
1536 bool Invalid = false;
1537 T = SemaRef.CheckNonTypeTemplateParameterType(T, D->getLocation());
1538 if (T.isNull()) {
1539 T = SemaRef.Context.IntTy;
1540 Invalid = true;
1541 }
1542
1543 NonTypeTemplateParmDecl *Param
1544 = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor71b87e42010-08-30 23:23:59 +00001545 D->getDepth() - TemplateArgs.getNumLevels(),
1546 D->getPosition(), D->getIdentifier(), T,
1547 DI);
Douglas Gregor33642df2009-10-23 23:25:44 +00001548 if (Invalid)
1549 Param->setInvalidDecl();
1550
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001551 Param->setDefaultArgument(D->getDefaultArgument(), false);
Douglas Gregor550d9b22009-10-31 17:21:17 +00001552
1553 // Introduce this template parameter's instantiation into the instantiation
1554 // scope.
1555 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor33642df2009-10-23 23:25:44 +00001556 return Param;
1557}
1558
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001559Decl *
Douglas Gregor9106ef72009-11-11 16:58:32 +00001560TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1561 TemplateTemplateParmDecl *D) {
1562 // Instantiate the template parameter list of the template template parameter.
1563 TemplateParameterList *TempParams = D->getTemplateParameters();
1564 TemplateParameterList *InstParams;
1565 {
1566 // Perform the actual substitution of template parameters within a new,
1567 // local instantiation scope.
John McCall2a7fb272010-08-25 05:32:35 +00001568 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor9106ef72009-11-11 16:58:32 +00001569 InstParams = SubstTemplateParams(TempParams);
1570 if (!InstParams)
1571 return NULL;
1572 }
1573
1574 // Build the template template parameter.
1575 TemplateTemplateParmDecl *Param
1576 = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor71b87e42010-08-30 23:23:59 +00001577 D->getDepth() - TemplateArgs.getNumLevels(),
1578 D->getPosition(), D->getIdentifier(),
1579 InstParams);
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001580 Param->setDefaultArgument(D->getDefaultArgument(), false);
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001581
Douglas Gregor9106ef72009-11-11 16:58:32 +00001582 // Introduce this template parameter's instantiation into the instantiation
1583 // scope.
1584 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1585
1586 return Param;
1587}
1588
Douglas Gregor48c32a72009-11-17 06:07:40 +00001589Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1590 // Using directives are never dependent, so they require no explicit
1591
1592 UsingDirectiveDecl *Inst
1593 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1594 D->getNamespaceKeyLocation(),
1595 D->getQualifierRange(), D->getQualifier(),
1596 D->getIdentLocation(),
1597 D->getNominatedNamespace(),
1598 D->getCommonAncestor());
1599 Owner->addDecl(Inst);
1600 return Inst;
1601}
1602
John McCalled976492009-12-04 22:46:56 +00001603Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
Douglas Gregor1b398202010-09-29 17:58:28 +00001604
1605 // The nested name specifier may be dependent, for example
1606 // template <typename T> struct t {
1607 // struct s1 { T f1(); };
1608 // struct s2 : s1 { using s1::f1; };
1609 // };
1610 // template struct t<int>;
1611 // Here, in using s1::f1, s1 refers to t<T>::s1;
1612 // we need to substitute for t<int>::s1.
1613 NestedNameSpecifier *NNS =
1614 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameDecl(),
1615 D->getNestedNameRange(),
1616 TemplateArgs);
1617 if (!NNS)
1618 return 0;
1619
1620 // The name info is non-dependent, so no transformation
1621 // is required.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001622 DeclarationNameInfo NameInfo = D->getNameInfo();
John McCalled976492009-12-04 22:46:56 +00001623
John McCall9f54ad42009-12-10 09:41:52 +00001624 // We only need to do redeclaration lookups if we're in a class
1625 // scope (in fact, it's not really even possible in non-class
1626 // scopes).
1627 bool CheckRedeclaration = Owner->isRecord();
1628
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001629 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
1630 Sema::ForRedeclaration);
John McCall9f54ad42009-12-10 09:41:52 +00001631
John McCalled976492009-12-04 22:46:56 +00001632 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
John McCalled976492009-12-04 22:46:56 +00001633 D->getNestedNameRange(),
1634 D->getUsingLocation(),
Douglas Gregor1b398202010-09-29 17:58:28 +00001635 NNS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001636 NameInfo,
John McCalled976492009-12-04 22:46:56 +00001637 D->isTypeName());
1638
1639 CXXScopeSpec SS;
Douglas Gregor1b398202010-09-29 17:58:28 +00001640 SS.setScopeRep(NNS);
John McCalled976492009-12-04 22:46:56 +00001641 SS.setRange(D->getNestedNameRange());
John McCall9f54ad42009-12-10 09:41:52 +00001642
1643 if (CheckRedeclaration) {
1644 Prev.setHideTags(false);
1645 SemaRef.LookupQualifiedName(Prev, Owner);
1646
1647 // Check for invalid redeclarations.
1648 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
1649 D->isTypeName(), SS,
1650 D->getLocation(), Prev))
1651 NewUD->setInvalidDecl();
1652
1653 }
1654
1655 if (!NewUD->isInvalidDecl() &&
1656 SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
John McCalled976492009-12-04 22:46:56 +00001657 D->getLocation()))
1658 NewUD->setInvalidDecl();
John McCall9f54ad42009-12-10 09:41:52 +00001659
John McCalled976492009-12-04 22:46:56 +00001660 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
1661 NewUD->setAccess(D->getAccess());
1662 Owner->addDecl(NewUD);
1663
John McCall9f54ad42009-12-10 09:41:52 +00001664 // Don't process the shadow decls for an invalid decl.
1665 if (NewUD->isInvalidDecl())
1666 return NewUD;
1667
John McCall323c3102009-12-22 22:26:37 +00001668 bool isFunctionScope = Owner->isFunctionOrMethod();
1669
John McCall9f54ad42009-12-10 09:41:52 +00001670 // Process the shadow decls.
1671 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
1672 I != E; ++I) {
1673 UsingShadowDecl *Shadow = *I;
1674 NamedDecl *InstTarget =
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001675 cast<NamedDecl>(SemaRef.FindInstantiatedDecl(Shadow->getLocation(),
1676 Shadow->getTargetDecl(),
John McCall9f54ad42009-12-10 09:41:52 +00001677 TemplateArgs));
1678
1679 if (CheckRedeclaration &&
1680 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
1681 continue;
1682
1683 UsingShadowDecl *InstShadow
1684 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
1685 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCall323c3102009-12-22 22:26:37 +00001686
1687 if (isFunctionScope)
1688 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall9f54ad42009-12-10 09:41:52 +00001689 }
John McCalled976492009-12-04 22:46:56 +00001690
1691 return NewUD;
1692}
1693
1694Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall9f54ad42009-12-10 09:41:52 +00001695 // Ignore these; we handle them in bulk when processing the UsingDecl.
1696 return 0;
John McCalled976492009-12-04 22:46:56 +00001697}
1698
John McCall7ba107a2009-11-18 02:36:19 +00001699Decl * TemplateDeclInstantiator
1700 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +00001701 NestedNameSpecifier *NNS =
1702 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1703 D->getTargetNestedNameRange(),
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001704 TemplateArgs);
1705 if (!NNS)
1706 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001707
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001708 CXXScopeSpec SS;
1709 SS.setRange(D->getTargetNestedNameRange());
1710 SS.setScopeRep(NNS);
Mike Stump1eb44332009-09-09 15:08:12 +00001711
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001712 // Since NameInfo refers to a typename, it cannot be a C++ special name.
1713 // Hence, no tranformation is required for it.
1714 DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001715 NamedDecl *UD =
John McCall9488ea12009-11-17 05:59:44 +00001716 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001717 D->getUsingLoc(), SS, NameInfo, 0,
John McCall7ba107a2009-11-18 02:36:19 +00001718 /*instantiation*/ true,
1719 /*typename*/ true, D->getTypenameLoc());
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001720 if (UD)
John McCalled976492009-12-04 22:46:56 +00001721 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1722
John McCall7ba107a2009-11-18 02:36:19 +00001723 return UD;
1724}
1725
1726Decl * TemplateDeclInstantiator
1727 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1728 NestedNameSpecifier *NNS =
1729 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1730 D->getTargetNestedNameRange(),
1731 TemplateArgs);
1732 if (!NNS)
1733 return 0;
1734
1735 CXXScopeSpec SS;
1736 SS.setRange(D->getTargetNestedNameRange());
1737 SS.setScopeRep(NNS);
1738
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001739 DeclarationNameInfo NameInfo
1740 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
1741
John McCall7ba107a2009-11-18 02:36:19 +00001742 NamedDecl *UD =
1743 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001744 D->getUsingLoc(), SS, NameInfo, 0,
John McCall7ba107a2009-11-18 02:36:19 +00001745 /*instantiation*/ true,
1746 /*typename*/ false, SourceLocation());
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001747 if (UD)
John McCalled976492009-12-04 22:46:56 +00001748 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1749
Anders Carlsson0d8df782009-08-29 19:37:28 +00001750 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001751}
1752
John McCallce3ff2b2009-08-25 22:02:44 +00001753Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001754 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +00001755 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor2fa98002010-02-16 19:28:15 +00001756 if (D->isInvalidDecl())
1757 return 0;
1758
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001759 return Instantiator.Visit(D);
1760}
1761
John McCalle29ba202009-08-20 01:44:21 +00001762/// \brief Instantiates a nested template parameter list in the current
1763/// instantiation context.
1764///
1765/// \param L The parameter list to instantiate
1766///
1767/// \returns NULL if there was an error
1768TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +00001769TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +00001770 // Get errors for all the parameters before bailing out.
1771 bool Invalid = false;
1772
1773 unsigned N = L->size();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001774 typedef llvm::SmallVector<NamedDecl *, 8> ParamVector;
John McCalle29ba202009-08-20 01:44:21 +00001775 ParamVector Params;
1776 Params.reserve(N);
1777 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
1778 PI != PE; ++PI) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001779 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCalle29ba202009-08-20 01:44:21 +00001780 Params.push_back(D);
Douglas Gregor9148c3f2009-11-11 19:13:48 +00001781 Invalid = Invalid || !D || D->isInvalidDecl();
John McCalle29ba202009-08-20 01:44:21 +00001782 }
1783
1784 // Clean up if we had an error.
Douglas Gregorff331c12010-07-25 18:17:45 +00001785 if (Invalid)
John McCalle29ba202009-08-20 01:44:21 +00001786 return NULL;
John McCalle29ba202009-08-20 01:44:21 +00001787
1788 TemplateParameterList *InstL
1789 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
1790 L->getLAngleLoc(), &Params.front(), N,
1791 L->getRAngleLoc());
1792 return InstL;
Mike Stump1eb44332009-09-09 15:08:12 +00001793}
John McCalle29ba202009-08-20 01:44:21 +00001794
Douglas Gregored9c0f92009-10-29 00:04:11 +00001795/// \brief Instantiate the declaration of a class template partial
1796/// specialization.
1797///
1798/// \param ClassTemplate the (instantiated) class template that is partially
1799// specialized by the instantiation of \p PartialSpec.
1800///
1801/// \param PartialSpec the (uninstantiated) class template partial
1802/// specialization that we are instantiating.
1803///
1804/// \returns true if there was an error, false otherwise.
1805bool
1806TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
1807 ClassTemplateDecl *ClassTemplate,
1808 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00001809 // Create a local instantiation scope for this class template partial
1810 // specialization, which will contain the instantiations of the template
1811 // parameters.
John McCall2a7fb272010-08-25 05:32:35 +00001812 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor550d9b22009-10-31 17:21:17 +00001813
Douglas Gregored9c0f92009-10-29 00:04:11 +00001814 // Substitute into the template parameters of the class template partial
1815 // specialization.
1816 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
1817 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1818 if (!InstParams)
1819 return true;
1820
1821 // Substitute into the template arguments of the class template partial
1822 // specialization.
John McCall833ca992009-10-29 08:12:44 +00001823 const TemplateArgumentLoc *PartialSpecTemplateArgs
1824 = PartialSpec->getTemplateArgsAsWritten();
1825 unsigned N = PartialSpec->getNumTemplateArgsAsWritten();
1826
John McCalld5532b62009-11-23 01:53:49 +00001827 TemplateArgumentListInfo InstTemplateArgs; // no angle locations
John McCall833ca992009-10-29 08:12:44 +00001828 for (unsigned I = 0; I != N; ++I) {
John McCalld5532b62009-11-23 01:53:49 +00001829 TemplateArgumentLoc Loc;
1830 if (SemaRef.Subst(PartialSpecTemplateArgs[I], Loc, TemplateArgs))
Douglas Gregored9c0f92009-10-29 00:04:11 +00001831 return true;
John McCalld5532b62009-11-23 01:53:49 +00001832 InstTemplateArgs.addArgument(Loc);
Douglas Gregored9c0f92009-10-29 00:04:11 +00001833 }
1834
1835
1836 // Check that the template argument list is well-formed for this
1837 // class template.
1838 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
1839 InstTemplateArgs.size());
1840 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
1841 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001842 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001843 false,
1844 Converted))
1845 return true;
1846
1847 // Figure out where to insert this class template partial specialization
1848 // in the member template's set of class template partial specializations.
Douglas Gregored9c0f92009-10-29 00:04:11 +00001849 void *InsertPos = 0;
1850 ClassTemplateSpecializationDecl *PrevDecl
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00001851 = ClassTemplate->findPartialSpecialization(Converted.getFlatArguments(),
1852 Converted.flatSize(), InsertPos);
Douglas Gregored9c0f92009-10-29 00:04:11 +00001853
1854 // Build the canonical type that describes the converted template
1855 // arguments of the class template partial specialization.
1856 QualType CanonType
1857 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
1858 Converted.getFlatArguments(),
1859 Converted.flatSize());
1860
1861 // Build the fully-sugared type for this class template
1862 // specialization as the user wrote in the specialization
1863 // itself. This means that we'll pretty-print the type retrieved
1864 // from the specialization's declaration the way that the user
1865 // actually wrote the specialization, rather than formatting the
1866 // name based on the "canonical" representation used to store the
1867 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00001868 TypeSourceInfo *WrittenTy
1869 = SemaRef.Context.getTemplateSpecializationTypeInfo(
1870 TemplateName(ClassTemplate),
1871 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001872 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001873 CanonType);
1874
1875 if (PrevDecl) {
1876 // We've already seen a partial specialization with the same template
1877 // parameters and template arguments. This can happen, for example, when
1878 // substituting the outer template arguments ends up causing two
1879 // class template partial specializations of a member class template
1880 // to have identical forms, e.g.,
1881 //
1882 // template<typename T, typename U>
1883 // struct Outer {
1884 // template<typename X, typename Y> struct Inner;
1885 // template<typename Y> struct Inner<T, Y>;
1886 // template<typename Y> struct Inner<U, Y>;
1887 // };
1888 //
1889 // Outer<int, int> outer; // error: the partial specializations of Inner
1890 // // have the same signature.
1891 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
1892 << WrittenTy;
1893 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
1894 << SemaRef.Context.getTypeDeclType(PrevDecl);
1895 return true;
1896 }
1897
1898
1899 // Create the class template partial specialization declaration.
1900 ClassTemplatePartialSpecializationDecl *InstPartialSpec
Douglas Gregor13c85772010-05-06 00:28:52 +00001901 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
1902 PartialSpec->getTagKind(),
1903 Owner,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001904 PartialSpec->getLocation(),
1905 InstParams,
1906 ClassTemplate,
1907 Converted,
John McCalld5532b62009-11-23 01:53:49 +00001908 InstTemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00001909 CanonType,
Douglas Gregordc60c1e2010-04-30 05:56:50 +00001910 0,
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00001911 ClassTemplate->getNextPartialSpecSequenceNumber());
John McCallb6217662010-03-15 10:12:16 +00001912 // Substitute the nested name specifier, if any.
1913 if (SubstQualifier(PartialSpec, InstPartialSpec))
1914 return 0;
1915
Douglas Gregored9c0f92009-10-29 00:04:11 +00001916 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001917 InstPartialSpec->setTypeAsWritten(WrittenTy);
1918
Douglas Gregored9c0f92009-10-29 00:04:11 +00001919 // Add this partial specialization to the set of class template partial
1920 // specializations.
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00001921 ClassTemplate->AddPartialSpecialization(InstPartialSpec, InsertPos);
Douglas Gregored9c0f92009-10-29 00:04:11 +00001922 return false;
1923}
1924
John McCall21ef0fa2010-03-11 09:03:00 +00001925TypeSourceInfo*
John McCallce3ff2b2009-08-25 22:02:44 +00001926TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +00001927 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
John McCall21ef0fa2010-03-11 09:03:00 +00001928 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
1929 assert(OldTInfo && "substituting function without type source info");
1930 assert(Params.empty() && "parameter vector is non-empty at start");
John McCall6cd3b9f2010-04-09 17:38:44 +00001931 TypeSourceInfo *NewTInfo
1932 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
1933 D->getTypeSpecStartLoc(),
1934 D->getDeclName());
John McCall21ef0fa2010-03-11 09:03:00 +00001935 if (!NewTInfo)
1936 return 0;
Douglas Gregor5545e162009-03-24 00:38:23 +00001937
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001938 if (NewTInfo != OldTInfo) {
1939 // Get parameters from the new type info.
Douglas Gregor895162d2010-04-30 18:55:50 +00001940 TypeLoc OldTL = OldTInfo->getTypeLoc();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00001941 if (FunctionProtoTypeLoc *OldProtoLoc
1942 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
1943 TypeLoc NewTL = NewTInfo->getTypeLoc();
1944 FunctionProtoTypeLoc *NewProtoLoc = cast<FunctionProtoTypeLoc>(&NewTL);
1945 assert(NewProtoLoc && "Missing prototype?");
1946 for (unsigned i = 0, i_end = NewProtoLoc->getNumArgs(); i != i_end; ++i) {
1947 // FIXME: Variadic templates will break this.
1948 Params.push_back(NewProtoLoc->getArg(i));
1949 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
Douglas Gregor895162d2010-04-30 18:55:50 +00001950 OldProtoLoc->getArg(i),
1951 NewProtoLoc->getArg(i));
Douglas Gregor6920cdc2010-05-03 15:32:18 +00001952 }
Douglas Gregor895162d2010-04-30 18:55:50 +00001953 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001954 } else {
1955 // The function type itself was not dependent and therefore no
1956 // substitution occurred. However, we still need to instantiate
1957 // the function parameters themselves.
1958 TypeLoc OldTL = OldTInfo->getTypeLoc();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00001959 if (FunctionProtoTypeLoc *OldProtoLoc
1960 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
1961 for (unsigned i = 0, i_end = OldProtoLoc->getNumArgs(); i != i_end; ++i) {
1962 ParmVarDecl *Parm = VisitParmVarDecl(OldProtoLoc->getArg(i));
1963 if (!Parm)
1964 return 0;
1965 Params.push_back(Parm);
1966 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001967 }
1968 }
John McCall21ef0fa2010-03-11 09:03:00 +00001969 return NewTInfo;
Douglas Gregor5545e162009-03-24 00:38:23 +00001970}
1971
Mike Stump1eb44332009-09-09 15:08:12 +00001972/// \brief Initializes the common fields of an instantiation function
Douglas Gregore53060f2009-06-25 22:08:12 +00001973/// declaration (New) from the corresponding fields of its template (Tmpl).
1974///
1975/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001976bool
1977TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregore53060f2009-06-25 22:08:12 +00001978 FunctionDecl *Tmpl) {
1979 if (Tmpl->isDeleted())
1980 New->setDeleted();
Mike Stump1eb44332009-09-09 15:08:12 +00001981
Douglas Gregorcca9e962009-07-01 22:01:06 +00001982 // If we are performing substituting explicitly-specified template arguments
1983 // or deduced template arguments into a function template and we reach this
1984 // point, we are now past the point where SFINAE applies and have committed
Mike Stump1eb44332009-09-09 15:08:12 +00001985 // to keeping the new function template specialization. We therefore
1986 // convert the active template instantiation for the function template
Douglas Gregorcca9e962009-07-01 22:01:06 +00001987 // into a template instantiation for this specific function template
1988 // specialization, which is not a SFINAE context, so that we diagnose any
1989 // further errors in the declaration itself.
1990 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
1991 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
1992 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
1993 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump1eb44332009-09-09 15:08:12 +00001994 if (FunctionTemplateDecl *FunTmpl
Douglas Gregorcca9e962009-07-01 22:01:06 +00001995 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001996 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorcca9e962009-07-01 22:01:06 +00001997 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +00001998 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001999 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
2000 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
Douglas Gregorf35f8282009-11-11 21:54:23 +00002001 --SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +00002002 }
2003 }
Mike Stump1eb44332009-09-09 15:08:12 +00002004
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002005 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
2006 assert(Proto && "Function template without prototype?");
2007
2008 if (Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec() ||
2009 Proto->getNoReturnAttr()) {
2010 // The function has an exception specification or a "noreturn"
2011 // attribute. Substitute into each of the exception types.
2012 llvm::SmallVector<QualType, 4> Exceptions;
2013 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
2014 // FIXME: Poor location information!
2015 QualType T
2016 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
2017 New->getLocation(), New->getDeclName());
2018 if (T.isNull() ||
2019 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
2020 continue;
2021
2022 Exceptions.push_back(T);
2023 }
2024
2025 // Rebuild the function type
2026
2027 const FunctionProtoType *NewProto
2028 = New->getType()->getAs<FunctionProtoType>();
2029 assert(NewProto && "Template instantiation without function prototype?");
2030 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
2031 NewProto->arg_type_begin(),
2032 NewProto->getNumArgs(),
2033 NewProto->isVariadic(),
2034 NewProto->getTypeQuals(),
2035 Proto->hasExceptionSpec(),
2036 Proto->hasAnyExceptionSpec(),
2037 Exceptions.size(),
2038 Exceptions.data(),
Rafael Espindola264ba482010-03-30 20:24:48 +00002039 Proto->getExtInfo()));
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002040 }
2041
John McCall1d8d1cc2010-08-01 02:01:53 +00002042 SemaRef.InstantiateAttrs(TemplateArgs, Tmpl, New);
Douglas Gregor7cf84d62010-06-15 17:05:35 +00002043
Douglas Gregore53060f2009-06-25 22:08:12 +00002044 return false;
2045}
2046
Douglas Gregor5545e162009-03-24 00:38:23 +00002047/// \brief Initializes common fields of an instantiated method
2048/// declaration (New) from the corresponding fields of its template
2049/// (Tmpl).
2050///
2051/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00002052bool
2053TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor5545e162009-03-24 00:38:23 +00002054 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +00002055 if (InitFunctionInstantiation(New, Tmpl))
2056 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002057
Douglas Gregor5545e162009-03-24 00:38:23 +00002058 New->setAccess(Tmpl->getAccess());
Fariborz Jahaniane7184df2009-12-03 18:44:40 +00002059 if (Tmpl->isVirtualAsWritten())
Douglas Gregor85606eb2010-09-28 20:50:54 +00002060 New->setVirtualAsWritten(true);
Douglas Gregor5545e162009-03-24 00:38:23 +00002061
2062 // FIXME: attributes
2063 // FIXME: New needs a pointer to Tmpl
2064 return false;
2065}
Douglas Gregora58861f2009-05-13 20:28:22 +00002066
2067/// \brief Instantiate the definition of the given function from its
2068/// template.
2069///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002070/// \param PointOfInstantiation the point at which the instantiation was
2071/// required. Note that this is not precisely a "point of instantiation"
2072/// for the function, but it's close.
2073///
Douglas Gregora58861f2009-05-13 20:28:22 +00002074/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002075/// function template specialization or member function of a class template
2076/// specialization.
2077///
2078/// \param Recursive if true, recursively instantiates any functions that
2079/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002080///
2081/// \param DefinitionRequired if true, then we are performing an explicit
2082/// instantiation where the body of the function is required. Complain if
2083/// there is no such body.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002084void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002085 FunctionDecl *Function,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002086 bool Recursive,
2087 bool DefinitionRequired) {
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00002088 if (Function->isInvalidDecl() || Function->hasBody())
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002089 return;
2090
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002091 // Never instantiate an explicit specialization.
2092 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
2093 return;
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00002094
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002095 // Find the function body that we'll be substituting.
Douglas Gregor3b846b62009-10-27 20:53:28 +00002096 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002097 Stmt *Pattern = 0;
2098 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002099 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002100
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002101 if (!Pattern) {
2102 if (DefinitionRequired) {
2103 if (Function->getPrimaryTemplate())
2104 Diag(PointOfInstantiation,
2105 diag::err_explicit_instantiation_undefined_func_template)
2106 << Function->getPrimaryTemplate();
2107 else
2108 Diag(PointOfInstantiation,
2109 diag::err_explicit_instantiation_undefined_member)
2110 << 1 << Function->getDeclName() << Function->getDeclContext();
2111
2112 if (PatternDecl)
2113 Diag(PatternDecl->getLocation(),
2114 diag::note_explicit_instantiation_here);
Douglas Gregorcfe833b2010-05-17 17:57:54 +00002115 Function->setInvalidDecl();
Chandler Carruth58e390e2010-08-25 08:27:02 +00002116 } else if (Function->getTemplateSpecializationKind()
2117 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00002118 PendingInstantiations.push_back(
Chandler Carruth58e390e2010-08-25 08:27:02 +00002119 std::make_pair(Function, PointOfInstantiation));
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002120 }
Chandler Carruth58e390e2010-08-25 08:27:02 +00002121
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002122 return;
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002123 }
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002124
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002125 // C++0x [temp.explicit]p9:
2126 // Except for inline functions, other explicit instantiation declarations
Mike Stump1eb44332009-09-09 15:08:12 +00002127 // have the effect of suppressing the implicit instantiation of the entity
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002128 // to which they refer.
Mike Stump1eb44332009-09-09 15:08:12 +00002129 if (Function->getTemplateSpecializationKind()
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002130 == TSK_ExplicitInstantiationDeclaration &&
Douglas Gregor7ced9c82009-10-27 21:11:48 +00002131 !PatternDecl->isInlined())
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002132 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002133
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002134 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
2135 if (Inst)
Douglas Gregore7089b02010-05-03 23:29:10 +00002136 return;
2137
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002138 // If we're performing recursive template instantiation, create our own
2139 // queue of pending implicit instantiations that we will instantiate later,
2140 // while we're still within our own instantiation context.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002141 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002142 if (Recursive)
Chandler Carruth62c78d52010-08-25 08:44:16 +00002143 PendingInstantiations.swap(SavedPendingInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002144
Douglas Gregor9679caf2010-05-12 17:27:19 +00002145 EnterExpressionEvaluationContext EvalContext(*this,
John McCallf312b1e2010-08-26 23:41:50 +00002146 Sema::PotentiallyEvaluated);
John McCalld226f652010-08-21 09:40:31 +00002147 ActOnStartOfFunctionDef(0, Function);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002148
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002149 // Introduce a new scope where local variable instantiations will be
Douglas Gregor60406be2010-01-16 22:29:39 +00002150 // recorded, unless we're actually a member function within a local
2151 // class, in which case we need to merge our results with the parent
2152 // scope (of the enclosing function).
2153 bool MergeWithParentScope = false;
2154 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
2155 MergeWithParentScope = Rec->isLocalClass();
2156
2157 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +00002158
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002159 // Introduce the instantiated function parameters into the local
Peter Collingbourne8a6c0f12010-07-18 16:45:46 +00002160 // instantiation scope, and set the parameter names to those used
2161 // in the template.
2162 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
2163 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
2164 ParmVarDecl *FunctionParam = Function->getParamDecl(I);
2165 FunctionParam->setDeclName(PatternParam->getDeclName());
2166 Scope.InstantiatedLocal(PatternParam, FunctionParam);
2167 }
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002168
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002169 // Enter the scope of this instantiation. We don't use
2170 // PushDeclContext because we don't have a scope.
2171 DeclContext *PreviousContext = CurContext;
2172 CurContext = Function;
2173
Mike Stump1eb44332009-09-09 15:08:12 +00002174 MultiLevelTemplateArgumentList TemplateArgs =
Douglas Gregore7089b02010-05-03 23:29:10 +00002175 getTemplateInstantiationArgs(Function, 0, false, PatternDecl);
Anders Carlsson09025312009-08-29 05:16:22 +00002176
2177 // If this is a constructor, instantiate the member initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00002178 if (const CXXConstructorDecl *Ctor =
Anders Carlsson09025312009-08-29 05:16:22 +00002179 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
2180 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
2181 TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002182 }
2183
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002184 // Instantiate the function body.
John McCall60d7b3a2010-08-24 06:29:42 +00002185 StmtResult Body = SubstStmt(Pattern, TemplateArgs);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002186
Douglas Gregor52604ab2009-09-11 21:19:12 +00002187 if (Body.isInvalid())
2188 Function->setInvalidDecl();
2189
John McCall9ae2f072010-08-23 23:25:46 +00002190 ActOnFinishFunctionBody(Function, Body.get(),
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002191 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002192
John McCall0c01d182010-03-24 05:22:00 +00002193 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
2194
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002195 CurContext = PreviousContext;
Douglas Gregoraba43bb2009-05-26 20:50:29 +00002196
2197 DeclGroupRef DG(Function);
2198 Consumer.HandleTopLevelDecl(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00002199
Douglas Gregor60406be2010-01-16 22:29:39 +00002200 // This class may have local implicit instantiations that need to be
2201 // instantiation within this scope.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002202 PerformPendingInstantiations(/*LocalOnly=*/true);
Douglas Gregor60406be2010-01-16 22:29:39 +00002203 Scope.Exit();
2204
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002205 if (Recursive) {
2206 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002207 // instantiation of this template.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002208 PerformPendingInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002209
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002210 // Restore the set of pending implicit instantiations.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002211 PendingInstantiations.swap(SavedPendingInstantiations);
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002212 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002213}
2214
2215/// \brief Instantiate the definition of the given variable from its
2216/// template.
2217///
Douglas Gregor7caa6822009-07-24 20:34:43 +00002218/// \param PointOfInstantiation the point at which the instantiation was
2219/// required. Note that this is not precisely a "point of instantiation"
2220/// for the function, but it's close.
2221///
2222/// \param Var the already-instantiated declaration of a static member
2223/// variable of a class template specialization.
2224///
2225/// \param Recursive if true, recursively instantiates any functions that
2226/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002227///
2228/// \param DefinitionRequired if true, then we are performing an explicit
2229/// instantiation where an out-of-line definition of the member variable
2230/// is required. Complain if there is no such definition.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002231void Sema::InstantiateStaticDataMemberDefinition(
2232 SourceLocation PointOfInstantiation,
2233 VarDecl *Var,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002234 bool Recursive,
2235 bool DefinitionRequired) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002236 if (Var->isInvalidDecl())
2237 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002238
Douglas Gregor7caa6822009-07-24 20:34:43 +00002239 // Find the out-of-line definition of this static data member.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002240 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregor7caa6822009-07-24 20:34:43 +00002241 assert(Def && "This data member was not instantiated from a template?");
Douglas Gregor0d035142009-10-27 18:42:08 +00002242 assert(Def->isStaticDataMember() && "Not a static data member?");
2243 Def = Def->getOutOfLineDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00002244
Douglas Gregor0d035142009-10-27 18:42:08 +00002245 if (!Def) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002246 // We did not find an out-of-line definition of this static data member,
2247 // so we won't perform any instantiation. Rather, we rely on the user to
Mike Stump1eb44332009-09-09 15:08:12 +00002248 // instantiate this definition (or provide a specialization for it) in
2249 // another translation unit.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002250 if (DefinitionRequired) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002251 Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002252 Diag(PointOfInstantiation,
2253 diag::err_explicit_instantiation_undefined_member)
2254 << 2 << Var->getDeclName() << Var->getDeclContext();
2255 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
Chandler Carruth58e390e2010-08-25 08:27:02 +00002256 } else if (Var->getTemplateSpecializationKind()
2257 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00002258 PendingInstantiations.push_back(
Chandler Carruth58e390e2010-08-25 08:27:02 +00002259 std::make_pair(Var, PointOfInstantiation));
2260 }
2261
Douglas Gregor7caa6822009-07-24 20:34:43 +00002262 return;
2263 }
2264
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002265 // Never instantiate an explicit specialization.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002266 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002267 return;
2268
2269 // C++0x [temp.explicit]p9:
2270 // Except for inline functions, other explicit instantiation declarations
2271 // have the effect of suppressing the implicit instantiation of the entity
2272 // to which they refer.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002273 if (Var->getTemplateSpecializationKind()
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002274 == TSK_ExplicitInstantiationDeclaration)
2275 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002276
Douglas Gregor7caa6822009-07-24 20:34:43 +00002277 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
2278 if (Inst)
2279 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002280
Douglas Gregor7caa6822009-07-24 20:34:43 +00002281 // If we're performing recursive template instantiation, create our own
2282 // queue of pending implicit instantiations that we will instantiate later,
2283 // while we're still within our own instantiation context.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002284 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
Douglas Gregor7caa6822009-07-24 20:34:43 +00002285 if (Recursive)
Chandler Carruth62c78d52010-08-25 08:44:16 +00002286 PendingInstantiations.swap(SavedPendingInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002287
Douglas Gregor7caa6822009-07-24 20:34:43 +00002288 // Enter the scope of this instantiation. We don't use
2289 // PushDeclContext because we don't have a scope.
2290 DeclContext *PreviousContext = CurContext;
2291 CurContext = Var->getDeclContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002292
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002293 VarDecl *OldVar = Var;
John McCallce3ff2b2009-08-25 22:02:44 +00002294 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Douglas Gregor7caa6822009-07-24 20:34:43 +00002295 getTemplateInstantiationArgs(Var)));
Douglas Gregor7caa6822009-07-24 20:34:43 +00002296 CurContext = PreviousContext;
2297
2298 if (Var) {
Douglas Gregor583f33b2009-10-15 18:07:02 +00002299 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
2300 assert(MSInfo && "Missing member specialization information?");
2301 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
2302 MSInfo->getPointOfInstantiation());
Douglas Gregor7caa6822009-07-24 20:34:43 +00002303 DeclGroupRef DG(Var);
2304 Consumer.HandleTopLevelDecl(DG);
2305 }
Mike Stump1eb44332009-09-09 15:08:12 +00002306
Douglas Gregor7caa6822009-07-24 20:34:43 +00002307 if (Recursive) {
2308 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002309 // instantiation of this template.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002310 PerformPendingInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002311
Douglas Gregor7caa6822009-07-24 20:34:43 +00002312 // Restore the set of pending implicit instantiations.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002313 PendingInstantiations.swap(SavedPendingInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002314 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002315}
Douglas Gregor815215d2009-05-27 05:35:12 +00002316
Anders Carlsson09025312009-08-29 05:16:22 +00002317void
2318Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
2319 const CXXConstructorDecl *Tmpl,
2320 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00002321
Anders Carlsson09025312009-08-29 05:16:22 +00002322 llvm::SmallVector<MemInitTy*, 4> NewInits;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002323 bool AnyErrors = false;
2324
Anders Carlsson09025312009-08-29 05:16:22 +00002325 // Instantiate all the initializers.
2326 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00002327 InitsEnd = Tmpl->init_end();
2328 Inits != InitsEnd; ++Inits) {
Anders Carlsson09025312009-08-29 05:16:22 +00002329 CXXBaseOrMemberInitializer *Init = *Inits;
2330
Chandler Carruth030ef472010-09-03 21:54:20 +00002331 // Only instantiate written initializers, let Sema re-construct implicit
2332 // ones.
2333 if (!Init->isWritten())
2334 continue;
2335
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002336 SourceLocation LParenLoc, RParenLoc;
John McCallca0408f2010-08-23 06:44:23 +00002337 ASTOwningVector<Expr*> NewArgs(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00002338
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002339 // Instantiate the initializer.
2340 if (InstantiateInitializer(*this, Init->getInit(), TemplateArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00002341 LParenLoc, NewArgs, RParenLoc)) {
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002342 AnyErrors = true;
2343 continue;
Anders Carlsson09025312009-08-29 05:16:22 +00002344 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002345
Anders Carlsson09025312009-08-29 05:16:22 +00002346 MemInitResult NewInit;
Anders Carlsson09025312009-08-29 05:16:22 +00002347 if (Init->isBaseInitializer()) {
John McCalla93c9342009-12-07 02:54:59 +00002348 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002349 TemplateArgs,
2350 Init->getSourceLocation(),
2351 New->getDeclName());
John McCalla93c9342009-12-07 02:54:59 +00002352 if (!BaseTInfo) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002353 AnyErrors = true;
Douglas Gregor802ab452009-12-02 22:36:29 +00002354 New->setInvalidDecl();
2355 continue;
2356 }
2357
John McCalla93c9342009-12-07 02:54:59 +00002358 NewInit = BuildBaseInitializer(BaseTInfo->getType(), BaseTInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00002359 (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00002360 NewArgs.size(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002361 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00002362 Init->getRParenLoc(),
2363 New->getParent());
2364 } else if (Init->isMemberInitializer()) {
Anders Carlsson9988d5d2009-09-01 04:31:02 +00002365 FieldDecl *Member;
Mike Stump1eb44332009-09-09 15:08:12 +00002366
Anders Carlsson9988d5d2009-09-01 04:31:02 +00002367 // Is this an anonymous union?
2368 if (FieldDecl *UnionInit = Init->getAnonUnionMember())
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002369 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMemberLocation(),
2370 UnionInit, TemplateArgs));
Anders Carlsson9988d5d2009-09-01 04:31:02 +00002371 else
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002372 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMemberLocation(),
2373 Init->getMember(),
Douglas Gregore95b4092009-09-16 18:34:49 +00002374 TemplateArgs));
Mike Stump1eb44332009-09-09 15:08:12 +00002375
2376 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00002377 NewArgs.size(),
2378 Init->getSourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002379 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00002380 Init->getRParenLoc());
2381 }
2382
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002383 if (NewInit.isInvalid()) {
2384 AnyErrors = true;
Anders Carlsson09025312009-08-29 05:16:22 +00002385 New->setInvalidDecl();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002386 } else {
Anders Carlsson09025312009-08-29 05:16:22 +00002387 // FIXME: It would be nice if ASTOwningVector had a release function.
2388 NewArgs.take();
Mike Stump1eb44332009-09-09 15:08:12 +00002389
Anders Carlsson09025312009-08-29 05:16:22 +00002390 NewInits.push_back((MemInitTy *)NewInit.get());
2391 }
2392 }
Mike Stump1eb44332009-09-09 15:08:12 +00002393
Anders Carlsson09025312009-08-29 05:16:22 +00002394 // Assign all the initializers to the new constructor.
John McCalld226f652010-08-21 09:40:31 +00002395 ActOnMemInitializers(New,
Anders Carlsson09025312009-08-29 05:16:22 +00002396 /*FIXME: ColonLoc */
2397 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002398 NewInits.data(), NewInits.size(),
2399 AnyErrors);
Anders Carlsson09025312009-08-29 05:16:22 +00002400}
2401
John McCall52a575a2009-08-29 08:11:13 +00002402// TODO: this could be templated if the various decl types used the
2403// same method name.
2404static bool isInstantiationOf(ClassTemplateDecl *Pattern,
2405 ClassTemplateDecl *Instance) {
2406 Pattern = Pattern->getCanonicalDecl();
2407
2408 do {
2409 Instance = Instance->getCanonicalDecl();
2410 if (Pattern == Instance) return true;
2411 Instance = Instance->getInstantiatedFromMemberTemplate();
2412 } while (Instance);
2413
2414 return false;
2415}
2416
Douglas Gregor0d696532009-09-28 06:34:35 +00002417static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
2418 FunctionTemplateDecl *Instance) {
2419 Pattern = Pattern->getCanonicalDecl();
2420
2421 do {
2422 Instance = Instance->getCanonicalDecl();
2423 if (Pattern == Instance) return true;
2424 Instance = Instance->getInstantiatedFromMemberTemplate();
2425 } while (Instance);
2426
2427 return false;
2428}
2429
Douglas Gregored9c0f92009-10-29 00:04:11 +00002430static bool
2431isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
2432 ClassTemplatePartialSpecializationDecl *Instance) {
2433 Pattern
2434 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
2435 do {
2436 Instance = cast<ClassTemplatePartialSpecializationDecl>(
2437 Instance->getCanonicalDecl());
2438 if (Pattern == Instance)
2439 return true;
2440 Instance = Instance->getInstantiatedFromMember();
2441 } while (Instance);
2442
2443 return false;
2444}
2445
John McCall52a575a2009-08-29 08:11:13 +00002446static bool isInstantiationOf(CXXRecordDecl *Pattern,
2447 CXXRecordDecl *Instance) {
2448 Pattern = Pattern->getCanonicalDecl();
2449
2450 do {
2451 Instance = Instance->getCanonicalDecl();
2452 if (Pattern == Instance) return true;
2453 Instance = Instance->getInstantiatedFromMemberClass();
2454 } while (Instance);
2455
2456 return false;
2457}
2458
2459static bool isInstantiationOf(FunctionDecl *Pattern,
2460 FunctionDecl *Instance) {
2461 Pattern = Pattern->getCanonicalDecl();
2462
2463 do {
2464 Instance = Instance->getCanonicalDecl();
2465 if (Pattern == Instance) return true;
2466 Instance = Instance->getInstantiatedFromMemberFunction();
2467 } while (Instance);
2468
2469 return false;
2470}
2471
2472static bool isInstantiationOf(EnumDecl *Pattern,
2473 EnumDecl *Instance) {
2474 Pattern = Pattern->getCanonicalDecl();
2475
2476 do {
2477 Instance = Instance->getCanonicalDecl();
2478 if (Pattern == Instance) return true;
2479 Instance = Instance->getInstantiatedFromMemberEnum();
2480 } while (Instance);
2481
2482 return false;
2483}
2484
John McCalled976492009-12-04 22:46:56 +00002485static bool isInstantiationOf(UsingShadowDecl *Pattern,
2486 UsingShadowDecl *Instance,
2487 ASTContext &C) {
2488 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
2489}
2490
2491static bool isInstantiationOf(UsingDecl *Pattern,
2492 UsingDecl *Instance,
2493 ASTContext &C) {
2494 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
2495}
2496
John McCall7ba107a2009-11-18 02:36:19 +00002497static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
2498 UsingDecl *Instance,
2499 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002500 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCall7ba107a2009-11-18 02:36:19 +00002501}
2502
2503static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson0d8df782009-08-29 19:37:28 +00002504 UsingDecl *Instance,
2505 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002506 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00002507}
2508
John McCall52a575a2009-08-29 08:11:13 +00002509static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
2510 VarDecl *Instance) {
2511 assert(Instance->isStaticDataMember());
2512
2513 Pattern = Pattern->getCanonicalDecl();
2514
2515 do {
2516 Instance = Instance->getCanonicalDecl();
2517 if (Pattern == Instance) return true;
2518 Instance = Instance->getInstantiatedFromStaticDataMember();
2519 } while (Instance);
2520
2521 return false;
2522}
2523
John McCalled976492009-12-04 22:46:56 +00002524// Other is the prospective instantiation
2525// D is the prospective pattern
Douglas Gregor815215d2009-05-27 05:35:12 +00002526static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002527 if (D->getKind() != Other->getKind()) {
John McCall7ba107a2009-11-18 02:36:19 +00002528 if (UnresolvedUsingTypenameDecl *UUD
2529 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
2530 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2531 return isInstantiationOf(UUD, UD, Ctx);
2532 }
2533 }
2534
2535 if (UnresolvedUsingValueDecl *UUD
2536 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002537 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2538 return isInstantiationOf(UUD, UD, Ctx);
2539 }
2540 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002541
Anders Carlsson0d8df782009-08-29 19:37:28 +00002542 return false;
2543 }
Mike Stump1eb44332009-09-09 15:08:12 +00002544
John McCall52a575a2009-08-29 08:11:13 +00002545 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
2546 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00002547
John McCall52a575a2009-08-29 08:11:13 +00002548 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
2549 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00002550
John McCall52a575a2009-08-29 08:11:13 +00002551 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
2552 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00002553
Douglas Gregor7caa6822009-07-24 20:34:43 +00002554 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00002555 if (Var->isStaticDataMember())
2556 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
2557
2558 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
2559 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00002560
Douglas Gregor0d696532009-09-28 06:34:35 +00002561 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
2562 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
2563
Douglas Gregored9c0f92009-10-29 00:04:11 +00002564 if (ClassTemplatePartialSpecializationDecl *PartialSpec
2565 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
2566 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
2567 PartialSpec);
2568
Anders Carlssond8b285f2009-09-01 04:26:58 +00002569 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
2570 if (!Field->getDeclName()) {
2571 // This is an unnamed field.
Mike Stump1eb44332009-09-09 15:08:12 +00002572 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlssond8b285f2009-09-01 04:26:58 +00002573 cast<FieldDecl>(D);
2574 }
2575 }
Mike Stump1eb44332009-09-09 15:08:12 +00002576
John McCalled976492009-12-04 22:46:56 +00002577 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
2578 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
2579
2580 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
2581 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
2582
Douglas Gregor815215d2009-05-27 05:35:12 +00002583 return D->getDeclName() && isa<NamedDecl>(Other) &&
2584 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
2585}
2586
2587template<typename ForwardIterator>
Mike Stump1eb44332009-09-09 15:08:12 +00002588static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor815215d2009-05-27 05:35:12 +00002589 NamedDecl *D,
2590 ForwardIterator first,
2591 ForwardIterator last) {
2592 for (; first != last; ++first)
2593 if (isInstantiationOf(Ctx, D, *first))
2594 return cast<NamedDecl>(*first);
2595
2596 return 0;
2597}
2598
John McCall02cace72009-08-28 07:59:38 +00002599/// \brief Finds the instantiation of the given declaration context
2600/// within the current instantiation.
2601///
2602/// \returns NULL if there was an error
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002603DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
Douglas Gregore95b4092009-09-16 18:34:49 +00002604 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCall02cace72009-08-28 07:59:38 +00002605 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002606 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +00002607 return cast_or_null<DeclContext>(ID);
2608 } else return DC;
2609}
2610
Douglas Gregored961e72009-05-27 17:54:46 +00002611/// \brief Find the instantiation of the given declaration within the
2612/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00002613///
2614/// This routine is intended to be used when \p D is a declaration
2615/// referenced from within a template, that needs to mapped into the
2616/// corresponding declaration within an instantiation. For example,
2617/// given:
2618///
2619/// \code
2620/// template<typename T>
2621/// struct X {
2622/// enum Kind {
2623/// KnownValue = sizeof(T)
2624/// };
2625///
2626/// bool getKind() const { return KnownValue; }
2627/// };
2628///
2629/// template struct X<int>;
2630/// \endcode
2631///
2632/// In the instantiation of X<int>::getKind(), we need to map the
2633/// EnumConstantDecl for KnownValue (which refers to
2634/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00002635/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
2636/// this mapping from within the instantiation of X<int>.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002637NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
Douglas Gregore95b4092009-09-16 18:34:49 +00002638 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor815215d2009-05-27 05:35:12 +00002639 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor550d9b22009-10-31 17:21:17 +00002640 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
Douglas Gregor6d3e6272010-02-05 19:54:12 +00002641 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
John McCall76672452010-08-19 23:06:02 +00002642 (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext())) {
Douglas Gregor2bba76b2009-05-27 17:07:49 +00002643 // D is a local of some kind. Look into the map of local
2644 // declarations to their instantiations.
Fariborz Jahanian8dd0c562010-07-13 00:16:40 +00002645 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
Douglas Gregor2bba76b2009-05-27 17:07:49 +00002646 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002647
Douglas Gregore95b4092009-09-16 18:34:49 +00002648 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
2649 if (!Record->isDependentContext())
2650 return D;
2651
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002652 // If the RecordDecl is actually the injected-class-name or a
2653 // "templated" declaration for a class template, class template
2654 // partial specialization, or a member class of a class template,
2655 // substitute into the injected-class-name of the class template
2656 // or partial specialization to find the new DeclContext.
Douglas Gregore95b4092009-09-16 18:34:49 +00002657 QualType T;
2658 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
2659
2660 if (ClassTemplate) {
Douglas Gregor24bae922010-07-08 18:37:38 +00002661 T = ClassTemplate->getInjectedClassNameSpecialization();
Douglas Gregore95b4092009-09-16 18:34:49 +00002662 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2663 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
Douglas Gregore95b4092009-09-16 18:34:49 +00002664 ClassTemplate = PartialSpec->getSpecializedTemplate();
John McCall3cb0ebd2010-03-10 03:28:59 +00002665
2666 // If we call SubstType with an InjectedClassNameType here we
2667 // can end up in an infinite loop.
2668 T = Context.getTypeDeclType(Record);
2669 assert(isa<InjectedClassNameType>(T) &&
2670 "type of partial specialization is not an InjectedClassNameType");
John McCall31f17ec2010-04-27 00:57:59 +00002671 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
John McCall3cb0ebd2010-03-10 03:28:59 +00002672 }
Douglas Gregore95b4092009-09-16 18:34:49 +00002673
2674 if (!T.isNull()) {
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002675 // Substitute into the injected-class-name to get the type
2676 // corresponding to the instantiation we want, which may also be
2677 // the current instantiation (if we're in a template
2678 // definition). This substitution should never fail, since we
2679 // know we can instantiate the injected-class-name or we
2680 // wouldn't have gotten to the injected-class-name!
2681
2682 // FIXME: Can we use the CurrentInstantiationScope to avoid this
2683 // extra instantiation in the common case?
Douglas Gregore95b4092009-09-16 18:34:49 +00002684 T = SubstType(T, TemplateArgs, SourceLocation(), DeclarationName());
2685 assert(!T.isNull() && "Instantiation of injected-class-name cannot fail.");
2686
2687 if (!T->isDependentType()) {
2688 assert(T->isRecordType() && "Instantiation must produce a record type");
2689 return T->getAs<RecordType>()->getDecl();
2690 }
2691
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002692 // We are performing "partial" template instantiation to create
2693 // the member declarations for the members of a class template
2694 // specialization. Therefore, D is actually referring to something
2695 // in the current instantiation. Look through the current
2696 // context, which contains actual instantiations, to find the
2697 // instantiation of the "current instantiation" that D refers
2698 // to.
2699 bool SawNonDependentContext = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002700 for (DeclContext *DC = CurContext; !DC->isFileContext();
John McCall52a575a2009-08-29 08:11:13 +00002701 DC = DC->getParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002702 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002703 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Douglas Gregore95b4092009-09-16 18:34:49 +00002704 if (isInstantiationOf(ClassTemplate,
2705 Spec->getSpecializedTemplate()))
John McCall52a575a2009-08-29 08:11:13 +00002706 return Spec;
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002707
2708 if (!DC->isDependentContext())
2709 SawNonDependentContext = true;
John McCall52a575a2009-08-29 08:11:13 +00002710 }
2711
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002712 // We're performing "instantiation" of a member of the current
2713 // instantiation while we are type-checking the
2714 // definition. Compute the declaration context and return that.
2715 assert(!SawNonDependentContext &&
2716 "No dependent context while instantiating record");
2717 DeclContext *DC = computeDeclContext(T);
2718 assert(DC &&
John McCall52a575a2009-08-29 08:11:13 +00002719 "Unable to find declaration for the current instantiation");
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002720 return cast<CXXRecordDecl>(DC);
John McCall52a575a2009-08-29 08:11:13 +00002721 }
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002722
Douglas Gregore95b4092009-09-16 18:34:49 +00002723 // Fall through to deal with other dependent record types (e.g.,
2724 // anonymous unions in class templates).
2725 }
John McCall52a575a2009-08-29 08:11:13 +00002726
Douglas Gregore95b4092009-09-16 18:34:49 +00002727 if (!ParentDC->isDependentContext())
2728 return D;
2729
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002730 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002731 if (!ParentDC)
Douglas Gregor44c73842009-09-01 17:53:10 +00002732 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002733
Douglas Gregor815215d2009-05-27 05:35:12 +00002734 if (ParentDC != D->getDeclContext()) {
2735 // We performed some kind of instantiation in the parent context,
2736 // so now we need to look into the instantiated parent context to
2737 // find the instantiation of the declaration D.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002738
John McCall3cb0ebd2010-03-10 03:28:59 +00002739 // If our context used to be dependent, we may need to instantiate
2740 // it before performing lookup into that context.
2741 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002742 if (!Spec->isDependentContext()) {
2743 QualType T = Context.getTypeDeclType(Spec);
John McCall3cb0ebd2010-03-10 03:28:59 +00002744 const RecordType *Tag = T->getAs<RecordType>();
2745 assert(Tag && "type of non-dependent record is not a RecordType");
2746 if (!Tag->isBeingDefined() &&
2747 RequireCompleteType(Loc, T, diag::err_incomplete_type))
2748 return 0;
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002749 }
2750 }
2751
Douglas Gregor815215d2009-05-27 05:35:12 +00002752 NamedDecl *Result = 0;
2753 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002754 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00002755 Result = findInstantiationOf(Context, D, Found.first, Found.second);
2756 } else {
2757 // Since we don't have a name for the entity we're looking for,
2758 // our only option is to walk through all of the declarations to
2759 // find that name. This will occur in a few cases:
2760 //
2761 // - anonymous struct/union within a template
2762 // - unnamed class/struct/union/enum within a template
2763 //
2764 // FIXME: Find a better way to find these instantiations!
Mike Stump1eb44332009-09-09 15:08:12 +00002765 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002766 ParentDC->decls_begin(),
2767 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00002768 }
Mike Stump1eb44332009-09-09 15:08:12 +00002769
John McCall9f54ad42009-12-10 09:41:52 +00002770 // UsingShadowDecls can instantiate to nothing because of using hiding.
Douglas Gregor00225542010-03-01 18:27:54 +00002771 assert((Result || isa<UsingShadowDecl>(D) || D->isInvalidDecl() ||
2772 cast<Decl>(ParentDC)->isInvalidDecl())
John McCall9f54ad42009-12-10 09:41:52 +00002773 && "Unable to find instantiation of declaration!");
2774
Douglas Gregor815215d2009-05-27 05:35:12 +00002775 D = Result;
2776 }
2777
Douglas Gregor815215d2009-05-27 05:35:12 +00002778 return D;
2779}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002780
Mike Stump1eb44332009-09-09 15:08:12 +00002781/// \brief Performs template instantiation for all implicit template
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002782/// instantiations we have seen until this point.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002783void Sema::PerformPendingInstantiations(bool LocalOnly) {
Douglas Gregor60406be2010-01-16 22:29:39 +00002784 while (!PendingLocalImplicitInstantiations.empty() ||
Chandler Carruth62c78d52010-08-25 08:44:16 +00002785 (!LocalOnly && !PendingInstantiations.empty())) {
Douglas Gregor60406be2010-01-16 22:29:39 +00002786 PendingImplicitInstantiation Inst;
2787
2788 if (PendingLocalImplicitInstantiations.empty()) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00002789 Inst = PendingInstantiations.front();
2790 PendingInstantiations.pop_front();
Douglas Gregor60406be2010-01-16 22:29:39 +00002791 } else {
2792 Inst = PendingLocalImplicitInstantiations.front();
2793 PendingLocalImplicitInstantiations.pop_front();
2794 }
Mike Stump1eb44332009-09-09 15:08:12 +00002795
Douglas Gregor7caa6822009-07-24 20:34:43 +00002796 // Instantiate function definitions
2797 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
John McCallf312b1e2010-08-26 23:41:50 +00002798 PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(),
2799 "instantiating function definition");
Chandler Carruth58e390e2010-08-25 08:27:02 +00002800 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
2801 TSK_ExplicitInstantiationDefinition;
2802 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true,
2803 DefinitionRequired);
Douglas Gregor7caa6822009-07-24 20:34:43 +00002804 continue;
2805 }
Mike Stump1eb44332009-09-09 15:08:12 +00002806
Douglas Gregor7caa6822009-07-24 20:34:43 +00002807 // Instantiate static data member definitions.
2808 VarDecl *Var = cast<VarDecl>(Inst.first);
2809 assert(Var->isStaticDataMember() && "Not a static data member?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002810
Chandler Carruth291b4412010-02-13 10:17:50 +00002811 // Don't try to instantiate declarations if the most recent redeclaration
2812 // is invalid.
2813 if (Var->getMostRecentDeclaration()->isInvalidDecl())
2814 continue;
2815
2816 // Check if the most recent declaration has changed the specialization kind
2817 // and removed the need for implicit instantiation.
2818 switch (Var->getMostRecentDeclaration()->getTemplateSpecializationKind()) {
2819 case TSK_Undeclared:
2820 assert(false && "Cannot instantitiate an undeclared specialization.");
2821 case TSK_ExplicitInstantiationDeclaration:
Chandler Carruth291b4412010-02-13 10:17:50 +00002822 case TSK_ExplicitSpecialization:
Chandler Carruth58e390e2010-08-25 08:27:02 +00002823 continue; // No longer need to instantiate this type.
2824 case TSK_ExplicitInstantiationDefinition:
2825 // We only need an instantiation if the pending instantiation *is* the
2826 // explicit instantiation.
2827 if (Var != Var->getMostRecentDeclaration()) continue;
Chandler Carruth291b4412010-02-13 10:17:50 +00002828 case TSK_ImplicitInstantiation:
2829 break;
2830 }
2831
John McCallf312b1e2010-08-26 23:41:50 +00002832 PrettyDeclStackTraceEntry CrashInfo(*this, Var, Var->getLocation(),
2833 "instantiating static data member "
2834 "definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002835
Chandler Carruth58e390e2010-08-25 08:27:02 +00002836 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
2837 TSK_ExplicitInstantiationDefinition;
2838 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true,
2839 DefinitionRequired);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002840 }
2841}
John McCall0c01d182010-03-24 05:22:00 +00002842
2843void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
2844 const MultiLevelTemplateArgumentList &TemplateArgs) {
2845 for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(),
2846 E = Pattern->ddiag_end(); I != E; ++I) {
2847 DependentDiagnostic *DD = *I;
2848
2849 switch (DD->getKind()) {
2850 case DependentDiagnostic::Access:
2851 HandleDependentAccessCheck(*DD, TemplateArgs);
2852 break;
2853 }
2854 }
2855}
John McCallf312b1e2010-08-26 23:41:50 +00002856