blob: 5e917890836ef9a3b82c61eed356381e9f3f4304 [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 Gregor2dc0e642009-03-23 23:06:20 +000051 Decl *VisitCXXMethodDecl(CXXMethodDecl *D);
Douglas Gregor615c5d42009-03-24 16:43:20 +000052 Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
Douglas Gregor03b2b072009-03-24 00:15:49 +000053 Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +000054 Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000055 ParmVarDecl *VisitParmVarDecl(ParmVarDecl *D);
Douglas Gregor2dc0e642009-03-23 23:06:20 +000056 Decl *VisitOriginalParmVarDecl(OriginalParmVarDecl *D);
John McCalle29ba202009-08-20 01:44:21 +000057 Decl *VisitClassTemplateDecl(ClassTemplateDecl *D);
58 Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Douglas Gregor5545e162009-03-24 00:38:23 +000059
Douglas Gregor8dbc2692009-03-17 21:15:40 +000060 // Base case. FIXME: Remove once we can instantiate everything.
61 Decl *VisitDecl(Decl *) {
Douglas Gregor3d7a12a2009-03-25 23:32:15 +000062 assert(false && "Template instantiation of unknown declaration kind!");
Douglas Gregor8dbc2692009-03-17 21:15:40 +000063 return 0;
64 }
Douglas Gregor5545e162009-03-24 00:38:23 +000065
John McCallfd810b12009-08-14 02:03:10 +000066 const LangOptions &getLangOptions() {
67 return SemaRef.getLangOptions();
68 }
69
Douglas Gregor5545e162009-03-24 00:38:23 +000070 // Helper functions for instantiating methods.
John McCallce3ff2b2009-08-25 22:02:44 +000071 QualType SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +000072 llvm::SmallVectorImpl<ParmVarDecl *> &Params);
Douglas Gregore53060f2009-06-25 22:08:12 +000073 bool InitFunctionInstantiation(FunctionDecl *New, FunctionDecl *Tmpl);
Douglas Gregor5545e162009-03-24 00:38:23 +000074 bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl);
John McCalle29ba202009-08-20 01:44:21 +000075
76 TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +000077 SubstTemplateParams(TemplateParameterList *List);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000078 };
79}
80
Douglas Gregor4f722be2009-03-25 15:45:12 +000081Decl *
82TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
83 assert(false && "Translation units cannot be instantiated");
84 return D;
85}
86
87Decl *
88TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
89 assert(false && "Namespaces cannot be instantiated");
90 return D;
91}
92
Douglas Gregor8dbc2692009-03-17 21:15:40 +000093Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
94 bool Invalid = false;
95 QualType T = D->getUnderlyingType();
96 if (T->isDependentType()) {
John McCallce3ff2b2009-08-25 22:02:44 +000097 T = SemaRef.SubstType(T, TemplateArgs,
98 D->getLocation(), D->getDeclName());
Douglas Gregor8dbc2692009-03-17 21:15:40 +000099 if (T.isNull()) {
100 Invalid = true;
101 T = SemaRef.Context.IntTy;
102 }
103 }
104
105 // Create the new typedef
106 TypedefDecl *Typedef
107 = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(),
108 D->getIdentifier(), T);
109 if (Invalid)
110 Typedef->setInvalidDecl();
111
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000112 Owner->addDecl(Typedef);
Douglas Gregorbc221632009-05-28 16:34:51 +0000113
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000114 return Typedef;
115}
116
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000117Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
John McCallce3ff2b2009-08-25 22:02:44 +0000118 // Do substitution on the type of the declaration
119 QualType T = SemaRef.SubstType(D->getType(), TemplateArgs,
120 D->getTypeSpecStartLoc(),
121 D->getDeclName());
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000122 if (T.isNull())
123 return 0;
124
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000125 // Build the instantiated declaration
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000126 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
127 D->getLocation(), D->getIdentifier(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000128 T, D->getDeclaratorInfo(),
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +0000129 D->getStorageClass());
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000130 Var->setThreadSpecified(D->isThreadSpecified());
131 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
132 Var->setDeclaredInCondition(D->isDeclaredInCondition());
133
Douglas Gregor7caa6822009-07-24 20:34:43 +0000134 // If we are instantiating a static data member defined
135 // out-of-line, the instantiation will have the same lexical
136 // context (which will be a namespace scope) as the template.
137 if (D->isOutOfLine())
138 Var->setLexicalDeclContext(D->getLexicalDeclContext());
139
Mike Stump390b4cc2009-05-16 07:39:55 +0000140 // FIXME: In theory, we could have a previous declaration for variables that
141 // are not static data members.
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000142 bool Redeclaration = false;
Chris Lattnereaaebc72009-04-25 08:06:05 +0000143 SemaRef.CheckVariableDeclaration(Var, 0, Redeclaration);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000144
145 if (D->isOutOfLine()) {
146 D->getLexicalDeclContext()->addDecl(Var);
147 Owner->makeDeclVisibleInContext(Var);
148 } else {
149 Owner->addDecl(Var);
150 }
151
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000152 if (D->getInit()) {
153 OwningExprResult Init
John McCallce3ff2b2009-08-25 22:02:44 +0000154 = SemaRef.SubstExpr(D->getInit(), TemplateArgs);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000155 if (Init.isInvalid())
156 Var->setInvalidDecl();
Douglas Gregor83ddad32009-08-26 21:14:46 +0000157 else if (ParenListExpr *PLE = dyn_cast<ParenListExpr>((Expr *)Init.get())) {
158 // FIXME: We're faking all of the comma locations, which is suboptimal.
159 // Do we even need these comma locations?
160 llvm::SmallVector<SourceLocation, 4> FakeCommaLocs;
161 if (PLE->getNumExprs() > 0) {
162 FakeCommaLocs.reserve(PLE->getNumExprs() - 1);
163 for (unsigned I = 0, N = PLE->getNumExprs() - 1; I != N; ++I) {
164 Expr *E = PLE->getExpr(I)->Retain();
165 FakeCommaLocs.push_back(
166 SemaRef.PP.getLocForEndOfToken(E->getLocEnd()));
167 }
Douglas Gregore9f8eb62009-08-26 23:26:04 +0000168 PLE->getExpr(PLE->getNumExprs() - 1)->Retain();
Douglas Gregor83ddad32009-08-26 21:14:46 +0000169 }
170
171 // Add the direct initializer to the declaration.
172 SemaRef.AddCXXDirectInitializerToDecl(Sema::DeclPtrTy::make(Var),
173 PLE->getLParenLoc(),
174 Sema::MultiExprArg(SemaRef,
175 (void**)PLE->getExprs(),
176 PLE->getNumExprs()),
177 FakeCommaLocs.data(),
178 PLE->getRParenLoc());
179
180 // When Init is destroyed, it will destroy the instantiated ParenListExpr;
181 // we've explicitly retained all of its subexpressions already.
182 } else
Chris Lattnerb28317a2009-03-28 19:18:32 +0000183 SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var), move(Init),
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000184 D->hasCXXDirectInitializer());
Douglas Gregor65b90052009-07-27 17:43:39 +0000185 } else if (!Var->isStaticDataMember() || Var->isOutOfLine())
186 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000187
Douglas Gregor7caa6822009-07-24 20:34:43 +0000188 // Link instantiations of static data members back to the template from
189 // which they were instantiated.
190 if (Var->isStaticDataMember())
191 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D);
192
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000193 return Var;
194}
195
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000196Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
197 bool Invalid = false;
198 QualType T = D->getType();
199 if (T->isDependentType()) {
John McCallce3ff2b2009-08-25 22:02:44 +0000200 T = SemaRef.SubstType(T, TemplateArgs,
201 D->getLocation(), D->getDeclName());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000202 if (!T.isNull() && T->isFunctionType()) {
203 // C++ [temp.arg.type]p3:
204 // If a declaration acquires a function type through a type
205 // dependent on a template-parameter and this causes a
206 // declaration that does not use the syntactic form of a
207 // function declarator to have function type, the program is
208 // ill-formed.
209 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
210 << T;
211 T = QualType();
212 Invalid = true;
213 }
214 }
215
216 Expr *BitWidth = D->getBitWidth();
217 if (Invalid)
218 BitWidth = 0;
219 else if (BitWidth) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000220 // The bit-width expression is not potentially evaluated.
221 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
222
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000223 OwningExprResult InstantiatedBitWidth
John McCallce3ff2b2009-08-25 22:02:44 +0000224 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000225 if (InstantiatedBitWidth.isInvalid()) {
226 Invalid = true;
227 BitWidth = 0;
228 } else
Anders Carlssone9146f22009-05-01 19:49:17 +0000229 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000230 }
231
232 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(), T,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000233 D->getDeclaratorInfo(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000234 cast<RecordDecl>(Owner),
235 D->getLocation(),
236 D->isMutable(),
237 BitWidth,
Steve Naroffea218b82009-07-14 14:58:18 +0000238 D->getTypeSpecStartLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000239 D->getAccess(),
240 0);
241 if (Field) {
242 if (Invalid)
243 Field->setInvalidDecl();
244
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000245 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000246 }
247
248 return Field;
249}
250
John McCallfd810b12009-08-14 02:03:10 +0000251Decl *TemplateDeclInstantiator::VisitFriendClassDecl(FriendClassDecl *D) {
252 QualType T = D->getFriendType();
253 if (T->isDependentType()) {
John McCallce3ff2b2009-08-25 22:02:44 +0000254 T = SemaRef.SubstType(T, TemplateArgs, D->getLocation(),
255 DeclarationName());
John McCallfd810b12009-08-14 02:03:10 +0000256 assert(T.isNull() || getLangOptions().CPlusPlus0x || T->isRecordType());
257 }
258
259 // FIXME: the target context might be dependent.
260 DeclContext *DC = D->getDeclContext();
261 assert(DC->isFileContext());
262
263 FriendClassDecl *NewD =
264 FriendClassDecl::Create(SemaRef.Context, DC, D->getLocation(), T,
265 D->getFriendLoc());
266 Owner->addDecl(NewD);
267 return NewD;
268}
269
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000270Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
271 Expr *AssertExpr = D->getAssertExpr();
272
Douglas Gregorac7610d2009-06-22 20:57:11 +0000273 // The expression in a static assertion is not potentially evaluated.
274 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
275
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000276 OwningExprResult InstantiatedAssertExpr
John McCallce3ff2b2009-08-25 22:02:44 +0000277 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000278 if (InstantiatedAssertExpr.isInvalid())
279 return 0;
280
Douglas Gregor43d9d922009-08-08 01:41:12 +0000281 OwningExprResult Message(SemaRef, D->getMessage());
282 D->getMessage()->Retain();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000283 Decl *StaticAssert
Chris Lattnerb28317a2009-03-28 19:18:32 +0000284 = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
285 move(InstantiatedAssertExpr),
286 move(Message)).getAs<Decl>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000287 return StaticAssert;
288}
289
290Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
291 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
292 D->getLocation(), D->getIdentifier(),
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000293 D->getTagKeywordLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000294 /*PrevDecl=*/0);
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000295 Enum->setInstantiationOfMemberEnum(D);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000296 Enum->setAccess(D->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000297 Owner->addDecl(Enum);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000298 Enum->startDefinition();
299
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000300 llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000301
302 EnumConstantDecl *LastEnumConst = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000303 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
304 ECEnd = D->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000305 EC != ECEnd; ++EC) {
306 // The specified value for the enumerator.
307 OwningExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000308 if (Expr *UninstValue = EC->getInitExpr()) {
309 // The enumerator's value expression is not potentially evaluated.
310 EnterExpressionEvaluationContext Unevaluated(SemaRef,
311 Action::Unevaluated);
312
John McCallce3ff2b2009-08-25 22:02:44 +0000313 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000314 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000315
316 // Drop the initial value and continue.
317 bool isInvalid = false;
318 if (Value.isInvalid()) {
319 Value = SemaRef.Owned((Expr *)0);
320 isInvalid = true;
321 }
322
323 EnumConstantDecl *EnumConst
324 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
325 EC->getLocation(), EC->getIdentifier(),
326 move(Value));
327
328 if (isInvalid) {
329 if (EnumConst)
330 EnumConst->setInvalidDecl();
331 Enum->setInvalidDecl();
332 }
333
334 if (EnumConst) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000335 Enum->addDecl(EnumConst);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000336 Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst));
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000337 LastEnumConst = EnumConst;
338 }
339 }
340
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000341 // FIXME: Fixup LBraceLoc and RBraceLoc
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000342 // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000343 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
344 Sema::DeclPtrTy::make(Enum),
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000345 &Enumerators[0], Enumerators.size(),
346 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000347
348 return Enum;
349}
350
Douglas Gregor6477b692009-03-25 15:04:13 +0000351Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
352 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
353 return 0;
354}
355
John McCalle29ba202009-08-20 01:44:21 +0000356Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
357 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000358 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
John McCalle29ba202009-08-20 01:44:21 +0000359 if (!InstParams) return NULL;
360
361 CXXRecordDecl *Pattern = D->getTemplatedDecl();
362 CXXRecordDecl *RecordInst
363 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), Owner,
364 Pattern->getLocation(), Pattern->getIdentifier(),
365 Pattern->getTagKeywordLoc(), /*PrevDecl=*/ NULL);
366
367 ClassTemplateDecl *Inst
368 = ClassTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
369 D->getIdentifier(), InstParams, RecordInst, 0);
370 RecordInst->setDescribedClassTemplate(Inst);
371 Inst->setAccess(D->getAccess());
372 Inst->setInstantiatedFromMemberTemplate(D);
373
374 Owner->addDecl(Inst);
375 return Inst;
376}
377
Douglas Gregord475b8d2009-03-25 21:17:03 +0000378Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
379 CXXRecordDecl *PrevDecl = 0;
380 if (D->isInjectedClassName())
381 PrevDecl = cast<CXXRecordDecl>(Owner);
382
383 CXXRecordDecl *Record
384 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000385 D->getLocation(), D->getIdentifier(),
386 D->getTagKeywordLoc(), PrevDecl);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000387 Record->setImplicit(D->isImplicit());
388 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000389 if (!D->isInjectedClassName())
390 Record->setInstantiationOfMemberClass(D);
391
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000392 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000393 return Record;
394}
395
Douglas Gregore53060f2009-06-25 22:08:12 +0000396Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000397 // Check whether there is already a function template specialization for
398 // this declaration.
399 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
400 void *InsertPos = 0;
401 if (FunctionTemplate) {
402 llvm::FoldingSetNodeID ID;
403 FunctionTemplateSpecializationInfo::Profile(ID,
404 TemplateArgs.getFlatArgumentList(),
Douglas Gregor828e2262009-07-29 16:09:57 +0000405 TemplateArgs.flat_size(),
406 SemaRef.Context);
Douglas Gregor127102b2009-06-29 20:59:39 +0000407
408 FunctionTemplateSpecializationInfo *Info
409 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
410 InsertPos);
411
412 // If we already have a function template specialization, return it.
413 if (Info)
414 return Info->Function;
415 }
Douglas Gregore53060f2009-06-25 22:08:12 +0000416
417 Sema::LocalInstantiationScope Scope(SemaRef);
418
419 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCallce3ff2b2009-08-25 22:02:44 +0000420 QualType T = SubstFunctionType(D, Params);
Douglas Gregore53060f2009-06-25 22:08:12 +0000421 if (T.isNull())
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000422 return 0;
John McCallfd810b12009-08-14 02:03:10 +0000423
Douglas Gregore53060f2009-06-25 22:08:12 +0000424 // Build the instantiated method declaration.
John McCallfd810b12009-08-14 02:03:10 +0000425 FunctionDecl *Function;
426 if (FriendFunctionDecl* FFD = dyn_cast<FriendFunctionDecl>(D)) {
427 // The new decl's semantic context. FIXME: this might need
428 // to be instantiated.
429 DeclContext *DC = D->getDeclContext();
430
431 // This assert is bogus and exists only to catch cases we don't
432 // handle yet.
433 assert(!DC->isDependentContext());
434
435 Function =
436 FriendFunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000437 D->getDeclName(), T, D->getDeclaratorInfo(),
438 D->isInline(), FFD->getFriendLoc());
John McCallfd810b12009-08-14 02:03:10 +0000439 Function->setLexicalDeclContext(Owner);
440 } else {
441 Function =
442 FunctionDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000443 D->getDeclName(), T, D->getDeclaratorInfo(),
444 D->getStorageClass(),
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +0000445 D->isInline(), D->hasWrittenPrototype());
John McCallfd810b12009-08-14 02:03:10 +0000446 }
Douglas Gregore53060f2009-06-25 22:08:12 +0000447
448 // Attach the parameters
449 for (unsigned P = 0; P < Params.size(); ++P)
450 Params[P]->setOwningFunction(Function);
451 Function->setParams(SemaRef.Context, Params.data(), Params.size());
452
453 if (InitFunctionInstantiation(Function, D))
454 Function->setInvalidDecl();
455
456 bool Redeclaration = false;
457 bool OverloadableAttrRequired = false;
458 NamedDecl *PrevDecl = 0;
459 SemaRef.CheckFunctionDeclaration(Function, PrevDecl, Redeclaration,
460 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000461
Douglas Gregor127102b2009-06-29 20:59:39 +0000462 if (FunctionTemplate) {
463 // Record this function template specialization.
464 Function->setFunctionTemplateSpecialization(SemaRef.Context,
465 FunctionTemplate,
466 &TemplateArgs,
467 InsertPos);
John McCallfd810b12009-08-14 02:03:10 +0000468 }
469
470 // If this was a friend function decl, it's a member which
471 // needs to be added.
472 if (isa<FriendFunctionDecl>(Function)) {
473 // If the new context is still dependent, this declaration
474 // needs to remain hidden.
475 if (Owner->isDependentContext())
476 Owner->addHiddenDecl(Function);
477 else
478 Owner->addDecl(Function);
479 }
Douglas Gregor127102b2009-06-29 20:59:39 +0000480
Douglas Gregore53060f2009-06-25 22:08:12 +0000481 return Function;
482}
483
484Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
Douglas Gregor6b906862009-08-21 00:16:32 +0000485 // Check whether there is already a function template specialization for
486 // this declaration.
487 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
488 void *InsertPos = 0;
489 if (FunctionTemplate) {
490 llvm::FoldingSetNodeID ID;
491 FunctionTemplateSpecializationInfo::Profile(ID,
492 TemplateArgs.getFlatArgumentList(),
493 TemplateArgs.flat_size(),
494 SemaRef.Context);
495
496 FunctionTemplateSpecializationInfo *Info
497 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
498 InsertPos);
499
500 // If we already have a function template specialization, return it.
501 if (Info)
502 return Info->Function;
503 }
504
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000505 Sema::LocalInstantiationScope Scope(SemaRef);
506
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000507 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCallce3ff2b2009-08-25 22:02:44 +0000508 QualType T = SubstFunctionType(D, Params);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000509 if (T.isNull())
510 return 0;
511
512 // Build the instantiated method declaration.
513 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
Douglas Gregordec06662009-08-21 18:42:58 +0000514 CXXMethodDecl *Method = 0;
515
516 DeclarationName Name = D->getDeclName();
Douglas Gregor17e32f32009-08-21 22:43:28 +0000517 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Douglas Gregordec06662009-08-21 18:42:58 +0000518 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
519 Name = SemaRef.Context.DeclarationNames.getCXXConstructorName(
520 SemaRef.Context.getCanonicalType(ClassTy));
521 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
Douglas Gregor17e32f32009-08-21 22:43:28 +0000522 Constructor->getLocation(),
Douglas Gregordec06662009-08-21 18:42:58 +0000523 Name, T,
Douglas Gregor17e32f32009-08-21 22:43:28 +0000524 Constructor->getDeclaratorInfo(),
525 Constructor->isExplicit(),
526 Constructor->isInline(), false);
527 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
528 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
529 Name = SemaRef.Context.DeclarationNames.getCXXDestructorName(
530 SemaRef.Context.getCanonicalType(ClassTy));
531 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
532 Destructor->getLocation(), Name,
533 T, Destructor->isInline(), false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000534 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
535 CanQualType ConvTy
536 = SemaRef.Context.getCanonicalType(
537 T->getAsFunctionType()->getResultType());
538 Name = SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(
539 ConvTy);
540 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
541 Conversion->getLocation(), Name,
542 T, Conversion->getDeclaratorInfo(),
543 Conversion->isInline(),
544 Conversion->isExplicit());
Douglas Gregordec06662009-08-21 18:42:58 +0000545 } else {
546 Method = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
547 D->getDeclName(), T, D->getDeclaratorInfo(),
548 D->isStatic(), D->isInline());
549 }
Douglas Gregor6b906862009-08-21 00:16:32 +0000550
551 if (!FunctionTemplate)
552 Method->setInstantiationOfMemberFunction(D);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000553
Douglas Gregor7caa6822009-07-24 20:34:43 +0000554 // If we are instantiating a member function defined
555 // out-of-line, the instantiation will have the same lexical
556 // context (which will be a namespace scope) as the template.
557 if (D->isOutOfLine())
558 Method->setLexicalDeclContext(D->getLexicalDeclContext());
559
Douglas Gregor5545e162009-03-24 00:38:23 +0000560 // Attach the parameters
561 for (unsigned P = 0; P < Params.size(); ++P)
562 Params[P]->setOwningFunction(Method);
Jay Foadbeaaccd2009-05-21 09:52:38 +0000563 Method->setParams(SemaRef.Context, Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +0000564
565 if (InitMethodInstantiation(Method, D))
566 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000567
Douglas Gregordec06662009-08-21 18:42:58 +0000568 NamedDecl *PrevDecl = 0;
569
570 if (!FunctionTemplate) {
571 PrevDecl = SemaRef.LookupQualifiedName(Owner, Name,
572 Sema::LookupOrdinaryName, true);
573
574 // In C++, the previous declaration we find might be a tag type
575 // (class or enum). In this case, the new declaration will hide the
576 // tag type. Note that this does does not apply if we're declaring a
577 // typedef (C++ [dcl.typedef]p4).
578 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
579 PrevDecl = 0;
580 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000581
Douglas Gregor6b906862009-08-21 00:16:32 +0000582 if (FunctionTemplate)
583 // Record this function template specialization.
584 Method->setFunctionTemplateSpecialization(SemaRef.Context,
585 FunctionTemplate,
586 &TemplateArgs,
587 InsertPos);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000588
589 bool Redeclaration = false;
590 bool OverloadableAttrRequired = false;
591 SemaRef.CheckFunctionDeclaration(Method, PrevDecl, Redeclaration,
592 /*FIXME:*/OverloadableAttrRequired);
593
594 if (!FunctionTemplate && (!Method->isInvalidDecl() || !PrevDecl))
Douglas Gregordec06662009-08-21 18:42:58 +0000595 Owner->addDecl(Method);
596
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000597 return Method;
598}
599
Douglas Gregor615c5d42009-03-24 16:43:20 +0000600Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +0000601 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +0000602}
603
Douglas Gregor03b2b072009-03-24 00:15:49 +0000604Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +0000605 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +0000606}
607
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000608Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000609 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000610}
611
Douglas Gregor6477b692009-03-25 15:04:13 +0000612ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
John McCallce3ff2b2009-08-25 22:02:44 +0000613 QualType OrigT = SemaRef.SubstType(D->getOriginalType(), TemplateArgs,
Douglas Gregor7e063902009-05-11 23:53:27 +0000614 D->getLocation(), D->getDeclName());
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000615 if (OrigT.isNull())
616 return 0;
617
618 QualType T = SemaRef.adjustParameterType(OrigT);
619
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000620 // Allocate the parameter
621 ParmVarDecl *Param = 0;
622 if (T == OrigT)
623 Param = ParmVarDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000624 D->getIdentifier(), T, D->getDeclaratorInfo(),
625 D->getStorageClass(), 0);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000626 else
627 Param = OriginalParmVarDecl::Create(SemaRef.Context, Owner,
628 D->getLocation(), D->getIdentifier(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000629 T, D->getDeclaratorInfo(), OrigT,
630 D->getStorageClass(), 0);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000631
Anders Carlsson9351c172009-08-25 03:18:48 +0000632 // Mark the default argument as being uninstantiated.
633 if (Expr *Arg = D->getDefaultArg())
634 Param->setUninstantiatedDefaultArg(Arg);
635
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000636 // Note: we don't try to instantiate function parameters until after
637 // we've instantiated the function's type. Therefore, we don't have
638 // to check for 'void' parameter types here.
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000639 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000640 return Param;
641}
642
643Decl *
644TemplateDeclInstantiator::VisitOriginalParmVarDecl(OriginalParmVarDecl *D) {
645 // Since parameter types can decay either before or after
646 // instantiation, we simply treat OriginalParmVarDecls as
647 // ParmVarDecls the same way, and create one or the other depending
648 // on what happens after template instantiation.
649 return VisitParmVarDecl(D);
650}
651
John McCalle29ba202009-08-20 01:44:21 +0000652Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
653 TemplateTypeParmDecl *D) {
654 // TODO: don't always clone when decls are refcounted.
655 const Type* T = D->getTypeForDecl();
656 assert(T->isTemplateTypeParmType());
657 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
658
659 TemplateTypeParmDecl *Inst =
660 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
661 TTPT->getDepth(), TTPT->getIndex(),
662 TTPT->getName(),
663 D->wasDeclaredWithTypename(),
664 D->isParameterPack());
665
666 if (D->hasDefaultArgument()) {
667 QualType DefaultPattern = D->getDefaultArgument();
668 QualType DefaultInst
John McCallce3ff2b2009-08-25 22:02:44 +0000669 = SemaRef.SubstType(DefaultPattern, TemplateArgs,
670 D->getDefaultArgumentLoc(),
671 D->getDeclName());
John McCalle29ba202009-08-20 01:44:21 +0000672
673 Inst->setDefaultArgument(DefaultInst,
674 D->getDefaultArgumentLoc(),
675 D->defaultArgumentWasInherited() /* preserve? */);
676 }
677
678 return Inst;
679}
680
John McCallce3ff2b2009-08-25 22:02:44 +0000681Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
682 const TemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +0000683 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000684 return Instantiator.Visit(D);
685}
686
John McCalle29ba202009-08-20 01:44:21 +0000687/// \brief Instantiates a nested template parameter list in the current
688/// instantiation context.
689///
690/// \param L The parameter list to instantiate
691///
692/// \returns NULL if there was an error
693TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +0000694TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +0000695 // Get errors for all the parameters before bailing out.
696 bool Invalid = false;
697
698 unsigned N = L->size();
699 typedef llvm::SmallVector<Decl*,8> ParamVector;
700 ParamVector Params;
701 Params.reserve(N);
702 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
703 PI != PE; ++PI) {
704 Decl *D = Visit(*PI);
705 Params.push_back(D);
706 Invalid = Invalid || !D;
707 }
708
709 // Clean up if we had an error.
710 if (Invalid) {
711 for (ParamVector::iterator PI = Params.begin(), PE = Params.end();
712 PI != PE; ++PI)
713 if (*PI)
714 (*PI)->Destroy(SemaRef.Context);
715 return NULL;
716 }
717
718 TemplateParameterList *InstL
719 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
720 L->getLAngleLoc(), &Params.front(), N,
721 L->getRAngleLoc());
722 return InstL;
723}
724
John McCallce3ff2b2009-08-25 22:02:44 +0000725/// \brief Does substitution on the type of the given function, including
726/// all of the function parameters.
Douglas Gregor5545e162009-03-24 00:38:23 +0000727///
John McCallce3ff2b2009-08-25 22:02:44 +0000728/// \param D The function whose type will be the basis of the substitution
Douglas Gregor5545e162009-03-24 00:38:23 +0000729///
730/// \param Params the instantiated parameter declarations
731
John McCallce3ff2b2009-08-25 22:02:44 +0000732/// \returns the instantiated function's type if successful, a NULL
Douglas Gregor5545e162009-03-24 00:38:23 +0000733/// type if there was an error.
734QualType
John McCallce3ff2b2009-08-25 22:02:44 +0000735TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +0000736 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
737 bool InvalidDecl = false;
738
John McCallce3ff2b2009-08-25 22:02:44 +0000739 // Substitute all of the function's formal parameter types.
Douglas Gregor7e063902009-05-11 23:53:27 +0000740 TemplateDeclInstantiator ParamInstantiator(SemaRef, 0, TemplateArgs);
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000741 llvm::SmallVector<QualType, 4> ParamTys;
Douglas Gregor5545e162009-03-24 00:38:23 +0000742 for (FunctionDecl::param_iterator P = D->param_begin(),
743 PEnd = D->param_end();
744 P != PEnd; ++P) {
Douglas Gregor6477b692009-03-25 15:04:13 +0000745 if (ParmVarDecl *PInst = ParamInstantiator.VisitParmVarDecl(*P)) {
Douglas Gregor5545e162009-03-24 00:38:23 +0000746 if (PInst->getType()->isVoidType()) {
747 SemaRef.Diag(PInst->getLocation(), diag::err_param_with_void_type);
748 PInst->setInvalidDecl();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000749 } else if (SemaRef.RequireNonAbstractType(PInst->getLocation(),
750 PInst->getType(),
751 diag::err_abstract_type_in_decl,
752 Sema::AbstractParamType))
Douglas Gregor5545e162009-03-24 00:38:23 +0000753 PInst->setInvalidDecl();
754
755 Params.push_back(PInst);
756 ParamTys.push_back(PInst->getType());
757
758 if (PInst->isInvalidDecl())
759 InvalidDecl = true;
760 } else
761 InvalidDecl = true;
762 }
763
764 // FIXME: Deallocate dead declarations.
765 if (InvalidDecl)
766 return QualType();
767
768 const FunctionProtoType *Proto = D->getType()->getAsFunctionProtoType();
769 assert(Proto && "Missing prototype?");
770 QualType ResultType
John McCallce3ff2b2009-08-25 22:02:44 +0000771 = SemaRef.SubstType(Proto->getResultType(), TemplateArgs,
772 D->getLocation(), D->getDeclName());
Douglas Gregor5545e162009-03-24 00:38:23 +0000773 if (ResultType.isNull())
774 return QualType();
775
Jay Foadbeaaccd2009-05-21 09:52:38 +0000776 return SemaRef.BuildFunctionType(ResultType, ParamTys.data(), ParamTys.size(),
Douglas Gregor5545e162009-03-24 00:38:23 +0000777 Proto->isVariadic(), Proto->getTypeQuals(),
778 D->getLocation(), D->getDeclName());
779}
780
Douglas Gregore53060f2009-06-25 22:08:12 +0000781/// \brief Initializes the common fields of an instantiation function
782/// declaration (New) from the corresponding fields of its template (Tmpl).
783///
784/// \returns true if there was an error
785bool
786TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
787 FunctionDecl *Tmpl) {
788 if (Tmpl->isDeleted())
789 New->setDeleted();
Douglas Gregorcca9e962009-07-01 22:01:06 +0000790
791 // If we are performing substituting explicitly-specified template arguments
792 // or deduced template arguments into a function template and we reach this
793 // point, we are now past the point where SFINAE applies and have committed
794 // to keeping the new function template specialization. We therefore
795 // convert the active template instantiation for the function template
796 // into a template instantiation for this specific function template
797 // specialization, which is not a SFINAE context, so that we diagnose any
798 // further errors in the declaration itself.
799 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
800 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
801 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
802 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
803 if (FunctionTemplateDecl *FunTmpl
804 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
805 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
806 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +0000807 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000808 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
809 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
810 }
811 }
812
Douglas Gregore53060f2009-06-25 22:08:12 +0000813 return false;
814}
815
Douglas Gregor5545e162009-03-24 00:38:23 +0000816/// \brief Initializes common fields of an instantiated method
817/// declaration (New) from the corresponding fields of its template
818/// (Tmpl).
819///
820/// \returns true if there was an error
821bool
822TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
823 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +0000824 if (InitFunctionInstantiation(New, Tmpl))
825 return true;
826
Douglas Gregor5545e162009-03-24 00:38:23 +0000827 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
828 New->setAccess(Tmpl->getAccess());
Anders Carlsson77b7f1d2009-05-14 22:15:41 +0000829 if (Tmpl->isVirtualAsWritten()) {
830 New->setVirtualAsWritten(true);
Douglas Gregor5545e162009-03-24 00:38:23 +0000831 Record->setAggregate(false);
832 Record->setPOD(false);
Eli Friedman1d954f62009-08-15 21:55:26 +0000833 Record->setEmpty(false);
Douglas Gregor5545e162009-03-24 00:38:23 +0000834 Record->setPolymorphic(true);
835 }
Douglas Gregor5545e162009-03-24 00:38:23 +0000836 if (Tmpl->isPure()) {
837 New->setPure();
838 Record->setAbstract(true);
839 }
840
841 // FIXME: attributes
842 // FIXME: New needs a pointer to Tmpl
843 return false;
844}
Douglas Gregora58861f2009-05-13 20:28:22 +0000845
846/// \brief Instantiate the definition of the given function from its
847/// template.
848///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000849/// \param PointOfInstantiation the point at which the instantiation was
850/// required. Note that this is not precisely a "point of instantiation"
851/// for the function, but it's close.
852///
Douglas Gregora58861f2009-05-13 20:28:22 +0000853/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000854/// function template specialization or member function of a class template
855/// specialization.
856///
857/// \param Recursive if true, recursively instantiates any functions that
858/// are required by this instantiation.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000859void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000860 FunctionDecl *Function,
861 bool Recursive) {
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000862 if (Function->isInvalidDecl())
863 return;
864
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000865 assert(!Function->getBody() && "Already instantiated!");
Douglas Gregord7f37bf2009-06-22 23:06:13 +0000866
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000867 // Find the function body that we'll be substituting.
Douglas Gregor1637be72009-06-26 00:10:03 +0000868 const FunctionDecl *PatternDecl = 0;
869 if (FunctionTemplateDecl *Primary = Function->getPrimaryTemplate())
870 PatternDecl = Primary->getTemplatedDecl();
871 else
872 PatternDecl = Function->getInstantiatedFromMemberFunction();
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000873 Stmt *Pattern = 0;
874 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000875 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000876
877 if (!Pattern)
878 return;
879
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000880 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
881 if (Inst)
882 return;
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000883
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000884 // If we're performing recursive template instantiation, create our own
885 // queue of pending implicit instantiations that we will instantiate later,
886 // while we're still within our own instantiation context.
887 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
888 if (Recursive)
889 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
890
Douglas Gregore2c31ff2009-05-15 17:59:04 +0000891 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
892
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000893 // Introduce a new scope where local variable instantiations will be
894 // recorded.
895 LocalInstantiationScope Scope(*this);
896
897 // Introduce the instantiated function parameters into the local
898 // instantiation scope.
899 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
900 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
901 Function->getParamDecl(I));
902
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000903 // Enter the scope of this instantiation. We don't use
904 // PushDeclContext because we don't have a scope.
905 DeclContext *PreviousContext = CurContext;
906 CurContext = Function;
907
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000908 // Instantiate the function body.
909 OwningStmtResult Body
John McCallce3ff2b2009-08-25 22:02:44 +0000910 = SubstStmt(Pattern, getTemplateInstantiationArgs(Function));
Douglas Gregore2c31ff2009-05-15 17:59:04 +0000911
912 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
913 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000914
915 CurContext = PreviousContext;
Douglas Gregoraba43bb2009-05-26 20:50:29 +0000916
917 DeclGroupRef DG(Function);
918 Consumer.HandleTopLevelDecl(DG);
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000919
920 if (Recursive) {
921 // Instantiate any pending implicit instantiations found during the
922 // instantiation of this template.
923 PerformPendingImplicitInstantiations();
924
925 // Restore the set of pending implicit instantiations.
926 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
927 }
Douglas Gregora58861f2009-05-13 20:28:22 +0000928}
929
930/// \brief Instantiate the definition of the given variable from its
931/// template.
932///
Douglas Gregor7caa6822009-07-24 20:34:43 +0000933/// \param PointOfInstantiation the point at which the instantiation was
934/// required. Note that this is not precisely a "point of instantiation"
935/// for the function, but it's close.
936///
937/// \param Var the already-instantiated declaration of a static member
938/// variable of a class template specialization.
939///
940/// \param Recursive if true, recursively instantiates any functions that
941/// are required by this instantiation.
942void Sema::InstantiateStaticDataMemberDefinition(
943 SourceLocation PointOfInstantiation,
944 VarDecl *Var,
945 bool Recursive) {
946 if (Var->isInvalidDecl())
947 return;
948
949 // Find the out-of-line definition of this static data member.
950 // FIXME: Do we have to look for specializations separately?
951 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
952 bool FoundOutOfLineDef = false;
953 assert(Def && "This data member was not instantiated from a template?");
954 assert(Def->isStaticDataMember() && "Not a static data member?");
955 for (VarDecl::redecl_iterator RD = Def->redecls_begin(),
956 RDEnd = Def->redecls_end();
957 RD != RDEnd; ++RD) {
958 if (RD->getLexicalDeclContext()->isFileContext()) {
959 Def = *RD;
960 FoundOutOfLineDef = true;
961 }
962 }
963
964 if (!FoundOutOfLineDef) {
965 // We did not find an out-of-line definition of this static data member,
966 // so we won't perform any instantiation. Rather, we rely on the user to
967 // instantiate this definition (or provide a specialization for it) in
968 // another translation unit.
969 return;
970 }
971
972 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
973 if (Inst)
974 return;
975
976 // If we're performing recursive template instantiation, create our own
977 // queue of pending implicit instantiations that we will instantiate later,
978 // while we're still within our own instantiation context.
979 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
980 if (Recursive)
981 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
982
983 // Enter the scope of this instantiation. We don't use
984 // PushDeclContext because we don't have a scope.
985 DeclContext *PreviousContext = CurContext;
986 CurContext = Var->getDeclContext();
987
988#if 0
989 // Instantiate the initializer of this static data member.
990 OwningExprResult Init
991 = InstantiateExpr(Def->getInit(), getTemplateInstantiationArgs(Var));
992 if (Init.isInvalid()) {
993 // If instantiation of the initializer failed, mark the declaration invalid
994 // and don't instantiate anything else that was triggered by this
995 // instantiation.
996 Var->setInvalidDecl();
997
998 // Restore the set of pending implicit instantiations.
999 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1000
1001 return;
1002 }
1003
1004 // Type-check the initializer.
1005 if (Init.get())
1006 AddInitializerToDecl(DeclPtrTy::make(Var), move(Init),
1007 Def->hasCXXDirectInitializer());
1008 else
1009 ActOnUninitializedDecl(DeclPtrTy::make(Var), false);
1010#else
John McCallce3ff2b2009-08-25 22:02:44 +00001011 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Douglas Gregor7caa6822009-07-24 20:34:43 +00001012 getTemplateInstantiationArgs(Var)));
1013#endif
1014
1015 CurContext = PreviousContext;
1016
1017 if (Var) {
1018 DeclGroupRef DG(Var);
1019 Consumer.HandleTopLevelDecl(DG);
1020 }
1021
1022 if (Recursive) {
1023 // Instantiate any pending implicit instantiations found during the
1024 // instantiation of this template.
1025 PerformPendingImplicitInstantiations();
1026
1027 // Restore the set of pending implicit instantiations.
1028 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1029 }
Douglas Gregora58861f2009-05-13 20:28:22 +00001030}
Douglas Gregor815215d2009-05-27 05:35:12 +00001031
1032static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
1033 if (D->getKind() != Other->getKind())
1034 return false;
1035
1036 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001037 return Record->getInstantiatedFromMemberClass()->getCanonicalDecl()
1038 == D->getCanonicalDecl();
Douglas Gregor815215d2009-05-27 05:35:12 +00001039
1040 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001041 return Function->getInstantiatedFromMemberFunction()->getCanonicalDecl()
1042 == D->getCanonicalDecl();
Douglas Gregor815215d2009-05-27 05:35:12 +00001043
Douglas Gregor8dbc3c62009-05-27 17:20:35 +00001044 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001045 return Enum->getInstantiatedFromMemberEnum()->getCanonicalDecl()
1046 == D->getCanonicalDecl();
Douglas Gregor815215d2009-05-27 05:35:12 +00001047
Douglas Gregor7caa6822009-07-24 20:34:43 +00001048 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
1049 if (Var->isStaticDataMember())
1050 return Var->getInstantiatedFromStaticDataMember()->getCanonicalDecl()
1051 == D->getCanonicalDecl();
1052
Douglas Gregor815215d2009-05-27 05:35:12 +00001053 // FIXME: How can we find instantiations of anonymous unions?
1054
1055 return D->getDeclName() && isa<NamedDecl>(Other) &&
1056 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
1057}
1058
1059template<typename ForwardIterator>
1060static NamedDecl *findInstantiationOf(ASTContext &Ctx,
1061 NamedDecl *D,
1062 ForwardIterator first,
1063 ForwardIterator last) {
1064 for (; first != last; ++first)
1065 if (isInstantiationOf(Ctx, D, *first))
1066 return cast<NamedDecl>(*first);
1067
1068 return 0;
1069}
1070
Douglas Gregored961e72009-05-27 17:54:46 +00001071/// \brief Find the instantiation of the given declaration within the
1072/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00001073///
1074/// This routine is intended to be used when \p D is a declaration
1075/// referenced from within a template, that needs to mapped into the
1076/// corresponding declaration within an instantiation. For example,
1077/// given:
1078///
1079/// \code
1080/// template<typename T>
1081/// struct X {
1082/// enum Kind {
1083/// KnownValue = sizeof(T)
1084/// };
1085///
1086/// bool getKind() const { return KnownValue; }
1087/// };
1088///
1089/// template struct X<int>;
1090/// \endcode
1091///
1092/// In the instantiation of X<int>::getKind(), we need to map the
1093/// EnumConstantDecl for KnownValue (which refers to
1094/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00001095/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
1096/// this mapping from within the instantiation of X<int>.
John McCallce3ff2b2009-08-25 22:02:44 +00001097NamedDecl * Sema::FindInstantiatedDecl(NamedDecl *D) {
Douglas Gregor815215d2009-05-27 05:35:12 +00001098 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor2bba76b2009-05-27 17:07:49 +00001099 if (isa<ParmVarDecl>(D) || ParentDC->isFunctionOrMethod()) {
1100 // D is a local of some kind. Look into the map of local
1101 // declarations to their instantiations.
1102 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
1103 }
Douglas Gregor815215d2009-05-27 05:35:12 +00001104
Douglas Gregor2bba76b2009-05-27 17:07:49 +00001105 if (NamedDecl *ParentDecl = dyn_cast<NamedDecl>(ParentDC)) {
John McCallce3ff2b2009-08-25 22:02:44 +00001106 ParentDecl = FindInstantiatedDecl(ParentDecl);
Douglas Gregor815215d2009-05-27 05:35:12 +00001107 if (!ParentDecl)
1108 return 0;
1109
1110 ParentDC = cast<DeclContext>(ParentDecl);
1111 }
1112
Douglas Gregor815215d2009-05-27 05:35:12 +00001113 if (ParentDC != D->getDeclContext()) {
1114 // We performed some kind of instantiation in the parent context,
1115 // so now we need to look into the instantiated parent context to
1116 // find the instantiation of the declaration D.
1117 NamedDecl *Result = 0;
1118 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001119 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00001120 Result = findInstantiationOf(Context, D, Found.first, Found.second);
1121 } else {
1122 // Since we don't have a name for the entity we're looking for,
1123 // our only option is to walk through all of the declarations to
1124 // find that name. This will occur in a few cases:
1125 //
1126 // - anonymous struct/union within a template
1127 // - unnamed class/struct/union/enum within a template
1128 //
1129 // FIXME: Find a better way to find these instantiations!
1130 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001131 ParentDC->decls_begin(),
1132 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00001133 }
1134 assert(Result && "Unable to find instantiation of declaration!");
1135 D = Result;
1136 }
1137
Douglas Gregor815215d2009-05-27 05:35:12 +00001138 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
Douglas Gregored961e72009-05-27 17:54:46 +00001139 if (ClassTemplateDecl *ClassTemplate
1140 = Record->getDescribedClassTemplate()) {
1141 // When the declaration D was parsed, it referred to the current
1142 // instantiation. Therefore, look through the current context,
1143 // which contains actual instantiations, to find the
1144 // instantiation of the "current instantiation" that D refers
1145 // to. Alternatively, we could just instantiate the
1146 // injected-class-name with the current template arguments, but
1147 // such an instantiation is far more expensive.
1148 for (DeclContext *DC = CurContext; !DC->isFileContext();
1149 DC = DC->getParent()) {
1150 if (ClassTemplateSpecializationDecl *Spec
1151 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001152 if (Spec->getSpecializedTemplate()->getCanonicalDecl()
1153 == ClassTemplate->getCanonicalDecl())
Douglas Gregored961e72009-05-27 17:54:46 +00001154 return Spec;
1155 }
1156
1157 assert(false &&
1158 "Unable to find declaration for the current instantiation");
Douglas Gregor815215d2009-05-27 05:35:12 +00001159 }
1160
1161 return D;
1162}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001163
1164/// \brief Performs template instantiation for all implicit template
1165/// instantiations we have seen until this point.
1166void Sema::PerformPendingImplicitInstantiations() {
1167 while (!PendingImplicitInstantiations.empty()) {
1168 PendingImplicitInstantiation Inst = PendingImplicitInstantiations.front();
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001169 PendingImplicitInstantiations.pop_front();
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001170
Douglas Gregor7caa6822009-07-24 20:34:43 +00001171 // Instantiate function definitions
1172 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001173 if (!Function->getBody())
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001174 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00001175 continue;
1176 }
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001177
Douglas Gregor7caa6822009-07-24 20:34:43 +00001178 // Instantiate static data member definitions.
1179 VarDecl *Var = cast<VarDecl>(Inst.first);
1180 assert(Var->isStaticDataMember() && "Not a static data member?");
1181 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001182 }
1183}