blob: 42fc1f8165d580d929a41ce0895e7a7b8f287f56 [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"
Douglas Gregor83ddad32009-08-26 21:14:46 +000018#include "clang/Lex/Preprocessor.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000019#include "llvm/Support/Compiler.h"
20
21using namespace clang;
22
23namespace {
24 class VISIBILITY_HIDDEN TemplateDeclInstantiator
Chris Lattnerb28317a2009-03-28 19:18:32 +000025 : public DeclVisitor<TemplateDeclInstantiator, Decl *> {
Douglas Gregor8dbc2692009-03-17 21:15:40 +000026 Sema &SemaRef;
27 DeclContext *Owner;
Douglas Gregor7e063902009-05-11 23:53:27 +000028 const TemplateArgumentList &TemplateArgs;
Douglas Gregor8dbc2692009-03-17 21:15:40 +000029
30 public:
31 typedef Sema::OwningExprResult OwningExprResult;
32
33 TemplateDeclInstantiator(Sema &SemaRef, DeclContext *Owner,
Douglas Gregor7e063902009-05-11 23:53:27 +000034 const TemplateArgumentList &TemplateArgs)
35 : SemaRef(SemaRef), Owner(Owner), TemplateArgs(TemplateArgs) { }
Douglas Gregor8dbc2692009-03-17 21:15:40 +000036
Mike Stump390b4cc2009-05-16 07:39:55 +000037 // FIXME: Once we get closer to completion, replace these manually-written
38 // declarations with automatically-generated ones from
39 // clang/AST/DeclNodes.def.
Douglas Gregor4f722be2009-03-25 15:45:12 +000040 Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D);
41 Decl *VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000042 Decl *VisitTypedefDecl(TypedefDecl *D);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +000043 Decl *VisitVarDecl(VarDecl *D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000044 Decl *VisitFieldDecl(FieldDecl *D);
45 Decl *VisitStaticAssertDecl(StaticAssertDecl *D);
46 Decl *VisitEnumDecl(EnumDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000047 Decl *VisitEnumConstantDecl(EnumConstantDecl *D);
John McCallfd810b12009-08-14 02:03:10 +000048 Decl *VisitFriendClassDecl(FriendClassDecl *D);
Douglas Gregore53060f2009-06-25 22:08:12 +000049 Decl *VisitFunctionDecl(FunctionDecl *D);
Douglas Gregord475b8d2009-03-25 21:17:03 +000050 Decl *VisitCXXRecordDecl(CXXRecordDecl *D);
Douglas Gregord60e1052009-08-27 16:57:43 +000051 Decl *VisitCXXMethodDecl(CXXMethodDecl *D,
52 TemplateParameterList *TemplateParams = 0);
Douglas Gregor615c5d42009-03-24 16:43:20 +000053 Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
Douglas Gregor03b2b072009-03-24 00:15:49 +000054 Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +000055 Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000056 ParmVarDecl *VisitParmVarDecl(ParmVarDecl *D);
Douglas Gregor2dc0e642009-03-23 23:06:20 +000057 Decl *VisitOriginalParmVarDecl(OriginalParmVarDecl *D);
John McCalle29ba202009-08-20 01:44:21 +000058 Decl *VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregord60e1052009-08-27 16:57:43 +000059 Decl *VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
John McCalle29ba202009-08-20 01:44:21 +000060 Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Douglas Gregor5545e162009-03-24 00:38:23 +000061
Douglas Gregor8dbc2692009-03-17 21:15:40 +000062 // Base case. FIXME: Remove once we can instantiate everything.
63 Decl *VisitDecl(Decl *) {
Douglas Gregor3d7a12a2009-03-25 23:32:15 +000064 assert(false && "Template instantiation of unknown declaration kind!");
Douglas Gregor8dbc2692009-03-17 21:15:40 +000065 return 0;
66 }
Douglas Gregor5545e162009-03-24 00:38:23 +000067
John McCallfd810b12009-08-14 02:03:10 +000068 const LangOptions &getLangOptions() {
69 return SemaRef.getLangOptions();
70 }
71
Douglas Gregor5545e162009-03-24 00:38:23 +000072 // Helper functions for instantiating methods.
John McCallce3ff2b2009-08-25 22:02:44 +000073 QualType SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +000074 llvm::SmallVectorImpl<ParmVarDecl *> &Params);
Douglas Gregore53060f2009-06-25 22:08:12 +000075 bool InitFunctionInstantiation(FunctionDecl *New, FunctionDecl *Tmpl);
Douglas Gregor5545e162009-03-24 00:38:23 +000076 bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl);
John McCalle29ba202009-08-20 01:44:21 +000077
78 TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +000079 SubstTemplateParams(TemplateParameterList *List);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000080 };
81}
82
Douglas Gregor4f722be2009-03-25 15:45:12 +000083Decl *
84TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
85 assert(false && "Translation units cannot be instantiated");
86 return D;
87}
88
89Decl *
90TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
91 assert(false && "Namespaces cannot be instantiated");
92 return D;
93}
94
Douglas Gregor8dbc2692009-03-17 21:15:40 +000095Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
96 bool Invalid = false;
97 QualType T = D->getUnderlyingType();
98 if (T->isDependentType()) {
John McCallce3ff2b2009-08-25 22:02:44 +000099 T = SemaRef.SubstType(T, TemplateArgs,
100 D->getLocation(), D->getDeclName());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000101 if (T.isNull()) {
102 Invalid = true;
103 T = SemaRef.Context.IntTy;
104 }
105 }
106
107 // Create the new typedef
108 TypedefDecl *Typedef
109 = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(),
110 D->getIdentifier(), T);
111 if (Invalid)
112 Typedef->setInvalidDecl();
113
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000114 Owner->addDecl(Typedef);
Douglas Gregorbc221632009-05-28 16:34:51 +0000115
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000116 return Typedef;
117}
118
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000119Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
John McCallce3ff2b2009-08-25 22:02:44 +0000120 // Do substitution on the type of the declaration
121 QualType T = SemaRef.SubstType(D->getType(), TemplateArgs,
122 D->getTypeSpecStartLoc(),
123 D->getDeclName());
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000124 if (T.isNull())
125 return 0;
126
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000127 // Build the instantiated declaration
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000128 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
129 D->getLocation(), D->getIdentifier(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000130 T, D->getDeclaratorInfo(),
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +0000131 D->getStorageClass());
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000132 Var->setThreadSpecified(D->isThreadSpecified());
133 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
134 Var->setDeclaredInCondition(D->isDeclaredInCondition());
135
Douglas Gregor7caa6822009-07-24 20:34:43 +0000136 // If we are instantiating a static data member defined
137 // out-of-line, the instantiation will have the same lexical
138 // context (which will be a namespace scope) as the template.
139 if (D->isOutOfLine())
140 Var->setLexicalDeclContext(D->getLexicalDeclContext());
141
Mike Stump390b4cc2009-05-16 07:39:55 +0000142 // FIXME: In theory, we could have a previous declaration for variables that
143 // are not static data members.
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000144 bool Redeclaration = false;
Chris Lattnereaaebc72009-04-25 08:06:05 +0000145 SemaRef.CheckVariableDeclaration(Var, 0, Redeclaration);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000146
147 if (D->isOutOfLine()) {
148 D->getLexicalDeclContext()->addDecl(Var);
149 Owner->makeDeclVisibleInContext(Var);
150 } else {
151 Owner->addDecl(Var);
152 }
153
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000154 if (D->getInit()) {
155 OwningExprResult Init
John McCallce3ff2b2009-08-25 22:02:44 +0000156 = SemaRef.SubstExpr(D->getInit(), TemplateArgs);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000157 if (Init.isInvalid())
158 Var->setInvalidDecl();
Douglas Gregor83ddad32009-08-26 21:14:46 +0000159 else if (ParenListExpr *PLE = dyn_cast<ParenListExpr>((Expr *)Init.get())) {
160 // FIXME: We're faking all of the comma locations, which is suboptimal.
161 // Do we even need these comma locations?
162 llvm::SmallVector<SourceLocation, 4> FakeCommaLocs;
163 if (PLE->getNumExprs() > 0) {
164 FakeCommaLocs.reserve(PLE->getNumExprs() - 1);
165 for (unsigned I = 0, N = PLE->getNumExprs() - 1; I != N; ++I) {
166 Expr *E = PLE->getExpr(I)->Retain();
167 FakeCommaLocs.push_back(
168 SemaRef.PP.getLocForEndOfToken(E->getLocEnd()));
169 }
Douglas Gregore9f8eb62009-08-26 23:26:04 +0000170 PLE->getExpr(PLE->getNumExprs() - 1)->Retain();
Douglas Gregor83ddad32009-08-26 21:14:46 +0000171 }
172
173 // Add the direct initializer to the declaration.
174 SemaRef.AddCXXDirectInitializerToDecl(Sema::DeclPtrTy::make(Var),
175 PLE->getLParenLoc(),
176 Sema::MultiExprArg(SemaRef,
177 (void**)PLE->getExprs(),
178 PLE->getNumExprs()),
179 FakeCommaLocs.data(),
180 PLE->getRParenLoc());
181
182 // When Init is destroyed, it will destroy the instantiated ParenListExpr;
183 // we've explicitly retained all of its subexpressions already.
184 } else
Chris Lattnerb28317a2009-03-28 19:18:32 +0000185 SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var), move(Init),
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000186 D->hasCXXDirectInitializer());
Douglas Gregor65b90052009-07-27 17:43:39 +0000187 } else if (!Var->isStaticDataMember() || Var->isOutOfLine())
188 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000189
Douglas Gregor7caa6822009-07-24 20:34:43 +0000190 // Link instantiations of static data members back to the template from
191 // which they were instantiated.
192 if (Var->isStaticDataMember())
193 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D);
194
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000195 return Var;
196}
197
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000198Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
199 bool Invalid = false;
200 QualType T = D->getType();
201 if (T->isDependentType()) {
John McCallce3ff2b2009-08-25 22:02:44 +0000202 T = SemaRef.SubstType(T, TemplateArgs,
203 D->getLocation(), D->getDeclName());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000204 if (!T.isNull() && T->isFunctionType()) {
205 // C++ [temp.arg.type]p3:
206 // If a declaration acquires a function type through a type
207 // dependent on a template-parameter and this causes a
208 // declaration that does not use the syntactic form of a
209 // function declarator to have function type, the program is
210 // ill-formed.
211 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
212 << T;
213 T = QualType();
214 Invalid = true;
215 }
216 }
217
218 Expr *BitWidth = D->getBitWidth();
219 if (Invalid)
220 BitWidth = 0;
221 else if (BitWidth) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000222 // The bit-width expression is not potentially evaluated.
223 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
224
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000225 OwningExprResult InstantiatedBitWidth
John McCallce3ff2b2009-08-25 22:02:44 +0000226 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000227 if (InstantiatedBitWidth.isInvalid()) {
228 Invalid = true;
229 BitWidth = 0;
230 } else
Anders Carlssone9146f22009-05-01 19:49:17 +0000231 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000232 }
233
234 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(), T,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000235 D->getDeclaratorInfo(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000236 cast<RecordDecl>(Owner),
237 D->getLocation(),
238 D->isMutable(),
239 BitWidth,
Steve Naroffea218b82009-07-14 14:58:18 +0000240 D->getTypeSpecStartLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000241 D->getAccess(),
242 0);
243 if (Field) {
244 if (Invalid)
245 Field->setInvalidDecl();
246
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000247 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000248 }
249
250 return Field;
251}
252
John McCallfd810b12009-08-14 02:03:10 +0000253Decl *TemplateDeclInstantiator::VisitFriendClassDecl(FriendClassDecl *D) {
254 QualType T = D->getFriendType();
255 if (T->isDependentType()) {
John McCallce3ff2b2009-08-25 22:02:44 +0000256 T = SemaRef.SubstType(T, TemplateArgs, D->getLocation(),
257 DeclarationName());
John McCallfd810b12009-08-14 02:03:10 +0000258 assert(T.isNull() || getLangOptions().CPlusPlus0x || T->isRecordType());
259 }
260
261 // FIXME: the target context might be dependent.
262 DeclContext *DC = D->getDeclContext();
263 assert(DC->isFileContext());
264
265 FriendClassDecl *NewD =
266 FriendClassDecl::Create(SemaRef.Context, DC, D->getLocation(), T,
267 D->getFriendLoc());
268 Owner->addDecl(NewD);
269 return NewD;
270}
271
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000272Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
273 Expr *AssertExpr = D->getAssertExpr();
274
Douglas Gregorac7610d2009-06-22 20:57:11 +0000275 // The expression in a static assertion is not potentially evaluated.
276 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
277
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000278 OwningExprResult InstantiatedAssertExpr
John McCallce3ff2b2009-08-25 22:02:44 +0000279 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000280 if (InstantiatedAssertExpr.isInvalid())
281 return 0;
282
Douglas Gregor43d9d922009-08-08 01:41:12 +0000283 OwningExprResult Message(SemaRef, D->getMessage());
284 D->getMessage()->Retain();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000285 Decl *StaticAssert
Chris Lattnerb28317a2009-03-28 19:18:32 +0000286 = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
287 move(InstantiatedAssertExpr),
288 move(Message)).getAs<Decl>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000289 return StaticAssert;
290}
291
292Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
293 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
294 D->getLocation(), D->getIdentifier(),
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000295 D->getTagKeywordLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000296 /*PrevDecl=*/0);
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000297 Enum->setInstantiationOfMemberEnum(D);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000298 Enum->setAccess(D->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000299 Owner->addDecl(Enum);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000300 Enum->startDefinition();
301
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000302 llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000303
304 EnumConstantDecl *LastEnumConst = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000305 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
306 ECEnd = D->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000307 EC != ECEnd; ++EC) {
308 // The specified value for the enumerator.
309 OwningExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000310 if (Expr *UninstValue = EC->getInitExpr()) {
311 // The enumerator's value expression is not potentially evaluated.
312 EnterExpressionEvaluationContext Unevaluated(SemaRef,
313 Action::Unevaluated);
314
John McCallce3ff2b2009-08-25 22:02:44 +0000315 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000316 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000317
318 // Drop the initial value and continue.
319 bool isInvalid = false;
320 if (Value.isInvalid()) {
321 Value = SemaRef.Owned((Expr *)0);
322 isInvalid = true;
323 }
324
325 EnumConstantDecl *EnumConst
326 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
327 EC->getLocation(), EC->getIdentifier(),
328 move(Value));
329
330 if (isInvalid) {
331 if (EnumConst)
332 EnumConst->setInvalidDecl();
333 Enum->setInvalidDecl();
334 }
335
336 if (EnumConst) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000337 Enum->addDecl(EnumConst);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000338 Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst));
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000339 LastEnumConst = EnumConst;
340 }
341 }
342
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000343 // FIXME: Fixup LBraceLoc and RBraceLoc
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000344 // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000345 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
346 Sema::DeclPtrTy::make(Enum),
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000347 &Enumerators[0], Enumerators.size(),
348 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000349
350 return Enum;
351}
352
Douglas Gregor6477b692009-03-25 15:04:13 +0000353Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
354 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
355 return 0;
356}
357
John McCalle29ba202009-08-20 01:44:21 +0000358Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
359 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000360 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Douglas Gregord60e1052009-08-27 16:57:43 +0000361 if (!InstParams)
362 return NULL;
John McCalle29ba202009-08-20 01:44:21 +0000363
364 CXXRecordDecl *Pattern = D->getTemplatedDecl();
365 CXXRecordDecl *RecordInst
366 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), Owner,
367 Pattern->getLocation(), Pattern->getIdentifier(),
368 Pattern->getTagKeywordLoc(), /*PrevDecl=*/ NULL);
369
370 ClassTemplateDecl *Inst
371 = ClassTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
372 D->getIdentifier(), InstParams, RecordInst, 0);
373 RecordInst->setDescribedClassTemplate(Inst);
374 Inst->setAccess(D->getAccess());
375 Inst->setInstantiatedFromMemberTemplate(D);
376
377 Owner->addDecl(Inst);
378 return Inst;
379}
380
Douglas Gregord60e1052009-08-27 16:57:43 +0000381Decl *
382TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
383 TemplateParameterList *TempParams = D->getTemplateParameters();
384 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
385 if (!InstParams)
386 return NULL;
387
388 // FIXME: Handle instantiation of nested function templates that aren't
389 // member function templates. This could happen inside a FriendDecl.
390 assert(isa<CXXMethodDecl>(D->getTemplatedDecl()));
391 CXXMethodDecl *InstMethod
392 = cast_or_null<CXXMethodDecl>(
393 VisitCXXMethodDecl(cast<CXXMethodDecl>(D->getTemplatedDecl()),
394 InstParams));
395 if (!InstMethod)
396 return 0;
397
398 // Link the instantiated function template declaration to the function
399 // template from which it was instantiated.
400 FunctionTemplateDecl *InstTemplate = InstMethod->getDescribedFunctionTemplate();
401 assert(InstTemplate && "VisitCXXMethodDecl didn't create a template!");
402 InstTemplate->setInstantiatedFromMemberTemplate(D);
403 Owner->addDecl(InstTemplate);
404 return InstTemplate;
405}
406
Douglas Gregord475b8d2009-03-25 21:17:03 +0000407Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
408 CXXRecordDecl *PrevDecl = 0;
409 if (D->isInjectedClassName())
410 PrevDecl = cast<CXXRecordDecl>(Owner);
411
412 CXXRecordDecl *Record
413 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000414 D->getLocation(), D->getIdentifier(),
415 D->getTagKeywordLoc(), PrevDecl);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000416 Record->setImplicit(D->isImplicit());
417 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000418 if (!D->isInjectedClassName())
419 Record->setInstantiationOfMemberClass(D);
420
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000421 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000422 return Record;
423}
424
Douglas Gregore53060f2009-06-25 22:08:12 +0000425Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000426 // Check whether there is already a function template specialization for
427 // this declaration.
428 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
429 void *InsertPos = 0;
430 if (FunctionTemplate) {
431 llvm::FoldingSetNodeID ID;
432 FunctionTemplateSpecializationInfo::Profile(ID,
433 TemplateArgs.getFlatArgumentList(),
Douglas Gregor828e2262009-07-29 16:09:57 +0000434 TemplateArgs.flat_size(),
435 SemaRef.Context);
Douglas Gregor127102b2009-06-29 20:59:39 +0000436
437 FunctionTemplateSpecializationInfo *Info
438 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
439 InsertPos);
440
441 // If we already have a function template specialization, return it.
442 if (Info)
443 return Info->Function;
444 }
Douglas Gregore53060f2009-06-25 22:08:12 +0000445
446 Sema::LocalInstantiationScope Scope(SemaRef);
447
448 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCallce3ff2b2009-08-25 22:02:44 +0000449 QualType T = SubstFunctionType(D, Params);
Douglas Gregore53060f2009-06-25 22:08:12 +0000450 if (T.isNull())
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000451 return 0;
John McCallfd810b12009-08-14 02:03:10 +0000452
Douglas Gregore53060f2009-06-25 22:08:12 +0000453 // Build the instantiated method declaration.
John McCallfd810b12009-08-14 02:03:10 +0000454 FunctionDecl *Function;
455 if (FriendFunctionDecl* FFD = dyn_cast<FriendFunctionDecl>(D)) {
456 // The new decl's semantic context. FIXME: this might need
457 // to be instantiated.
458 DeclContext *DC = D->getDeclContext();
459
460 // This assert is bogus and exists only to catch cases we don't
461 // handle yet.
462 assert(!DC->isDependentContext());
463
464 Function =
465 FriendFunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000466 D->getDeclName(), T, D->getDeclaratorInfo(),
467 D->isInline(), FFD->getFriendLoc());
John McCallfd810b12009-08-14 02:03:10 +0000468 Function->setLexicalDeclContext(Owner);
469 } else {
470 Function =
471 FunctionDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000472 D->getDeclName(), T, D->getDeclaratorInfo(),
473 D->getStorageClass(),
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +0000474 D->isInline(), D->hasWrittenPrototype());
John McCallfd810b12009-08-14 02:03:10 +0000475 }
Douglas Gregore53060f2009-06-25 22:08:12 +0000476
477 // Attach the parameters
478 for (unsigned P = 0; P < Params.size(); ++P)
479 Params[P]->setOwningFunction(Function);
480 Function->setParams(SemaRef.Context, Params.data(), Params.size());
481
482 if (InitFunctionInstantiation(Function, D))
483 Function->setInvalidDecl();
484
485 bool Redeclaration = false;
486 bool OverloadableAttrRequired = false;
487 NamedDecl *PrevDecl = 0;
488 SemaRef.CheckFunctionDeclaration(Function, PrevDecl, Redeclaration,
489 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000490
Douglas Gregor127102b2009-06-29 20:59:39 +0000491 if (FunctionTemplate) {
492 // Record this function template specialization.
493 Function->setFunctionTemplateSpecialization(SemaRef.Context,
494 FunctionTemplate,
495 &TemplateArgs,
496 InsertPos);
John McCallfd810b12009-08-14 02:03:10 +0000497 }
498
499 // If this was a friend function decl, it's a member which
500 // needs to be added.
501 if (isa<FriendFunctionDecl>(Function)) {
502 // If the new context is still dependent, this declaration
503 // needs to remain hidden.
504 if (Owner->isDependentContext())
505 Owner->addHiddenDecl(Function);
506 else
507 Owner->addDecl(Function);
508 }
Douglas Gregor127102b2009-06-29 20:59:39 +0000509
Douglas Gregore53060f2009-06-25 22:08:12 +0000510 return Function;
511}
512
Douglas Gregord60e1052009-08-27 16:57:43 +0000513Decl *
514TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
515 TemplateParameterList *TemplateParams) {
Douglas Gregor6b906862009-08-21 00:16:32 +0000516 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
517 void *InsertPos = 0;
Douglas Gregord60e1052009-08-27 16:57:43 +0000518 if (FunctionTemplate && !TemplateParams) {
519 // We are creating a function template specialization from a function
520 // template. Check whether there is already a function template
521 // specialization for this particular set of template arguments.
Douglas Gregor6b906862009-08-21 00:16:32 +0000522 llvm::FoldingSetNodeID ID;
523 FunctionTemplateSpecializationInfo::Profile(ID,
524 TemplateArgs.getFlatArgumentList(),
525 TemplateArgs.flat_size(),
526 SemaRef.Context);
527
528 FunctionTemplateSpecializationInfo *Info
529 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
530 InsertPos);
531
532 // If we already have a function template specialization, return it.
533 if (Info)
534 return Info->Function;
535 }
536
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000537 Sema::LocalInstantiationScope Scope(SemaRef);
538
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000539 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCallce3ff2b2009-08-25 22:02:44 +0000540 QualType T = SubstFunctionType(D, Params);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000541 if (T.isNull())
542 return 0;
543
544 // Build the instantiated method declaration.
545 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
Douglas Gregordec06662009-08-21 18:42:58 +0000546 CXXMethodDecl *Method = 0;
547
548 DeclarationName Name = D->getDeclName();
Douglas Gregor17e32f32009-08-21 22:43:28 +0000549 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Douglas Gregordec06662009-08-21 18:42:58 +0000550 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
551 Name = SemaRef.Context.DeclarationNames.getCXXConstructorName(
552 SemaRef.Context.getCanonicalType(ClassTy));
553 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
Douglas Gregor17e32f32009-08-21 22:43:28 +0000554 Constructor->getLocation(),
Douglas Gregordec06662009-08-21 18:42:58 +0000555 Name, T,
Douglas Gregor17e32f32009-08-21 22:43:28 +0000556 Constructor->getDeclaratorInfo(),
557 Constructor->isExplicit(),
558 Constructor->isInline(), false);
559 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
560 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
561 Name = SemaRef.Context.DeclarationNames.getCXXDestructorName(
562 SemaRef.Context.getCanonicalType(ClassTy));
563 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
564 Destructor->getLocation(), Name,
565 T, Destructor->isInline(), false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000566 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
567 CanQualType ConvTy
568 = SemaRef.Context.getCanonicalType(
569 T->getAsFunctionType()->getResultType());
570 Name = SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(
571 ConvTy);
572 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
573 Conversion->getLocation(), Name,
574 T, Conversion->getDeclaratorInfo(),
575 Conversion->isInline(),
576 Conversion->isExplicit());
Douglas Gregordec06662009-08-21 18:42:58 +0000577 } else {
578 Method = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
579 D->getDeclName(), T, D->getDeclaratorInfo(),
580 D->isStatic(), D->isInline());
581 }
Douglas Gregor6b906862009-08-21 00:16:32 +0000582
Douglas Gregord60e1052009-08-27 16:57:43 +0000583 if (TemplateParams) {
584 // Our resulting instantiation is actually a function template, since we
585 // are substituting only the outer template parameters. For example, given
586 //
587 // template<typename T>
588 // struct X {
589 // template<typename U> void f(T, U);
590 // };
591 //
592 // X<int> x;
593 //
594 // We are instantiating the member template "f" within X<int>, which means
595 // substituting int for T, but leaving "f" as a member function template.
596 // Build the function template itself.
597 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
598 Method->getLocation(),
599 Method->getDeclName(),
600 TemplateParams, Method);
601 if (D->isOutOfLine())
602 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
603 Method->setDescribedFunctionTemplate(FunctionTemplate);
604 } else if (!FunctionTemplate)
Douglas Gregor6b906862009-08-21 00:16:32 +0000605 Method->setInstantiationOfMemberFunction(D);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000606
Douglas Gregor7caa6822009-07-24 20:34:43 +0000607 // If we are instantiating a member function defined
608 // out-of-line, the instantiation will have the same lexical
609 // context (which will be a namespace scope) as the template.
610 if (D->isOutOfLine())
611 Method->setLexicalDeclContext(D->getLexicalDeclContext());
612
Douglas Gregor5545e162009-03-24 00:38:23 +0000613 // Attach the parameters
614 for (unsigned P = 0; P < Params.size(); ++P)
615 Params[P]->setOwningFunction(Method);
Jay Foadbeaaccd2009-05-21 09:52:38 +0000616 Method->setParams(SemaRef.Context, Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +0000617
618 if (InitMethodInstantiation(Method, D))
619 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000620
Douglas Gregordec06662009-08-21 18:42:58 +0000621 NamedDecl *PrevDecl = 0;
622
Douglas Gregord60e1052009-08-27 16:57:43 +0000623 if (!FunctionTemplate || TemplateParams) {
Douglas Gregordec06662009-08-21 18:42:58 +0000624 PrevDecl = SemaRef.LookupQualifiedName(Owner, Name,
625 Sema::LookupOrdinaryName, true);
626
627 // In C++, the previous declaration we find might be a tag type
628 // (class or enum). In this case, the new declaration will hide the
629 // tag type. Note that this does does not apply if we're declaring a
630 // typedef (C++ [dcl.typedef]p4).
631 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
632 PrevDecl = 0;
633 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000634
Douglas Gregord60e1052009-08-27 16:57:43 +0000635 if (FunctionTemplate && !TemplateParams)
Douglas Gregor6b906862009-08-21 00:16:32 +0000636 // Record this function template specialization.
637 Method->setFunctionTemplateSpecialization(SemaRef.Context,
638 FunctionTemplate,
639 &TemplateArgs,
640 InsertPos);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000641
642 bool Redeclaration = false;
643 bool OverloadableAttrRequired = false;
644 SemaRef.CheckFunctionDeclaration(Method, PrevDecl, Redeclaration,
645 /*FIXME:*/OverloadableAttrRequired);
646
647 if (!FunctionTemplate && (!Method->isInvalidDecl() || !PrevDecl))
Douglas Gregordec06662009-08-21 18:42:58 +0000648 Owner->addDecl(Method);
649
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000650 return Method;
651}
652
Douglas Gregor615c5d42009-03-24 16:43:20 +0000653Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +0000654 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +0000655}
656
Douglas Gregor03b2b072009-03-24 00:15:49 +0000657Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +0000658 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +0000659}
660
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000661Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000662 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000663}
664
Douglas Gregor6477b692009-03-25 15:04:13 +0000665ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
John McCallce3ff2b2009-08-25 22:02:44 +0000666 QualType OrigT = SemaRef.SubstType(D->getOriginalType(), TemplateArgs,
Douglas Gregor7e063902009-05-11 23:53:27 +0000667 D->getLocation(), D->getDeclName());
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000668 if (OrigT.isNull())
669 return 0;
670
671 QualType T = SemaRef.adjustParameterType(OrigT);
672
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000673 // Allocate the parameter
674 ParmVarDecl *Param = 0;
675 if (T == OrigT)
676 Param = ParmVarDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000677 D->getIdentifier(), T, D->getDeclaratorInfo(),
678 D->getStorageClass(), 0);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000679 else
680 Param = OriginalParmVarDecl::Create(SemaRef.Context, Owner,
681 D->getLocation(), D->getIdentifier(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000682 T, D->getDeclaratorInfo(), OrigT,
683 D->getStorageClass(), 0);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000684
Anders Carlsson9351c172009-08-25 03:18:48 +0000685 // Mark the default argument as being uninstantiated.
686 if (Expr *Arg = D->getDefaultArg())
687 Param->setUninstantiatedDefaultArg(Arg);
688
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000689 // Note: we don't try to instantiate function parameters until after
690 // we've instantiated the function's type. Therefore, we don't have
691 // to check for 'void' parameter types here.
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000692 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000693 return Param;
694}
695
696Decl *
697TemplateDeclInstantiator::VisitOriginalParmVarDecl(OriginalParmVarDecl *D) {
698 // Since parameter types can decay either before or after
699 // instantiation, we simply treat OriginalParmVarDecls as
700 // ParmVarDecls the same way, and create one or the other depending
701 // on what happens after template instantiation.
702 return VisitParmVarDecl(D);
703}
704
John McCalle29ba202009-08-20 01:44:21 +0000705Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
706 TemplateTypeParmDecl *D) {
707 // TODO: don't always clone when decls are refcounted.
708 const Type* T = D->getTypeForDecl();
709 assert(T->isTemplateTypeParmType());
710 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
711
712 TemplateTypeParmDecl *Inst =
713 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
714 TTPT->getDepth(), TTPT->getIndex(),
715 TTPT->getName(),
716 D->wasDeclaredWithTypename(),
717 D->isParameterPack());
718
719 if (D->hasDefaultArgument()) {
720 QualType DefaultPattern = D->getDefaultArgument();
721 QualType DefaultInst
John McCallce3ff2b2009-08-25 22:02:44 +0000722 = SemaRef.SubstType(DefaultPattern, TemplateArgs,
723 D->getDefaultArgumentLoc(),
724 D->getDeclName());
John McCalle29ba202009-08-20 01:44:21 +0000725
726 Inst->setDefaultArgument(DefaultInst,
727 D->getDefaultArgumentLoc(),
728 D->defaultArgumentWasInherited() /* preserve? */);
729 }
730
731 return Inst;
732}
733
John McCallce3ff2b2009-08-25 22:02:44 +0000734Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
735 const TemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +0000736 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000737 return Instantiator.Visit(D);
738}
739
John McCalle29ba202009-08-20 01:44:21 +0000740/// \brief Instantiates a nested template parameter list in the current
741/// instantiation context.
742///
743/// \param L The parameter list to instantiate
744///
745/// \returns NULL if there was an error
746TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +0000747TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +0000748 // Get errors for all the parameters before bailing out.
749 bool Invalid = false;
750
751 unsigned N = L->size();
752 typedef llvm::SmallVector<Decl*,8> ParamVector;
753 ParamVector Params;
754 Params.reserve(N);
755 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
756 PI != PE; ++PI) {
757 Decl *D = Visit(*PI);
758 Params.push_back(D);
759 Invalid = Invalid || !D;
760 }
761
762 // Clean up if we had an error.
763 if (Invalid) {
764 for (ParamVector::iterator PI = Params.begin(), PE = Params.end();
765 PI != PE; ++PI)
766 if (*PI)
767 (*PI)->Destroy(SemaRef.Context);
768 return NULL;
769 }
770
771 TemplateParameterList *InstL
772 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
773 L->getLAngleLoc(), &Params.front(), N,
774 L->getRAngleLoc());
775 return InstL;
776}
777
John McCallce3ff2b2009-08-25 22:02:44 +0000778/// \brief Does substitution on the type of the given function, including
779/// all of the function parameters.
Douglas Gregor5545e162009-03-24 00:38:23 +0000780///
John McCallce3ff2b2009-08-25 22:02:44 +0000781/// \param D The function whose type will be the basis of the substitution
Douglas Gregor5545e162009-03-24 00:38:23 +0000782///
783/// \param Params the instantiated parameter declarations
784
John McCallce3ff2b2009-08-25 22:02:44 +0000785/// \returns the instantiated function's type if successful, a NULL
Douglas Gregor5545e162009-03-24 00:38:23 +0000786/// type if there was an error.
787QualType
John McCallce3ff2b2009-08-25 22:02:44 +0000788TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +0000789 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
790 bool InvalidDecl = false;
791
John McCallce3ff2b2009-08-25 22:02:44 +0000792 // Substitute all of the function's formal parameter types.
Douglas Gregor7e063902009-05-11 23:53:27 +0000793 TemplateDeclInstantiator ParamInstantiator(SemaRef, 0, TemplateArgs);
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000794 llvm::SmallVector<QualType, 4> ParamTys;
Douglas Gregor5545e162009-03-24 00:38:23 +0000795 for (FunctionDecl::param_iterator P = D->param_begin(),
796 PEnd = D->param_end();
797 P != PEnd; ++P) {
Douglas Gregor6477b692009-03-25 15:04:13 +0000798 if (ParmVarDecl *PInst = ParamInstantiator.VisitParmVarDecl(*P)) {
Douglas Gregor5545e162009-03-24 00:38:23 +0000799 if (PInst->getType()->isVoidType()) {
800 SemaRef.Diag(PInst->getLocation(), diag::err_param_with_void_type);
801 PInst->setInvalidDecl();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000802 } else if (SemaRef.RequireNonAbstractType(PInst->getLocation(),
803 PInst->getType(),
804 diag::err_abstract_type_in_decl,
805 Sema::AbstractParamType))
Douglas Gregor5545e162009-03-24 00:38:23 +0000806 PInst->setInvalidDecl();
807
808 Params.push_back(PInst);
809 ParamTys.push_back(PInst->getType());
810
811 if (PInst->isInvalidDecl())
812 InvalidDecl = true;
813 } else
814 InvalidDecl = true;
815 }
816
817 // FIXME: Deallocate dead declarations.
818 if (InvalidDecl)
819 return QualType();
820
821 const FunctionProtoType *Proto = D->getType()->getAsFunctionProtoType();
822 assert(Proto && "Missing prototype?");
823 QualType ResultType
John McCallce3ff2b2009-08-25 22:02:44 +0000824 = SemaRef.SubstType(Proto->getResultType(), TemplateArgs,
825 D->getLocation(), D->getDeclName());
Douglas Gregor5545e162009-03-24 00:38:23 +0000826 if (ResultType.isNull())
827 return QualType();
828
Jay Foadbeaaccd2009-05-21 09:52:38 +0000829 return SemaRef.BuildFunctionType(ResultType, ParamTys.data(), ParamTys.size(),
Douglas Gregor5545e162009-03-24 00:38:23 +0000830 Proto->isVariadic(), Proto->getTypeQuals(),
831 D->getLocation(), D->getDeclName());
832}
833
Douglas Gregore53060f2009-06-25 22:08:12 +0000834/// \brief Initializes the common fields of an instantiation function
835/// declaration (New) from the corresponding fields of its template (Tmpl).
836///
837/// \returns true if there was an error
838bool
839TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
840 FunctionDecl *Tmpl) {
841 if (Tmpl->isDeleted())
842 New->setDeleted();
Douglas Gregorcca9e962009-07-01 22:01:06 +0000843
844 // If we are performing substituting explicitly-specified template arguments
845 // or deduced template arguments into a function template and we reach this
846 // point, we are now past the point where SFINAE applies and have committed
847 // to keeping the new function template specialization. We therefore
848 // convert the active template instantiation for the function template
849 // into a template instantiation for this specific function template
850 // specialization, which is not a SFINAE context, so that we diagnose any
851 // further errors in the declaration itself.
852 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
853 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
854 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
855 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
856 if (FunctionTemplateDecl *FunTmpl
857 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
858 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
859 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +0000860 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000861 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
862 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
863 }
864 }
865
Douglas Gregore53060f2009-06-25 22:08:12 +0000866 return false;
867}
868
Douglas Gregor5545e162009-03-24 00:38:23 +0000869/// \brief Initializes common fields of an instantiated method
870/// declaration (New) from the corresponding fields of its template
871/// (Tmpl).
872///
873/// \returns true if there was an error
874bool
875TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
876 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +0000877 if (InitFunctionInstantiation(New, Tmpl))
878 return true;
879
Douglas Gregor5545e162009-03-24 00:38:23 +0000880 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
881 New->setAccess(Tmpl->getAccess());
Anders Carlsson77b7f1d2009-05-14 22:15:41 +0000882 if (Tmpl->isVirtualAsWritten()) {
883 New->setVirtualAsWritten(true);
Douglas Gregor5545e162009-03-24 00:38:23 +0000884 Record->setAggregate(false);
885 Record->setPOD(false);
Eli Friedman1d954f62009-08-15 21:55:26 +0000886 Record->setEmpty(false);
Douglas Gregor5545e162009-03-24 00:38:23 +0000887 Record->setPolymorphic(true);
888 }
Douglas Gregor5545e162009-03-24 00:38:23 +0000889 if (Tmpl->isPure()) {
890 New->setPure();
891 Record->setAbstract(true);
892 }
893
894 // FIXME: attributes
895 // FIXME: New needs a pointer to Tmpl
896 return false;
897}
Douglas Gregora58861f2009-05-13 20:28:22 +0000898
899/// \brief Instantiate the definition of the given function from its
900/// template.
901///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000902/// \param PointOfInstantiation the point at which the instantiation was
903/// required. Note that this is not precisely a "point of instantiation"
904/// for the function, but it's close.
905///
Douglas Gregora58861f2009-05-13 20:28:22 +0000906/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000907/// function template specialization or member function of a class template
908/// specialization.
909///
910/// \param Recursive if true, recursively instantiates any functions that
911/// are required by this instantiation.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000912void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000913 FunctionDecl *Function,
914 bool Recursive) {
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000915 if (Function->isInvalidDecl())
916 return;
917
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000918 assert(!Function->getBody() && "Already instantiated!");
Douglas Gregord7f37bf2009-06-22 23:06:13 +0000919
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000920 // Find the function body that we'll be substituting.
Douglas Gregor1637be72009-06-26 00:10:03 +0000921 const FunctionDecl *PatternDecl = 0;
922 if (FunctionTemplateDecl *Primary = Function->getPrimaryTemplate())
923 PatternDecl = Primary->getTemplatedDecl();
924 else
925 PatternDecl = Function->getInstantiatedFromMemberFunction();
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000926 Stmt *Pattern = 0;
927 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000928 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000929
930 if (!Pattern)
931 return;
932
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000933 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
934 if (Inst)
935 return;
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000936
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000937 // If we're performing recursive template instantiation, create our own
938 // queue of pending implicit instantiations that we will instantiate later,
939 // while we're still within our own instantiation context.
940 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
941 if (Recursive)
942 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
943
Douglas Gregore2c31ff2009-05-15 17:59:04 +0000944 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
945
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000946 // Introduce a new scope where local variable instantiations will be
947 // recorded.
948 LocalInstantiationScope Scope(*this);
949
950 // Introduce the instantiated function parameters into the local
951 // instantiation scope.
952 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
953 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
954 Function->getParamDecl(I));
955
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000956 // Enter the scope of this instantiation. We don't use
957 // PushDeclContext because we don't have a scope.
958 DeclContext *PreviousContext = CurContext;
959 CurContext = Function;
960
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000961 // Instantiate the function body.
962 OwningStmtResult Body
John McCallce3ff2b2009-08-25 22:02:44 +0000963 = SubstStmt(Pattern, getTemplateInstantiationArgs(Function));
Douglas Gregore2c31ff2009-05-15 17:59:04 +0000964
965 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
966 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000967
968 CurContext = PreviousContext;
Douglas Gregoraba43bb2009-05-26 20:50:29 +0000969
970 DeclGroupRef DG(Function);
971 Consumer.HandleTopLevelDecl(DG);
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000972
973 if (Recursive) {
974 // Instantiate any pending implicit instantiations found during the
975 // instantiation of this template.
976 PerformPendingImplicitInstantiations();
977
978 // Restore the set of pending implicit instantiations.
979 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
980 }
Douglas Gregora58861f2009-05-13 20:28:22 +0000981}
982
983/// \brief Instantiate the definition of the given variable from its
984/// template.
985///
Douglas Gregor7caa6822009-07-24 20:34:43 +0000986/// \param PointOfInstantiation the point at which the instantiation was
987/// required. Note that this is not precisely a "point of instantiation"
988/// for the function, but it's close.
989///
990/// \param Var the already-instantiated declaration of a static member
991/// variable of a class template specialization.
992///
993/// \param Recursive if true, recursively instantiates any functions that
994/// are required by this instantiation.
995void Sema::InstantiateStaticDataMemberDefinition(
996 SourceLocation PointOfInstantiation,
997 VarDecl *Var,
998 bool Recursive) {
999 if (Var->isInvalidDecl())
1000 return;
1001
1002 // Find the out-of-line definition of this static data member.
1003 // FIXME: Do we have to look for specializations separately?
1004 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
1005 bool FoundOutOfLineDef = false;
1006 assert(Def && "This data member was not instantiated from a template?");
1007 assert(Def->isStaticDataMember() && "Not a static data member?");
1008 for (VarDecl::redecl_iterator RD = Def->redecls_begin(),
1009 RDEnd = Def->redecls_end();
1010 RD != RDEnd; ++RD) {
1011 if (RD->getLexicalDeclContext()->isFileContext()) {
1012 Def = *RD;
1013 FoundOutOfLineDef = true;
1014 }
1015 }
1016
1017 if (!FoundOutOfLineDef) {
1018 // We did not find an out-of-line definition of this static data member,
1019 // so we won't perform any instantiation. Rather, we rely on the user to
1020 // instantiate this definition (or provide a specialization for it) in
1021 // another translation unit.
1022 return;
1023 }
1024
1025 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
1026 if (Inst)
1027 return;
1028
1029 // If we're performing recursive template instantiation, create our own
1030 // queue of pending implicit instantiations that we will instantiate later,
1031 // while we're still within our own instantiation context.
1032 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1033 if (Recursive)
1034 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1035
1036 // Enter the scope of this instantiation. We don't use
1037 // PushDeclContext because we don't have a scope.
1038 DeclContext *PreviousContext = CurContext;
1039 CurContext = Var->getDeclContext();
1040
1041#if 0
1042 // Instantiate the initializer of this static data member.
1043 OwningExprResult Init
1044 = InstantiateExpr(Def->getInit(), getTemplateInstantiationArgs(Var));
1045 if (Init.isInvalid()) {
1046 // If instantiation of the initializer failed, mark the declaration invalid
1047 // and don't instantiate anything else that was triggered by this
1048 // instantiation.
1049 Var->setInvalidDecl();
1050
1051 // Restore the set of pending implicit instantiations.
1052 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1053
1054 return;
1055 }
1056
1057 // Type-check the initializer.
1058 if (Init.get())
1059 AddInitializerToDecl(DeclPtrTy::make(Var), move(Init),
1060 Def->hasCXXDirectInitializer());
1061 else
1062 ActOnUninitializedDecl(DeclPtrTy::make(Var), false);
1063#else
John McCallce3ff2b2009-08-25 22:02:44 +00001064 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Douglas Gregor7caa6822009-07-24 20:34:43 +00001065 getTemplateInstantiationArgs(Var)));
1066#endif
1067
1068 CurContext = PreviousContext;
1069
1070 if (Var) {
1071 DeclGroupRef DG(Var);
1072 Consumer.HandleTopLevelDecl(DG);
1073 }
1074
1075 if (Recursive) {
1076 // Instantiate any pending implicit instantiations found during the
1077 // instantiation of this template.
1078 PerformPendingImplicitInstantiations();
1079
1080 // Restore the set of pending implicit instantiations.
1081 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1082 }
Douglas Gregora58861f2009-05-13 20:28:22 +00001083}
Douglas Gregor815215d2009-05-27 05:35:12 +00001084
1085static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
1086 if (D->getKind() != Other->getKind())
1087 return false;
1088
1089 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001090 return Record->getInstantiatedFromMemberClass()->getCanonicalDecl()
1091 == D->getCanonicalDecl();
Douglas Gregor815215d2009-05-27 05:35:12 +00001092
1093 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001094 return Function->getInstantiatedFromMemberFunction()->getCanonicalDecl()
1095 == D->getCanonicalDecl();
Douglas Gregor815215d2009-05-27 05:35:12 +00001096
Douglas Gregor8dbc3c62009-05-27 17:20:35 +00001097 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001098 return Enum->getInstantiatedFromMemberEnum()->getCanonicalDecl()
1099 == D->getCanonicalDecl();
Douglas Gregor815215d2009-05-27 05:35:12 +00001100
Douglas Gregor7caa6822009-07-24 20:34:43 +00001101 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
1102 if (Var->isStaticDataMember())
1103 return Var->getInstantiatedFromStaticDataMember()->getCanonicalDecl()
1104 == D->getCanonicalDecl();
1105
Douglas Gregor815215d2009-05-27 05:35:12 +00001106 // FIXME: How can we find instantiations of anonymous unions?
1107
1108 return D->getDeclName() && isa<NamedDecl>(Other) &&
1109 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
1110}
1111
1112template<typename ForwardIterator>
1113static NamedDecl *findInstantiationOf(ASTContext &Ctx,
1114 NamedDecl *D,
1115 ForwardIterator first,
1116 ForwardIterator last) {
1117 for (; first != last; ++first)
1118 if (isInstantiationOf(Ctx, D, *first))
1119 return cast<NamedDecl>(*first);
1120
1121 return 0;
1122}
1123
Douglas Gregored961e72009-05-27 17:54:46 +00001124/// \brief Find the instantiation of the given declaration within the
1125/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00001126///
1127/// This routine is intended to be used when \p D is a declaration
1128/// referenced from within a template, that needs to mapped into the
1129/// corresponding declaration within an instantiation. For example,
1130/// given:
1131///
1132/// \code
1133/// template<typename T>
1134/// struct X {
1135/// enum Kind {
1136/// KnownValue = sizeof(T)
1137/// };
1138///
1139/// bool getKind() const { return KnownValue; }
1140/// };
1141///
1142/// template struct X<int>;
1143/// \endcode
1144///
1145/// In the instantiation of X<int>::getKind(), we need to map the
1146/// EnumConstantDecl for KnownValue (which refers to
1147/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00001148/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
1149/// this mapping from within the instantiation of X<int>.
John McCallce3ff2b2009-08-25 22:02:44 +00001150NamedDecl * Sema::FindInstantiatedDecl(NamedDecl *D) {
Douglas Gregor815215d2009-05-27 05:35:12 +00001151 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor2bba76b2009-05-27 17:07:49 +00001152 if (isa<ParmVarDecl>(D) || ParentDC->isFunctionOrMethod()) {
1153 // D is a local of some kind. Look into the map of local
1154 // declarations to their instantiations.
1155 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
1156 }
Douglas Gregor815215d2009-05-27 05:35:12 +00001157
Douglas Gregor2bba76b2009-05-27 17:07:49 +00001158 if (NamedDecl *ParentDecl = dyn_cast<NamedDecl>(ParentDC)) {
John McCallce3ff2b2009-08-25 22:02:44 +00001159 ParentDecl = FindInstantiatedDecl(ParentDecl);
Douglas Gregor815215d2009-05-27 05:35:12 +00001160 if (!ParentDecl)
1161 return 0;
1162
1163 ParentDC = cast<DeclContext>(ParentDecl);
1164 }
1165
Douglas Gregor815215d2009-05-27 05:35:12 +00001166 if (ParentDC != D->getDeclContext()) {
1167 // We performed some kind of instantiation in the parent context,
1168 // so now we need to look into the instantiated parent context to
1169 // find the instantiation of the declaration D.
1170 NamedDecl *Result = 0;
1171 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001172 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00001173 Result = findInstantiationOf(Context, D, Found.first, Found.second);
1174 } else {
1175 // Since we don't have a name for the entity we're looking for,
1176 // our only option is to walk through all of the declarations to
1177 // find that name. This will occur in a few cases:
1178 //
1179 // - anonymous struct/union within a template
1180 // - unnamed class/struct/union/enum within a template
1181 //
1182 // FIXME: Find a better way to find these instantiations!
1183 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001184 ParentDC->decls_begin(),
1185 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00001186 }
1187 assert(Result && "Unable to find instantiation of declaration!");
1188 D = Result;
1189 }
1190
Douglas Gregor815215d2009-05-27 05:35:12 +00001191 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
Douglas Gregored961e72009-05-27 17:54:46 +00001192 if (ClassTemplateDecl *ClassTemplate
1193 = Record->getDescribedClassTemplate()) {
1194 // When the declaration D was parsed, it referred to the current
1195 // instantiation. Therefore, look through the current context,
1196 // which contains actual instantiations, to find the
1197 // instantiation of the "current instantiation" that D refers
1198 // to. Alternatively, we could just instantiate the
1199 // injected-class-name with the current template arguments, but
1200 // such an instantiation is far more expensive.
1201 for (DeclContext *DC = CurContext; !DC->isFileContext();
1202 DC = DC->getParent()) {
1203 if (ClassTemplateSpecializationDecl *Spec
1204 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001205 if (Spec->getSpecializedTemplate()->getCanonicalDecl()
1206 == ClassTemplate->getCanonicalDecl())
Douglas Gregored961e72009-05-27 17:54:46 +00001207 return Spec;
1208 }
1209
1210 assert(false &&
1211 "Unable to find declaration for the current instantiation");
Douglas Gregor815215d2009-05-27 05:35:12 +00001212 }
1213
1214 return D;
1215}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001216
1217/// \brief Performs template instantiation for all implicit template
1218/// instantiations we have seen until this point.
1219void Sema::PerformPendingImplicitInstantiations() {
1220 while (!PendingImplicitInstantiations.empty()) {
1221 PendingImplicitInstantiation Inst = PendingImplicitInstantiations.front();
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001222 PendingImplicitInstantiations.pop_front();
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001223
Douglas Gregor7caa6822009-07-24 20:34:43 +00001224 // Instantiate function definitions
1225 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001226 if (!Function->getBody())
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001227 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00001228 continue;
1229 }
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001230
Douglas Gregor7caa6822009-07-24 20:34:43 +00001231 // Instantiate static data member definitions.
1232 VarDecl *Var = cast<VarDecl>(Inst.first);
1233 assert(Var->isStaticDataMember() && "Not a static data member?");
1234 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001235 }
1236}