blob: 8d5741df29f9222e5fdfea13a024e718d6590995 [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//===----------------------------------------------------------------------===/
12#include "Sema.h"
Douglas Gregoraba43bb2009-05-26 20:50:29 +000013#include "clang/AST/ASTConsumer.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000014#include "clang/AST/ASTContext.h"
15#include "clang/AST/DeclTemplate.h"
16#include "clang/AST/DeclVisitor.h"
17#include "clang/AST/Expr.h"
Anders Carlssonc17fb7b2009-09-01 05:12:24 +000018#include "clang/Basic/PrettyStackTrace.h"
Douglas Gregor83ddad32009-08-26 21:14:46 +000019#include "clang/Lex/Preprocessor.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000020#include "llvm/Support/Compiler.h"
21
22using namespace clang;
23
24namespace {
Mike Stump1eb44332009-09-09 15:08:12 +000025 class VISIBILITY_HIDDEN TemplateDeclInstantiator
Chris Lattnerb28317a2009-03-28 19:18:32 +000026 : public DeclVisitor<TemplateDeclInstantiator, Decl *> {
Douglas Gregor8dbc2692009-03-17 21:15:40 +000027 Sema &SemaRef;
28 DeclContext *Owner;
Douglas Gregord6350ae2009-08-28 20:31:08 +000029 const MultiLevelTemplateArgumentList &TemplateArgs;
Mike Stump1eb44332009-09-09 15:08:12 +000030
Anders Carlssond8fe2d52009-11-07 06:07:58 +000031 void InstantiateAttrs(Decl *Tmpl, Decl *New);
32
Douglas Gregor8dbc2692009-03-17 21:15:40 +000033 public:
34 typedef Sema::OwningExprResult OwningExprResult;
35
36 TemplateDeclInstantiator(Sema &SemaRef, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +000037 const MultiLevelTemplateArgumentList &TemplateArgs)
Douglas Gregor7e063902009-05-11 23:53:27 +000038 : SemaRef(SemaRef), Owner(Owner), TemplateArgs(TemplateArgs) { }
Mike Stump1eb44332009-09-09 15:08:12 +000039
Mike Stump390b4cc2009-05-16 07:39:55 +000040 // FIXME: Once we get closer to completion, replace these manually-written
41 // declarations with automatically-generated ones from
42 // clang/AST/DeclNodes.def.
Douglas Gregor4f722be2009-03-25 15:45:12 +000043 Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D);
44 Decl *VisitNamespaceDecl(NamespaceDecl *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);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000047 Decl *VisitFieldDecl(FieldDecl *D);
48 Decl *VisitStaticAssertDecl(StaticAssertDecl *D);
49 Decl *VisitEnumDecl(EnumDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000050 Decl *VisitEnumConstantDecl(EnumConstantDecl *D);
John McCall02cace72009-08-28 07:59:38 +000051 Decl *VisitFriendDecl(FriendDecl *D);
Douglas Gregora735b202009-10-13 14:39:41 +000052 Decl *VisitFunctionDecl(FunctionDecl *D,
53 TemplateParameterList *TemplateParams = 0);
Douglas Gregord475b8d2009-03-25 21:17:03 +000054 Decl *VisitCXXRecordDecl(CXXRecordDecl *D);
Douglas Gregord60e1052009-08-27 16:57:43 +000055 Decl *VisitCXXMethodDecl(CXXMethodDecl *D,
56 TemplateParameterList *TemplateParams = 0);
Douglas Gregor615c5d42009-03-24 16:43:20 +000057 Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
Douglas Gregor03b2b072009-03-24 00:15:49 +000058 Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +000059 Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000060 ParmVarDecl *VisitParmVarDecl(ParmVarDecl *D);
John McCalle29ba202009-08-20 01:44:21 +000061 Decl *VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor7974c3b2009-10-07 17:21:34 +000062 Decl *VisitClassTemplatePartialSpecializationDecl(
63 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregord60e1052009-08-27 16:57:43 +000064 Decl *VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
John McCalle29ba202009-08-20 01:44:21 +000065 Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Douglas Gregor33642df2009-10-23 23:25:44 +000066 Decl *VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregor9106ef72009-11-11 16:58:32 +000067 Decl *VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Douglas Gregor48c32a72009-11-17 06:07:40 +000068 Decl *VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
John McCall7ba107a2009-11-18 02:36:19 +000069 Decl *VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
70 Decl *VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Mike Stump1eb44332009-09-09 15:08:12 +000071
Douglas Gregor8dbc2692009-03-17 21:15:40 +000072 // Base case. FIXME: Remove once we can instantiate everything.
Douglas Gregor48c32a72009-11-17 06:07:40 +000073 Decl *VisitDecl(Decl *D) {
74 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
75 Diagnostic::Error,
76 "cannot instantiate %0 yet");
77 SemaRef.Diag(D->getLocation(), DiagID)
78 << D->getDeclKindName();
79
Douglas Gregor8dbc2692009-03-17 21:15:40 +000080 return 0;
81 }
Douglas Gregor5545e162009-03-24 00:38:23 +000082
John McCallfd810b12009-08-14 02:03:10 +000083 const LangOptions &getLangOptions() {
84 return SemaRef.getLangOptions();
85 }
86
Douglas Gregor5545e162009-03-24 00:38:23 +000087 // Helper functions for instantiating methods.
John McCallce3ff2b2009-08-25 22:02:44 +000088 QualType SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +000089 llvm::SmallVectorImpl<ParmVarDecl *> &Params);
Douglas Gregore53060f2009-06-25 22:08:12 +000090 bool InitFunctionInstantiation(FunctionDecl *New, FunctionDecl *Tmpl);
Douglas Gregor5545e162009-03-24 00:38:23 +000091 bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl);
John McCalle29ba202009-08-20 01:44:21 +000092
93 TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +000094 SubstTemplateParams(TemplateParameterList *List);
Douglas Gregored9c0f92009-10-29 00:04:11 +000095
96 bool InstantiateClassTemplatePartialSpecialization(
97 ClassTemplateDecl *ClassTemplate,
98 ClassTemplatePartialSpecializationDecl *PartialSpec);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000099 };
100}
101
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000102// FIXME: Is this too simple?
103void TemplateDeclInstantiator::InstantiateAttrs(Decl *Tmpl, Decl *New) {
104 for (const Attr *TmplAttr = Tmpl->getAttrs(); TmplAttr;
105 TmplAttr = TmplAttr->getNext()) {
106
107 // FIXME: Is cloning correct for all attributes?
108 Attr *NewAttr = TmplAttr->clone(SemaRef.Context);
109
110 New->addAttr(NewAttr);
111 }
112}
113
Douglas Gregor4f722be2009-03-25 15:45:12 +0000114Decl *
115TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
116 assert(false && "Translation units cannot be instantiated");
117 return D;
118}
119
120Decl *
121TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
122 assert(false && "Namespaces cannot be instantiated");
123 return D;
124}
125
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000126Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
127 bool Invalid = false;
John McCallba6a9bd2009-10-24 08:00:42 +0000128 DeclaratorInfo *DI = D->getTypeDeclaratorInfo();
129 if (DI->getType()->isDependentType()) {
130 DI = SemaRef.SubstType(DI, TemplateArgs,
131 D->getLocation(), D->getDeclName());
132 if (!DI) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000133 Invalid = true;
John McCallba6a9bd2009-10-24 08:00:42 +0000134 DI = SemaRef.Context.getTrivialDeclaratorInfo(SemaRef.Context.IntTy);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000135 }
136 }
Mike Stump1eb44332009-09-09 15:08:12 +0000137
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000138 // Create the new typedef
139 TypedefDecl *Typedef
140 = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(),
John McCallba6a9bd2009-10-24 08:00:42 +0000141 D->getIdentifier(), DI);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000142 if (Invalid)
143 Typedef->setInvalidDecl();
144
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000145 Owner->addDecl(Typedef);
Mike Stump1eb44332009-09-09 15:08:12 +0000146
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000147 return Typedef;
148}
149
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000150Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
John McCallce3ff2b2009-08-25 22:02:44 +0000151 // Do substitution on the type of the declaration
John McCall0a5fa062009-10-21 02:39:02 +0000152 DeclaratorInfo *DI = SemaRef.SubstType(D->getDeclaratorInfo(),
153 TemplateArgs,
154 D->getTypeSpecStartLoc(),
155 D->getDeclName());
156 if (!DI)
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000157 return 0;
158
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000159 // Build the instantiated declaration
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000160 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
161 D->getLocation(), D->getIdentifier(),
John McCall0a5fa062009-10-21 02:39:02 +0000162 DI->getType(), DI,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +0000163 D->getStorageClass());
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000164 Var->setThreadSpecified(D->isThreadSpecified());
165 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
166 Var->setDeclaredInCondition(D->isDeclaredInCondition());
Mike Stump1eb44332009-09-09 15:08:12 +0000167
168 // If we are instantiating a static data member defined
Douglas Gregor7caa6822009-07-24 20:34:43 +0000169 // out-of-line, the instantiation will have the same lexical
170 // context (which will be a namespace scope) as the template.
171 if (D->isOutOfLine())
172 Var->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000173
Mike Stump390b4cc2009-05-16 07:39:55 +0000174 // FIXME: In theory, we could have a previous declaration for variables that
175 // are not static data members.
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000176 bool Redeclaration = false;
Chris Lattnereaaebc72009-04-25 08:06:05 +0000177 SemaRef.CheckVariableDeclaration(Var, 0, Redeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +0000178
Douglas Gregor7caa6822009-07-24 20:34:43 +0000179 if (D->isOutOfLine()) {
180 D->getLexicalDeclContext()->addDecl(Var);
181 Owner->makeDeclVisibleInContext(Var);
182 } else {
183 Owner->addDecl(Var);
184 }
Mike Stump1eb44332009-09-09 15:08:12 +0000185
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000186 // Link instantiations of static data members back to the template from
187 // which they were instantiated.
188 if (Var->isStaticDataMember())
189 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D,
Douglas Gregorcf3293e2009-11-01 20:32:48 +0000190 TSK_ImplicitInstantiation);
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000191
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000192 if (D->getInit()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000193 OwningExprResult Init
John McCallce3ff2b2009-08-25 22:02:44 +0000194 = SemaRef.SubstExpr(D->getInit(), TemplateArgs);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000195 if (Init.isInvalid())
196 Var->setInvalidDecl();
Sebastian Redl42dddbe2009-11-08 10:16:43 +0000197 else if (!D->getType()->isDependentType() &&
198 !D->getInit()->isTypeDependent() &&
Douglas Gregore48319a2009-11-09 17:16:50 +0000199 !D->getInit()->isValueDependent()) {
Sebastian Redl42dddbe2009-11-08 10:16:43 +0000200 // If neither the declaration's type nor its initializer are dependent,
201 // we don't want to redo all the checking, especially since the
202 // initializer might have been wrapped by a CXXConstructExpr since we did
203 // it the first time.
204 Var->setInit(SemaRef.Context, Init.takeAs<Expr>());
205 }
Douglas Gregor83ddad32009-08-26 21:14:46 +0000206 else if (ParenListExpr *PLE = dyn_cast<ParenListExpr>((Expr *)Init.get())) {
Mike Stump1eb44332009-09-09 15:08:12 +0000207 // FIXME: We're faking all of the comma locations, which is suboptimal.
Douglas Gregor83ddad32009-08-26 21:14:46 +0000208 // Do we even need these comma locations?
209 llvm::SmallVector<SourceLocation, 4> FakeCommaLocs;
210 if (PLE->getNumExprs() > 0) {
211 FakeCommaLocs.reserve(PLE->getNumExprs() - 1);
212 for (unsigned I = 0, N = PLE->getNumExprs() - 1; I != N; ++I) {
213 Expr *E = PLE->getExpr(I)->Retain();
214 FakeCommaLocs.push_back(
215 SemaRef.PP.getLocForEndOfToken(E->getLocEnd()));
216 }
Douglas Gregore9f8eb62009-08-26 23:26:04 +0000217 PLE->getExpr(PLE->getNumExprs() - 1)->Retain();
Douglas Gregor83ddad32009-08-26 21:14:46 +0000218 }
Mike Stump1eb44332009-09-09 15:08:12 +0000219
Douglas Gregor83ddad32009-08-26 21:14:46 +0000220 // Add the direct initializer to the declaration.
221 SemaRef.AddCXXDirectInitializerToDecl(Sema::DeclPtrTy::make(Var),
Mike Stump1eb44332009-09-09 15:08:12 +0000222 PLE->getLParenLoc(),
Douglas Gregor83ddad32009-08-26 21:14:46 +0000223 Sema::MultiExprArg(SemaRef,
224 (void**)PLE->getExprs(),
225 PLE->getNumExprs()),
226 FakeCommaLocs.data(),
227 PLE->getRParenLoc());
Mike Stump1eb44332009-09-09 15:08:12 +0000228
Douglas Gregor83ddad32009-08-26 21:14:46 +0000229 // When Init is destroyed, it will destroy the instantiated ParenListExpr;
230 // we've explicitly retained all of its subexpressions already.
231 } else
Chris Lattnerb28317a2009-03-28 19:18:32 +0000232 SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var), move(Init),
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000233 D->hasCXXDirectInitializer());
Douglas Gregor65b90052009-07-27 17:43:39 +0000234 } else if (!Var->isStaticDataMember() || Var->isOutOfLine())
235 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000236
237 return Var;
238}
239
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000240Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
241 bool Invalid = false;
John McCall07fb6be2009-10-22 23:33:21 +0000242 DeclaratorInfo *DI = D->getDeclaratorInfo();
243 if (DI->getType()->isDependentType()) {
244 DI = SemaRef.SubstType(DI, TemplateArgs,
245 D->getLocation(), D->getDeclName());
246 if (!DI) {
247 DI = D->getDeclaratorInfo();
248 Invalid = true;
249 } else if (DI->getType()->isFunctionType()) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000250 // C++ [temp.arg.type]p3:
251 // If a declaration acquires a function type through a type
252 // dependent on a template-parameter and this causes a
253 // declaration that does not use the syntactic form of a
254 // function declarator to have function type, the program is
255 // ill-formed.
256 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
John McCall07fb6be2009-10-22 23:33:21 +0000257 << DI->getType();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000258 Invalid = true;
259 }
260 }
261
262 Expr *BitWidth = D->getBitWidth();
263 if (Invalid)
264 BitWidth = 0;
265 else if (BitWidth) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000266 // The bit-width expression is not potentially evaluated.
267 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000268
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000269 OwningExprResult InstantiatedBitWidth
John McCallce3ff2b2009-08-25 22:02:44 +0000270 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000271 if (InstantiatedBitWidth.isInvalid()) {
272 Invalid = true;
273 BitWidth = 0;
274 } else
Anders Carlssone9146f22009-05-01 19:49:17 +0000275 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000276 }
277
John McCall07fb6be2009-10-22 23:33:21 +0000278 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
279 DI->getType(), DI,
Mike Stump1eb44332009-09-09 15:08:12 +0000280 cast<RecordDecl>(Owner),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000281 D->getLocation(),
282 D->isMutable(),
283 BitWidth,
Steve Naroffea218b82009-07-14 14:58:18 +0000284 D->getTypeSpecStartLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000285 D->getAccess(),
286 0);
Douglas Gregor663b5a02009-10-14 20:14:33 +0000287 if (!Field) {
288 cast<Decl>(Owner)->setInvalidDecl();
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000289 return 0;
Douglas Gregor663b5a02009-10-14 20:14:33 +0000290 }
Mike Stump1eb44332009-09-09 15:08:12 +0000291
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000292 InstantiateAttrs(D, Field);
293
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000294 if (Invalid)
295 Field->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000296
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000297 if (!Field->getDeclName()) {
298 // Keep track of where this decl came from.
299 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000300 }
Mike Stump1eb44332009-09-09 15:08:12 +0000301
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000302 Field->setImplicit(D->isImplicit());
303 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000304
305 return Field;
306}
307
John McCall02cace72009-08-28 07:59:38 +0000308Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
309 FriendDecl::FriendUnion FU;
310
311 // Handle friend type expressions by simply substituting template
312 // parameters into the pattern type.
313 if (Type *Ty = D->getFriendType()) {
314 QualType T = SemaRef.SubstType(QualType(Ty,0), TemplateArgs,
315 D->getLocation(), DeclarationName());
316 if (T.isNull()) return 0;
317
318 assert(getLangOptions().CPlusPlus0x || T->isRecordType());
319 FU = T.getTypePtr();
320
321 // Handle everything else by appropriate substitution.
322 } else {
323 NamedDecl *ND = D->getFriendDecl();
324 assert(ND && "friend decl must be a decl or a type!");
325
Douglas Gregora735b202009-10-13 14:39:41 +0000326 // FIXME: We have a problem here, because the nested call to Visit(ND)
327 // will inject the thing that the friend references into the current
328 // owner, which is wrong.
John McCall02cace72009-08-28 07:59:38 +0000329 Decl *NewND = Visit(ND);
330 if (!NewND) return 0;
331
332 FU = cast<NamedDecl>(NewND);
John McCallfd810b12009-08-14 02:03:10 +0000333 }
Mike Stump1eb44332009-09-09 15:08:12 +0000334
John McCall02cace72009-08-28 07:59:38 +0000335 FriendDecl *FD =
336 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(), FU,
337 D->getFriendLoc());
John McCall5fee1102009-08-29 03:50:18 +0000338 FD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +0000339 Owner->addDecl(FD);
340 return FD;
John McCallfd810b12009-08-14 02:03:10 +0000341}
342
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000343Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
344 Expr *AssertExpr = D->getAssertExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000345
Douglas Gregorac7610d2009-06-22 20:57:11 +0000346 // The expression in a static assertion is not potentially evaluated.
347 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000348
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000349 OwningExprResult InstantiatedAssertExpr
John McCallce3ff2b2009-08-25 22:02:44 +0000350 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000351 if (InstantiatedAssertExpr.isInvalid())
352 return 0;
353
Douglas Gregor43d9d922009-08-08 01:41:12 +0000354 OwningExprResult Message(SemaRef, D->getMessage());
355 D->getMessage()->Retain();
Mike Stump1eb44332009-09-09 15:08:12 +0000356 Decl *StaticAssert
357 = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
Chris Lattnerb28317a2009-03-28 19:18:32 +0000358 move(InstantiatedAssertExpr),
359 move(Message)).getAs<Decl>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000360 return StaticAssert;
361}
362
363Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +0000364 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000365 D->getLocation(), D->getIdentifier(),
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000366 D->getTagKeywordLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000367 /*PrevDecl=*/0);
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000368 Enum->setInstantiationOfMemberEnum(D);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000369 Enum->setAccess(D->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000370 Owner->addDecl(Enum);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000371 Enum->startDefinition();
372
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000373 llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000374
375 EnumConstantDecl *LastEnumConst = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000376 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
377 ECEnd = D->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000378 EC != ECEnd; ++EC) {
379 // The specified value for the enumerator.
380 OwningExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000381 if (Expr *UninstValue = EC->getInitExpr()) {
382 // The enumerator's value expression is not potentially evaluated.
Mike Stump1eb44332009-09-09 15:08:12 +0000383 EnterExpressionEvaluationContext Unevaluated(SemaRef,
Douglas Gregorac7610d2009-06-22 20:57:11 +0000384 Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000385
John McCallce3ff2b2009-08-25 22:02:44 +0000386 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000387 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000388
389 // Drop the initial value and continue.
390 bool isInvalid = false;
391 if (Value.isInvalid()) {
392 Value = SemaRef.Owned((Expr *)0);
393 isInvalid = true;
394 }
395
Mike Stump1eb44332009-09-09 15:08:12 +0000396 EnumConstantDecl *EnumConst
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000397 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
398 EC->getLocation(), EC->getIdentifier(),
399 move(Value));
400
401 if (isInvalid) {
402 if (EnumConst)
403 EnumConst->setInvalidDecl();
404 Enum->setInvalidDecl();
405 }
406
407 if (EnumConst) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000408 Enum->addDecl(EnumConst);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000409 Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst));
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000410 LastEnumConst = EnumConst;
411 }
412 }
Mike Stump1eb44332009-09-09 15:08:12 +0000413
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000414 // FIXME: Fixup LBraceLoc and RBraceLoc
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000415 // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000416 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
417 Sema::DeclPtrTy::make(Enum),
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000418 &Enumerators[0], Enumerators.size(),
419 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000420
421 return Enum;
422}
423
Douglas Gregor6477b692009-03-25 15:04:13 +0000424Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
425 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
426 return 0;
427}
428
Douglas Gregored9c0f92009-10-29 00:04:11 +0000429namespace {
430 class SortDeclByLocation {
431 SourceManager &SourceMgr;
432
433 public:
434 explicit SortDeclByLocation(SourceManager &SourceMgr)
435 : SourceMgr(SourceMgr) { }
436
437 bool operator()(const Decl *X, const Decl *Y) const {
438 return SourceMgr.isBeforeInTranslationUnit(X->getLocation(),
439 Y->getLocation());
440 }
441 };
442}
443
John McCalle29ba202009-08-20 01:44:21 +0000444Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000445 // Create a local instantiation scope for this class template, which
446 // will contain the instantiations of the template parameters.
447 Sema::LocalInstantiationScope Scope(SemaRef);
John McCalle29ba202009-08-20 01:44:21 +0000448 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000449 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000450 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000451 return NULL;
John McCalle29ba202009-08-20 01:44:21 +0000452
453 CXXRecordDecl *Pattern = D->getTemplatedDecl();
454 CXXRecordDecl *RecordInst
455 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), Owner,
456 Pattern->getLocation(), Pattern->getIdentifier(),
Douglas Gregorf0510d42009-10-12 23:11:44 +0000457 Pattern->getTagKeywordLoc(), /*PrevDecl=*/ NULL,
458 /*DelayTypeCreation=*/true);
John McCalle29ba202009-08-20 01:44:21 +0000459
460 ClassTemplateDecl *Inst
461 = ClassTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
462 D->getIdentifier(), InstParams, RecordInst, 0);
463 RecordInst->setDescribedClassTemplate(Inst);
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000464 if (D->getFriendObjectKind())
465 Inst->setObjectOfFriendDecl(true);
466 else
467 Inst->setAccess(D->getAccess());
John McCalle29ba202009-08-20 01:44:21 +0000468 Inst->setInstantiatedFromMemberTemplate(D);
Douglas Gregorf0510d42009-10-12 23:11:44 +0000469
470 // Trigger creation of the type for the instantiation.
471 SemaRef.Context.getTypeDeclType(RecordInst);
472
Douglas Gregor259571e2009-10-30 22:42:42 +0000473 // Finish handling of friends.
474 if (Inst->getFriendObjectKind()) {
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000475 return Inst;
Douglas Gregor259571e2009-10-30 22:42:42 +0000476 }
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000477
John McCalle29ba202009-08-20 01:44:21 +0000478 Owner->addDecl(Inst);
Douglas Gregored9c0f92009-10-29 00:04:11 +0000479
480 // First, we sort the partial specializations by location, so
481 // that we instantiate them in the order they were declared.
482 llvm::SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
483 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
484 P = D->getPartialSpecializations().begin(),
485 PEnd = D->getPartialSpecializations().end();
486 P != PEnd; ++P)
487 PartialSpecs.push_back(&*P);
488 std::sort(PartialSpecs.begin(), PartialSpecs.end(),
489 SortDeclByLocation(SemaRef.SourceMgr));
490
491 // Instantiate all of the partial specializations of this member class
492 // template.
493 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
494 InstantiateClassTemplatePartialSpecialization(Inst, PartialSpecs[I]);
495
John McCalle29ba202009-08-20 01:44:21 +0000496 return Inst;
497}
498
Douglas Gregord60e1052009-08-27 16:57:43 +0000499Decl *
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000500TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
501 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregored9c0f92009-10-29 00:04:11 +0000502 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
503
504 // Lookup the already-instantiated declaration in the instantiation
505 // of the class template and return that.
506 DeclContext::lookup_result Found
507 = Owner->lookup(ClassTemplate->getDeclName());
508 if (Found.first == Found.second)
509 return 0;
510
511 ClassTemplateDecl *InstClassTemplate
512 = dyn_cast<ClassTemplateDecl>(*Found.first);
513 if (!InstClassTemplate)
514 return 0;
515
516 Decl *DCanon = D->getCanonicalDecl();
517 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
518 P = InstClassTemplate->getPartialSpecializations().begin(),
519 PEnd = InstClassTemplate->getPartialSpecializations().end();
520 P != PEnd; ++P) {
521 if (P->getInstantiatedFromMember()->getCanonicalDecl() == DCanon)
522 return &*P;
523 }
524
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000525 return 0;
526}
527
528Decl *
Douglas Gregord60e1052009-08-27 16:57:43 +0000529TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000530 // Create a local instantiation scope for this function template, which
531 // will contain the instantiations of the template parameters and then get
532 // merged with the local instantiation scope for the function template
533 // itself.
534 Sema::LocalInstantiationScope Scope(SemaRef);
535
Douglas Gregord60e1052009-08-27 16:57:43 +0000536 TemplateParameterList *TempParams = D->getTemplateParameters();
537 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000538 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000539 return NULL;
Douglas Gregored9c0f92009-10-29 00:04:11 +0000540
Douglas Gregora735b202009-10-13 14:39:41 +0000541 FunctionDecl *Instantiated = 0;
542 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
543 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
544 InstParams));
545 else
546 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
547 D->getTemplatedDecl(),
548 InstParams));
549
550 if (!Instantiated)
Douglas Gregord60e1052009-08-27 16:57:43 +0000551 return 0;
552
Mike Stump1eb44332009-09-09 15:08:12 +0000553 // Link the instantiated function template declaration to the function
Douglas Gregord60e1052009-08-27 16:57:43 +0000554 // template from which it was instantiated.
Douglas Gregor37d681852009-10-12 22:27:17 +0000555 FunctionTemplateDecl *InstTemplate
Douglas Gregora735b202009-10-13 14:39:41 +0000556 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregor37d681852009-10-12 22:27:17 +0000557 InstTemplate->setAccess(D->getAccess());
Douglas Gregora735b202009-10-13 14:39:41 +0000558 assert(InstTemplate &&
559 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
560 if (!InstTemplate->getInstantiatedFromMemberTemplate())
561 InstTemplate->setInstantiatedFromMemberTemplate(D);
562
563 // Add non-friends into the owner.
564 if (!InstTemplate->getFriendObjectKind())
565 Owner->addDecl(InstTemplate);
Douglas Gregord60e1052009-08-27 16:57:43 +0000566 return InstTemplate;
567}
568
Douglas Gregord475b8d2009-03-25 21:17:03 +0000569Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
570 CXXRecordDecl *PrevDecl = 0;
571 if (D->isInjectedClassName())
572 PrevDecl = cast<CXXRecordDecl>(Owner);
573
574 CXXRecordDecl *Record
Mike Stump1eb44332009-09-09 15:08:12 +0000575 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000576 D->getLocation(), D->getIdentifier(),
577 D->getTagKeywordLoc(), PrevDecl);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000578 Record->setImplicit(D->isImplicit());
Eli Friedmaneaba1af2009-08-27 19:11:42 +0000579 // FIXME: Check against AS_none is an ugly hack to work around the issue that
580 // the tag decls introduced by friend class declarations don't have an access
581 // specifier. Remove once this area of the code gets sorted out.
582 if (D->getAccess() != AS_none)
583 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000584 if (!D->isInjectedClassName())
Douglas Gregorf6b11852009-10-08 15:14:33 +0000585 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000586
John McCall02cace72009-08-28 07:59:38 +0000587 // If the original function was part of a friend declaration,
588 // inherit its namespace state.
589 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
590 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
591
Anders Carlssond8b285f2009-09-01 04:26:58 +0000592 Record->setAnonymousStructOrUnion(D->isAnonymousStructOrUnion());
593
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000594 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000595 return Record;
596}
597
John McCall02cace72009-08-28 07:59:38 +0000598/// Normal class members are of more specific types and therefore
599/// don't make it here. This function serves two purposes:
600/// 1) instantiating function templates
601/// 2) substituting friend declarations
602/// FIXME: preserve function definitions in case #2
Douglas Gregora735b202009-10-13 14:39:41 +0000603 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
604 TemplateParameterList *TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000605 // Check whether there is already a function template specialization for
606 // this declaration.
607 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
608 void *InsertPos = 0;
Douglas Gregora735b202009-10-13 14:39:41 +0000609 if (FunctionTemplate && !TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000610 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000611 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000612 TemplateArgs.getInnermost().getFlatArgumentList(),
613 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor828e2262009-07-29 16:09:57 +0000614 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000615
616 FunctionTemplateSpecializationInfo *Info
617 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor127102b2009-06-29 20:59:39 +0000618 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000619
Douglas Gregor127102b2009-06-29 20:59:39 +0000620 // If we already have a function template specialization, return it.
621 if (Info)
622 return Info->Function;
623 }
Mike Stump1eb44332009-09-09 15:08:12 +0000624
Douglas Gregor550d9b22009-10-31 17:21:17 +0000625 Sema::LocalInstantiationScope Scope(SemaRef, TemplateParams != 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000626
Douglas Gregore53060f2009-06-25 22:08:12 +0000627 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCallce3ff2b2009-08-25 22:02:44 +0000628 QualType T = SubstFunctionType(D, Params);
Douglas Gregore53060f2009-06-25 22:08:12 +0000629 if (T.isNull())
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000630 return 0;
John McCallfd810b12009-08-14 02:03:10 +0000631
Douglas Gregore53060f2009-06-25 22:08:12 +0000632 // Build the instantiated method declaration.
Douglas Gregore95b4092009-09-16 18:34:49 +0000633 DeclContext *DC = SemaRef.FindInstantiatedContext(D->getDeclContext(),
634 TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +0000635 FunctionDecl *Function =
Mike Stump1eb44332009-09-09 15:08:12 +0000636 FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000637 D->getDeclName(), T, D->getDeclaratorInfo(),
638 D->getStorageClass(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000639 D->isInlineSpecified(), D->hasWrittenPrototype());
John McCall02cace72009-08-28 07:59:38 +0000640 Function->setLexicalDeclContext(Owner);
Mike Stump1eb44332009-09-09 15:08:12 +0000641
Douglas Gregore53060f2009-06-25 22:08:12 +0000642 // Attach the parameters
643 for (unsigned P = 0; P < Params.size(); ++P)
644 Params[P]->setOwningFunction(Function);
645 Function->setParams(SemaRef.Context, Params.data(), Params.size());
John McCall02cace72009-08-28 07:59:38 +0000646
Douglas Gregora735b202009-10-13 14:39:41 +0000647 if (TemplateParams) {
648 // Our resulting instantiation is actually a function template, since we
649 // are substituting only the outer template parameters. For example, given
650 //
651 // template<typename T>
652 // struct X {
653 // template<typename U> friend void f(T, U);
654 // };
655 //
656 // X<int> x;
657 //
658 // We are instantiating the friend function template "f" within X<int>,
659 // which means substituting int for T, but leaving "f" as a friend function
660 // template.
661 // Build the function template itself.
662 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Owner,
663 Function->getLocation(),
664 Function->getDeclName(),
665 TemplateParams, Function);
666 Function->setDescribedFunctionTemplate(FunctionTemplate);
667 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregor66724ea2009-11-14 01:20:54 +0000668 } else if (FunctionTemplate) {
669 // Record this function template specialization.
670 Function->setFunctionTemplateSpecialization(SemaRef.Context,
671 FunctionTemplate,
672 &TemplateArgs.getInnermost(),
673 InsertPos);
John McCall02cace72009-08-28 07:59:38 +0000674 }
Douglas Gregora735b202009-10-13 14:39:41 +0000675
Douglas Gregore53060f2009-06-25 22:08:12 +0000676 if (InitFunctionInstantiation(Function, D))
677 Function->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000678
Douglas Gregore53060f2009-06-25 22:08:12 +0000679 bool Redeclaration = false;
680 bool OverloadableAttrRequired = false;
Douglas Gregora735b202009-10-13 14:39:41 +0000681
Douglas Gregore53060f2009-06-25 22:08:12 +0000682 NamedDecl *PrevDecl = 0;
Douglas Gregora735b202009-10-13 14:39:41 +0000683 if (TemplateParams || !FunctionTemplate) {
684 // Look only into the namespace where the friend would be declared to
685 // find a previous declaration. This is the innermost enclosing namespace,
686 // as described in ActOnFriendFunctionDecl.
John McCalla24dc2e2009-11-17 02:14:36 +0000687 Sema::LookupResult R(SemaRef, Function->getDeclName(), SourceLocation(),
688 Sema::LookupOrdinaryName,
689 Sema::LookupResult::ForRedeclaration);
690 SemaRef.LookupQualifiedName(R, DC);
Douglas Gregora735b202009-10-13 14:39:41 +0000691
692 PrevDecl = R.getAsSingleDecl(SemaRef.Context);
693
694 // In C++, the previous declaration we find might be a tag type
695 // (class or enum). In this case, the new declaration will hide the
696 // tag type. Note that this does does not apply if we're declaring a
697 // typedef (C++ [dcl.typedef]p4).
698 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
699 PrevDecl = 0;
700 }
701
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000702 SemaRef.CheckFunctionDeclaration(Function, PrevDecl, false, Redeclaration,
Douglas Gregore53060f2009-06-25 22:08:12 +0000703 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000704
Douglas Gregora735b202009-10-13 14:39:41 +0000705 // If the original function was part of a friend declaration,
706 // inherit its namespace state and add it to the owner.
707 NamedDecl *FromFriendD
708 = TemplateParams? cast<NamedDecl>(D->getDescribedFunctionTemplate()) : D;
709 if (FromFriendD->getFriendObjectKind()) {
710 NamedDecl *ToFriendD = 0;
711 if (TemplateParams) {
712 ToFriendD = cast<NamedDecl>(FunctionTemplate);
713 PrevDecl = FunctionTemplate->getPreviousDeclaration();
714 } else {
715 ToFriendD = Function;
716 PrevDecl = Function->getPreviousDeclaration();
717 }
718 ToFriendD->setObjectOfFriendDecl(PrevDecl != NULL);
719 if (!Owner->isDependentContext() && !PrevDecl)
720 DC->makeDeclVisibleInContext(ToFriendD, /* Recoverable = */ false);
721
722 if (!TemplateParams)
723 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
724 }
725
Douglas Gregore53060f2009-06-25 22:08:12 +0000726 return Function;
727}
728
Douglas Gregord60e1052009-08-27 16:57:43 +0000729Decl *
730TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
731 TemplateParameterList *TemplateParams) {
Douglas Gregor6b906862009-08-21 00:16:32 +0000732 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
733 void *InsertPos = 0;
Douglas Gregord60e1052009-08-27 16:57:43 +0000734 if (FunctionTemplate && !TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +0000735 // We are creating a function template specialization from a function
736 // template. Check whether there is already a function template
Douglas Gregord60e1052009-08-27 16:57:43 +0000737 // specialization for this particular set of template arguments.
Douglas Gregor6b906862009-08-21 00:16:32 +0000738 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000739 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000740 TemplateArgs.getInnermost().getFlatArgumentList(),
741 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor6b906862009-08-21 00:16:32 +0000742 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000743
744 FunctionTemplateSpecializationInfo *Info
745 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor6b906862009-08-21 00:16:32 +0000746 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000747
Douglas Gregor6b906862009-08-21 00:16:32 +0000748 // If we already have a function template specialization, return it.
749 if (Info)
750 return Info->Function;
751 }
752
Douglas Gregor550d9b22009-10-31 17:21:17 +0000753 Sema::LocalInstantiationScope Scope(SemaRef, TemplateParams != 0);
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000754
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000755 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCallce3ff2b2009-08-25 22:02:44 +0000756 QualType T = SubstFunctionType(D, Params);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000757 if (T.isNull())
758 return 0;
759
760 // Build the instantiated method declaration.
761 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
Douglas Gregordec06662009-08-21 18:42:58 +0000762 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000763
Douglas Gregordec06662009-08-21 18:42:58 +0000764 DeclarationName Name = D->getDeclName();
Douglas Gregor17e32f32009-08-21 22:43:28 +0000765 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Douglas Gregordec06662009-08-21 18:42:58 +0000766 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
767 Name = SemaRef.Context.DeclarationNames.getCXXConstructorName(
768 SemaRef.Context.getCanonicalType(ClassTy));
Mike Stump1eb44332009-09-09 15:08:12 +0000769 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
770 Constructor->getLocation(),
771 Name, T,
Douglas Gregor17e32f32009-08-21 22:43:28 +0000772 Constructor->getDeclaratorInfo(),
Mike Stump1eb44332009-09-09 15:08:12 +0000773 Constructor->isExplicit(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000774 Constructor->isInlineSpecified(), false);
Douglas Gregor17e32f32009-08-21 22:43:28 +0000775 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
776 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
777 Name = SemaRef.Context.DeclarationNames.getCXXDestructorName(
778 SemaRef.Context.getCanonicalType(ClassTy));
779 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
780 Destructor->getLocation(), Name,
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000781 T, Destructor->isInlineSpecified(), false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000782 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000783 CanQualType ConvTy
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000784 = SemaRef.Context.getCanonicalType(
John McCall183700f2009-09-21 23:43:11 +0000785 T->getAs<FunctionType>()->getResultType());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000786 Name = SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(
787 ConvTy);
788 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
789 Conversion->getLocation(), Name,
790 T, Conversion->getDeclaratorInfo(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000791 Conversion->isInlineSpecified(),
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000792 Conversion->isExplicit());
Douglas Gregordec06662009-08-21 18:42:58 +0000793 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000794 Method = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
Douglas Gregordec06662009-08-21 18:42:58 +0000795 D->getDeclName(), T, D->getDeclaratorInfo(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000796 D->isStatic(), D->isInlineSpecified());
Douglas Gregordec06662009-08-21 18:42:58 +0000797 }
Douglas Gregor6b906862009-08-21 00:16:32 +0000798
Douglas Gregord60e1052009-08-27 16:57:43 +0000799 if (TemplateParams) {
800 // Our resulting instantiation is actually a function template, since we
801 // are substituting only the outer template parameters. For example, given
Mike Stump1eb44332009-09-09 15:08:12 +0000802 //
Douglas Gregord60e1052009-08-27 16:57:43 +0000803 // template<typename T>
804 // struct X {
805 // template<typename U> void f(T, U);
806 // };
807 //
808 // X<int> x;
809 //
810 // We are instantiating the member template "f" within X<int>, which means
811 // substituting int for T, but leaving "f" as a member function template.
812 // Build the function template itself.
813 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
814 Method->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +0000815 Method->getDeclName(),
Douglas Gregord60e1052009-08-27 16:57:43 +0000816 TemplateParams, Method);
817 if (D->isOutOfLine())
Mike Stump1eb44332009-09-09 15:08:12 +0000818 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregord60e1052009-08-27 16:57:43 +0000819 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregor66724ea2009-11-14 01:20:54 +0000820 } else if (FunctionTemplate) {
821 // Record this function template specialization.
822 Method->setFunctionTemplateSpecialization(SemaRef.Context,
823 FunctionTemplate,
824 &TemplateArgs.getInnermost(),
825 InsertPos);
826 } else {
827 // Record that this is an instantiation of a member function.
Douglas Gregor2db32322009-10-07 23:56:10 +0000828 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregor66724ea2009-11-14 01:20:54 +0000829 }
830
Mike Stump1eb44332009-09-09 15:08:12 +0000831 // If we are instantiating a member function defined
Douglas Gregor7caa6822009-07-24 20:34:43 +0000832 // out-of-line, the instantiation will have the same lexical
833 // context (which will be a namespace scope) as the template.
834 if (D->isOutOfLine())
835 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000836
Douglas Gregor5545e162009-03-24 00:38:23 +0000837 // Attach the parameters
838 for (unsigned P = 0; P < Params.size(); ++P)
839 Params[P]->setOwningFunction(Method);
Jay Foadbeaaccd2009-05-21 09:52:38 +0000840 Method->setParams(SemaRef.Context, Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +0000841
842 if (InitMethodInstantiation(Method, D))
843 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000844
Douglas Gregordec06662009-08-21 18:42:58 +0000845 NamedDecl *PrevDecl = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000846
Douglas Gregord60e1052009-08-27 16:57:43 +0000847 if (!FunctionTemplate || TemplateParams) {
John McCalla24dc2e2009-11-17 02:14:36 +0000848 Sema::LookupResult R(SemaRef, Name, SourceLocation(),
849 Sema::LookupOrdinaryName,
850 Sema::LookupResult::ForRedeclaration);
851 SemaRef.LookupQualifiedName(R, Owner);
John McCallf36e02d2009-10-09 21:13:30 +0000852 PrevDecl = R.getAsSingleDecl(SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000853
Douglas Gregordec06662009-08-21 18:42:58 +0000854 // In C++, the previous declaration we find might be a tag type
855 // (class or enum). In this case, the new declaration will hide the
856 // tag type. Note that this does does not apply if we're declaring a
857 // typedef (C++ [dcl.typedef]p4).
858 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
859 PrevDecl = 0;
860 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000861
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000862 bool Redeclaration = false;
863 bool OverloadableAttrRequired = false;
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000864 SemaRef.CheckFunctionDeclaration(Method, PrevDecl, false, Redeclaration,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000865 /*FIXME:*/OverloadableAttrRequired);
866
Douglas Gregora735b202009-10-13 14:39:41 +0000867 if (!FunctionTemplate && (!Method->isInvalidDecl() || !PrevDecl) &&
868 !Method->getFriendObjectKind())
Douglas Gregordec06662009-08-21 18:42:58 +0000869 Owner->addDecl(Method);
Mike Stump1eb44332009-09-09 15:08:12 +0000870
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000871 return Method;
872}
873
Douglas Gregor615c5d42009-03-24 16:43:20 +0000874Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +0000875 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +0000876}
877
Douglas Gregor03b2b072009-03-24 00:15:49 +0000878Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +0000879 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +0000880}
881
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000882Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000883 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000884}
885
Douglas Gregor6477b692009-03-25 15:04:13 +0000886ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
John McCall58e46772009-10-23 21:48:59 +0000887 QualType T;
888 DeclaratorInfo *DI = D->getDeclaratorInfo();
889 if (DI) {
890 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
891 D->getDeclName());
892 if (DI) T = DI->getType();
893 } else {
894 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
895 D->getDeclName());
896 DI = 0;
897 }
898
899 if (T.isNull())
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000900 return 0;
901
John McCall58e46772009-10-23 21:48:59 +0000902 T = SemaRef.adjustParameterType(T);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000903
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000904 // Allocate the parameter
John McCall58e46772009-10-23 21:48:59 +0000905 ParmVarDecl *Param
906 = ParmVarDecl::Create(SemaRef.Context, Owner, D->getLocation(),
907 D->getIdentifier(), T, DI, D->getStorageClass(), 0);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000908
Anders Carlsson9351c172009-08-25 03:18:48 +0000909 // Mark the default argument as being uninstantiated.
Douglas Gregorf43d0b32009-09-25 06:56:31 +0000910 if (D->hasUninstantiatedDefaultArg())
911 Param->setUninstantiatedDefaultArg(D->getUninstantiatedDefaultArg());
Douglas Gregor0ed09302009-09-25 07:03:22 +0000912 else if (Expr *Arg = D->getDefaultArg())
913 Param->setUninstantiatedDefaultArg(Arg);
914
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000915 // Note: we don't try to instantiate function parameters until after
916 // we've instantiated the function's type. Therefore, we don't have
917 // to check for 'void' parameter types here.
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000918 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000919 return Param;
920}
921
John McCalle29ba202009-08-20 01:44:21 +0000922Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
923 TemplateTypeParmDecl *D) {
924 // TODO: don't always clone when decls are refcounted.
925 const Type* T = D->getTypeForDecl();
926 assert(T->isTemplateTypeParmType());
927 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
Mike Stump1eb44332009-09-09 15:08:12 +0000928
John McCalle29ba202009-08-20 01:44:21 +0000929 TemplateTypeParmDecl *Inst =
930 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor550d9b22009-10-31 17:21:17 +0000931 TTPT->getDepth() - 1, TTPT->getIndex(),
John McCalle29ba202009-08-20 01:44:21 +0000932 TTPT->getName(),
933 D->wasDeclaredWithTypename(),
934 D->isParameterPack());
935
Douglas Gregor0f8716b2009-11-09 19:17:50 +0000936 if (D->hasDefaultArgument())
937 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
John McCalle29ba202009-08-20 01:44:21 +0000938
Douglas Gregor550d9b22009-10-31 17:21:17 +0000939 // Introduce this template parameter's instantiation into the instantiation
940 // scope.
941 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
942
John McCalle29ba202009-08-20 01:44:21 +0000943 return Inst;
944}
945
Douglas Gregor33642df2009-10-23 23:25:44 +0000946Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
947 NonTypeTemplateParmDecl *D) {
948 // Substitute into the type of the non-type template parameter.
949 QualType T;
950 DeclaratorInfo *DI = D->getDeclaratorInfo();
951 if (DI) {
952 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
953 D->getDeclName());
954 if (DI) T = DI->getType();
955 } else {
956 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
957 D->getDeclName());
958 DI = 0;
959 }
960 if (T.isNull())
961 return 0;
962
963 // Check that this type is acceptable for a non-type template parameter.
964 bool Invalid = false;
965 T = SemaRef.CheckNonTypeTemplateParameterType(T, D->getLocation());
966 if (T.isNull()) {
967 T = SemaRef.Context.IntTy;
968 Invalid = true;
969 }
970
971 NonTypeTemplateParmDecl *Param
972 = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
973 D->getDepth() - 1, D->getPosition(),
974 D->getIdentifier(), T, DI);
975 if (Invalid)
976 Param->setInvalidDecl();
977
978 Param->setDefaultArgument(D->getDefaultArgument());
Douglas Gregor550d9b22009-10-31 17:21:17 +0000979
980 // Introduce this template parameter's instantiation into the instantiation
981 // scope.
982 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor33642df2009-10-23 23:25:44 +0000983 return Param;
984}
985
Anders Carlsson0dde18e2009-08-28 15:18:15 +0000986Decl *
Douglas Gregor9106ef72009-11-11 16:58:32 +0000987TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
988 TemplateTemplateParmDecl *D) {
989 // Instantiate the template parameter list of the template template parameter.
990 TemplateParameterList *TempParams = D->getTemplateParameters();
991 TemplateParameterList *InstParams;
992 {
993 // Perform the actual substitution of template parameters within a new,
994 // local instantiation scope.
995 Sema::LocalInstantiationScope Scope(SemaRef);
996 InstParams = SubstTemplateParams(TempParams);
997 if (!InstParams)
998 return NULL;
999 }
1000
1001 // Build the template template parameter.
1002 TemplateTemplateParmDecl *Param
1003 = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1004 D->getDepth() - 1, D->getPosition(),
1005 D->getIdentifier(), InstParams);
1006 Param->setDefaultArgument(D->getDefaultArgument());
1007
1008 // Introduce this template parameter's instantiation into the instantiation
1009 // scope.
1010 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1011
1012 return Param;
1013}
1014
Douglas Gregor48c32a72009-11-17 06:07:40 +00001015Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1016 // Using directives are never dependent, so they require no explicit
1017
1018 UsingDirectiveDecl *Inst
1019 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1020 D->getNamespaceKeyLocation(),
1021 D->getQualifierRange(), D->getQualifier(),
1022 D->getIdentLocation(),
1023 D->getNominatedNamespace(),
1024 D->getCommonAncestor());
1025 Owner->addDecl(Inst);
1026 return Inst;
1027}
1028
John McCall7ba107a2009-11-18 02:36:19 +00001029Decl * TemplateDeclInstantiator
1030 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +00001031 NestedNameSpecifier *NNS =
1032 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1033 D->getTargetNestedNameRange(),
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001034 TemplateArgs);
1035 if (!NNS)
1036 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001037
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001038 CXXScopeSpec SS;
1039 SS.setRange(D->getTargetNestedNameRange());
1040 SS.setScopeRep(NNS);
Mike Stump1eb44332009-09-09 15:08:12 +00001041
1042 NamedDecl *UD =
John McCall9488ea12009-11-17 05:59:44 +00001043 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
John McCall7ba107a2009-11-18 02:36:19 +00001044 D->getUsingLoc(), SS, D->getLocation(),
1045 D->getDeclName(), 0,
1046 /*instantiation*/ true,
1047 /*typename*/ true, D->getTypenameLoc());
1048 if (UD)
1049 SemaRef.Context.setInstantiatedFromUnresolvedUsingDecl(cast<UsingDecl>(UD),
1050 D);
1051 return UD;
1052}
1053
1054Decl * TemplateDeclInstantiator
1055 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1056 NestedNameSpecifier *NNS =
1057 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1058 D->getTargetNestedNameRange(),
1059 TemplateArgs);
1060 if (!NNS)
1061 return 0;
1062
1063 CXXScopeSpec SS;
1064 SS.setRange(D->getTargetNestedNameRange());
1065 SS.setScopeRep(NNS);
1066
1067 NamedDecl *UD =
1068 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
1069 D->getUsingLoc(), SS, D->getLocation(),
1070 D->getDeclName(), 0,
1071 /*instantiation*/ true,
1072 /*typename*/ false, SourceLocation());
Anders Carlsson0d8df782009-08-29 19:37:28 +00001073 if (UD)
Mike Stump1eb44332009-09-09 15:08:12 +00001074 SemaRef.Context.setInstantiatedFromUnresolvedUsingDecl(cast<UsingDecl>(UD),
Anders Carlsson0d8df782009-08-29 19:37:28 +00001075 D);
1076 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001077}
1078
John McCallce3ff2b2009-08-25 22:02:44 +00001079Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001080 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +00001081 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001082 return Instantiator.Visit(D);
1083}
1084
John McCalle29ba202009-08-20 01:44:21 +00001085/// \brief Instantiates a nested template parameter list in the current
1086/// instantiation context.
1087///
1088/// \param L The parameter list to instantiate
1089///
1090/// \returns NULL if there was an error
1091TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +00001092TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +00001093 // Get errors for all the parameters before bailing out.
1094 bool Invalid = false;
1095
1096 unsigned N = L->size();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001097 typedef llvm::SmallVector<NamedDecl *, 8> ParamVector;
John McCalle29ba202009-08-20 01:44:21 +00001098 ParamVector Params;
1099 Params.reserve(N);
1100 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
1101 PI != PE; ++PI) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001102 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCalle29ba202009-08-20 01:44:21 +00001103 Params.push_back(D);
Douglas Gregor9148c3f2009-11-11 19:13:48 +00001104 Invalid = Invalid || !D || D->isInvalidDecl();
John McCalle29ba202009-08-20 01:44:21 +00001105 }
1106
1107 // Clean up if we had an error.
1108 if (Invalid) {
1109 for (ParamVector::iterator PI = Params.begin(), PE = Params.end();
1110 PI != PE; ++PI)
1111 if (*PI)
1112 (*PI)->Destroy(SemaRef.Context);
1113 return NULL;
1114 }
1115
1116 TemplateParameterList *InstL
1117 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
1118 L->getLAngleLoc(), &Params.front(), N,
1119 L->getRAngleLoc());
1120 return InstL;
Mike Stump1eb44332009-09-09 15:08:12 +00001121}
John McCalle29ba202009-08-20 01:44:21 +00001122
Douglas Gregored9c0f92009-10-29 00:04:11 +00001123/// \brief Instantiate the declaration of a class template partial
1124/// specialization.
1125///
1126/// \param ClassTemplate the (instantiated) class template that is partially
1127// specialized by the instantiation of \p PartialSpec.
1128///
1129/// \param PartialSpec the (uninstantiated) class template partial
1130/// specialization that we are instantiating.
1131///
1132/// \returns true if there was an error, false otherwise.
1133bool
1134TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
1135 ClassTemplateDecl *ClassTemplate,
1136 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00001137 // Create a local instantiation scope for this class template partial
1138 // specialization, which will contain the instantiations of the template
1139 // parameters.
1140 Sema::LocalInstantiationScope Scope(SemaRef);
1141
Douglas Gregored9c0f92009-10-29 00:04:11 +00001142 // Substitute into the template parameters of the class template partial
1143 // specialization.
1144 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
1145 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1146 if (!InstParams)
1147 return true;
1148
1149 // Substitute into the template arguments of the class template partial
1150 // specialization.
John McCall833ca992009-10-29 08:12:44 +00001151 const TemplateArgumentLoc *PartialSpecTemplateArgs
1152 = PartialSpec->getTemplateArgsAsWritten();
1153 unsigned N = PartialSpec->getNumTemplateArgsAsWritten();
1154
1155 llvm::SmallVector<TemplateArgumentLoc, 4> InstTemplateArgs(N);
1156 for (unsigned I = 0; I != N; ++I) {
1157 if (SemaRef.Subst(PartialSpecTemplateArgs[I], InstTemplateArgs[I],
1158 TemplateArgs))
Douglas Gregored9c0f92009-10-29 00:04:11 +00001159 return true;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001160 }
1161
1162
1163 // Check that the template argument list is well-formed for this
1164 // class template.
1165 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
1166 InstTemplateArgs.size());
1167 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
1168 PartialSpec->getLocation(),
1169 /*FIXME:*/PartialSpec->getLocation(),
1170 InstTemplateArgs.data(),
1171 InstTemplateArgs.size(),
1172 /*FIXME:*/PartialSpec->getLocation(),
1173 false,
1174 Converted))
1175 return true;
1176
1177 // Figure out where to insert this class template partial specialization
1178 // in the member template's set of class template partial specializations.
1179 llvm::FoldingSetNodeID ID;
1180 ClassTemplatePartialSpecializationDecl::Profile(ID,
1181 Converted.getFlatArguments(),
1182 Converted.flatSize(),
1183 SemaRef.Context);
1184 void *InsertPos = 0;
1185 ClassTemplateSpecializationDecl *PrevDecl
1186 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
1187 InsertPos);
1188
1189 // Build the canonical type that describes the converted template
1190 // arguments of the class template partial specialization.
1191 QualType CanonType
1192 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
1193 Converted.getFlatArguments(),
1194 Converted.flatSize());
1195
1196 // Build the fully-sugared type for this class template
1197 // specialization as the user wrote in the specialization
1198 // itself. This means that we'll pretty-print the type retrieved
1199 // from the specialization's declaration the way that the user
1200 // actually wrote the specialization, rather than formatting the
1201 // name based on the "canonical" representation used to store the
1202 // template arguments in the specialization.
1203 QualType WrittenTy
1204 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
1205 InstTemplateArgs.data(),
1206 InstTemplateArgs.size(),
1207 CanonType);
1208
1209 if (PrevDecl) {
1210 // We've already seen a partial specialization with the same template
1211 // parameters and template arguments. This can happen, for example, when
1212 // substituting the outer template arguments ends up causing two
1213 // class template partial specializations of a member class template
1214 // to have identical forms, e.g.,
1215 //
1216 // template<typename T, typename U>
1217 // struct Outer {
1218 // template<typename X, typename Y> struct Inner;
1219 // template<typename Y> struct Inner<T, Y>;
1220 // template<typename Y> struct Inner<U, Y>;
1221 // };
1222 //
1223 // Outer<int, int> outer; // error: the partial specializations of Inner
1224 // // have the same signature.
1225 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
1226 << WrittenTy;
1227 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
1228 << SemaRef.Context.getTypeDeclType(PrevDecl);
1229 return true;
1230 }
1231
1232
1233 // Create the class template partial specialization declaration.
1234 ClassTemplatePartialSpecializationDecl *InstPartialSpec
1235 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context, Owner,
1236 PartialSpec->getLocation(),
1237 InstParams,
1238 ClassTemplate,
1239 Converted,
John McCall833ca992009-10-29 08:12:44 +00001240 InstTemplateArgs.data(),
1241 InstTemplateArgs.size(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00001242 0);
1243 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
1244 InstPartialSpec->setTypeAsWritten(WrittenTy);
1245
1246 // Add this partial specialization to the set of class template partial
1247 // specializations.
1248 ClassTemplate->getPartialSpecializations().InsertNode(InstPartialSpec,
1249 InsertPos);
1250 return false;
1251}
1252
John McCallce3ff2b2009-08-25 22:02:44 +00001253/// \brief Does substitution on the type of the given function, including
1254/// all of the function parameters.
Douglas Gregor5545e162009-03-24 00:38:23 +00001255///
John McCallce3ff2b2009-08-25 22:02:44 +00001256/// \param D The function whose type will be the basis of the substitution
Douglas Gregor5545e162009-03-24 00:38:23 +00001257///
1258/// \param Params the instantiated parameter declarations
1259
John McCallce3ff2b2009-08-25 22:02:44 +00001260/// \returns the instantiated function's type if successful, a NULL
Douglas Gregor5545e162009-03-24 00:38:23 +00001261/// type if there was an error.
Mike Stump1eb44332009-09-09 15:08:12 +00001262QualType
John McCallce3ff2b2009-08-25 22:02:44 +00001263TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +00001264 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
1265 bool InvalidDecl = false;
1266
John McCallce3ff2b2009-08-25 22:02:44 +00001267 // Substitute all of the function's formal parameter types.
Douglas Gregor7e063902009-05-11 23:53:27 +00001268 TemplateDeclInstantiator ParamInstantiator(SemaRef, 0, TemplateArgs);
Douglas Gregor0ca20ac2009-05-29 18:27:38 +00001269 llvm::SmallVector<QualType, 4> ParamTys;
Mike Stump1eb44332009-09-09 15:08:12 +00001270 for (FunctionDecl::param_iterator P = D->param_begin(),
Douglas Gregor5545e162009-03-24 00:38:23 +00001271 PEnd = D->param_end();
1272 P != PEnd; ++P) {
Douglas Gregor6477b692009-03-25 15:04:13 +00001273 if (ParmVarDecl *PInst = ParamInstantiator.VisitParmVarDecl(*P)) {
Douglas Gregor5545e162009-03-24 00:38:23 +00001274 if (PInst->getType()->isVoidType()) {
1275 SemaRef.Diag(PInst->getLocation(), diag::err_param_with_void_type);
1276 PInst->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001277 } else if (SemaRef.RequireNonAbstractType(PInst->getLocation(),
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001278 PInst->getType(),
1279 diag::err_abstract_type_in_decl,
1280 Sema::AbstractParamType))
Douglas Gregor5545e162009-03-24 00:38:23 +00001281 PInst->setInvalidDecl();
1282
1283 Params.push_back(PInst);
1284 ParamTys.push_back(PInst->getType());
1285
1286 if (PInst->isInvalidDecl())
1287 InvalidDecl = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001288 } else
Douglas Gregor5545e162009-03-24 00:38:23 +00001289 InvalidDecl = true;
1290 }
1291
1292 // FIXME: Deallocate dead declarations.
1293 if (InvalidDecl)
1294 return QualType();
1295
John McCall183700f2009-09-21 23:43:11 +00001296 const FunctionProtoType *Proto = D->getType()->getAs<FunctionProtoType>();
Douglas Gregor5545e162009-03-24 00:38:23 +00001297 assert(Proto && "Missing prototype?");
Mike Stump1eb44332009-09-09 15:08:12 +00001298 QualType ResultType
John McCallce3ff2b2009-08-25 22:02:44 +00001299 = SemaRef.SubstType(Proto->getResultType(), TemplateArgs,
1300 D->getLocation(), D->getDeclName());
Douglas Gregor5545e162009-03-24 00:38:23 +00001301 if (ResultType.isNull())
1302 return QualType();
1303
Jay Foadbeaaccd2009-05-21 09:52:38 +00001304 return SemaRef.BuildFunctionType(ResultType, ParamTys.data(), ParamTys.size(),
Douglas Gregor5545e162009-03-24 00:38:23 +00001305 Proto->isVariadic(), Proto->getTypeQuals(),
1306 D->getLocation(), D->getDeclName());
1307}
1308
Mike Stump1eb44332009-09-09 15:08:12 +00001309/// \brief Initializes the common fields of an instantiation function
Douglas Gregore53060f2009-06-25 22:08:12 +00001310/// declaration (New) from the corresponding fields of its template (Tmpl).
1311///
1312/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001313bool
1314TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregore53060f2009-06-25 22:08:12 +00001315 FunctionDecl *Tmpl) {
1316 if (Tmpl->isDeleted())
1317 New->setDeleted();
Mike Stump1eb44332009-09-09 15:08:12 +00001318
Douglas Gregorcca9e962009-07-01 22:01:06 +00001319 // If we are performing substituting explicitly-specified template arguments
1320 // or deduced template arguments into a function template and we reach this
1321 // point, we are now past the point where SFINAE applies and have committed
Mike Stump1eb44332009-09-09 15:08:12 +00001322 // to keeping the new function template specialization. We therefore
1323 // convert the active template instantiation for the function template
Douglas Gregorcca9e962009-07-01 22:01:06 +00001324 // into a template instantiation for this specific function template
1325 // specialization, which is not a SFINAE context, so that we diagnose any
1326 // further errors in the declaration itself.
1327 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
1328 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
1329 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
1330 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump1eb44332009-09-09 15:08:12 +00001331 if (FunctionTemplateDecl *FunTmpl
Douglas Gregorcca9e962009-07-01 22:01:06 +00001332 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001333 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorcca9e962009-07-01 22:01:06 +00001334 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +00001335 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001336 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
1337 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
Douglas Gregorf35f8282009-11-11 21:54:23 +00001338 --SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001339 }
1340 }
Mike Stump1eb44332009-09-09 15:08:12 +00001341
Douglas Gregore53060f2009-06-25 22:08:12 +00001342 return false;
1343}
1344
Douglas Gregor5545e162009-03-24 00:38:23 +00001345/// \brief Initializes common fields of an instantiated method
1346/// declaration (New) from the corresponding fields of its template
1347/// (Tmpl).
1348///
1349/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001350bool
1351TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor5545e162009-03-24 00:38:23 +00001352 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +00001353 if (InitFunctionInstantiation(New, Tmpl))
1354 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001355
Douglas Gregor5545e162009-03-24 00:38:23 +00001356 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
1357 New->setAccess(Tmpl->getAccess());
Anders Carlsson77b7f1d2009-05-14 22:15:41 +00001358 if (Tmpl->isVirtualAsWritten()) {
1359 New->setVirtualAsWritten(true);
Douglas Gregor5545e162009-03-24 00:38:23 +00001360 Record->setAggregate(false);
1361 Record->setPOD(false);
Eli Friedman1d954f62009-08-15 21:55:26 +00001362 Record->setEmpty(false);
Douglas Gregor5545e162009-03-24 00:38:23 +00001363 Record->setPolymorphic(true);
1364 }
Douglas Gregor5545e162009-03-24 00:38:23 +00001365 if (Tmpl->isPure()) {
1366 New->setPure();
1367 Record->setAbstract(true);
1368 }
1369
1370 // FIXME: attributes
1371 // FIXME: New needs a pointer to Tmpl
1372 return false;
1373}
Douglas Gregora58861f2009-05-13 20:28:22 +00001374
1375/// \brief Instantiate the definition of the given function from its
1376/// template.
1377///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001378/// \param PointOfInstantiation the point at which the instantiation was
1379/// required. Note that this is not precisely a "point of instantiation"
1380/// for the function, but it's close.
1381///
Douglas Gregora58861f2009-05-13 20:28:22 +00001382/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001383/// function template specialization or member function of a class template
1384/// specialization.
1385///
1386/// \param Recursive if true, recursively instantiates any functions that
1387/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001388///
1389/// \param DefinitionRequired if true, then we are performing an explicit
1390/// instantiation where the body of the function is required. Complain if
1391/// there is no such body.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001392void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001393 FunctionDecl *Function,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001394 bool Recursive,
1395 bool DefinitionRequired) {
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001396 if (Function->isInvalidDecl())
1397 return;
1398
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001399 assert(!Function->getBody() && "Already instantiated!");
Mike Stump1eb44332009-09-09 15:08:12 +00001400
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001401 // Never instantiate an explicit specialization.
1402 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1403 return;
1404
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001405 // Find the function body that we'll be substituting.
Douglas Gregor3b846b62009-10-27 20:53:28 +00001406 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001407 Stmt *Pattern = 0;
1408 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001409 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001410
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001411 if (!Pattern) {
1412 if (DefinitionRequired) {
1413 if (Function->getPrimaryTemplate())
1414 Diag(PointOfInstantiation,
1415 diag::err_explicit_instantiation_undefined_func_template)
1416 << Function->getPrimaryTemplate();
1417 else
1418 Diag(PointOfInstantiation,
1419 diag::err_explicit_instantiation_undefined_member)
1420 << 1 << Function->getDeclName() << Function->getDeclContext();
1421
1422 if (PatternDecl)
1423 Diag(PatternDecl->getLocation(),
1424 diag::note_explicit_instantiation_here);
1425 }
1426
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001427 return;
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001428 }
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001429
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001430 // C++0x [temp.explicit]p9:
1431 // Except for inline functions, other explicit instantiation declarations
Mike Stump1eb44332009-09-09 15:08:12 +00001432 // have the effect of suppressing the implicit instantiation of the entity
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001433 // to which they refer.
Mike Stump1eb44332009-09-09 15:08:12 +00001434 if (Function->getTemplateSpecializationKind()
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001435 == TSK_ExplicitInstantiationDeclaration &&
Douglas Gregor7ced9c82009-10-27 21:11:48 +00001436 !PatternDecl->isInlined())
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001437 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001438
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001439 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
1440 if (Inst)
1441 return;
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001442
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001443 // If we're performing recursive template instantiation, create our own
1444 // queue of pending implicit instantiations that we will instantiate later,
1445 // while we're still within our own instantiation context.
1446 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1447 if (Recursive)
1448 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001449
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001450 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
1451
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001452 // Introduce a new scope where local variable instantiations will be
1453 // recorded.
1454 LocalInstantiationScope Scope(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00001455
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001456 // Introduce the instantiated function parameters into the local
1457 // instantiation scope.
1458 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
1459 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
1460 Function->getParamDecl(I));
1461
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001462 // Enter the scope of this instantiation. We don't use
1463 // PushDeclContext because we don't have a scope.
1464 DeclContext *PreviousContext = CurContext;
1465 CurContext = Function;
1466
Mike Stump1eb44332009-09-09 15:08:12 +00001467 MultiLevelTemplateArgumentList TemplateArgs =
Anders Carlsson09025312009-08-29 05:16:22 +00001468 getTemplateInstantiationArgs(Function);
1469
1470 // If this is a constructor, instantiate the member initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001471 if (const CXXConstructorDecl *Ctor =
Anders Carlsson09025312009-08-29 05:16:22 +00001472 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
1473 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
1474 TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001475 }
1476
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001477 // Instantiate the function body.
Anders Carlsson09025312009-08-29 05:16:22 +00001478 OwningStmtResult Body = SubstStmt(Pattern, TemplateArgs);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001479
Douglas Gregor52604ab2009-09-11 21:19:12 +00001480 if (Body.isInvalid())
1481 Function->setInvalidDecl();
1482
Mike Stump1eb44332009-09-09 15:08:12 +00001483 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001484 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001485
1486 CurContext = PreviousContext;
Douglas Gregoraba43bb2009-05-26 20:50:29 +00001487
1488 DeclGroupRef DG(Function);
1489 Consumer.HandleTopLevelDecl(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00001490
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001491 if (Recursive) {
1492 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00001493 // instantiation of this template.
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001494 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00001495
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001496 // Restore the set of pending implicit instantiations.
1497 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1498 }
Douglas Gregora58861f2009-05-13 20:28:22 +00001499}
1500
1501/// \brief Instantiate the definition of the given variable from its
1502/// template.
1503///
Douglas Gregor7caa6822009-07-24 20:34:43 +00001504/// \param PointOfInstantiation the point at which the instantiation was
1505/// required. Note that this is not precisely a "point of instantiation"
1506/// for the function, but it's close.
1507///
1508/// \param Var the already-instantiated declaration of a static member
1509/// variable of a class template specialization.
1510///
1511/// \param Recursive if true, recursively instantiates any functions that
1512/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001513///
1514/// \param DefinitionRequired if true, then we are performing an explicit
1515/// instantiation where an out-of-line definition of the member variable
1516/// is required. Complain if there is no such definition.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001517void Sema::InstantiateStaticDataMemberDefinition(
1518 SourceLocation PointOfInstantiation,
1519 VarDecl *Var,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001520 bool Recursive,
1521 bool DefinitionRequired) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001522 if (Var->isInvalidDecl())
1523 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001524
Douglas Gregor7caa6822009-07-24 20:34:43 +00001525 // Find the out-of-line definition of this static data member.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001526 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregor7caa6822009-07-24 20:34:43 +00001527 assert(Def && "This data member was not instantiated from a template?");
Douglas Gregor0d035142009-10-27 18:42:08 +00001528 assert(Def->isStaticDataMember() && "Not a static data member?");
1529 Def = Def->getOutOfLineDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00001530
Douglas Gregor0d035142009-10-27 18:42:08 +00001531 if (!Def) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001532 // We did not find an out-of-line definition of this static data member,
1533 // so we won't perform any instantiation. Rather, we rely on the user to
Mike Stump1eb44332009-09-09 15:08:12 +00001534 // instantiate this definition (or provide a specialization for it) in
1535 // another translation unit.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001536 if (DefinitionRequired) {
Douglas Gregor0d035142009-10-27 18:42:08 +00001537 Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001538 Diag(PointOfInstantiation,
1539 diag::err_explicit_instantiation_undefined_member)
1540 << 2 << Var->getDeclName() << Var->getDeclContext();
1541 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
1542 }
1543
Douglas Gregor7caa6822009-07-24 20:34:43 +00001544 return;
1545 }
1546
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001547 // Never instantiate an explicit specialization.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001548 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001549 return;
1550
1551 // C++0x [temp.explicit]p9:
1552 // Except for inline functions, other explicit instantiation declarations
1553 // have the effect of suppressing the implicit instantiation of the entity
1554 // to which they refer.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001555 if (Var->getTemplateSpecializationKind()
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001556 == TSK_ExplicitInstantiationDeclaration)
1557 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001558
Douglas Gregor7caa6822009-07-24 20:34:43 +00001559 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
1560 if (Inst)
1561 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001562
Douglas Gregor7caa6822009-07-24 20:34:43 +00001563 // If we're performing recursive template instantiation, create our own
1564 // queue of pending implicit instantiations that we will instantiate later,
1565 // while we're still within our own instantiation context.
1566 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1567 if (Recursive)
1568 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001569
Douglas Gregor7caa6822009-07-24 20:34:43 +00001570 // Enter the scope of this instantiation. We don't use
1571 // PushDeclContext because we don't have a scope.
1572 DeclContext *PreviousContext = CurContext;
1573 CurContext = Var->getDeclContext();
Mike Stump1eb44332009-09-09 15:08:12 +00001574
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001575 VarDecl *OldVar = Var;
John McCallce3ff2b2009-08-25 22:02:44 +00001576 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Douglas Gregor7caa6822009-07-24 20:34:43 +00001577 getTemplateInstantiationArgs(Var)));
Douglas Gregor7caa6822009-07-24 20:34:43 +00001578 CurContext = PreviousContext;
1579
1580 if (Var) {
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001581 Var->setPreviousDeclaration(OldVar);
Douglas Gregor583f33b2009-10-15 18:07:02 +00001582 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
1583 assert(MSInfo && "Missing member specialization information?");
1584 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
1585 MSInfo->getPointOfInstantiation());
Douglas Gregor7caa6822009-07-24 20:34:43 +00001586 DeclGroupRef DG(Var);
1587 Consumer.HandleTopLevelDecl(DG);
1588 }
Mike Stump1eb44332009-09-09 15:08:12 +00001589
Douglas Gregor7caa6822009-07-24 20:34:43 +00001590 if (Recursive) {
1591 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00001592 // instantiation of this template.
Douglas Gregor7caa6822009-07-24 20:34:43 +00001593 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00001594
Douglas Gregor7caa6822009-07-24 20:34:43 +00001595 // Restore the set of pending implicit instantiations.
1596 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001597 }
Douglas Gregora58861f2009-05-13 20:28:22 +00001598}
Douglas Gregor815215d2009-05-27 05:35:12 +00001599
Anders Carlsson09025312009-08-29 05:16:22 +00001600void
1601Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
1602 const CXXConstructorDecl *Tmpl,
1603 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00001604
Anders Carlsson09025312009-08-29 05:16:22 +00001605 llvm::SmallVector<MemInitTy*, 4> NewInits;
1606
1607 // Instantiate all the initializers.
1608 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00001609 InitsEnd = Tmpl->init_end();
1610 Inits != InitsEnd; ++Inits) {
Anders Carlsson09025312009-08-29 05:16:22 +00001611 CXXBaseOrMemberInitializer *Init = *Inits;
1612
1613 ASTOwningVector<&ActionBase::DeleteExpr> NewArgs(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00001614
Anders Carlsson09025312009-08-29 05:16:22 +00001615 // Instantiate all the arguments.
1616 for (ExprIterator Args = Init->arg_begin(), ArgsEnd = Init->arg_end();
1617 Args != ArgsEnd; ++Args) {
1618 OwningExprResult NewArg = SubstExpr(*Args, TemplateArgs);
1619
1620 if (NewArg.isInvalid())
1621 New->setInvalidDecl();
1622 else
1623 NewArgs.push_back(NewArg.takeAs<Expr>());
1624 }
1625
1626 MemInitResult NewInit;
1627
1628 if (Init->isBaseInitializer()) {
Eli Friedmanc5573a82009-08-29 22:22:07 +00001629 QualType BaseType(Init->getBaseClass(), 0);
1630 BaseType = SubstType(BaseType, TemplateArgs, Init->getSourceLocation(),
1631 New->getDeclName());
Anders Carlsson09025312009-08-29 05:16:22 +00001632
1633 NewInit = BuildBaseInitializer(BaseType,
Mike Stump1eb44332009-09-09 15:08:12 +00001634 (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00001635 NewArgs.size(),
1636 Init->getSourceLocation(),
1637 Init->getRParenLoc(),
1638 New->getParent());
1639 } else if (Init->isMemberInitializer()) {
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001640 FieldDecl *Member;
Mike Stump1eb44332009-09-09 15:08:12 +00001641
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001642 // Is this an anonymous union?
1643 if (FieldDecl *UnionInit = Init->getAnonUnionMember())
Douglas Gregore95b4092009-09-16 18:34:49 +00001644 Member = cast<FieldDecl>(FindInstantiatedDecl(UnionInit, TemplateArgs));
Anders Carlsson9988d5d2009-09-01 04:31:02 +00001645 else
Douglas Gregore95b4092009-09-16 18:34:49 +00001646 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMember(),
1647 TemplateArgs));
Mike Stump1eb44332009-09-09 15:08:12 +00001648
1649 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00001650 NewArgs.size(),
1651 Init->getSourceLocation(),
1652 Init->getRParenLoc());
1653 }
1654
1655 if (NewInit.isInvalid())
1656 New->setInvalidDecl();
1657 else {
1658 // FIXME: It would be nice if ASTOwningVector had a release function.
1659 NewArgs.take();
Mike Stump1eb44332009-09-09 15:08:12 +00001660
Anders Carlsson09025312009-08-29 05:16:22 +00001661 NewInits.push_back((MemInitTy *)NewInit.get());
1662 }
1663 }
Mike Stump1eb44332009-09-09 15:08:12 +00001664
Anders Carlsson09025312009-08-29 05:16:22 +00001665 // Assign all the initializers to the new constructor.
Mike Stump1eb44332009-09-09 15:08:12 +00001666 ActOnMemInitializers(DeclPtrTy::make(New),
Anders Carlsson09025312009-08-29 05:16:22 +00001667 /*FIXME: ColonLoc */
1668 SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001669 NewInits.data(), NewInits.size());
Anders Carlsson09025312009-08-29 05:16:22 +00001670}
1671
John McCall52a575a2009-08-29 08:11:13 +00001672// TODO: this could be templated if the various decl types used the
1673// same method name.
1674static bool isInstantiationOf(ClassTemplateDecl *Pattern,
1675 ClassTemplateDecl *Instance) {
1676 Pattern = Pattern->getCanonicalDecl();
1677
1678 do {
1679 Instance = Instance->getCanonicalDecl();
1680 if (Pattern == Instance) return true;
1681 Instance = Instance->getInstantiatedFromMemberTemplate();
1682 } while (Instance);
1683
1684 return false;
1685}
1686
Douglas Gregor0d696532009-09-28 06:34:35 +00001687static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
1688 FunctionTemplateDecl *Instance) {
1689 Pattern = Pattern->getCanonicalDecl();
1690
1691 do {
1692 Instance = Instance->getCanonicalDecl();
1693 if (Pattern == Instance) return true;
1694 Instance = Instance->getInstantiatedFromMemberTemplate();
1695 } while (Instance);
1696
1697 return false;
1698}
1699
Douglas Gregored9c0f92009-10-29 00:04:11 +00001700static bool
1701isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
1702 ClassTemplatePartialSpecializationDecl *Instance) {
1703 Pattern
1704 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
1705 do {
1706 Instance = cast<ClassTemplatePartialSpecializationDecl>(
1707 Instance->getCanonicalDecl());
1708 if (Pattern == Instance)
1709 return true;
1710 Instance = Instance->getInstantiatedFromMember();
1711 } while (Instance);
1712
1713 return false;
1714}
1715
John McCall52a575a2009-08-29 08:11:13 +00001716static bool isInstantiationOf(CXXRecordDecl *Pattern,
1717 CXXRecordDecl *Instance) {
1718 Pattern = Pattern->getCanonicalDecl();
1719
1720 do {
1721 Instance = Instance->getCanonicalDecl();
1722 if (Pattern == Instance) return true;
1723 Instance = Instance->getInstantiatedFromMemberClass();
1724 } while (Instance);
1725
1726 return false;
1727}
1728
1729static bool isInstantiationOf(FunctionDecl *Pattern,
1730 FunctionDecl *Instance) {
1731 Pattern = Pattern->getCanonicalDecl();
1732
1733 do {
1734 Instance = Instance->getCanonicalDecl();
1735 if (Pattern == Instance) return true;
1736 Instance = Instance->getInstantiatedFromMemberFunction();
1737 } while (Instance);
1738
1739 return false;
1740}
1741
1742static bool isInstantiationOf(EnumDecl *Pattern,
1743 EnumDecl *Instance) {
1744 Pattern = Pattern->getCanonicalDecl();
1745
1746 do {
1747 Instance = Instance->getCanonicalDecl();
1748 if (Pattern == Instance) return true;
1749 Instance = Instance->getInstantiatedFromMemberEnum();
1750 } while (Instance);
1751
1752 return false;
1753}
1754
John McCall7ba107a2009-11-18 02:36:19 +00001755static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
1756 UsingDecl *Instance,
1757 ASTContext &C) {
1758 return C.getInstantiatedFromUnresolvedUsingDecl(Instance) == Pattern;
1759}
1760
1761static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson0d8df782009-08-29 19:37:28 +00001762 UsingDecl *Instance,
1763 ASTContext &C) {
1764 return C.getInstantiatedFromUnresolvedUsingDecl(Instance) == Pattern;
1765}
1766
John McCall52a575a2009-08-29 08:11:13 +00001767static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
1768 VarDecl *Instance) {
1769 assert(Instance->isStaticDataMember());
1770
1771 Pattern = Pattern->getCanonicalDecl();
1772
1773 do {
1774 Instance = Instance->getCanonicalDecl();
1775 if (Pattern == Instance) return true;
1776 Instance = Instance->getInstantiatedFromStaticDataMember();
1777 } while (Instance);
1778
1779 return false;
1780}
1781
Douglas Gregor815215d2009-05-27 05:35:12 +00001782static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00001783 if (D->getKind() != Other->getKind()) {
John McCall7ba107a2009-11-18 02:36:19 +00001784 if (UnresolvedUsingTypenameDecl *UUD
1785 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
1786 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
1787 return isInstantiationOf(UUD, UD, Ctx);
1788 }
1789 }
1790
1791 if (UnresolvedUsingValueDecl *UUD
1792 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00001793 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
1794 return isInstantiationOf(UUD, UD, Ctx);
1795 }
1796 }
Douglas Gregor815215d2009-05-27 05:35:12 +00001797
Anders Carlsson0d8df782009-08-29 19:37:28 +00001798 return false;
1799 }
Mike Stump1eb44332009-09-09 15:08:12 +00001800
John McCall52a575a2009-08-29 08:11:13 +00001801 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
1802 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00001803
John McCall52a575a2009-08-29 08:11:13 +00001804 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
1805 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00001806
John McCall52a575a2009-08-29 08:11:13 +00001807 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
1808 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00001809
Douglas Gregor7caa6822009-07-24 20:34:43 +00001810 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00001811 if (Var->isStaticDataMember())
1812 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
1813
1814 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
1815 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00001816
Douglas Gregor0d696532009-09-28 06:34:35 +00001817 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
1818 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
1819
Douglas Gregored9c0f92009-10-29 00:04:11 +00001820 if (ClassTemplatePartialSpecializationDecl *PartialSpec
1821 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
1822 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
1823 PartialSpec);
1824
Anders Carlssond8b285f2009-09-01 04:26:58 +00001825 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
1826 if (!Field->getDeclName()) {
1827 // This is an unnamed field.
Mike Stump1eb44332009-09-09 15:08:12 +00001828 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlssond8b285f2009-09-01 04:26:58 +00001829 cast<FieldDecl>(D);
1830 }
1831 }
Mike Stump1eb44332009-09-09 15:08:12 +00001832
Douglas Gregor815215d2009-05-27 05:35:12 +00001833 return D->getDeclName() && isa<NamedDecl>(Other) &&
1834 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
1835}
1836
1837template<typename ForwardIterator>
Mike Stump1eb44332009-09-09 15:08:12 +00001838static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor815215d2009-05-27 05:35:12 +00001839 NamedDecl *D,
1840 ForwardIterator first,
1841 ForwardIterator last) {
1842 for (; first != last; ++first)
1843 if (isInstantiationOf(Ctx, D, *first))
1844 return cast<NamedDecl>(*first);
1845
1846 return 0;
1847}
1848
John McCall02cace72009-08-28 07:59:38 +00001849/// \brief Finds the instantiation of the given declaration context
1850/// within the current instantiation.
1851///
1852/// \returns NULL if there was an error
Douglas Gregore95b4092009-09-16 18:34:49 +00001853DeclContext *Sema::FindInstantiatedContext(DeclContext* DC,
1854 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCall02cace72009-08-28 07:59:38 +00001855 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregore95b4092009-09-16 18:34:49 +00001856 Decl* ID = FindInstantiatedDecl(D, TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +00001857 return cast_or_null<DeclContext>(ID);
1858 } else return DC;
1859}
1860
Douglas Gregored961e72009-05-27 17:54:46 +00001861/// \brief Find the instantiation of the given declaration within the
1862/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00001863///
1864/// This routine is intended to be used when \p D is a declaration
1865/// referenced from within a template, that needs to mapped into the
1866/// corresponding declaration within an instantiation. For example,
1867/// given:
1868///
1869/// \code
1870/// template<typename T>
1871/// struct X {
1872/// enum Kind {
1873/// KnownValue = sizeof(T)
1874/// };
1875///
1876/// bool getKind() const { return KnownValue; }
1877/// };
1878///
1879/// template struct X<int>;
1880/// \endcode
1881///
1882/// In the instantiation of X<int>::getKind(), we need to map the
1883/// EnumConstantDecl for KnownValue (which refers to
1884/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00001885/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
1886/// this mapping from within the instantiation of X<int>.
Douglas Gregore95b4092009-09-16 18:34:49 +00001887NamedDecl *Sema::FindInstantiatedDecl(NamedDecl *D,
1888 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor44c73842009-09-01 17:53:10 +00001889 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D)) {
1890 // Transform all of the elements of the overloaded function set.
Mike Stump1eb44332009-09-09 15:08:12 +00001891 OverloadedFunctionDecl *Result
Douglas Gregor44c73842009-09-01 17:53:10 +00001892 = OverloadedFunctionDecl::Create(Context, CurContext, Ovl->getDeclName());
Mike Stump1eb44332009-09-09 15:08:12 +00001893
Douglas Gregor44c73842009-09-01 17:53:10 +00001894 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
1895 FEnd = Ovl->function_end();
1896 F != FEnd; ++F) {
1897 Result->addOverload(
Douglas Gregore95b4092009-09-16 18:34:49 +00001898 AnyFunctionDecl::getFromNamedDecl(FindInstantiatedDecl(*F,
1899 TemplateArgs)));
Douglas Gregor44c73842009-09-01 17:53:10 +00001900 }
Mike Stump1eb44332009-09-09 15:08:12 +00001901
Douglas Gregor44c73842009-09-01 17:53:10 +00001902 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00001903 }
1904
Douglas Gregor815215d2009-05-27 05:35:12 +00001905 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor550d9b22009-10-31 17:21:17 +00001906 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
1907 isa<TemplateTypeParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
1908 ParentDC->isFunctionOrMethod()) {
Douglas Gregor2bba76b2009-05-27 17:07:49 +00001909 // D is a local of some kind. Look into the map of local
1910 // declarations to their instantiations.
1911 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
1912 }
Douglas Gregor815215d2009-05-27 05:35:12 +00001913
Douglas Gregore95b4092009-09-16 18:34:49 +00001914 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
1915 if (!Record->isDependentContext())
1916 return D;
1917
1918 // If the RecordDecl is actually the injected-class-name or a "templated"
1919 // declaration for a class template or class template partial
1920 // specialization, substitute into the injected-class-name of the
1921 // class template or partial specialization to find the new DeclContext.
1922 QualType T;
1923 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
1924
1925 if (ClassTemplate) {
1926 T = ClassTemplate->getInjectedClassNameType(Context);
1927 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
1928 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
1929 T = Context.getTypeDeclType(Record);
1930 ClassTemplate = PartialSpec->getSpecializedTemplate();
1931 }
1932
1933 if (!T.isNull()) {
1934 // Substitute into the injected-class-name to get the type corresponding
1935 // to the instantiation we want. This substitution should never fail,
1936 // since we know we can instantiate the injected-class-name or we wouldn't
1937 // have gotten to the injected-class-name!
1938 // FIXME: Can we use the CurrentInstantiationScope to avoid this extra
1939 // instantiation in the common case?
1940 T = SubstType(T, TemplateArgs, SourceLocation(), DeclarationName());
1941 assert(!T.isNull() && "Instantiation of injected-class-name cannot fail.");
1942
1943 if (!T->isDependentType()) {
1944 assert(T->isRecordType() && "Instantiation must produce a record type");
1945 return T->getAs<RecordType>()->getDecl();
1946 }
1947
1948 // We are performing "partial" template instantiation to create the
1949 // member declarations for the members of a class template
1950 // specialization. Therefore, D is actually referring to something in
1951 // the current instantiation. Look through the current context,
1952 // which contains actual instantiations, to find the instantiation of
1953 // the "current instantiation" that D refers to.
Mike Stump1eb44332009-09-09 15:08:12 +00001954 for (DeclContext *DC = CurContext; !DC->isFileContext();
John McCall52a575a2009-08-29 08:11:13 +00001955 DC = DC->getParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001956 if (ClassTemplateSpecializationDecl *Spec
John McCall52a575a2009-08-29 08:11:13 +00001957 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Douglas Gregore95b4092009-09-16 18:34:49 +00001958 if (isInstantiationOf(ClassTemplate,
1959 Spec->getSpecializedTemplate()))
John McCall52a575a2009-08-29 08:11:13 +00001960 return Spec;
1961 }
1962
Mike Stump1eb44332009-09-09 15:08:12 +00001963 assert(false &&
John McCall52a575a2009-08-29 08:11:13 +00001964 "Unable to find declaration for the current instantiation");
Douglas Gregore95b4092009-09-16 18:34:49 +00001965 return Record;
John McCall52a575a2009-08-29 08:11:13 +00001966 }
Douglas Gregore95b4092009-09-16 18:34:49 +00001967
1968 // Fall through to deal with other dependent record types (e.g.,
1969 // anonymous unions in class templates).
1970 }
John McCall52a575a2009-08-29 08:11:13 +00001971
Douglas Gregore95b4092009-09-16 18:34:49 +00001972 if (!ParentDC->isDependentContext())
1973 return D;
1974
1975 ParentDC = FindInstantiatedContext(ParentDC, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001976 if (!ParentDC)
Douglas Gregor44c73842009-09-01 17:53:10 +00001977 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001978
Douglas Gregor815215d2009-05-27 05:35:12 +00001979 if (ParentDC != D->getDeclContext()) {
1980 // We performed some kind of instantiation in the parent context,
1981 // so now we need to look into the instantiated parent context to
1982 // find the instantiation of the declaration D.
1983 NamedDecl *Result = 0;
1984 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001985 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00001986 Result = findInstantiationOf(Context, D, Found.first, Found.second);
1987 } else {
1988 // Since we don't have a name for the entity we're looking for,
1989 // our only option is to walk through all of the declarations to
1990 // find that name. This will occur in a few cases:
1991 //
1992 // - anonymous struct/union within a template
1993 // - unnamed class/struct/union/enum within a template
1994 //
1995 // FIXME: Find a better way to find these instantiations!
Mike Stump1eb44332009-09-09 15:08:12 +00001996 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001997 ParentDC->decls_begin(),
1998 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00001999 }
Mike Stump1eb44332009-09-09 15:08:12 +00002000
Douglas Gregor815215d2009-05-27 05:35:12 +00002001 assert(Result && "Unable to find instantiation of declaration!");
2002 D = Result;
2003 }
2004
Douglas Gregor815215d2009-05-27 05:35:12 +00002005 return D;
2006}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002007
Mike Stump1eb44332009-09-09 15:08:12 +00002008/// \brief Performs template instantiation for all implicit template
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002009/// instantiations we have seen until this point.
2010void Sema::PerformPendingImplicitInstantiations() {
2011 while (!PendingImplicitInstantiations.empty()) {
2012 PendingImplicitInstantiation Inst = PendingImplicitInstantiations.front();
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002013 PendingImplicitInstantiations.pop_front();
Mike Stump1eb44332009-09-09 15:08:12 +00002014
Douglas Gregor7caa6822009-07-24 20:34:43 +00002015 // Instantiate function definitions
2016 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002017 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Function),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002018 Function->getLocation(), *this,
2019 Context.getSourceManager(),
2020 "instantiating function definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002021
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002022 if (!Function->getBody())
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002023 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00002024 continue;
2025 }
Mike Stump1eb44332009-09-09 15:08:12 +00002026
Douglas Gregor7caa6822009-07-24 20:34:43 +00002027 // Instantiate static data member definitions.
2028 VarDecl *Var = cast<VarDecl>(Inst.first);
2029 assert(Var->isStaticDataMember() && "Not a static data member?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002030
Mike Stump1eb44332009-09-09 15:08:12 +00002031 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Var),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002032 Var->getLocation(), *this,
2033 Context.getSourceManager(),
2034 "instantiating static data member "
2035 "definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002036
Douglas Gregor7caa6822009-07-24 20:34:43 +00002037 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002038 }
2039}