blob: 5574a61df2d1ca6956eb9013b6272e044e6bba8d [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//===----------------------------------------------------------------------===/
Douglas Gregore737f502010-08-12 20:07:10 +000012#include "clang/Sema/Sema.h"
13#include "clang/Sema/Lookup.h"
Douglas Gregoraba43bb2009-05-26 20:50:29 +000014#include "clang/AST/ASTConsumer.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000015#include "clang/AST/ASTContext.h"
16#include "clang/AST/DeclTemplate.h"
17#include "clang/AST/DeclVisitor.h"
John McCall0c01d182010-03-24 05:22:00 +000018#include "clang/AST/DependentDiagnostic.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000019#include "clang/AST/Expr.h"
Douglas Gregora88cfbf2009-12-12 18:16:41 +000020#include "clang/AST/ExprCXX.h"
John McCall21ef0fa2010-03-11 09:03:00 +000021#include "clang/AST/TypeLoc.h"
Anders Carlssonc17fb7b2009-09-01 05:12:24 +000022#include "clang/Basic/PrettyStackTrace.h"
Douglas Gregor83ddad32009-08-26 21:14:46 +000023#include "clang/Lex/Preprocessor.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000024
25using namespace clang;
26
27namespace {
Benjamin Kramer85b45212009-11-28 19:45:26 +000028 class TemplateDeclInstantiator
Chris Lattnerb28317a2009-03-28 19:18:32 +000029 : public DeclVisitor<TemplateDeclInstantiator, Decl *> {
Douglas Gregor8dbc2692009-03-17 21:15:40 +000030 Sema &SemaRef;
31 DeclContext *Owner;
Douglas Gregord6350ae2009-08-28 20:31:08 +000032 const MultiLevelTemplateArgumentList &TemplateArgs;
Mike Stump1eb44332009-09-09 15:08:12 +000033
Douglas Gregor8dbc2692009-03-17 21:15:40 +000034 public:
Douglas Gregor8dbc2692009-03-17 21:15:40 +000035 TemplateDeclInstantiator(Sema &SemaRef, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +000036 const MultiLevelTemplateArgumentList &TemplateArgs)
Douglas Gregor7e063902009-05-11 23:53:27 +000037 : SemaRef(SemaRef), Owner(Owner), TemplateArgs(TemplateArgs) { }
Mike Stump1eb44332009-09-09 15:08:12 +000038
Mike Stump390b4cc2009-05-16 07:39:55 +000039 // FIXME: Once we get closer to completion, replace these manually-written
40 // declarations with automatically-generated ones from
Sean Hunt9a555912010-05-30 07:21:58 +000041 // clang/AST/DeclNodes.inc.
Douglas Gregor4f722be2009-03-25 15:45:12 +000042 Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D);
43 Decl *VisitNamespaceDecl(NamespaceDecl *D);
John McCall3dbd3d52010-02-16 06:53:13 +000044 Decl *VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000045 Decl *VisitTypedefDecl(TypedefDecl *D);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +000046 Decl *VisitVarDecl(VarDecl *D);
Abramo Bagnara6206d532010-06-05 05:09:32 +000047 Decl *VisitAccessSpecDecl(AccessSpecDecl *D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000048 Decl *VisitFieldDecl(FieldDecl *D);
49 Decl *VisitStaticAssertDecl(StaticAssertDecl *D);
50 Decl *VisitEnumDecl(EnumDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000051 Decl *VisitEnumConstantDecl(EnumConstantDecl *D);
John McCall02cace72009-08-28 07:59:38 +000052 Decl *VisitFriendDecl(FriendDecl *D);
Douglas Gregora735b202009-10-13 14:39:41 +000053 Decl *VisitFunctionDecl(FunctionDecl *D,
54 TemplateParameterList *TemplateParams = 0);
Douglas Gregord475b8d2009-03-25 21:17:03 +000055 Decl *VisitCXXRecordDecl(CXXRecordDecl *D);
Douglas Gregord60e1052009-08-27 16:57:43 +000056 Decl *VisitCXXMethodDecl(CXXMethodDecl *D,
57 TemplateParameterList *TemplateParams = 0);
Douglas Gregor615c5d42009-03-24 16:43:20 +000058 Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
Douglas Gregor03b2b072009-03-24 00:15:49 +000059 Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +000060 Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000061 ParmVarDecl *VisitParmVarDecl(ParmVarDecl *D);
John McCalle29ba202009-08-20 01:44:21 +000062 Decl *VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor7974c3b2009-10-07 17:21:34 +000063 Decl *VisitClassTemplatePartialSpecializationDecl(
64 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregord60e1052009-08-27 16:57:43 +000065 Decl *VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
John McCalle29ba202009-08-20 01:44:21 +000066 Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Douglas Gregor33642df2009-10-23 23:25:44 +000067 Decl *VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregor9106ef72009-11-11 16:58:32 +000068 Decl *VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Douglas Gregor48c32a72009-11-17 06:07:40 +000069 Decl *VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
John McCalled976492009-12-04 22:46:56 +000070 Decl *VisitUsingDecl(UsingDecl *D);
71 Decl *VisitUsingShadowDecl(UsingShadowDecl *D);
John McCall7ba107a2009-11-18 02:36:19 +000072 Decl *VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
73 Decl *VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Mike Stump1eb44332009-09-09 15:08:12 +000074
Douglas Gregor8dbc2692009-03-17 21:15:40 +000075 // Base case. FIXME: Remove once we can instantiate everything.
Douglas Gregor48c32a72009-11-17 06:07:40 +000076 Decl *VisitDecl(Decl *D) {
77 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
78 Diagnostic::Error,
79 "cannot instantiate %0 yet");
80 SemaRef.Diag(D->getLocation(), DiagID)
81 << D->getDeclKindName();
82
Douglas Gregor8dbc2692009-03-17 21:15:40 +000083 return 0;
84 }
Douglas Gregor5545e162009-03-24 00:38:23 +000085
86 // Helper functions for instantiating methods.
John McCall21ef0fa2010-03-11 09:03:00 +000087 TypeSourceInfo *SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +000088 llvm::SmallVectorImpl<ParmVarDecl *> &Params);
Douglas Gregore53060f2009-06-25 22:08:12 +000089 bool InitFunctionInstantiation(FunctionDecl *New, FunctionDecl *Tmpl);
Douglas Gregor5545e162009-03-24 00:38:23 +000090 bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl);
John McCalle29ba202009-08-20 01:44:21 +000091
92 TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +000093 SubstTemplateParams(TemplateParameterList *List);
John McCallb6217662010-03-15 10:12:16 +000094
95 bool SubstQualifier(const DeclaratorDecl *OldDecl,
96 DeclaratorDecl *NewDecl);
97 bool SubstQualifier(const TagDecl *OldDecl,
98 TagDecl *NewDecl);
Douglas Gregored9c0f92009-10-29 00:04:11 +000099
100 bool InstantiateClassTemplatePartialSpecialization(
101 ClassTemplateDecl *ClassTemplate,
102 ClassTemplatePartialSpecializationDecl *PartialSpec);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000103 };
104}
105
John McCallb6217662010-03-15 10:12:16 +0000106bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
107 DeclaratorDecl *NewDecl) {
108 NestedNameSpecifier *OldQual = OldDecl->getQualifier();
109 if (!OldQual) return false;
110
111 SourceRange QualRange = OldDecl->getQualifierRange();
112
113 NestedNameSpecifier *NewQual
114 = SemaRef.SubstNestedNameSpecifier(OldQual, QualRange, TemplateArgs);
115 if (!NewQual)
116 return true;
117
118 NewDecl->setQualifierInfo(NewQual, QualRange);
119 return false;
120}
121
122bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
123 TagDecl *NewDecl) {
124 NestedNameSpecifier *OldQual = OldDecl->getQualifier();
125 if (!OldQual) return false;
126
127 SourceRange QualRange = OldDecl->getQualifierRange();
128
129 NestedNameSpecifier *NewQual
130 = SemaRef.SubstNestedNameSpecifier(OldQual, QualRange, TemplateArgs);
131 if (!NewQual)
132 return true;
133
134 NewDecl->setQualifierInfo(NewQual, QualRange);
135 return false;
136}
137
Chandler Carruth4ced79f2010-06-25 03:22:07 +0000138// FIXME: Is this still too simple?
John McCall1d8d1cc2010-08-01 02:01:53 +0000139void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
140 Decl *Tmpl, Decl *New) {
Sean Huntcf807c42010-08-18 23:23:40 +0000141 for (AttrVec::const_iterator i = Tmpl->attr_begin(), e = Tmpl->attr_end();
142 i != e; ++i) {
143 const Attr *TmplAttr = *i;
Chandler Carruth4ced79f2010-06-25 03:22:07 +0000144 // FIXME: This should be generalized to more than just the AlignedAttr.
145 if (const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr)) {
Sean Huntcf807c42010-08-18 23:23:40 +0000146 if (Aligned->isAlignmentDependent()) {
Chandler Carruth4ced79f2010-06-25 03:22:07 +0000147 // The alignment expression is not potentially evaluated.
John McCall1d8d1cc2010-08-01 02:01:53 +0000148 EnterExpressionEvaluationContext Unevaluated(*this,
Chandler Carruth4ced79f2010-06-25 03:22:07 +0000149 Action::Unevaluated);
150
Sean Huntcf807c42010-08-18 23:23:40 +0000151 if (Aligned->isAlignmentExpr()) {
John McCall60d7b3a2010-08-24 06:29:42 +0000152 ExprResult Result = SubstExpr(Aligned->getAlignmentExpr(),
Sean Huntcf807c42010-08-18 23:23:40 +0000153 TemplateArgs);
154 if (!Result.isInvalid())
155 AddAlignedAttr(Aligned->getLocation(), New, Result.takeAs<Expr>());
156 }
157 else {
158 TypeSourceInfo *Result = SubstType(Aligned->getAlignmentType(),
159 TemplateArgs,
160 Aligned->getLocation(),
161 DeclarationName());
162 if (Result)
163 AddAlignedAttr(Aligned->getLocation(), New, Result);
164 }
Chandler Carruth4ced79f2010-06-25 03:22:07 +0000165 continue;
166 }
167 }
168
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000169 // FIXME: Is cloning correct for all attributes?
John McCall1d8d1cc2010-08-01 02:01:53 +0000170 Attr *NewAttr = TmplAttr->clone(Context);
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000171 New->addAttr(NewAttr);
172 }
173}
174
Douglas Gregor4f722be2009-03-25 15:45:12 +0000175Decl *
176TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
177 assert(false && "Translation units cannot be instantiated");
178 return D;
179}
180
181Decl *
182TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
183 assert(false && "Namespaces cannot be instantiated");
184 return D;
185}
186
John McCall3dbd3d52010-02-16 06:53:13 +0000187Decl *
188TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
189 NamespaceAliasDecl *Inst
190 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
191 D->getNamespaceLoc(),
192 D->getAliasLoc(),
193 D->getNamespace()->getIdentifier(),
194 D->getQualifierRange(),
195 D->getQualifier(),
196 D->getTargetNameLoc(),
197 D->getNamespace());
198 Owner->addDecl(Inst);
199 return Inst;
200}
201
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000202Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
203 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000204 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor836adf62010-05-24 17:22:01 +0000205 if (DI->getType()->isDependentType() ||
206 DI->getType()->isVariablyModifiedType()) {
John McCallba6a9bd2009-10-24 08:00:42 +0000207 DI = SemaRef.SubstType(DI, TemplateArgs,
208 D->getLocation(), D->getDeclName());
209 if (!DI) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000210 Invalid = true;
John McCalla93c9342009-12-07 02:54:59 +0000211 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000212 }
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000213 } else {
214 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000215 }
Mike Stump1eb44332009-09-09 15:08:12 +0000216
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000217 // Create the new typedef
218 TypedefDecl *Typedef
219 = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(),
John McCallba6a9bd2009-10-24 08:00:42 +0000220 D->getIdentifier(), DI);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000221 if (Invalid)
222 Typedef->setInvalidDecl();
223
Douglas Gregord57a38e2010-04-23 16:25:07 +0000224 if (const TagType *TT = DI->getType()->getAs<TagType>()) {
225 TagDecl *TD = TT->getDecl();
226
227 // If the TagDecl that the TypedefDecl points to is an anonymous decl
228 // keep track of the TypedefDecl.
229 if (!TD->getIdentifier() && !TD->getTypedefForAnonDecl())
230 TD->setTypedefForAnonDecl(Typedef);
231 }
232
John McCall5126fd02009-12-30 00:31:22 +0000233 if (TypedefDecl *Prev = D->getPreviousDeclaration()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000234 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
235 TemplateArgs);
John McCall5126fd02009-12-30 00:31:22 +0000236 Typedef->setPreviousDeclaration(cast<TypedefDecl>(InstPrev));
237 }
238
John McCall1d8d1cc2010-08-01 02:01:53 +0000239 SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
Douglas Gregord57a38e2010-04-23 16:25:07 +0000240
John McCall46460a62010-01-20 21:53:11 +0000241 Typedef->setAccess(D->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000242 Owner->addDecl(Typedef);
Mike Stump1eb44332009-09-09 15:08:12 +0000243
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000244 return Typedef;
245}
246
Douglas Gregor6eef5192009-12-14 19:27:10 +0000247/// \brief Instantiate the arguments provided as part of initialization.
248///
249/// \returns true if an error occurred, false otherwise.
250static bool InstantiateInitializationArguments(Sema &SemaRef,
251 Expr **Args, unsigned NumArgs,
252 const MultiLevelTemplateArgumentList &TemplateArgs,
253 llvm::SmallVectorImpl<SourceLocation> &FakeCommaLocs,
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
265 Expr *ArgExpr = (Expr *)Arg.get();
266 InitArgs.push_back(Arg.release());
267
268 // FIXME: We're faking all of the comma locations. Do we need them?
269 FakeCommaLocs.push_back(
270 SemaRef.PP.getLocForEndOfToken(ArgExpr->getLocEnd()));
271 }
272
273 return false;
274}
275
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000276/// \brief Instantiate an initializer, breaking it into separate
277/// initialization arguments.
278///
279/// \param S The semantic analysis object.
280///
281/// \param Init The initializer to instantiate.
282///
283/// \param TemplateArgs Template arguments to be substituted into the
284/// initializer.
285///
286/// \param NewArgs Will be filled in with the instantiation arguments.
287///
288/// \returns true if an error occurred, false otherwise
289static bool InstantiateInitializer(Sema &S, Expr *Init,
290 const MultiLevelTemplateArgumentList &TemplateArgs,
291 SourceLocation &LParenLoc,
292 llvm::SmallVector<SourceLocation, 4> &CommaLocs,
John McCallca0408f2010-08-23 06:44:23 +0000293 ASTOwningVector<Expr*> &NewArgs,
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000294 SourceLocation &RParenLoc) {
295 NewArgs.clear();
296 LParenLoc = SourceLocation();
297 RParenLoc = SourceLocation();
298
299 if (!Init)
300 return false;
301
302 if (CXXExprWithTemporaries *ExprTemp = dyn_cast<CXXExprWithTemporaries>(Init))
303 Init = ExprTemp->getSubExpr();
304
305 while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
306 Init = Binder->getSubExpr();
307
308 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
309 Init = ICE->getSubExprAsWritten();
310
311 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
312 LParenLoc = ParenList->getLParenLoc();
313 RParenLoc = ParenList->getRParenLoc();
314 return InstantiateInitializationArguments(S, ParenList->getExprs(),
315 ParenList->getNumExprs(),
316 TemplateArgs, CommaLocs,
317 NewArgs);
318 }
319
320 if (CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init)) {
Douglas Gregor28329e52010-03-24 21:22:47 +0000321 if (!isa<CXXTemporaryObjectExpr>(Construct)) {
322 if (InstantiateInitializationArguments(S,
323 Construct->getArgs(),
324 Construct->getNumArgs(),
325 TemplateArgs,
326 CommaLocs, NewArgs))
327 return true;
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000328
Douglas Gregor28329e52010-03-24 21:22:47 +0000329 // FIXME: Fake locations!
330 LParenLoc = S.PP.getLocForEndOfToken(Init->getLocStart());
331 RParenLoc = CommaLocs.empty()? LParenLoc : CommaLocs.back();
332 return false;
333 }
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000334 }
335
John McCall60d7b3a2010-08-24 06:29:42 +0000336 ExprResult Result = S.SubstExpr(Init, TemplateArgs);
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000337 if (Result.isInvalid())
338 return true;
339
340 NewArgs.push_back(Result.takeAs<Expr>());
341 return false;
342}
343
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000344Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
Douglas Gregor9901c572010-05-21 00:31:19 +0000345 // If this is the variable for an anonymous struct or union,
346 // instantiate the anonymous struct/union type first.
347 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
348 if (RecordTy->getDecl()->isAnonymousStructOrUnion())
349 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
350 return 0;
351
John McCallce3ff2b2009-08-25 22:02:44 +0000352 // Do substitution on the type of the declaration
John McCalla93c9342009-12-07 02:54:59 +0000353 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
John McCall0a5fa062009-10-21 02:39:02 +0000354 TemplateArgs,
355 D->getTypeSpecStartLoc(),
356 D->getDeclName());
357 if (!DI)
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000358 return 0;
359
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000360 // Build the instantiated declaration
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000361 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
362 D->getLocation(), D->getIdentifier(),
John McCall0a5fa062009-10-21 02:39:02 +0000363 DI->getType(), DI,
Douglas Gregor16573fa2010-04-19 22:54:31 +0000364 D->getStorageClass(),
365 D->getStorageClassAsWritten());
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000366 Var->setThreadSpecified(D->isThreadSpecified());
367 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
Mike Stump1eb44332009-09-09 15:08:12 +0000368
John McCallb6217662010-03-15 10:12:16 +0000369 // Substitute the nested name specifier, if any.
370 if (SubstQualifier(D, Var))
371 return 0;
372
Mike Stump1eb44332009-09-09 15:08:12 +0000373 // If we are instantiating a static data member defined
Douglas Gregor7caa6822009-07-24 20:34:43 +0000374 // out-of-line, the instantiation will have the same lexical
375 // context (which will be a namespace scope) as the template.
376 if (D->isOutOfLine())
377 Var->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000378
John McCall46460a62010-01-20 21:53:11 +0000379 Var->setAccess(D->getAccess());
Douglas Gregorc070cc62010-06-17 23:14:26 +0000380
381 if (!D->isStaticDataMember())
382 Var->setUsed(D->isUsed(false));
Douglas Gregor4469e8a2010-05-19 17:02:24 +0000383
Mike Stump390b4cc2009-05-16 07:39:55 +0000384 // FIXME: In theory, we could have a previous declaration for variables that
385 // are not static data members.
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000386 bool Redeclaration = false;
John McCall68263142009-11-18 22:49:29 +0000387 // FIXME: having to fake up a LookupResult is dumb.
388 LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(),
Douglas Gregor449d0a82010-03-01 19:11:54 +0000389 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Douglas Gregor60c93c92010-02-09 07:26:29 +0000390 if (D->isStaticDataMember())
391 SemaRef.LookupQualifiedName(Previous, Owner, false);
John McCall68263142009-11-18 22:49:29 +0000392 SemaRef.CheckVariableDeclaration(Var, Previous, Redeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +0000393
Douglas Gregor7caa6822009-07-24 20:34:43 +0000394 if (D->isOutOfLine()) {
Abramo Bagnaraea7b4882010-06-04 09:35:39 +0000395 if (!D->isStaticDataMember())
396 D->getLexicalDeclContext()->addDecl(Var);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000397 Owner->makeDeclVisibleInContext(Var);
398 } else {
399 Owner->addDecl(Var);
Douglas Gregorf7d72f52010-05-03 20:22:41 +0000400 if (Owner->isFunctionOrMethod())
401 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Var);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000402 }
John McCall1d8d1cc2010-08-01 02:01:53 +0000403 SemaRef.InstantiateAttrs(TemplateArgs, D, Var);
Fariborz Jahanian8dd0c562010-07-13 00:16:40 +0000404
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000405 // Link instantiations of static data members back to the template from
406 // which they were instantiated.
407 if (Var->isStaticDataMember())
408 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D,
Douglas Gregorcf3293e2009-11-01 20:32:48 +0000409 TSK_ImplicitInstantiation);
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000410
Douglas Gregor60c93c92010-02-09 07:26:29 +0000411 if (Var->getAnyInitializer()) {
412 // We already have an initializer in the class.
413 } else if (D->getInit()) {
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000414 if (Var->isStaticDataMember() && !D->isOutOfLine())
415 SemaRef.PushExpressionEvaluationContext(Sema::Unevaluated);
416 else
417 SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
418
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000419 // Instantiate the initializer.
420 SourceLocation LParenLoc, RParenLoc;
421 llvm::SmallVector<SourceLocation, 4> CommaLocs;
John McCallca0408f2010-08-23 06:44:23 +0000422 ASTOwningVector<Expr*> InitArgs(SemaRef);
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000423 if (!InstantiateInitializer(SemaRef, D->getInit(), TemplateArgs, LParenLoc,
424 CommaLocs, InitArgs, RParenLoc)) {
425 // Attach the initializer to the declaration.
426 if (D->hasCXXDirectInitializer()) {
Douglas Gregor6eef5192009-12-14 19:27:10 +0000427 // Add the direct initializer to the declaration.
John McCalld226f652010-08-21 09:40:31 +0000428 SemaRef.AddCXXDirectInitializerToDecl(Var,
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000429 LParenLoc,
Douglas Gregor6eef5192009-12-14 19:27:10 +0000430 move_arg(InitArgs),
431 CommaLocs.data(),
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000432 RParenLoc);
433 } else if (InitArgs.size() == 1) {
John McCall9ae2f072010-08-23 23:25:46 +0000434 Expr *Init = InitArgs.take()[0];
435 SemaRef.AddInitializerToDecl(Var, Init, false);
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000436 } else {
437 assert(InitArgs.size() == 0);
John McCalld226f652010-08-21 09:40:31 +0000438 SemaRef.ActOnUninitializedDecl(Var, false);
Douglas Gregor6eef5192009-12-14 19:27:10 +0000439 }
Douglas Gregor6eef5192009-12-14 19:27:10 +0000440 } else {
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000441 // FIXME: Not too happy about invalidating the declaration
442 // because of a bogus initializer.
443 Var->setInvalidDecl();
Douglas Gregor6eef5192009-12-14 19:27:10 +0000444 }
445
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000446 SemaRef.PopExpressionEvaluationContext();
Douglas Gregor65b90052009-07-27 17:43:39 +0000447 } else if (!Var->isStaticDataMember() || Var->isOutOfLine())
John McCalld226f652010-08-21 09:40:31 +0000448 SemaRef.ActOnUninitializedDecl(Var, false);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000449
Douglas Gregor5764f612010-05-08 23:05:03 +0000450 // Diagnose unused local variables.
451 if (!Var->isInvalidDecl() && Owner->isFunctionOrMethod() && !Var->isUsed())
452 SemaRef.DiagnoseUnusedDecl(Var);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +0000453
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000454 return Var;
455}
456
Abramo Bagnara6206d532010-06-05 05:09:32 +0000457Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
458 AccessSpecDecl* AD
459 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
460 D->getAccessSpecifierLoc(), D->getColonLoc());
461 Owner->addHiddenDecl(AD);
462 return AD;
463}
464
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000465Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
466 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000467 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor836adf62010-05-24 17:22:01 +0000468 if (DI->getType()->isDependentType() ||
469 DI->getType()->isVariablyModifiedType()) {
John McCall07fb6be2009-10-22 23:33:21 +0000470 DI = SemaRef.SubstType(DI, TemplateArgs,
471 D->getLocation(), D->getDeclName());
472 if (!DI) {
John McCalla93c9342009-12-07 02:54:59 +0000473 DI = D->getTypeSourceInfo();
John McCall07fb6be2009-10-22 23:33:21 +0000474 Invalid = true;
475 } else if (DI->getType()->isFunctionType()) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000476 // C++ [temp.arg.type]p3:
477 // If a declaration acquires a function type through a type
478 // dependent on a template-parameter and this causes a
479 // declaration that does not use the syntactic form of a
480 // function declarator to have function type, the program is
481 // ill-formed.
482 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
John McCall07fb6be2009-10-22 23:33:21 +0000483 << DI->getType();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000484 Invalid = true;
485 }
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000486 } else {
487 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000488 }
489
490 Expr *BitWidth = D->getBitWidth();
491 if (Invalid)
492 BitWidth = 0;
493 else if (BitWidth) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000494 // The bit-width expression is not potentially evaluated.
495 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000496
John McCall60d7b3a2010-08-24 06:29:42 +0000497 ExprResult InstantiatedBitWidth
John McCallce3ff2b2009-08-25 22:02:44 +0000498 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000499 if (InstantiatedBitWidth.isInvalid()) {
500 Invalid = true;
501 BitWidth = 0;
502 } else
Anders Carlssone9146f22009-05-01 19:49:17 +0000503 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000504 }
505
John McCall07fb6be2009-10-22 23:33:21 +0000506 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
507 DI->getType(), DI,
Mike Stump1eb44332009-09-09 15:08:12 +0000508 cast<RecordDecl>(Owner),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000509 D->getLocation(),
510 D->isMutable(),
511 BitWidth,
Steve Naroffea218b82009-07-14 14:58:18 +0000512 D->getTypeSpecStartLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000513 D->getAccess(),
514 0);
Douglas Gregor663b5a02009-10-14 20:14:33 +0000515 if (!Field) {
516 cast<Decl>(Owner)->setInvalidDecl();
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000517 return 0;
Douglas Gregor663b5a02009-10-14 20:14:33 +0000518 }
Mike Stump1eb44332009-09-09 15:08:12 +0000519
John McCall1d8d1cc2010-08-01 02:01:53 +0000520 SemaRef.InstantiateAttrs(TemplateArgs, D, Field);
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000521
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000522 if (Invalid)
523 Field->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000524
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000525 if (!Field->getDeclName()) {
526 // Keep track of where this decl came from.
527 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
Douglas Gregor9901c572010-05-21 00:31:19 +0000528 }
529 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
530 if (Parent->isAnonymousStructOrUnion() &&
531 Parent->getLookupContext()->isFunctionOrMethod())
532 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000533 }
Mike Stump1eb44332009-09-09 15:08:12 +0000534
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000535 Field->setImplicit(D->isImplicit());
John McCall46460a62010-01-20 21:53:11 +0000536 Field->setAccess(D->getAccess());
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000537 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000538
539 return Field;
540}
541
John McCall02cace72009-08-28 07:59:38 +0000542Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
John McCall02cace72009-08-28 07:59:38 +0000543 // Handle friend type expressions by simply substituting template
Douglas Gregor06245bf2010-04-07 17:57:12 +0000544 // parameters into the pattern type and checking the result.
John McCall32f2fb52010-03-25 18:04:51 +0000545 if (TypeSourceInfo *Ty = D->getFriendType()) {
546 TypeSourceInfo *InstTy =
547 SemaRef.SubstType(Ty, TemplateArgs,
548 D->getLocation(), DeclarationName());
Douglas Gregor06245bf2010-04-07 17:57:12 +0000549 if (!InstTy)
Douglas Gregor7557a132009-12-24 20:56:24 +0000550 return 0;
John McCall02cace72009-08-28 07:59:38 +0000551
Douglas Gregor06245bf2010-04-07 17:57:12 +0000552 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getFriendLoc(), InstTy);
553 if (!FD)
554 return 0;
555
556 FD->setAccess(AS_public);
557 Owner->addDecl(FD);
558 return FD;
559 }
560
561 NamedDecl *ND = D->getFriendDecl();
562 assert(ND && "friend decl must be a decl or a type!");
563
John McCallaf2094e2010-04-08 09:05:18 +0000564 // All of the Visit implementations for the various potential friend
565 // declarations have to be carefully written to work for friend
566 // objects, with the most important detail being that the target
567 // decl should almost certainly not be placed in Owner.
568 Decl *NewND = Visit(ND);
Douglas Gregor06245bf2010-04-07 17:57:12 +0000569 if (!NewND) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000570
John McCall02cace72009-08-28 07:59:38 +0000571 FriendDecl *FD =
Douglas Gregor06245bf2010-04-07 17:57:12 +0000572 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
573 cast<NamedDecl>(NewND), D->getFriendLoc());
John McCall5fee1102009-08-29 03:50:18 +0000574 FD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +0000575 Owner->addDecl(FD);
576 return FD;
John McCallfd810b12009-08-14 02:03:10 +0000577}
578
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000579Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
580 Expr *AssertExpr = D->getAssertExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000581
Douglas Gregorac7610d2009-06-22 20:57:11 +0000582 // The expression in a static assertion is not potentially evaluated.
583 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000584
John McCall60d7b3a2010-08-24 06:29:42 +0000585 ExprResult InstantiatedAssertExpr
John McCallce3ff2b2009-08-25 22:02:44 +0000586 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000587 if (InstantiatedAssertExpr.isInvalid())
588 return 0;
589
John McCall60d7b3a2010-08-24 06:29:42 +0000590 ExprResult Message(D->getMessage());
Douglas Gregor43d9d922009-08-08 01:41:12 +0000591 D->getMessage()->Retain();
John McCalld226f652010-08-21 09:40:31 +0000592 return SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
John McCall9ae2f072010-08-23 23:25:46 +0000593 InstantiatedAssertExpr.get(),
594 Message.get());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000595}
596
597Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +0000598 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000599 D->getLocation(), D->getIdentifier(),
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000600 D->getTagKeywordLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000601 /*PrevDecl=*/0);
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000602 Enum->setInstantiationOfMemberEnum(D);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000603 Enum->setAccess(D->getAccess());
John McCallb6217662010-03-15 10:12:16 +0000604 if (SubstQualifier(D, Enum)) return 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000605 Owner->addDecl(Enum);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000606 Enum->startDefinition();
607
Douglas Gregor96084f12010-03-01 19:00:07 +0000608 if (D->getDeclContext()->isFunctionOrMethod())
609 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
610
John McCalld226f652010-08-21 09:40:31 +0000611 llvm::SmallVector<Decl*, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000612
613 EnumConstantDecl *LastEnumConst = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000614 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
615 ECEnd = D->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000616 EC != ECEnd; ++EC) {
617 // The specified value for the enumerator.
John McCall60d7b3a2010-08-24 06:29:42 +0000618 ExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000619 if (Expr *UninstValue = EC->getInitExpr()) {
620 // The enumerator's value expression is not potentially evaluated.
Mike Stump1eb44332009-09-09 15:08:12 +0000621 EnterExpressionEvaluationContext Unevaluated(SemaRef,
Douglas Gregorac7610d2009-06-22 20:57:11 +0000622 Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000623
John McCallce3ff2b2009-08-25 22:02:44 +0000624 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000625 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000626
627 // Drop the initial value and continue.
628 bool isInvalid = false;
629 if (Value.isInvalid()) {
630 Value = SemaRef.Owned((Expr *)0);
631 isInvalid = true;
632 }
633
Mike Stump1eb44332009-09-09 15:08:12 +0000634 EnumConstantDecl *EnumConst
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000635 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
636 EC->getLocation(), EC->getIdentifier(),
John McCall9ae2f072010-08-23 23:25:46 +0000637 Value.get());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000638
639 if (isInvalid) {
640 if (EnumConst)
641 EnumConst->setInvalidDecl();
642 Enum->setInvalidDecl();
643 }
644
645 if (EnumConst) {
John McCall3b85ecf2010-01-23 22:37:59 +0000646 EnumConst->setAccess(Enum->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000647 Enum->addDecl(EnumConst);
John McCalld226f652010-08-21 09:40:31 +0000648 Enumerators.push_back(EnumConst);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000649 LastEnumConst = EnumConst;
Douglas Gregor96084f12010-03-01 19:00:07 +0000650
651 if (D->getDeclContext()->isFunctionOrMethod()) {
652 // If the enumeration is within a function or method, record the enum
653 // constant as a local.
654 SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst);
655 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000656 }
657 }
Mike Stump1eb44332009-09-09 15:08:12 +0000658
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000659 // FIXME: Fixup LBraceLoc and RBraceLoc
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000660 // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000661 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
John McCalld226f652010-08-21 09:40:31 +0000662 Enum,
Eli Friedmande7a0fc2010-08-15 02:27:09 +0000663 Enumerators.data(), Enumerators.size(),
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000664 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000665
666 return Enum;
667}
668
Douglas Gregor6477b692009-03-25 15:04:13 +0000669Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
670 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
671 return 0;
672}
673
John McCalle29ba202009-08-20 01:44:21 +0000674Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
John McCall93ba8572010-03-25 06:39:04 +0000675 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
676
Douglas Gregor550d9b22009-10-31 17:21:17 +0000677 // Create a local instantiation scope for this class template, which
678 // will contain the instantiations of the template parameters.
679 Sema::LocalInstantiationScope Scope(SemaRef);
John McCalle29ba202009-08-20 01:44:21 +0000680 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000681 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000682 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000683 return NULL;
John McCalle29ba202009-08-20 01:44:21 +0000684
685 CXXRecordDecl *Pattern = D->getTemplatedDecl();
John McCall93ba8572010-03-25 06:39:04 +0000686
687 // Instantiate the qualifier. We have to do this first in case
688 // we're a friend declaration, because if we are then we need to put
689 // the new declaration in the appropriate context.
690 NestedNameSpecifier *Qualifier = Pattern->getQualifier();
691 if (Qualifier) {
692 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
693 Pattern->getQualifierRange(),
694 TemplateArgs);
695 if (!Qualifier) return 0;
696 }
697
698 CXXRecordDecl *PrevDecl = 0;
699 ClassTemplateDecl *PrevClassTemplate = 0;
700
701 // If this isn't a friend, then it's a member template, in which
702 // case we just want to build the instantiation in the
703 // specialization. If it is a friend, we want to build it in
704 // the appropriate context.
705 DeclContext *DC = Owner;
706 if (isFriend) {
707 if (Qualifier) {
708 CXXScopeSpec SS;
709 SS.setScopeRep(Qualifier);
710 SS.setRange(Pattern->getQualifierRange());
711 DC = SemaRef.computeDeclContext(SS);
712 if (!DC) return 0;
713 } else {
714 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
715 Pattern->getDeclContext(),
716 TemplateArgs);
717 }
718
719 // Look for a previous declaration of the template in the owning
720 // context.
721 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
722 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
723 SemaRef.LookupQualifiedName(R, DC);
724
725 if (R.isSingleResult()) {
726 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
727 if (PrevClassTemplate)
728 PrevDecl = PrevClassTemplate->getTemplatedDecl();
729 }
730
731 if (!PrevClassTemplate && Qualifier) {
732 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
Douglas Gregor1eabb7d2010-03-31 23:17:41 +0000733 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
734 << Pattern->getQualifierRange();
John McCall93ba8572010-03-25 06:39:04 +0000735 return 0;
736 }
737
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000738 bool AdoptedPreviousTemplateParams = false;
John McCall93ba8572010-03-25 06:39:04 +0000739 if (PrevClassTemplate) {
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000740 bool Complain = true;
741
742 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
743 // template for struct std::tr1::__detail::_Map_base, where the
744 // template parameters of the friend declaration don't match the
745 // template parameters of the original declaration. In this one
746 // case, we don't complain about the ill-formed friend
747 // declaration.
748 if (isFriend && Pattern->getIdentifier() &&
749 Pattern->getIdentifier()->isStr("_Map_base") &&
750 DC->isNamespace() &&
751 cast<NamespaceDecl>(DC)->getIdentifier() &&
752 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
753 DeclContext *DCParent = DC->getParent();
754 if (DCParent->isNamespace() &&
755 cast<NamespaceDecl>(DCParent)->getIdentifier() &&
756 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
757 DeclContext *DCParent2 = DCParent->getParent();
758 if (DCParent2->isNamespace() &&
759 cast<NamespaceDecl>(DCParent2)->getIdentifier() &&
760 cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") &&
761 DCParent2->getParent()->isTranslationUnit())
762 Complain = false;
763 }
764 }
765
John McCall93ba8572010-03-25 06:39:04 +0000766 TemplateParameterList *PrevParams
767 = PrevClassTemplate->getTemplateParameters();
768
769 // Make sure the parameter lists match.
770 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000771 Complain,
772 Sema::TPL_TemplateMatch)) {
773 if (Complain)
774 return 0;
775
776 AdoptedPreviousTemplateParams = true;
777 InstParams = PrevParams;
778 }
John McCall93ba8572010-03-25 06:39:04 +0000779
780 // Do some additional validation, then merge default arguments
781 // from the existing declarations.
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000782 if (!AdoptedPreviousTemplateParams &&
783 SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
John McCall93ba8572010-03-25 06:39:04 +0000784 Sema::TPC_ClassTemplate))
785 return 0;
786 }
787 }
788
John McCalle29ba202009-08-20 01:44:21 +0000789 CXXRecordDecl *RecordInst
John McCall93ba8572010-03-25 06:39:04 +0000790 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
John McCalle29ba202009-08-20 01:44:21 +0000791 Pattern->getLocation(), Pattern->getIdentifier(),
John McCall93ba8572010-03-25 06:39:04 +0000792 Pattern->getTagKeywordLoc(), PrevDecl,
Douglas Gregorf0510d42009-10-12 23:11:44 +0000793 /*DelayTypeCreation=*/true);
John McCalle29ba202009-08-20 01:44:21 +0000794
John McCall93ba8572010-03-25 06:39:04 +0000795 if (Qualifier)
796 RecordInst->setQualifierInfo(Qualifier, Pattern->getQualifierRange());
John McCallb6217662010-03-15 10:12:16 +0000797
John McCalle29ba202009-08-20 01:44:21 +0000798 ClassTemplateDecl *Inst
John McCall93ba8572010-03-25 06:39:04 +0000799 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
800 D->getIdentifier(), InstParams, RecordInst,
801 PrevClassTemplate);
John McCalle29ba202009-08-20 01:44:21 +0000802 RecordInst->setDescribedClassTemplate(Inst);
John McCallea7390c2010-04-08 20:25:50 +0000803
John McCall93ba8572010-03-25 06:39:04 +0000804 if (isFriend) {
John McCallea7390c2010-04-08 20:25:50 +0000805 if (PrevClassTemplate)
806 Inst->setAccess(PrevClassTemplate->getAccess());
807 else
808 Inst->setAccess(D->getAccess());
809
John McCall93ba8572010-03-25 06:39:04 +0000810 Inst->setObjectOfFriendDecl(PrevClassTemplate != 0);
811 // TODO: do we want to track the instantiation progeny of this
812 // friend target decl?
813 } else {
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000814 Inst->setAccess(D->getAccess());
John McCall93ba8572010-03-25 06:39:04 +0000815 Inst->setInstantiatedFromMemberTemplate(D);
816 }
Douglas Gregorf0510d42009-10-12 23:11:44 +0000817
818 // Trigger creation of the type for the instantiation.
John McCall3cb0ebd2010-03-10 03:28:59 +0000819 SemaRef.Context.getInjectedClassNameType(RecordInst,
Douglas Gregor24bae922010-07-08 18:37:38 +0000820 Inst->getInjectedClassNameSpecialization());
John McCallea7390c2010-04-08 20:25:50 +0000821
Douglas Gregor259571e2009-10-30 22:42:42 +0000822 // Finish handling of friends.
John McCall93ba8572010-03-25 06:39:04 +0000823 if (isFriend) {
824 DC->makeDeclVisibleInContext(Inst, /*Recoverable*/ false);
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000825 return Inst;
Douglas Gregor259571e2009-10-30 22:42:42 +0000826 }
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000827
John McCalle29ba202009-08-20 01:44:21 +0000828 Owner->addDecl(Inst);
Douglas Gregored9c0f92009-10-29 00:04:11 +0000829
Douglas Gregored9c0f92009-10-29 00:04:11 +0000830 // Instantiate all of the partial specializations of this member class
831 // template.
Douglas Gregordc60c1e2010-04-30 05:56:50 +0000832 llvm::SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
833 D->getPartialSpecializations(PartialSpecs);
Douglas Gregored9c0f92009-10-29 00:04:11 +0000834 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
835 InstantiateClassTemplatePartialSpecialization(Inst, PartialSpecs[I]);
836
John McCalle29ba202009-08-20 01:44:21 +0000837 return Inst;
838}
839
Douglas Gregord60e1052009-08-27 16:57:43 +0000840Decl *
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000841TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
842 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregored9c0f92009-10-29 00:04:11 +0000843 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
844
845 // Lookup the already-instantiated declaration in the instantiation
846 // of the class template and return that.
847 DeclContext::lookup_result Found
848 = Owner->lookup(ClassTemplate->getDeclName());
849 if (Found.first == Found.second)
850 return 0;
851
852 ClassTemplateDecl *InstClassTemplate
853 = dyn_cast<ClassTemplateDecl>(*Found.first);
854 if (!InstClassTemplate)
855 return 0;
856
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +0000857 return InstClassTemplate->findPartialSpecInstantiatedFromMember(D);
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000858}
859
860Decl *
Douglas Gregord60e1052009-08-27 16:57:43 +0000861TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000862 // Create a local instantiation scope for this function template, which
863 // will contain the instantiations of the template parameters and then get
864 // merged with the local instantiation scope for the function template
865 // itself.
866 Sema::LocalInstantiationScope Scope(SemaRef);
Douglas Gregor895162d2010-04-30 18:55:50 +0000867
Douglas Gregord60e1052009-08-27 16:57:43 +0000868 TemplateParameterList *TempParams = D->getTemplateParameters();
869 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000870 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000871 return NULL;
Douglas Gregored9c0f92009-10-29 00:04:11 +0000872
Douglas Gregora735b202009-10-13 14:39:41 +0000873 FunctionDecl *Instantiated = 0;
874 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
875 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
876 InstParams));
877 else
878 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
879 D->getTemplatedDecl(),
880 InstParams));
881
882 if (!Instantiated)
Douglas Gregord60e1052009-08-27 16:57:43 +0000883 return 0;
884
John McCall46460a62010-01-20 21:53:11 +0000885 Instantiated->setAccess(D->getAccess());
886
Mike Stump1eb44332009-09-09 15:08:12 +0000887 // Link the instantiated function template declaration to the function
Douglas Gregord60e1052009-08-27 16:57:43 +0000888 // template from which it was instantiated.
Douglas Gregor37d681852009-10-12 22:27:17 +0000889 FunctionTemplateDecl *InstTemplate
Douglas Gregora735b202009-10-13 14:39:41 +0000890 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregor37d681852009-10-12 22:27:17 +0000891 InstTemplate->setAccess(D->getAccess());
Douglas Gregora735b202009-10-13 14:39:41 +0000892 assert(InstTemplate &&
893 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCalle976ffe2009-12-14 23:19:40 +0000894
John McCallb1a56e72010-03-26 23:10:15 +0000895 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
896
John McCalle976ffe2009-12-14 23:19:40 +0000897 // Link the instantiation back to the pattern *unless* this is a
898 // non-definition friend declaration.
899 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
John McCallb1a56e72010-03-26 23:10:15 +0000900 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregora735b202009-10-13 14:39:41 +0000901 InstTemplate->setInstantiatedFromMemberTemplate(D);
902
John McCallb1a56e72010-03-26 23:10:15 +0000903 // Make declarations visible in the appropriate context.
904 if (!isFriend)
Douglas Gregora735b202009-10-13 14:39:41 +0000905 Owner->addDecl(InstTemplate);
John McCallb1a56e72010-03-26 23:10:15 +0000906
Douglas Gregord60e1052009-08-27 16:57:43 +0000907 return InstTemplate;
908}
909
Douglas Gregord475b8d2009-03-25 21:17:03 +0000910Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
911 CXXRecordDecl *PrevDecl = 0;
912 if (D->isInjectedClassName())
913 PrevDecl = cast<CXXRecordDecl>(Owner);
John McCall6c1c1b82009-12-15 22:29:06 +0000914 else if (D->getPreviousDeclaration()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000915 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
916 D->getPreviousDeclaration(),
John McCall6c1c1b82009-12-15 22:29:06 +0000917 TemplateArgs);
918 if (!Prev) return 0;
919 PrevDecl = cast<CXXRecordDecl>(Prev);
920 }
Douglas Gregord475b8d2009-03-25 21:17:03 +0000921
922 CXXRecordDecl *Record
Mike Stump1eb44332009-09-09 15:08:12 +0000923 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000924 D->getLocation(), D->getIdentifier(),
925 D->getTagKeywordLoc(), PrevDecl);
John McCallb6217662010-03-15 10:12:16 +0000926
927 // Substitute the nested name specifier, if any.
928 if (SubstQualifier(D, Record))
929 return 0;
930
Douglas Gregord475b8d2009-03-25 21:17:03 +0000931 Record->setImplicit(D->isImplicit());
Eli Friedmaneaba1af2009-08-27 19:11:42 +0000932 // FIXME: Check against AS_none is an ugly hack to work around the issue that
933 // the tag decls introduced by friend class declarations don't have an access
934 // specifier. Remove once this area of the code gets sorted out.
935 if (D->getAccess() != AS_none)
936 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000937 if (!D->isInjectedClassName())
Douglas Gregorf6b11852009-10-08 15:14:33 +0000938 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000939
John McCall02cace72009-08-28 07:59:38 +0000940 // If the original function was part of a friend declaration,
941 // inherit its namespace state.
942 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
943 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
944
Douglas Gregor9901c572010-05-21 00:31:19 +0000945 // Make sure that anonymous structs and unions are recorded.
946 if (D->isAnonymousStructOrUnion()) {
947 Record->setAnonymousStructOrUnion(true);
948 if (Record->getDeclContext()->getLookupContext()->isFunctionOrMethod())
949 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
950 }
Anders Carlssond8b285f2009-09-01 04:26:58 +0000951
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000952 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000953 return Record;
954}
955
John McCall02cace72009-08-28 07:59:38 +0000956/// Normal class members are of more specific types and therefore
957/// don't make it here. This function serves two purposes:
958/// 1) instantiating function templates
959/// 2) substituting friend declarations
960/// FIXME: preserve function definitions in case #2
Douglas Gregor7557a132009-12-24 20:56:24 +0000961Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
Douglas Gregora735b202009-10-13 14:39:41 +0000962 TemplateParameterList *TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000963 // Check whether there is already a function template specialization for
964 // this declaration.
965 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
966 void *InsertPos = 0;
John McCallb0cb0222010-03-27 05:57:59 +0000967 if (FunctionTemplate && !TemplateParams) {
Douglas Gregor24bae922010-07-08 18:37:38 +0000968 std::pair<const TemplateArgument *, unsigned> Innermost
969 = TemplateArgs.getInnermost();
Mike Stump1eb44332009-09-09 15:08:12 +0000970
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +0000971 FunctionDecl *SpecFunc
972 = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
973 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000974
Douglas Gregor127102b2009-06-29 20:59:39 +0000975 // If we already have a function template specialization, return it.
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +0000976 if (SpecFunc)
977 return SpecFunc;
Douglas Gregor127102b2009-06-29 20:59:39 +0000978 }
Mike Stump1eb44332009-09-09 15:08:12 +0000979
John McCallb0cb0222010-03-27 05:57:59 +0000980 bool isFriend;
981 if (FunctionTemplate)
982 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
983 else
984 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
985
Douglas Gregor79c22782010-01-16 20:21:20 +0000986 bool MergeWithParentScope = (TemplateParams != 0) ||
Douglas Gregorb212d9a2010-05-21 21:25:08 +0000987 Owner->isFunctionOrMethod() ||
Douglas Gregor79c22782010-01-16 20:21:20 +0000988 !(isa<Decl>(Owner) &&
989 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
990 Sema::LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +0000991
Douglas Gregore53060f2009-06-25 22:08:12 +0000992 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall21ef0fa2010-03-11 09:03:00 +0000993 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
994 TInfo = SubstFunctionType(D, Params);
995 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000996 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +0000997 QualType T = TInfo->getType();
John McCallfd810b12009-08-14 02:03:10 +0000998
John McCalld325daa2010-03-26 04:53:08 +0000999 NestedNameSpecifier *Qualifier = D->getQualifier();
1000 if (Qualifier) {
1001 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
1002 D->getQualifierRange(),
1003 TemplateArgs);
1004 if (!Qualifier) return 0;
1005 }
1006
John McCall68b6b872010-02-06 01:50:47 +00001007 // If we're instantiating a local function declaration, put the result
1008 // in the owner; otherwise we need to find the instantiated context.
1009 DeclContext *DC;
1010 if (D->getDeclContext()->isFunctionOrMethod())
1011 DC = Owner;
John McCalld325daa2010-03-26 04:53:08 +00001012 else if (isFriend && Qualifier) {
1013 CXXScopeSpec SS;
1014 SS.setScopeRep(Qualifier);
1015 SS.setRange(D->getQualifierRange());
1016 DC = SemaRef.computeDeclContext(SS);
1017 if (!DC) return 0;
1018 } else {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001019 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
1020 TemplateArgs);
John McCalld325daa2010-03-26 04:53:08 +00001021 }
John McCall68b6b872010-02-06 01:50:47 +00001022
John McCall02cace72009-08-28 07:59:38 +00001023 FunctionDecl *Function =
Mike Stump1eb44332009-09-09 15:08:12 +00001024 FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
John McCall21ef0fa2010-03-11 09:03:00 +00001025 D->getDeclName(), T, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001026 D->getStorageClass(), D->getStorageClassAsWritten(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001027 D->isInlineSpecified(), D->hasWrittenPrototype());
John McCallb6217662010-03-15 10:12:16 +00001028
John McCalld325daa2010-03-26 04:53:08 +00001029 if (Qualifier)
1030 Function->setQualifierInfo(Qualifier, D->getQualifierRange());
John McCallb6217662010-03-15 10:12:16 +00001031
John McCallb1a56e72010-03-26 23:10:15 +00001032 DeclContext *LexicalDC = Owner;
1033 if (!isFriend && D->isOutOfLine()) {
1034 assert(D->getDeclContext()->isFileContext());
1035 LexicalDC = D->getDeclContext();
1036 }
1037
1038 Function->setLexicalDeclContext(LexicalDC);
Mike Stump1eb44332009-09-09 15:08:12 +00001039
Douglas Gregore53060f2009-06-25 22:08:12 +00001040 // Attach the parameters
1041 for (unsigned P = 0; P < Params.size(); ++P)
1042 Params[P]->setOwningFunction(Function);
Douglas Gregor838db382010-02-11 01:19:42 +00001043 Function->setParams(Params.data(), Params.size());
John McCall02cace72009-08-28 07:59:38 +00001044
Douglas Gregorac7c2c82010-05-17 16:38:00 +00001045 SourceLocation InstantiateAtPOI;
Douglas Gregora735b202009-10-13 14:39:41 +00001046 if (TemplateParams) {
1047 // Our resulting instantiation is actually a function template, since we
1048 // are substituting only the outer template parameters. For example, given
1049 //
1050 // template<typename T>
1051 // struct X {
1052 // template<typename U> friend void f(T, U);
1053 // };
1054 //
1055 // X<int> x;
1056 //
1057 // We are instantiating the friend function template "f" within X<int>,
1058 // which means substituting int for T, but leaving "f" as a friend function
1059 // template.
1060 // Build the function template itself.
John McCalld325daa2010-03-26 04:53:08 +00001061 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
Douglas Gregora735b202009-10-13 14:39:41 +00001062 Function->getLocation(),
1063 Function->getDeclName(),
1064 TemplateParams, Function);
1065 Function->setDescribedFunctionTemplate(FunctionTemplate);
John McCallb1a56e72010-03-26 23:10:15 +00001066
1067 FunctionTemplate->setLexicalDeclContext(LexicalDC);
John McCalld325daa2010-03-26 04:53:08 +00001068
1069 if (isFriend && D->isThisDeclarationADefinition()) {
1070 // TODO: should we remember this connection regardless of whether
1071 // the friend declaration provided a body?
1072 FunctionTemplate->setInstantiatedFromMemberTemplate(
1073 D->getDescribedFunctionTemplate());
1074 }
Douglas Gregor66724ea2009-11-14 01:20:54 +00001075 } else if (FunctionTemplate) {
1076 // Record this function template specialization.
Douglas Gregor24bae922010-07-08 18:37:38 +00001077 std::pair<const TemplateArgument *, unsigned> Innermost
1078 = TemplateArgs.getInnermost();
Douglas Gregor838db382010-02-11 01:19:42 +00001079 Function->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor24bae922010-07-08 18:37:38 +00001080 new (SemaRef.Context) TemplateArgumentList(SemaRef.Context,
1081 Innermost.first,
1082 Innermost.second),
Douglas Gregor66724ea2009-11-14 01:20:54 +00001083 InsertPos);
John McCalld325daa2010-03-26 04:53:08 +00001084 } else if (isFriend && D->isThisDeclarationADefinition()) {
1085 // TODO: should we remember this connection regardless of whether
1086 // the friend declaration provided a body?
1087 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
John McCall02cace72009-08-28 07:59:38 +00001088 }
Douglas Gregora735b202009-10-13 14:39:41 +00001089
Douglas Gregore53060f2009-06-25 22:08:12 +00001090 if (InitFunctionInstantiation(Function, D))
1091 Function->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001092
Douglas Gregore53060f2009-06-25 22:08:12 +00001093 bool Redeclaration = false;
1094 bool OverloadableAttrRequired = false;
John McCallaf2094e2010-04-08 09:05:18 +00001095 bool isExplicitSpecialization = false;
Douglas Gregora735b202009-10-13 14:39:41 +00001096
John McCall68263142009-11-18 22:49:29 +00001097 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
1098 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
1099
John McCallaf2094e2010-04-08 09:05:18 +00001100 if (DependentFunctionTemplateSpecializationInfo *Info
1101 = D->getDependentSpecializationInfo()) {
1102 assert(isFriend && "non-friend has dependent specialization info?");
1103
1104 // This needs to be set now for future sanity.
1105 Function->setObjectOfFriendDecl(/*HasPrevious*/ true);
1106
1107 // Instantiate the explicit template arguments.
1108 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1109 Info->getRAngleLoc());
1110 for (unsigned I = 0, E = Info->getNumTemplateArgs(); I != E; ++I) {
1111 TemplateArgumentLoc Loc;
1112 if (SemaRef.Subst(Info->getTemplateArg(I), Loc, TemplateArgs))
1113 return 0;
1114
1115 ExplicitArgs.addArgument(Loc);
1116 }
1117
1118 // Map the candidate templates to their instantiations.
1119 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1120 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1121 Info->getTemplate(I),
1122 TemplateArgs);
1123 if (!Temp) return 0;
1124
1125 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1126 }
1127
1128 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1129 &ExplicitArgs,
1130 Previous))
1131 Function->setInvalidDecl();
1132
1133 isExplicitSpecialization = true;
1134
1135 } else if (TemplateParams || !FunctionTemplate) {
Douglas Gregora735b202009-10-13 14:39:41 +00001136 // Look only into the namespace where the friend would be declared to
1137 // find a previous declaration. This is the innermost enclosing namespace,
1138 // as described in ActOnFriendFunctionDecl.
John McCall68263142009-11-18 22:49:29 +00001139 SemaRef.LookupQualifiedName(Previous, DC);
Douglas Gregora735b202009-10-13 14:39:41 +00001140
Douglas Gregora735b202009-10-13 14:39:41 +00001141 // In C++, the previous declaration we find might be a tag type
1142 // (class or enum). In this case, the new declaration will hide the
1143 // tag type. Note that this does does not apply if we're declaring a
1144 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001145 if (Previous.isSingleTagDecl())
1146 Previous.clear();
Douglas Gregora735b202009-10-13 14:39:41 +00001147 }
1148
John McCall9f54ad42009-12-10 09:41:52 +00001149 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
John McCallaf2094e2010-04-08 09:05:18 +00001150 isExplicitSpecialization, Redeclaration,
Douglas Gregore53060f2009-06-25 22:08:12 +00001151 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001152
John McCall76d32642010-04-24 01:30:58 +00001153 NamedDecl *PrincipalDecl = (TemplateParams
1154 ? cast<NamedDecl>(FunctionTemplate)
1155 : Function);
1156
Douglas Gregora735b202009-10-13 14:39:41 +00001157 // If the original function was part of a friend declaration,
1158 // inherit its namespace state and add it to the owner.
John McCalld325daa2010-03-26 04:53:08 +00001159 if (isFriend) {
John McCall68263142009-11-18 22:49:29 +00001160 NamedDecl *PrevDecl;
John McCall76d32642010-04-24 01:30:58 +00001161 if (TemplateParams)
Douglas Gregora735b202009-10-13 14:39:41 +00001162 PrevDecl = FunctionTemplate->getPreviousDeclaration();
John McCall76d32642010-04-24 01:30:58 +00001163 else
Douglas Gregora735b202009-10-13 14:39:41 +00001164 PrevDecl = Function->getPreviousDeclaration();
John McCall76d32642010-04-24 01:30:58 +00001165
1166 PrincipalDecl->setObjectOfFriendDecl(PrevDecl != 0);
1167 DC->makeDeclVisibleInContext(PrincipalDecl, /*Recoverable=*/ false);
Douglas Gregor238058c2010-05-18 05:45:02 +00001168
1169 if (!SemaRef.getLangOptions().CPlusPlus0x &&
1170 D->isThisDeclarationADefinition()) {
1171 // Check for a function body.
1172 const FunctionDecl *Definition = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001173 if (Function->hasBody(Definition) &&
Douglas Gregor238058c2010-05-18 05:45:02 +00001174 Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
1175 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1176 << Function->getDeclName();
1177 SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
1178 Function->setInvalidDecl();
1179 }
1180 // Check for redefinitions due to other instantiations of this or
1181 // a similar friend function.
1182 else for (FunctionDecl::redecl_iterator R = Function->redecls_begin(),
1183 REnd = Function->redecls_end();
1184 R != REnd; ++R) {
1185 if (*R != Function &&
1186 ((*R)->getFriendObjectKind() != Decl::FOK_None)) {
1187 if (const FunctionDecl *RPattern
1188 = (*R)->getTemplateInstantiationPattern())
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001189 if (RPattern->hasBody(RPattern)) {
Douglas Gregor238058c2010-05-18 05:45:02 +00001190 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1191 << Function->getDeclName();
1192 SemaRef.Diag((*R)->getLocation(), diag::note_previous_definition);
1193 Function->setInvalidDecl();
1194 break;
1195 }
1196 }
1197 }
1198 }
1199
Douglas Gregora735b202009-10-13 14:39:41 +00001200 }
1201
John McCall76d32642010-04-24 01:30:58 +00001202 if (Function->isOverloadedOperator() && !DC->isRecord() &&
1203 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1204 PrincipalDecl->setNonMemberOperator();
1205
Douglas Gregore53060f2009-06-25 22:08:12 +00001206 return Function;
1207}
1208
Douglas Gregord60e1052009-08-27 16:57:43 +00001209Decl *
1210TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
1211 TemplateParameterList *TemplateParams) {
Douglas Gregor6b906862009-08-21 00:16:32 +00001212 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1213 void *InsertPos = 0;
Douglas Gregord60e1052009-08-27 16:57:43 +00001214 if (FunctionTemplate && !TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +00001215 // We are creating a function template specialization from a function
1216 // template. Check whether there is already a function template
Douglas Gregord60e1052009-08-27 16:57:43 +00001217 // specialization for this particular set of template arguments.
Douglas Gregor24bae922010-07-08 18:37:38 +00001218 std::pair<const TemplateArgument *, unsigned> Innermost
1219 = TemplateArgs.getInnermost();
Mike Stump1eb44332009-09-09 15:08:12 +00001220
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001221 FunctionDecl *SpecFunc
1222 = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
1223 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001224
Douglas Gregor6b906862009-08-21 00:16:32 +00001225 // If we already have a function template specialization, return it.
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001226 if (SpecFunc)
1227 return SpecFunc;
Douglas Gregor6b906862009-08-21 00:16:32 +00001228 }
1229
John McCallb0cb0222010-03-27 05:57:59 +00001230 bool isFriend;
1231 if (FunctionTemplate)
1232 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1233 else
1234 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1235
Douglas Gregor79c22782010-01-16 20:21:20 +00001236 bool MergeWithParentScope = (TemplateParams != 0) ||
1237 !(isa<Decl>(Owner) &&
1238 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1239 Sema::LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Douglas Gregor48dd19b2009-05-14 21:44:34 +00001240
Douglas Gregor0ca20ac2009-05-29 18:27:38 +00001241 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall21ef0fa2010-03-11 09:03:00 +00001242 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
1243 TInfo = SubstFunctionType(D, Params);
1244 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001245 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +00001246 QualType T = TInfo->getType();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001247
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001248 // \brief If the type of this function is not *directly* a function
1249 // type, then we're instantiating the a function that was declared
1250 // via a typedef, e.g.,
1251 //
1252 // typedef int functype(int, int);
1253 // functype func;
1254 //
1255 // In this case, we'll just go instantiate the ParmVarDecls that we
1256 // synthesized in the method declaration.
1257 if (!isa<FunctionProtoType>(T)) {
1258 assert(!Params.size() && "Instantiating type could not yield parameters");
1259 for (unsigned I = 0, N = D->getNumParams(); I != N; ++I) {
1260 ParmVarDecl *P = SemaRef.SubstParmVarDecl(D->getParamDecl(I),
1261 TemplateArgs);
1262 if (!P)
1263 return 0;
1264
1265 Params.push_back(P);
1266 }
1267 }
1268
John McCallb0cb0222010-03-27 05:57:59 +00001269 NestedNameSpecifier *Qualifier = D->getQualifier();
1270 if (Qualifier) {
1271 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
1272 D->getQualifierRange(),
1273 TemplateArgs);
1274 if (!Qualifier) return 0;
1275 }
1276
1277 DeclContext *DC = Owner;
1278 if (isFriend) {
1279 if (Qualifier) {
1280 CXXScopeSpec SS;
1281 SS.setScopeRep(Qualifier);
1282 SS.setRange(D->getQualifierRange());
1283 DC = SemaRef.computeDeclContext(SS);
1284 } else {
1285 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1286 D->getDeclContext(),
1287 TemplateArgs);
1288 }
1289 if (!DC) return 0;
1290 }
1291
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001292 // Build the instantiated method declaration.
John McCallb0cb0222010-03-27 05:57:59 +00001293 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
Douglas Gregordec06662009-08-21 18:42:58 +00001294 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001295
Abramo Bagnara25777432010-08-11 22:01:17 +00001296 DeclarationNameInfo NameInfo
1297 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
Douglas Gregor17e32f32009-08-21 22:43:28 +00001298 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001299 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnara25777432010-08-11 22:01:17 +00001300 NameInfo, T, TInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00001301 Constructor->isExplicit(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001302 Constructor->isInlineSpecified(),
1303 false);
Douglas Gregor17e32f32009-08-21 22:43:28 +00001304 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001305 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnara25777432010-08-11 22:01:17 +00001306 NameInfo, T,
1307 Destructor->isInlineSpecified(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001308 false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001309 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001310 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
Abramo Bagnara25777432010-08-11 22:01:17 +00001311 NameInfo, T, TInfo,
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001312 Conversion->isInlineSpecified(),
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001313 Conversion->isExplicit());
Douglas Gregordec06662009-08-21 18:42:58 +00001314 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00001315 Method = CXXMethodDecl::Create(SemaRef.Context, Record,
1316 NameInfo, T, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001317 D->isStatic(),
1318 D->getStorageClassAsWritten(),
1319 D->isInlineSpecified());
Douglas Gregordec06662009-08-21 18:42:58 +00001320 }
Douglas Gregor6b906862009-08-21 00:16:32 +00001321
John McCallb0cb0222010-03-27 05:57:59 +00001322 if (Qualifier)
1323 Method->setQualifierInfo(Qualifier, D->getQualifierRange());
John McCallb6217662010-03-15 10:12:16 +00001324
Douglas Gregord60e1052009-08-27 16:57:43 +00001325 if (TemplateParams) {
1326 // Our resulting instantiation is actually a function template, since we
1327 // are substituting only the outer template parameters. For example, given
Mike Stump1eb44332009-09-09 15:08:12 +00001328 //
Douglas Gregord60e1052009-08-27 16:57:43 +00001329 // template<typename T>
1330 // struct X {
1331 // template<typename U> void f(T, U);
1332 // };
1333 //
1334 // X<int> x;
1335 //
1336 // We are instantiating the member template "f" within X<int>, which means
1337 // substituting int for T, but leaving "f" as a member function template.
1338 // Build the function template itself.
1339 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1340 Method->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001341 Method->getDeclName(),
Douglas Gregord60e1052009-08-27 16:57:43 +00001342 TemplateParams, Method);
John McCallb0cb0222010-03-27 05:57:59 +00001343 if (isFriend) {
1344 FunctionTemplate->setLexicalDeclContext(Owner);
1345 FunctionTemplate->setObjectOfFriendDecl(true);
1346 } else if (D->isOutOfLine())
Mike Stump1eb44332009-09-09 15:08:12 +00001347 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregord60e1052009-08-27 16:57:43 +00001348 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001349 } else if (FunctionTemplate) {
1350 // Record this function template specialization.
Douglas Gregor24bae922010-07-08 18:37:38 +00001351 std::pair<const TemplateArgument *, unsigned> Innermost
1352 = TemplateArgs.getInnermost();
Douglas Gregor838db382010-02-11 01:19:42 +00001353 Method->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor24bae922010-07-08 18:37:38 +00001354 new (SemaRef.Context) TemplateArgumentList(SemaRef.Context,
1355 Innermost.first,
1356 Innermost.second),
Douglas Gregor66724ea2009-11-14 01:20:54 +00001357 InsertPos);
John McCallb0cb0222010-03-27 05:57:59 +00001358 } else if (!isFriend) {
Douglas Gregor66724ea2009-11-14 01:20:54 +00001359 // Record that this is an instantiation of a member function.
Douglas Gregor2db32322009-10-07 23:56:10 +00001360 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001361 }
1362
Mike Stump1eb44332009-09-09 15:08:12 +00001363 // If we are instantiating a member function defined
Douglas Gregor7caa6822009-07-24 20:34:43 +00001364 // out-of-line, the instantiation will have the same lexical
1365 // context (which will be a namespace scope) as the template.
John McCallb0cb0222010-03-27 05:57:59 +00001366 if (isFriend) {
1367 Method->setLexicalDeclContext(Owner);
1368 Method->setObjectOfFriendDecl(true);
1369 } else if (D->isOutOfLine())
Douglas Gregor7caa6822009-07-24 20:34:43 +00001370 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00001371
Douglas Gregor5545e162009-03-24 00:38:23 +00001372 // Attach the parameters
1373 for (unsigned P = 0; P < Params.size(); ++P)
1374 Params[P]->setOwningFunction(Method);
Douglas Gregor838db382010-02-11 01:19:42 +00001375 Method->setParams(Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +00001376
1377 if (InitMethodInstantiation(Method, D))
1378 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001379
Abramo Bagnara25777432010-08-11 22:01:17 +00001380 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
1381 Sema::ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00001382
John McCallb0cb0222010-03-27 05:57:59 +00001383 if (!FunctionTemplate || TemplateParams || isFriend) {
1384 SemaRef.LookupQualifiedName(Previous, Record);
Mike Stump1eb44332009-09-09 15:08:12 +00001385
Douglas Gregordec06662009-08-21 18:42:58 +00001386 // In C++, the previous declaration we find might be a tag type
1387 // (class or enum). In this case, the new declaration will hide the
1388 // tag type. Note that this does does not apply if we're declaring a
1389 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001390 if (Previous.isSingleTagDecl())
1391 Previous.clear();
Douglas Gregordec06662009-08-21 18:42:58 +00001392 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001393
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001394 bool Redeclaration = false;
1395 bool OverloadableAttrRequired = false;
John McCall9f54ad42009-12-10 09:41:52 +00001396 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false, Redeclaration,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001397 /*FIXME:*/OverloadableAttrRequired);
1398
Douglas Gregor4ba31362009-12-01 17:24:26 +00001399 if (D->isPure())
1400 SemaRef.CheckPureMethod(Method, SourceRange());
1401
John McCall46460a62010-01-20 21:53:11 +00001402 Method->setAccess(D->getAccess());
1403
John McCallb0cb0222010-03-27 05:57:59 +00001404 if (FunctionTemplate) {
1405 // If there's a function template, let our caller handle it.
1406 } else if (Method->isInvalidDecl() && !Previous.empty()) {
1407 // Don't hide a (potentially) valid declaration with an invalid one.
1408 } else {
1409 NamedDecl *DeclToAdd = (TemplateParams
1410 ? cast<NamedDecl>(FunctionTemplate)
1411 : Method);
1412 if (isFriend)
1413 Record->makeDeclVisibleInContext(DeclToAdd);
1414 else
1415 Owner->addDecl(DeclToAdd);
1416 }
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001417
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001418 return Method;
1419}
1420
Douglas Gregor615c5d42009-03-24 16:43:20 +00001421Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +00001422 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +00001423}
1424
Douglas Gregor03b2b072009-03-24 00:15:49 +00001425Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001426 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +00001427}
1428
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001429Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001430 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001431}
1432
Douglas Gregor6477b692009-03-25 15:04:13 +00001433ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001434 return SemaRef.SubstParmVarDecl(D, TemplateArgs);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001435}
1436
John McCalle29ba202009-08-20 01:44:21 +00001437Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1438 TemplateTypeParmDecl *D) {
1439 // TODO: don't always clone when decls are refcounted.
Douglas Gregorefed5c82010-06-16 15:23:05 +00001440 const Type* T = D->getTypeForDecl();
1441 assert(T->isTemplateTypeParmType());
1442 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001443
John McCalle29ba202009-08-20 01:44:21 +00001444 TemplateTypeParmDecl *Inst =
1445 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregorefed5c82010-06-16 15:23:05 +00001446 TTPT->getDepth() - 1, TTPT->getIndex(),
1447 TTPT->getName(),
John McCalle29ba202009-08-20 01:44:21 +00001448 D->wasDeclaredWithTypename(),
1449 D->isParameterPack());
1450
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001451 if (D->hasDefaultArgument())
1452 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
John McCalle29ba202009-08-20 01:44:21 +00001453
Douglas Gregor550d9b22009-10-31 17:21:17 +00001454 // Introduce this template parameter's instantiation into the instantiation
1455 // scope.
1456 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1457
John McCalle29ba202009-08-20 01:44:21 +00001458 return Inst;
1459}
1460
Douglas Gregor33642df2009-10-23 23:25:44 +00001461Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1462 NonTypeTemplateParmDecl *D) {
1463 // Substitute into the type of the non-type template parameter.
1464 QualType T;
John McCalla93c9342009-12-07 02:54:59 +00001465 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor33642df2009-10-23 23:25:44 +00001466 if (DI) {
1467 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
1468 D->getDeclName());
1469 if (DI) T = DI->getType();
1470 } else {
1471 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
1472 D->getDeclName());
1473 DI = 0;
1474 }
1475 if (T.isNull())
1476 return 0;
1477
1478 // Check that this type is acceptable for a non-type template parameter.
1479 bool Invalid = false;
1480 T = SemaRef.CheckNonTypeTemplateParameterType(T, D->getLocation());
1481 if (T.isNull()) {
1482 T = SemaRef.Context.IntTy;
1483 Invalid = true;
1484 }
1485
1486 NonTypeTemplateParmDecl *Param
1487 = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1488 D->getDepth() - 1, D->getPosition(),
1489 D->getIdentifier(), T, DI);
1490 if (Invalid)
1491 Param->setInvalidDecl();
1492
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001493 Param->setDefaultArgument(D->getDefaultArgument(), false);
Douglas Gregor550d9b22009-10-31 17:21:17 +00001494
1495 // Introduce this template parameter's instantiation into the instantiation
1496 // scope.
1497 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor33642df2009-10-23 23:25:44 +00001498 return Param;
1499}
1500
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001501Decl *
Douglas Gregor9106ef72009-11-11 16:58:32 +00001502TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1503 TemplateTemplateParmDecl *D) {
1504 // Instantiate the template parameter list of the template template parameter.
1505 TemplateParameterList *TempParams = D->getTemplateParameters();
1506 TemplateParameterList *InstParams;
1507 {
1508 // Perform the actual substitution of template parameters within a new,
1509 // local instantiation scope.
1510 Sema::LocalInstantiationScope Scope(SemaRef);
1511 InstParams = SubstTemplateParams(TempParams);
1512 if (!InstParams)
1513 return NULL;
1514 }
1515
1516 // Build the template template parameter.
1517 TemplateTemplateParmDecl *Param
1518 = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1519 D->getDepth() - 1, D->getPosition(),
1520 D->getIdentifier(), InstParams);
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001521 Param->setDefaultArgument(D->getDefaultArgument(), false);
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001522
Douglas Gregor9106ef72009-11-11 16:58:32 +00001523 // Introduce this template parameter's instantiation into the instantiation
1524 // scope.
1525 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1526
1527 return Param;
1528}
1529
Douglas Gregor48c32a72009-11-17 06:07:40 +00001530Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1531 // Using directives are never dependent, so they require no explicit
1532
1533 UsingDirectiveDecl *Inst
1534 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1535 D->getNamespaceKeyLocation(),
1536 D->getQualifierRange(), D->getQualifier(),
1537 D->getIdentLocation(),
1538 D->getNominatedNamespace(),
1539 D->getCommonAncestor());
1540 Owner->addDecl(Inst);
1541 return Inst;
1542}
1543
John McCalled976492009-12-04 22:46:56 +00001544Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
1545 // The nested name specifier is non-dependent, so no transformation
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001546 // is required. The same holds for the name info.
1547 DeclarationNameInfo NameInfo = D->getNameInfo();
John McCalled976492009-12-04 22:46:56 +00001548
John McCall9f54ad42009-12-10 09:41:52 +00001549 // We only need to do redeclaration lookups if we're in a class
1550 // scope (in fact, it's not really even possible in non-class
1551 // scopes).
1552 bool CheckRedeclaration = Owner->isRecord();
1553
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001554 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
1555 Sema::ForRedeclaration);
John McCall9f54ad42009-12-10 09:41:52 +00001556
John McCalled976492009-12-04 22:46:56 +00001557 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
John McCalled976492009-12-04 22:46:56 +00001558 D->getNestedNameRange(),
1559 D->getUsingLocation(),
1560 D->getTargetNestedNameDecl(),
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001561 NameInfo,
John McCalled976492009-12-04 22:46:56 +00001562 D->isTypeName());
1563
1564 CXXScopeSpec SS;
1565 SS.setScopeRep(D->getTargetNestedNameDecl());
1566 SS.setRange(D->getNestedNameRange());
John McCall9f54ad42009-12-10 09:41:52 +00001567
1568 if (CheckRedeclaration) {
1569 Prev.setHideTags(false);
1570 SemaRef.LookupQualifiedName(Prev, Owner);
1571
1572 // Check for invalid redeclarations.
1573 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
1574 D->isTypeName(), SS,
1575 D->getLocation(), Prev))
1576 NewUD->setInvalidDecl();
1577
1578 }
1579
1580 if (!NewUD->isInvalidDecl() &&
1581 SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
John McCalled976492009-12-04 22:46:56 +00001582 D->getLocation()))
1583 NewUD->setInvalidDecl();
John McCall9f54ad42009-12-10 09:41:52 +00001584
John McCalled976492009-12-04 22:46:56 +00001585 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
1586 NewUD->setAccess(D->getAccess());
1587 Owner->addDecl(NewUD);
1588
John McCall9f54ad42009-12-10 09:41:52 +00001589 // Don't process the shadow decls for an invalid decl.
1590 if (NewUD->isInvalidDecl())
1591 return NewUD;
1592
John McCall323c3102009-12-22 22:26:37 +00001593 bool isFunctionScope = Owner->isFunctionOrMethod();
1594
John McCall9f54ad42009-12-10 09:41:52 +00001595 // Process the shadow decls.
1596 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
1597 I != E; ++I) {
1598 UsingShadowDecl *Shadow = *I;
1599 NamedDecl *InstTarget =
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001600 cast<NamedDecl>(SemaRef.FindInstantiatedDecl(Shadow->getLocation(),
1601 Shadow->getTargetDecl(),
John McCall9f54ad42009-12-10 09:41:52 +00001602 TemplateArgs));
1603
1604 if (CheckRedeclaration &&
1605 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
1606 continue;
1607
1608 UsingShadowDecl *InstShadow
1609 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
1610 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCall323c3102009-12-22 22:26:37 +00001611
1612 if (isFunctionScope)
1613 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall9f54ad42009-12-10 09:41:52 +00001614 }
John McCalled976492009-12-04 22:46:56 +00001615
1616 return NewUD;
1617}
1618
1619Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall9f54ad42009-12-10 09:41:52 +00001620 // Ignore these; we handle them in bulk when processing the UsingDecl.
1621 return 0;
John McCalled976492009-12-04 22:46:56 +00001622}
1623
John McCall7ba107a2009-11-18 02:36:19 +00001624Decl * TemplateDeclInstantiator
1625 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +00001626 NestedNameSpecifier *NNS =
1627 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1628 D->getTargetNestedNameRange(),
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001629 TemplateArgs);
1630 if (!NNS)
1631 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001632
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001633 CXXScopeSpec SS;
1634 SS.setRange(D->getTargetNestedNameRange());
1635 SS.setScopeRep(NNS);
Mike Stump1eb44332009-09-09 15:08:12 +00001636
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001637 // Since NameInfo refers to a typename, it cannot be a C++ special name.
1638 // Hence, no tranformation is required for it.
1639 DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001640 NamedDecl *UD =
John McCall9488ea12009-11-17 05:59:44 +00001641 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001642 D->getUsingLoc(), SS, NameInfo, 0,
John McCall7ba107a2009-11-18 02:36:19 +00001643 /*instantiation*/ true,
1644 /*typename*/ true, D->getTypenameLoc());
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001645 if (UD)
John McCalled976492009-12-04 22:46:56 +00001646 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1647
John McCall7ba107a2009-11-18 02:36:19 +00001648 return UD;
1649}
1650
1651Decl * TemplateDeclInstantiator
1652 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1653 NestedNameSpecifier *NNS =
1654 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1655 D->getTargetNestedNameRange(),
1656 TemplateArgs);
1657 if (!NNS)
1658 return 0;
1659
1660 CXXScopeSpec SS;
1661 SS.setRange(D->getTargetNestedNameRange());
1662 SS.setScopeRep(NNS);
1663
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001664 DeclarationNameInfo NameInfo
1665 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
1666
John McCall7ba107a2009-11-18 02:36:19 +00001667 NamedDecl *UD =
1668 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001669 D->getUsingLoc(), SS, NameInfo, 0,
John McCall7ba107a2009-11-18 02:36:19 +00001670 /*instantiation*/ true,
1671 /*typename*/ false, SourceLocation());
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001672 if (UD)
John McCalled976492009-12-04 22:46:56 +00001673 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1674
Anders Carlsson0d8df782009-08-29 19:37:28 +00001675 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001676}
1677
John McCallce3ff2b2009-08-25 22:02:44 +00001678Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001679 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +00001680 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor2fa98002010-02-16 19:28:15 +00001681 if (D->isInvalidDecl())
1682 return 0;
1683
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001684 return Instantiator.Visit(D);
1685}
1686
John McCalle29ba202009-08-20 01:44:21 +00001687/// \brief Instantiates a nested template parameter list in the current
1688/// instantiation context.
1689///
1690/// \param L The parameter list to instantiate
1691///
1692/// \returns NULL if there was an error
1693TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +00001694TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +00001695 // Get errors for all the parameters before bailing out.
1696 bool Invalid = false;
1697
1698 unsigned N = L->size();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001699 typedef llvm::SmallVector<NamedDecl *, 8> ParamVector;
John McCalle29ba202009-08-20 01:44:21 +00001700 ParamVector Params;
1701 Params.reserve(N);
1702 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
1703 PI != PE; ++PI) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001704 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCalle29ba202009-08-20 01:44:21 +00001705 Params.push_back(D);
Douglas Gregor9148c3f2009-11-11 19:13:48 +00001706 Invalid = Invalid || !D || D->isInvalidDecl();
John McCalle29ba202009-08-20 01:44:21 +00001707 }
1708
1709 // Clean up if we had an error.
Douglas Gregorff331c12010-07-25 18:17:45 +00001710 if (Invalid)
John McCalle29ba202009-08-20 01:44:21 +00001711 return NULL;
John McCalle29ba202009-08-20 01:44:21 +00001712
1713 TemplateParameterList *InstL
1714 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
1715 L->getLAngleLoc(), &Params.front(), N,
1716 L->getRAngleLoc());
1717 return InstL;
Mike Stump1eb44332009-09-09 15:08:12 +00001718}
John McCalle29ba202009-08-20 01:44:21 +00001719
Douglas Gregored9c0f92009-10-29 00:04:11 +00001720/// \brief Instantiate the declaration of a class template partial
1721/// specialization.
1722///
1723/// \param ClassTemplate the (instantiated) class template that is partially
1724// specialized by the instantiation of \p PartialSpec.
1725///
1726/// \param PartialSpec the (uninstantiated) class template partial
1727/// specialization that we are instantiating.
1728///
1729/// \returns true if there was an error, false otherwise.
1730bool
1731TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
1732 ClassTemplateDecl *ClassTemplate,
1733 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00001734 // Create a local instantiation scope for this class template partial
1735 // specialization, which will contain the instantiations of the template
1736 // parameters.
1737 Sema::LocalInstantiationScope Scope(SemaRef);
1738
Douglas Gregored9c0f92009-10-29 00:04:11 +00001739 // Substitute into the template parameters of the class template partial
1740 // specialization.
1741 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
1742 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1743 if (!InstParams)
1744 return true;
1745
1746 // Substitute into the template arguments of the class template partial
1747 // specialization.
John McCall833ca992009-10-29 08:12:44 +00001748 const TemplateArgumentLoc *PartialSpecTemplateArgs
1749 = PartialSpec->getTemplateArgsAsWritten();
1750 unsigned N = PartialSpec->getNumTemplateArgsAsWritten();
1751
John McCalld5532b62009-11-23 01:53:49 +00001752 TemplateArgumentListInfo InstTemplateArgs; // no angle locations
John McCall833ca992009-10-29 08:12:44 +00001753 for (unsigned I = 0; I != N; ++I) {
John McCalld5532b62009-11-23 01:53:49 +00001754 TemplateArgumentLoc Loc;
1755 if (SemaRef.Subst(PartialSpecTemplateArgs[I], Loc, TemplateArgs))
Douglas Gregored9c0f92009-10-29 00:04:11 +00001756 return true;
John McCalld5532b62009-11-23 01:53:49 +00001757 InstTemplateArgs.addArgument(Loc);
Douglas Gregored9c0f92009-10-29 00:04:11 +00001758 }
1759
1760
1761 // Check that the template argument list is well-formed for this
1762 // class template.
1763 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
1764 InstTemplateArgs.size());
1765 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
1766 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001767 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001768 false,
1769 Converted))
1770 return true;
1771
1772 // Figure out where to insert this class template partial specialization
1773 // in the member template's set of class template partial specializations.
Douglas Gregored9c0f92009-10-29 00:04:11 +00001774 void *InsertPos = 0;
1775 ClassTemplateSpecializationDecl *PrevDecl
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00001776 = ClassTemplate->findPartialSpecialization(Converted.getFlatArguments(),
1777 Converted.flatSize(), InsertPos);
Douglas Gregored9c0f92009-10-29 00:04:11 +00001778
1779 // Build the canonical type that describes the converted template
1780 // arguments of the class template partial specialization.
1781 QualType CanonType
1782 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
1783 Converted.getFlatArguments(),
1784 Converted.flatSize());
1785
1786 // Build the fully-sugared type for this class template
1787 // specialization as the user wrote in the specialization
1788 // itself. This means that we'll pretty-print the type retrieved
1789 // from the specialization's declaration the way that the user
1790 // actually wrote the specialization, rather than formatting the
1791 // name based on the "canonical" representation used to store the
1792 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00001793 TypeSourceInfo *WrittenTy
1794 = SemaRef.Context.getTemplateSpecializationTypeInfo(
1795 TemplateName(ClassTemplate),
1796 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001797 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001798 CanonType);
1799
1800 if (PrevDecl) {
1801 // We've already seen a partial specialization with the same template
1802 // parameters and template arguments. This can happen, for example, when
1803 // substituting the outer template arguments ends up causing two
1804 // class template partial specializations of a member class template
1805 // to have identical forms, e.g.,
1806 //
1807 // template<typename T, typename U>
1808 // struct Outer {
1809 // template<typename X, typename Y> struct Inner;
1810 // template<typename Y> struct Inner<T, Y>;
1811 // template<typename Y> struct Inner<U, Y>;
1812 // };
1813 //
1814 // Outer<int, int> outer; // error: the partial specializations of Inner
1815 // // have the same signature.
1816 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
1817 << WrittenTy;
1818 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
1819 << SemaRef.Context.getTypeDeclType(PrevDecl);
1820 return true;
1821 }
1822
1823
1824 // Create the class template partial specialization declaration.
1825 ClassTemplatePartialSpecializationDecl *InstPartialSpec
Douglas Gregor13c85772010-05-06 00:28:52 +00001826 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
1827 PartialSpec->getTagKind(),
1828 Owner,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001829 PartialSpec->getLocation(),
1830 InstParams,
1831 ClassTemplate,
1832 Converted,
John McCalld5532b62009-11-23 01:53:49 +00001833 InstTemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00001834 CanonType,
Douglas Gregordc60c1e2010-04-30 05:56:50 +00001835 0,
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00001836 ClassTemplate->getNextPartialSpecSequenceNumber());
John McCallb6217662010-03-15 10:12:16 +00001837 // Substitute the nested name specifier, if any.
1838 if (SubstQualifier(PartialSpec, InstPartialSpec))
1839 return 0;
1840
Douglas Gregored9c0f92009-10-29 00:04:11 +00001841 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001842 InstPartialSpec->setTypeAsWritten(WrittenTy);
1843
Douglas Gregored9c0f92009-10-29 00:04:11 +00001844 // Add this partial specialization to the set of class template partial
1845 // specializations.
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00001846 ClassTemplate->AddPartialSpecialization(InstPartialSpec, InsertPos);
Douglas Gregored9c0f92009-10-29 00:04:11 +00001847 return false;
1848}
1849
John McCall21ef0fa2010-03-11 09:03:00 +00001850TypeSourceInfo*
John McCallce3ff2b2009-08-25 22:02:44 +00001851TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +00001852 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
John McCall21ef0fa2010-03-11 09:03:00 +00001853 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
1854 assert(OldTInfo && "substituting function without type source info");
1855 assert(Params.empty() && "parameter vector is non-empty at start");
John McCall6cd3b9f2010-04-09 17:38:44 +00001856 TypeSourceInfo *NewTInfo
1857 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
1858 D->getTypeSpecStartLoc(),
1859 D->getDeclName());
John McCall21ef0fa2010-03-11 09:03:00 +00001860 if (!NewTInfo)
1861 return 0;
Douglas Gregor5545e162009-03-24 00:38:23 +00001862
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001863 if (NewTInfo != OldTInfo) {
1864 // Get parameters from the new type info.
Douglas Gregor895162d2010-04-30 18:55:50 +00001865 TypeLoc OldTL = OldTInfo->getTypeLoc();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00001866 if (FunctionProtoTypeLoc *OldProtoLoc
1867 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
1868 TypeLoc NewTL = NewTInfo->getTypeLoc();
1869 FunctionProtoTypeLoc *NewProtoLoc = cast<FunctionProtoTypeLoc>(&NewTL);
1870 assert(NewProtoLoc && "Missing prototype?");
1871 for (unsigned i = 0, i_end = NewProtoLoc->getNumArgs(); i != i_end; ++i) {
1872 // FIXME: Variadic templates will break this.
1873 Params.push_back(NewProtoLoc->getArg(i));
1874 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
Douglas Gregor895162d2010-04-30 18:55:50 +00001875 OldProtoLoc->getArg(i),
1876 NewProtoLoc->getArg(i));
Douglas Gregor6920cdc2010-05-03 15:32:18 +00001877 }
Douglas Gregor895162d2010-04-30 18:55:50 +00001878 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001879 } else {
1880 // The function type itself was not dependent and therefore no
1881 // substitution occurred. However, we still need to instantiate
1882 // the function parameters themselves.
1883 TypeLoc OldTL = OldTInfo->getTypeLoc();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00001884 if (FunctionProtoTypeLoc *OldProtoLoc
1885 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
1886 for (unsigned i = 0, i_end = OldProtoLoc->getNumArgs(); i != i_end; ++i) {
1887 ParmVarDecl *Parm = VisitParmVarDecl(OldProtoLoc->getArg(i));
1888 if (!Parm)
1889 return 0;
1890 Params.push_back(Parm);
1891 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001892 }
1893 }
John McCall21ef0fa2010-03-11 09:03:00 +00001894 return NewTInfo;
Douglas Gregor5545e162009-03-24 00:38:23 +00001895}
1896
Mike Stump1eb44332009-09-09 15:08:12 +00001897/// \brief Initializes the common fields of an instantiation function
Douglas Gregore53060f2009-06-25 22:08:12 +00001898/// declaration (New) from the corresponding fields of its template (Tmpl).
1899///
1900/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001901bool
1902TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregore53060f2009-06-25 22:08:12 +00001903 FunctionDecl *Tmpl) {
1904 if (Tmpl->isDeleted())
1905 New->setDeleted();
Mike Stump1eb44332009-09-09 15:08:12 +00001906
Douglas Gregorcca9e962009-07-01 22:01:06 +00001907 // If we are performing substituting explicitly-specified template arguments
1908 // or deduced template arguments into a function template and we reach this
1909 // point, we are now past the point where SFINAE applies and have committed
Mike Stump1eb44332009-09-09 15:08:12 +00001910 // to keeping the new function template specialization. We therefore
1911 // convert the active template instantiation for the function template
Douglas Gregorcca9e962009-07-01 22:01:06 +00001912 // into a template instantiation for this specific function template
1913 // specialization, which is not a SFINAE context, so that we diagnose any
1914 // further errors in the declaration itself.
1915 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
1916 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
1917 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
1918 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump1eb44332009-09-09 15:08:12 +00001919 if (FunctionTemplateDecl *FunTmpl
Douglas Gregorcca9e962009-07-01 22:01:06 +00001920 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001921 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorcca9e962009-07-01 22:01:06 +00001922 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +00001923 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001924 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
1925 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
Douglas Gregorf35f8282009-11-11 21:54:23 +00001926 --SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001927 }
1928 }
Mike Stump1eb44332009-09-09 15:08:12 +00001929
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00001930 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
1931 assert(Proto && "Function template without prototype?");
1932
1933 if (Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec() ||
1934 Proto->getNoReturnAttr()) {
1935 // The function has an exception specification or a "noreturn"
1936 // attribute. Substitute into each of the exception types.
1937 llvm::SmallVector<QualType, 4> Exceptions;
1938 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
1939 // FIXME: Poor location information!
1940 QualType T
1941 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
1942 New->getLocation(), New->getDeclName());
1943 if (T.isNull() ||
1944 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
1945 continue;
1946
1947 Exceptions.push_back(T);
1948 }
1949
1950 // Rebuild the function type
1951
1952 const FunctionProtoType *NewProto
1953 = New->getType()->getAs<FunctionProtoType>();
1954 assert(NewProto && "Template instantiation without function prototype?");
1955 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
1956 NewProto->arg_type_begin(),
1957 NewProto->getNumArgs(),
1958 NewProto->isVariadic(),
1959 NewProto->getTypeQuals(),
1960 Proto->hasExceptionSpec(),
1961 Proto->hasAnyExceptionSpec(),
1962 Exceptions.size(),
1963 Exceptions.data(),
Rafael Espindola264ba482010-03-30 20:24:48 +00001964 Proto->getExtInfo()));
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00001965 }
1966
John McCall1d8d1cc2010-08-01 02:01:53 +00001967 SemaRef.InstantiateAttrs(TemplateArgs, Tmpl, New);
Douglas Gregor7cf84d62010-06-15 17:05:35 +00001968
Douglas Gregore53060f2009-06-25 22:08:12 +00001969 return false;
1970}
1971
Douglas Gregor5545e162009-03-24 00:38:23 +00001972/// \brief Initializes common fields of an instantiated method
1973/// declaration (New) from the corresponding fields of its template
1974/// (Tmpl).
1975///
1976/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001977bool
1978TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor5545e162009-03-24 00:38:23 +00001979 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +00001980 if (InitFunctionInstantiation(New, Tmpl))
1981 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001982
Douglas Gregor5545e162009-03-24 00:38:23 +00001983 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
1984 New->setAccess(Tmpl->getAccess());
Fariborz Jahaniane7184df2009-12-03 18:44:40 +00001985 if (Tmpl->isVirtualAsWritten())
1986 Record->setMethodAsVirtual(New);
Douglas Gregor5545e162009-03-24 00:38:23 +00001987
1988 // FIXME: attributes
1989 // FIXME: New needs a pointer to Tmpl
1990 return false;
1991}
Douglas Gregora58861f2009-05-13 20:28:22 +00001992
1993/// \brief Instantiate the definition of the given function from its
1994/// template.
1995///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001996/// \param PointOfInstantiation the point at which the instantiation was
1997/// required. Note that this is not precisely a "point of instantiation"
1998/// for the function, but it's close.
1999///
Douglas Gregora58861f2009-05-13 20:28:22 +00002000/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002001/// function template specialization or member function of a class template
2002/// specialization.
2003///
2004/// \param Recursive if true, recursively instantiates any functions that
2005/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002006///
2007/// \param DefinitionRequired if true, then we are performing an explicit
2008/// instantiation where the body of the function is required. Complain if
2009/// there is no such body.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002010void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002011 FunctionDecl *Function,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002012 bool Recursive,
2013 bool DefinitionRequired) {
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00002014 if (Function->isInvalidDecl() || Function->hasBody())
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002015 return;
2016
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002017 // Never instantiate an explicit specialization.
2018 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
2019 return;
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00002020
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002021 // Find the function body that we'll be substituting.
Douglas Gregor3b846b62009-10-27 20:53:28 +00002022 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002023 Stmt *Pattern = 0;
2024 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002025 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002026
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002027 if (!Pattern) {
2028 if (DefinitionRequired) {
2029 if (Function->getPrimaryTemplate())
2030 Diag(PointOfInstantiation,
2031 diag::err_explicit_instantiation_undefined_func_template)
2032 << Function->getPrimaryTemplate();
2033 else
2034 Diag(PointOfInstantiation,
2035 diag::err_explicit_instantiation_undefined_member)
2036 << 1 << Function->getDeclName() << Function->getDeclContext();
2037
2038 if (PatternDecl)
2039 Diag(PatternDecl->getLocation(),
2040 diag::note_explicit_instantiation_here);
Douglas Gregorcfe833b2010-05-17 17:57:54 +00002041 Function->setInvalidDecl();
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002042 }
2043
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002044 return;
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002045 }
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002046
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002047 // C++0x [temp.explicit]p9:
2048 // Except for inline functions, other explicit instantiation declarations
Mike Stump1eb44332009-09-09 15:08:12 +00002049 // have the effect of suppressing the implicit instantiation of the entity
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002050 // to which they refer.
Mike Stump1eb44332009-09-09 15:08:12 +00002051 if (Function->getTemplateSpecializationKind()
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002052 == TSK_ExplicitInstantiationDeclaration &&
Douglas Gregor7ced9c82009-10-27 21:11:48 +00002053 !PatternDecl->isInlined())
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002054 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002055
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002056 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
2057 if (Inst)
Douglas Gregore7089b02010-05-03 23:29:10 +00002058 return;
2059
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002060 // If we're performing recursive template instantiation, create our own
2061 // queue of pending implicit instantiations that we will instantiate later,
2062 // while we're still within our own instantiation context.
2063 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
2064 if (Recursive)
2065 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002066
Douglas Gregor9679caf2010-05-12 17:27:19 +00002067 EnterExpressionEvaluationContext EvalContext(*this,
2068 Action::PotentiallyEvaluated);
John McCalld226f652010-08-21 09:40:31 +00002069 ActOnStartOfFunctionDef(0, Function);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002070
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002071 // Introduce a new scope where local variable instantiations will be
Douglas Gregor60406be2010-01-16 22:29:39 +00002072 // recorded, unless we're actually a member function within a local
2073 // class, in which case we need to merge our results with the parent
2074 // scope (of the enclosing function).
2075 bool MergeWithParentScope = false;
2076 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
2077 MergeWithParentScope = Rec->isLocalClass();
2078
2079 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +00002080
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002081 // Introduce the instantiated function parameters into the local
Peter Collingbourne8a6c0f12010-07-18 16:45:46 +00002082 // instantiation scope, and set the parameter names to those used
2083 // in the template.
2084 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
2085 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
2086 ParmVarDecl *FunctionParam = Function->getParamDecl(I);
2087 FunctionParam->setDeclName(PatternParam->getDeclName());
2088 Scope.InstantiatedLocal(PatternParam, FunctionParam);
2089 }
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002090
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002091 // Enter the scope of this instantiation. We don't use
2092 // PushDeclContext because we don't have a scope.
2093 DeclContext *PreviousContext = CurContext;
2094 CurContext = Function;
2095
Mike Stump1eb44332009-09-09 15:08:12 +00002096 MultiLevelTemplateArgumentList TemplateArgs =
Douglas Gregore7089b02010-05-03 23:29:10 +00002097 getTemplateInstantiationArgs(Function, 0, false, PatternDecl);
Anders Carlsson09025312009-08-29 05:16:22 +00002098
2099 // If this is a constructor, instantiate the member initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00002100 if (const CXXConstructorDecl *Ctor =
Anders Carlsson09025312009-08-29 05:16:22 +00002101 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
2102 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
2103 TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002104 }
2105
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002106 // Instantiate the function body.
John McCall60d7b3a2010-08-24 06:29:42 +00002107 StmtResult Body = SubstStmt(Pattern, TemplateArgs);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002108
Douglas Gregor52604ab2009-09-11 21:19:12 +00002109 if (Body.isInvalid())
2110 Function->setInvalidDecl();
2111
John McCall9ae2f072010-08-23 23:25:46 +00002112 ActOnFinishFunctionBody(Function, Body.get(),
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002113 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002114
John McCall0c01d182010-03-24 05:22:00 +00002115 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
2116
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002117 CurContext = PreviousContext;
Douglas Gregoraba43bb2009-05-26 20:50:29 +00002118
2119 DeclGroupRef DG(Function);
2120 Consumer.HandleTopLevelDecl(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00002121
Douglas Gregor60406be2010-01-16 22:29:39 +00002122 // This class may have local implicit instantiations that need to be
2123 // instantiation within this scope.
2124 PerformPendingImplicitInstantiations(/*LocalOnly=*/true);
2125 Scope.Exit();
2126
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002127 if (Recursive) {
2128 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002129 // instantiation of this template.
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002130 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002131
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002132 // Restore the set of pending implicit instantiations.
2133 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
2134 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002135}
2136
2137/// \brief Instantiate the definition of the given variable from its
2138/// template.
2139///
Douglas Gregor7caa6822009-07-24 20:34:43 +00002140/// \param PointOfInstantiation the point at which the instantiation was
2141/// required. Note that this is not precisely a "point of instantiation"
2142/// for the function, but it's close.
2143///
2144/// \param Var the already-instantiated declaration of a static member
2145/// variable of a class template specialization.
2146///
2147/// \param Recursive if true, recursively instantiates any functions that
2148/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002149///
2150/// \param DefinitionRequired if true, then we are performing an explicit
2151/// instantiation where an out-of-line definition of the member variable
2152/// is required. Complain if there is no such definition.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002153void Sema::InstantiateStaticDataMemberDefinition(
2154 SourceLocation PointOfInstantiation,
2155 VarDecl *Var,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002156 bool Recursive,
2157 bool DefinitionRequired) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002158 if (Var->isInvalidDecl())
2159 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002160
Douglas Gregor7caa6822009-07-24 20:34:43 +00002161 // Find the out-of-line definition of this static data member.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002162 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregor7caa6822009-07-24 20:34:43 +00002163 assert(Def && "This data member was not instantiated from a template?");
Douglas Gregor0d035142009-10-27 18:42:08 +00002164 assert(Def->isStaticDataMember() && "Not a static data member?");
2165 Def = Def->getOutOfLineDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00002166
Douglas Gregor0d035142009-10-27 18:42:08 +00002167 if (!Def) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002168 // We did not find an out-of-line definition of this static data member,
2169 // so we won't perform any instantiation. Rather, we rely on the user to
Mike Stump1eb44332009-09-09 15:08:12 +00002170 // instantiate this definition (or provide a specialization for it) in
2171 // another translation unit.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002172 if (DefinitionRequired) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002173 Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002174 Diag(PointOfInstantiation,
2175 diag::err_explicit_instantiation_undefined_member)
2176 << 2 << Var->getDeclName() << Var->getDeclContext();
2177 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
2178 }
2179
Douglas Gregor7caa6822009-07-24 20:34:43 +00002180 return;
2181 }
2182
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002183 // Never instantiate an explicit specialization.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002184 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002185 return;
2186
2187 // C++0x [temp.explicit]p9:
2188 // Except for inline functions, other explicit instantiation declarations
2189 // have the effect of suppressing the implicit instantiation of the entity
2190 // to which they refer.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002191 if (Var->getTemplateSpecializationKind()
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002192 == TSK_ExplicitInstantiationDeclaration)
2193 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002194
Douglas Gregor7caa6822009-07-24 20:34:43 +00002195 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
2196 if (Inst)
2197 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002198
Douglas Gregor7caa6822009-07-24 20:34:43 +00002199 // If we're performing recursive template instantiation, create our own
2200 // queue of pending implicit instantiations that we will instantiate later,
2201 // while we're still within our own instantiation context.
2202 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
2203 if (Recursive)
2204 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002205
Douglas Gregor7caa6822009-07-24 20:34:43 +00002206 // Enter the scope of this instantiation. We don't use
2207 // PushDeclContext because we don't have a scope.
2208 DeclContext *PreviousContext = CurContext;
2209 CurContext = Var->getDeclContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002210
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002211 VarDecl *OldVar = Var;
John McCallce3ff2b2009-08-25 22:02:44 +00002212 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Douglas Gregor7caa6822009-07-24 20:34:43 +00002213 getTemplateInstantiationArgs(Var)));
Douglas Gregor7caa6822009-07-24 20:34:43 +00002214 CurContext = PreviousContext;
2215
2216 if (Var) {
Douglas Gregor583f33b2009-10-15 18:07:02 +00002217 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
2218 assert(MSInfo && "Missing member specialization information?");
2219 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
2220 MSInfo->getPointOfInstantiation());
Douglas Gregor7caa6822009-07-24 20:34:43 +00002221 DeclGroupRef DG(Var);
2222 Consumer.HandleTopLevelDecl(DG);
2223 }
Mike Stump1eb44332009-09-09 15:08:12 +00002224
Douglas Gregor7caa6822009-07-24 20:34:43 +00002225 if (Recursive) {
2226 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002227 // instantiation of this template.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002228 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002229
Douglas Gregor7caa6822009-07-24 20:34:43 +00002230 // Restore the set of pending implicit instantiations.
2231 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002232 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002233}
Douglas Gregor815215d2009-05-27 05:35:12 +00002234
Anders Carlsson09025312009-08-29 05:16:22 +00002235void
2236Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
2237 const CXXConstructorDecl *Tmpl,
2238 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00002239
Anders Carlsson09025312009-08-29 05:16:22 +00002240 llvm::SmallVector<MemInitTy*, 4> NewInits;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002241 bool AnyErrors = false;
2242
Anders Carlsson09025312009-08-29 05:16:22 +00002243 // Instantiate all the initializers.
2244 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00002245 InitsEnd = Tmpl->init_end();
2246 Inits != InitsEnd; ++Inits) {
Anders Carlsson09025312009-08-29 05:16:22 +00002247 CXXBaseOrMemberInitializer *Init = *Inits;
2248
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002249 SourceLocation LParenLoc, RParenLoc;
John McCallca0408f2010-08-23 06:44:23 +00002250 ASTOwningVector<Expr*> NewArgs(*this);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002251 llvm::SmallVector<SourceLocation, 4> CommaLocs;
Mike Stump1eb44332009-09-09 15:08:12 +00002252
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002253 // Instantiate the initializer.
2254 if (InstantiateInitializer(*this, Init->getInit(), TemplateArgs,
2255 LParenLoc, CommaLocs, NewArgs, RParenLoc)) {
2256 AnyErrors = true;
2257 continue;
Anders Carlsson09025312009-08-29 05:16:22 +00002258 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002259
Anders Carlsson09025312009-08-29 05:16:22 +00002260 MemInitResult NewInit;
Anders Carlsson09025312009-08-29 05:16:22 +00002261 if (Init->isBaseInitializer()) {
John McCalla93c9342009-12-07 02:54:59 +00002262 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002263 TemplateArgs,
2264 Init->getSourceLocation(),
2265 New->getDeclName());
John McCalla93c9342009-12-07 02:54:59 +00002266 if (!BaseTInfo) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002267 AnyErrors = true;
Douglas Gregor802ab452009-12-02 22:36:29 +00002268 New->setInvalidDecl();
2269 continue;
2270 }
2271
John McCalla93c9342009-12-07 02:54:59 +00002272 NewInit = BuildBaseInitializer(BaseTInfo->getType(), BaseTInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00002273 (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00002274 NewArgs.size(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002275 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00002276 Init->getRParenLoc(),
2277 New->getParent());
2278 } else if (Init->isMemberInitializer()) {
Anders Carlsson9988d5d2009-09-01 04:31:02 +00002279 FieldDecl *Member;
Mike Stump1eb44332009-09-09 15:08:12 +00002280
Anders Carlsson9988d5d2009-09-01 04:31:02 +00002281 // Is this an anonymous union?
2282 if (FieldDecl *UnionInit = Init->getAnonUnionMember())
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002283 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMemberLocation(),
2284 UnionInit, TemplateArgs));
Anders Carlsson9988d5d2009-09-01 04:31:02 +00002285 else
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002286 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMemberLocation(),
2287 Init->getMember(),
Douglas Gregore95b4092009-09-16 18:34:49 +00002288 TemplateArgs));
Mike Stump1eb44332009-09-09 15:08:12 +00002289
2290 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00002291 NewArgs.size(),
2292 Init->getSourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002293 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00002294 Init->getRParenLoc());
2295 }
2296
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002297 if (NewInit.isInvalid()) {
2298 AnyErrors = true;
Anders Carlsson09025312009-08-29 05:16:22 +00002299 New->setInvalidDecl();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002300 } else {
Anders Carlsson09025312009-08-29 05:16:22 +00002301 // FIXME: It would be nice if ASTOwningVector had a release function.
2302 NewArgs.take();
Mike Stump1eb44332009-09-09 15:08:12 +00002303
Anders Carlsson09025312009-08-29 05:16:22 +00002304 NewInits.push_back((MemInitTy *)NewInit.get());
2305 }
2306 }
Mike Stump1eb44332009-09-09 15:08:12 +00002307
Anders Carlsson09025312009-08-29 05:16:22 +00002308 // Assign all the initializers to the new constructor.
John McCalld226f652010-08-21 09:40:31 +00002309 ActOnMemInitializers(New,
Anders Carlsson09025312009-08-29 05:16:22 +00002310 /*FIXME: ColonLoc */
2311 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002312 NewInits.data(), NewInits.size(),
2313 AnyErrors);
Anders Carlsson09025312009-08-29 05:16:22 +00002314}
2315
John McCall52a575a2009-08-29 08:11:13 +00002316// TODO: this could be templated if the various decl types used the
2317// same method name.
2318static bool isInstantiationOf(ClassTemplateDecl *Pattern,
2319 ClassTemplateDecl *Instance) {
2320 Pattern = Pattern->getCanonicalDecl();
2321
2322 do {
2323 Instance = Instance->getCanonicalDecl();
2324 if (Pattern == Instance) return true;
2325 Instance = Instance->getInstantiatedFromMemberTemplate();
2326 } while (Instance);
2327
2328 return false;
2329}
2330
Douglas Gregor0d696532009-09-28 06:34:35 +00002331static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
2332 FunctionTemplateDecl *Instance) {
2333 Pattern = Pattern->getCanonicalDecl();
2334
2335 do {
2336 Instance = Instance->getCanonicalDecl();
2337 if (Pattern == Instance) return true;
2338 Instance = Instance->getInstantiatedFromMemberTemplate();
2339 } while (Instance);
2340
2341 return false;
2342}
2343
Douglas Gregored9c0f92009-10-29 00:04:11 +00002344static bool
2345isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
2346 ClassTemplatePartialSpecializationDecl *Instance) {
2347 Pattern
2348 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
2349 do {
2350 Instance = cast<ClassTemplatePartialSpecializationDecl>(
2351 Instance->getCanonicalDecl());
2352 if (Pattern == Instance)
2353 return true;
2354 Instance = Instance->getInstantiatedFromMember();
2355 } while (Instance);
2356
2357 return false;
2358}
2359
John McCall52a575a2009-08-29 08:11:13 +00002360static bool isInstantiationOf(CXXRecordDecl *Pattern,
2361 CXXRecordDecl *Instance) {
2362 Pattern = Pattern->getCanonicalDecl();
2363
2364 do {
2365 Instance = Instance->getCanonicalDecl();
2366 if (Pattern == Instance) return true;
2367 Instance = Instance->getInstantiatedFromMemberClass();
2368 } while (Instance);
2369
2370 return false;
2371}
2372
2373static bool isInstantiationOf(FunctionDecl *Pattern,
2374 FunctionDecl *Instance) {
2375 Pattern = Pattern->getCanonicalDecl();
2376
2377 do {
2378 Instance = Instance->getCanonicalDecl();
2379 if (Pattern == Instance) return true;
2380 Instance = Instance->getInstantiatedFromMemberFunction();
2381 } while (Instance);
2382
2383 return false;
2384}
2385
2386static bool isInstantiationOf(EnumDecl *Pattern,
2387 EnumDecl *Instance) {
2388 Pattern = Pattern->getCanonicalDecl();
2389
2390 do {
2391 Instance = Instance->getCanonicalDecl();
2392 if (Pattern == Instance) return true;
2393 Instance = Instance->getInstantiatedFromMemberEnum();
2394 } while (Instance);
2395
2396 return false;
2397}
2398
John McCalled976492009-12-04 22:46:56 +00002399static bool isInstantiationOf(UsingShadowDecl *Pattern,
2400 UsingShadowDecl *Instance,
2401 ASTContext &C) {
2402 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
2403}
2404
2405static bool isInstantiationOf(UsingDecl *Pattern,
2406 UsingDecl *Instance,
2407 ASTContext &C) {
2408 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
2409}
2410
John McCall7ba107a2009-11-18 02:36:19 +00002411static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
2412 UsingDecl *Instance,
2413 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002414 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCall7ba107a2009-11-18 02:36:19 +00002415}
2416
2417static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson0d8df782009-08-29 19:37:28 +00002418 UsingDecl *Instance,
2419 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002420 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00002421}
2422
John McCall52a575a2009-08-29 08:11:13 +00002423static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
2424 VarDecl *Instance) {
2425 assert(Instance->isStaticDataMember());
2426
2427 Pattern = Pattern->getCanonicalDecl();
2428
2429 do {
2430 Instance = Instance->getCanonicalDecl();
2431 if (Pattern == Instance) return true;
2432 Instance = Instance->getInstantiatedFromStaticDataMember();
2433 } while (Instance);
2434
2435 return false;
2436}
2437
John McCalled976492009-12-04 22:46:56 +00002438// Other is the prospective instantiation
2439// D is the prospective pattern
Douglas Gregor815215d2009-05-27 05:35:12 +00002440static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002441 if (D->getKind() != Other->getKind()) {
John McCall7ba107a2009-11-18 02:36:19 +00002442 if (UnresolvedUsingTypenameDecl *UUD
2443 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
2444 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2445 return isInstantiationOf(UUD, UD, Ctx);
2446 }
2447 }
2448
2449 if (UnresolvedUsingValueDecl *UUD
2450 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002451 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2452 return isInstantiationOf(UUD, UD, Ctx);
2453 }
2454 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002455
Anders Carlsson0d8df782009-08-29 19:37:28 +00002456 return false;
2457 }
Mike Stump1eb44332009-09-09 15:08:12 +00002458
John McCall52a575a2009-08-29 08:11:13 +00002459 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
2460 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00002461
John McCall52a575a2009-08-29 08:11:13 +00002462 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
2463 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00002464
John McCall52a575a2009-08-29 08:11:13 +00002465 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
2466 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00002467
Douglas Gregor7caa6822009-07-24 20:34:43 +00002468 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00002469 if (Var->isStaticDataMember())
2470 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
2471
2472 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
2473 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00002474
Douglas Gregor0d696532009-09-28 06:34:35 +00002475 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
2476 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
2477
Douglas Gregored9c0f92009-10-29 00:04:11 +00002478 if (ClassTemplatePartialSpecializationDecl *PartialSpec
2479 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
2480 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
2481 PartialSpec);
2482
Anders Carlssond8b285f2009-09-01 04:26:58 +00002483 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
2484 if (!Field->getDeclName()) {
2485 // This is an unnamed field.
Mike Stump1eb44332009-09-09 15:08:12 +00002486 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlssond8b285f2009-09-01 04:26:58 +00002487 cast<FieldDecl>(D);
2488 }
2489 }
Mike Stump1eb44332009-09-09 15:08:12 +00002490
John McCalled976492009-12-04 22:46:56 +00002491 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
2492 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
2493
2494 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
2495 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
2496
Douglas Gregor815215d2009-05-27 05:35:12 +00002497 return D->getDeclName() && isa<NamedDecl>(Other) &&
2498 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
2499}
2500
2501template<typename ForwardIterator>
Mike Stump1eb44332009-09-09 15:08:12 +00002502static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor815215d2009-05-27 05:35:12 +00002503 NamedDecl *D,
2504 ForwardIterator first,
2505 ForwardIterator last) {
2506 for (; first != last; ++first)
2507 if (isInstantiationOf(Ctx, D, *first))
2508 return cast<NamedDecl>(*first);
2509
2510 return 0;
2511}
2512
John McCall02cace72009-08-28 07:59:38 +00002513/// \brief Finds the instantiation of the given declaration context
2514/// within the current instantiation.
2515///
2516/// \returns NULL if there was an error
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002517DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
Douglas Gregore95b4092009-09-16 18:34:49 +00002518 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCall02cace72009-08-28 07:59:38 +00002519 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002520 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +00002521 return cast_or_null<DeclContext>(ID);
2522 } else return DC;
2523}
2524
Douglas Gregored961e72009-05-27 17:54:46 +00002525/// \brief Find the instantiation of the given declaration within the
2526/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00002527///
2528/// This routine is intended to be used when \p D is a declaration
2529/// referenced from within a template, that needs to mapped into the
2530/// corresponding declaration within an instantiation. For example,
2531/// given:
2532///
2533/// \code
2534/// template<typename T>
2535/// struct X {
2536/// enum Kind {
2537/// KnownValue = sizeof(T)
2538/// };
2539///
2540/// bool getKind() const { return KnownValue; }
2541/// };
2542///
2543/// template struct X<int>;
2544/// \endcode
2545///
2546/// In the instantiation of X<int>::getKind(), we need to map the
2547/// EnumConstantDecl for KnownValue (which refers to
2548/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00002549/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
2550/// this mapping from within the instantiation of X<int>.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002551NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
Douglas Gregore95b4092009-09-16 18:34:49 +00002552 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor815215d2009-05-27 05:35:12 +00002553 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor550d9b22009-10-31 17:21:17 +00002554 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
Douglas Gregor6d3e6272010-02-05 19:54:12 +00002555 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
John McCall76672452010-08-19 23:06:02 +00002556 (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext())) {
Douglas Gregor2bba76b2009-05-27 17:07:49 +00002557 // D is a local of some kind. Look into the map of local
2558 // declarations to their instantiations.
Fariborz Jahanian8dd0c562010-07-13 00:16:40 +00002559 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
Douglas Gregor2bba76b2009-05-27 17:07:49 +00002560 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002561
Douglas Gregore95b4092009-09-16 18:34:49 +00002562 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
2563 if (!Record->isDependentContext())
2564 return D;
2565
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002566 // If the RecordDecl is actually the injected-class-name or a
2567 // "templated" declaration for a class template, class template
2568 // partial specialization, or a member class of a class template,
2569 // substitute into the injected-class-name of the class template
2570 // or partial specialization to find the new DeclContext.
Douglas Gregore95b4092009-09-16 18:34:49 +00002571 QualType T;
2572 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
2573
2574 if (ClassTemplate) {
Douglas Gregor24bae922010-07-08 18:37:38 +00002575 T = ClassTemplate->getInjectedClassNameSpecialization();
Douglas Gregore95b4092009-09-16 18:34:49 +00002576 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2577 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
Douglas Gregore95b4092009-09-16 18:34:49 +00002578 ClassTemplate = PartialSpec->getSpecializedTemplate();
John McCall3cb0ebd2010-03-10 03:28:59 +00002579
2580 // If we call SubstType with an InjectedClassNameType here we
2581 // can end up in an infinite loop.
2582 T = Context.getTypeDeclType(Record);
2583 assert(isa<InjectedClassNameType>(T) &&
2584 "type of partial specialization is not an InjectedClassNameType");
John McCall31f17ec2010-04-27 00:57:59 +00002585 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
John McCall3cb0ebd2010-03-10 03:28:59 +00002586 }
Douglas Gregore95b4092009-09-16 18:34:49 +00002587
2588 if (!T.isNull()) {
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002589 // Substitute into the injected-class-name to get the type
2590 // corresponding to the instantiation we want, which may also be
2591 // the current instantiation (if we're in a template
2592 // definition). This substitution should never fail, since we
2593 // know we can instantiate the injected-class-name or we
2594 // wouldn't have gotten to the injected-class-name!
2595
2596 // FIXME: Can we use the CurrentInstantiationScope to avoid this
2597 // extra instantiation in the common case?
Douglas Gregore95b4092009-09-16 18:34:49 +00002598 T = SubstType(T, TemplateArgs, SourceLocation(), DeclarationName());
2599 assert(!T.isNull() && "Instantiation of injected-class-name cannot fail.");
2600
2601 if (!T->isDependentType()) {
2602 assert(T->isRecordType() && "Instantiation must produce a record type");
2603 return T->getAs<RecordType>()->getDecl();
2604 }
2605
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002606 // We are performing "partial" template instantiation to create
2607 // the member declarations for the members of a class template
2608 // specialization. Therefore, D is actually referring to something
2609 // in the current instantiation. Look through the current
2610 // context, which contains actual instantiations, to find the
2611 // instantiation of the "current instantiation" that D refers
2612 // to.
2613 bool SawNonDependentContext = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002614 for (DeclContext *DC = CurContext; !DC->isFileContext();
John McCall52a575a2009-08-29 08:11:13 +00002615 DC = DC->getParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002616 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002617 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Douglas Gregore95b4092009-09-16 18:34:49 +00002618 if (isInstantiationOf(ClassTemplate,
2619 Spec->getSpecializedTemplate()))
John McCall52a575a2009-08-29 08:11:13 +00002620 return Spec;
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002621
2622 if (!DC->isDependentContext())
2623 SawNonDependentContext = true;
John McCall52a575a2009-08-29 08:11:13 +00002624 }
2625
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002626 // We're performing "instantiation" of a member of the current
2627 // instantiation while we are type-checking the
2628 // definition. Compute the declaration context and return that.
2629 assert(!SawNonDependentContext &&
2630 "No dependent context while instantiating record");
2631 DeclContext *DC = computeDeclContext(T);
2632 assert(DC &&
John McCall52a575a2009-08-29 08:11:13 +00002633 "Unable to find declaration for the current instantiation");
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002634 return cast<CXXRecordDecl>(DC);
John McCall52a575a2009-08-29 08:11:13 +00002635 }
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002636
Douglas Gregore95b4092009-09-16 18:34:49 +00002637 // Fall through to deal with other dependent record types (e.g.,
2638 // anonymous unions in class templates).
2639 }
John McCall52a575a2009-08-29 08:11:13 +00002640
Douglas Gregore95b4092009-09-16 18:34:49 +00002641 if (!ParentDC->isDependentContext())
2642 return D;
2643
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002644 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002645 if (!ParentDC)
Douglas Gregor44c73842009-09-01 17:53:10 +00002646 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002647
Douglas Gregor815215d2009-05-27 05:35:12 +00002648 if (ParentDC != D->getDeclContext()) {
2649 // We performed some kind of instantiation in the parent context,
2650 // so now we need to look into the instantiated parent context to
2651 // find the instantiation of the declaration D.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002652
John McCall3cb0ebd2010-03-10 03:28:59 +00002653 // If our context used to be dependent, we may need to instantiate
2654 // it before performing lookup into that context.
2655 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002656 if (!Spec->isDependentContext()) {
2657 QualType T = Context.getTypeDeclType(Spec);
John McCall3cb0ebd2010-03-10 03:28:59 +00002658 const RecordType *Tag = T->getAs<RecordType>();
2659 assert(Tag && "type of non-dependent record is not a RecordType");
2660 if (!Tag->isBeingDefined() &&
2661 RequireCompleteType(Loc, T, diag::err_incomplete_type))
2662 return 0;
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002663 }
2664 }
2665
Douglas Gregor815215d2009-05-27 05:35:12 +00002666 NamedDecl *Result = 0;
2667 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002668 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00002669 Result = findInstantiationOf(Context, D, Found.first, Found.second);
2670 } else {
2671 // Since we don't have a name for the entity we're looking for,
2672 // our only option is to walk through all of the declarations to
2673 // find that name. This will occur in a few cases:
2674 //
2675 // - anonymous struct/union within a template
2676 // - unnamed class/struct/union/enum within a template
2677 //
2678 // FIXME: Find a better way to find these instantiations!
Mike Stump1eb44332009-09-09 15:08:12 +00002679 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002680 ParentDC->decls_begin(),
2681 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00002682 }
Mike Stump1eb44332009-09-09 15:08:12 +00002683
John McCall9f54ad42009-12-10 09:41:52 +00002684 // UsingShadowDecls can instantiate to nothing because of using hiding.
Douglas Gregor00225542010-03-01 18:27:54 +00002685 assert((Result || isa<UsingShadowDecl>(D) || D->isInvalidDecl() ||
2686 cast<Decl>(ParentDC)->isInvalidDecl())
John McCall9f54ad42009-12-10 09:41:52 +00002687 && "Unable to find instantiation of declaration!");
2688
Douglas Gregor815215d2009-05-27 05:35:12 +00002689 D = Result;
2690 }
2691
Douglas Gregor815215d2009-05-27 05:35:12 +00002692 return D;
2693}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002694
Mike Stump1eb44332009-09-09 15:08:12 +00002695/// \brief Performs template instantiation for all implicit template
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002696/// instantiations we have seen until this point.
Douglas Gregor60406be2010-01-16 22:29:39 +00002697void Sema::PerformPendingImplicitInstantiations(bool LocalOnly) {
2698 while (!PendingLocalImplicitInstantiations.empty() ||
2699 (!LocalOnly && !PendingImplicitInstantiations.empty())) {
2700 PendingImplicitInstantiation Inst;
2701
2702 if (PendingLocalImplicitInstantiations.empty()) {
2703 Inst = PendingImplicitInstantiations.front();
2704 PendingImplicitInstantiations.pop_front();
2705 } else {
2706 Inst = PendingLocalImplicitInstantiations.front();
2707 PendingLocalImplicitInstantiations.pop_front();
2708 }
Mike Stump1eb44332009-09-09 15:08:12 +00002709
Douglas Gregor7caa6822009-07-24 20:34:43 +00002710 // Instantiate function definitions
2711 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
John McCalld226f652010-08-21 09:40:31 +00002712 PrettyStackTraceActionsDecl CrashInfo(Function,
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002713 Function->getLocation(), *this,
2714 Context.getSourceManager(),
2715 "instantiating function definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002716
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00002717 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00002718 continue;
2719 }
Mike Stump1eb44332009-09-09 15:08:12 +00002720
Douglas Gregor7caa6822009-07-24 20:34:43 +00002721 // Instantiate static data member definitions.
2722 VarDecl *Var = cast<VarDecl>(Inst.first);
2723 assert(Var->isStaticDataMember() && "Not a static data member?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002724
Chandler Carruth291b4412010-02-13 10:17:50 +00002725 // Don't try to instantiate declarations if the most recent redeclaration
2726 // is invalid.
2727 if (Var->getMostRecentDeclaration()->isInvalidDecl())
2728 continue;
2729
2730 // Check if the most recent declaration has changed the specialization kind
2731 // and removed the need for implicit instantiation.
2732 switch (Var->getMostRecentDeclaration()->getTemplateSpecializationKind()) {
2733 case TSK_Undeclared:
2734 assert(false && "Cannot instantitiate an undeclared specialization.");
2735 case TSK_ExplicitInstantiationDeclaration:
2736 case TSK_ExplicitInstantiationDefinition:
2737 case TSK_ExplicitSpecialization:
2738 continue; // No longer need implicit instantiation.
2739 case TSK_ImplicitInstantiation:
2740 break;
2741 }
2742
John McCalld226f652010-08-21 09:40:31 +00002743 PrettyStackTraceActionsDecl CrashInfo(Var, Var->getLocation(), *this,
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002744 Context.getSourceManager(),
2745 "instantiating static data member "
2746 "definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002747
Douglas Gregor7caa6822009-07-24 20:34:43 +00002748 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002749 }
2750}
John McCall0c01d182010-03-24 05:22:00 +00002751
2752void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
2753 const MultiLevelTemplateArgumentList &TemplateArgs) {
2754 for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(),
2755 E = Pattern->ddiag_end(); I != E; ++I) {
2756 DependentDiagnostic *DD = *I;
2757
2758 switch (DD->getKind()) {
2759 case DependentDiagnostic::Access:
2760 HandleDependentAccessCheck(*DD, TemplateArgs);
2761 break;
2762 }
2763 }
2764}