blob: 71fb36892b610598e2c7961b0597b94107f3ad10 [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 }
168 }
169
170 // Add the direct initializer to the declaration.
171 SemaRef.AddCXXDirectInitializerToDecl(Sema::DeclPtrTy::make(Var),
172 PLE->getLParenLoc(),
173 Sema::MultiExprArg(SemaRef,
174 (void**)PLE->getExprs(),
175 PLE->getNumExprs()),
176 FakeCommaLocs.data(),
177 PLE->getRParenLoc());
178
179 // When Init is destroyed, it will destroy the instantiated ParenListExpr;
180 // we've explicitly retained all of its subexpressions already.
181 } else
Chris Lattnerb28317a2009-03-28 19:18:32 +0000182 SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var), move(Init),
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000183 D->hasCXXDirectInitializer());
Douglas Gregor65b90052009-07-27 17:43:39 +0000184 } else if (!Var->isStaticDataMember() || Var->isOutOfLine())
185 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000186
Douglas Gregor7caa6822009-07-24 20:34:43 +0000187 // Link instantiations of static data members back to the template from
188 // which they were instantiated.
189 if (Var->isStaticDataMember())
190 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D);
191
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000192 return Var;
193}
194
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000195Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
196 bool Invalid = false;
197 QualType T = D->getType();
198 if (T->isDependentType()) {
John McCallce3ff2b2009-08-25 22:02:44 +0000199 T = SemaRef.SubstType(T, TemplateArgs,
200 D->getLocation(), D->getDeclName());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000201 if (!T.isNull() && T->isFunctionType()) {
202 // C++ [temp.arg.type]p3:
203 // If a declaration acquires a function type through a type
204 // dependent on a template-parameter and this causes a
205 // declaration that does not use the syntactic form of a
206 // function declarator to have function type, the program is
207 // ill-formed.
208 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
209 << T;
210 T = QualType();
211 Invalid = true;
212 }
213 }
214
215 Expr *BitWidth = D->getBitWidth();
216 if (Invalid)
217 BitWidth = 0;
218 else if (BitWidth) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000219 // The bit-width expression is not potentially evaluated.
220 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
221
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000222 OwningExprResult InstantiatedBitWidth
John McCallce3ff2b2009-08-25 22:02:44 +0000223 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000224 if (InstantiatedBitWidth.isInvalid()) {
225 Invalid = true;
226 BitWidth = 0;
227 } else
Anders Carlssone9146f22009-05-01 19:49:17 +0000228 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000229 }
230
231 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(), T,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000232 D->getDeclaratorInfo(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000233 cast<RecordDecl>(Owner),
234 D->getLocation(),
235 D->isMutable(),
236 BitWidth,
Steve Naroffea218b82009-07-14 14:58:18 +0000237 D->getTypeSpecStartLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000238 D->getAccess(),
239 0);
240 if (Field) {
241 if (Invalid)
242 Field->setInvalidDecl();
243
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000244 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000245 }
246
247 return Field;
248}
249
John McCallfd810b12009-08-14 02:03:10 +0000250Decl *TemplateDeclInstantiator::VisitFriendClassDecl(FriendClassDecl *D) {
251 QualType T = D->getFriendType();
252 if (T->isDependentType()) {
John McCallce3ff2b2009-08-25 22:02:44 +0000253 T = SemaRef.SubstType(T, TemplateArgs, D->getLocation(),
254 DeclarationName());
John McCallfd810b12009-08-14 02:03:10 +0000255 assert(T.isNull() || getLangOptions().CPlusPlus0x || T->isRecordType());
256 }
257
258 // FIXME: the target context might be dependent.
259 DeclContext *DC = D->getDeclContext();
260 assert(DC->isFileContext());
261
262 FriendClassDecl *NewD =
263 FriendClassDecl::Create(SemaRef.Context, DC, D->getLocation(), T,
264 D->getFriendLoc());
265 Owner->addDecl(NewD);
266 return NewD;
267}
268
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000269Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
270 Expr *AssertExpr = D->getAssertExpr();
271
Douglas Gregorac7610d2009-06-22 20:57:11 +0000272 // The expression in a static assertion is not potentially evaluated.
273 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
274
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000275 OwningExprResult InstantiatedAssertExpr
John McCallce3ff2b2009-08-25 22:02:44 +0000276 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000277 if (InstantiatedAssertExpr.isInvalid())
278 return 0;
279
Douglas Gregor43d9d922009-08-08 01:41:12 +0000280 OwningExprResult Message(SemaRef, D->getMessage());
281 D->getMessage()->Retain();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000282 Decl *StaticAssert
Chris Lattnerb28317a2009-03-28 19:18:32 +0000283 = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
284 move(InstantiatedAssertExpr),
285 move(Message)).getAs<Decl>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000286 return StaticAssert;
287}
288
289Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
290 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
291 D->getLocation(), D->getIdentifier(),
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000292 D->getTagKeywordLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000293 /*PrevDecl=*/0);
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000294 Enum->setInstantiationOfMemberEnum(D);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000295 Enum->setAccess(D->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000296 Owner->addDecl(Enum);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000297 Enum->startDefinition();
298
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000299 llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000300
301 EnumConstantDecl *LastEnumConst = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000302 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
303 ECEnd = D->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000304 EC != ECEnd; ++EC) {
305 // The specified value for the enumerator.
306 OwningExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000307 if (Expr *UninstValue = EC->getInitExpr()) {
308 // The enumerator's value expression is not potentially evaluated.
309 EnterExpressionEvaluationContext Unevaluated(SemaRef,
310 Action::Unevaluated);
311
John McCallce3ff2b2009-08-25 22:02:44 +0000312 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000313 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000314
315 // Drop the initial value and continue.
316 bool isInvalid = false;
317 if (Value.isInvalid()) {
318 Value = SemaRef.Owned((Expr *)0);
319 isInvalid = true;
320 }
321
322 EnumConstantDecl *EnumConst
323 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
324 EC->getLocation(), EC->getIdentifier(),
325 move(Value));
326
327 if (isInvalid) {
328 if (EnumConst)
329 EnumConst->setInvalidDecl();
330 Enum->setInvalidDecl();
331 }
332
333 if (EnumConst) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000334 Enum->addDecl(EnumConst);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000335 Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst));
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000336 LastEnumConst = EnumConst;
337 }
338 }
339
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000340 // FIXME: Fixup LBraceLoc and RBraceLoc
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000341 // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000342 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
343 Sema::DeclPtrTy::make(Enum),
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000344 &Enumerators[0], Enumerators.size(),
345 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000346
347 return Enum;
348}
349
Douglas Gregor6477b692009-03-25 15:04:13 +0000350Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
351 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
352 return 0;
353}
354
John McCalle29ba202009-08-20 01:44:21 +0000355Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
356 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000357 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
John McCalle29ba202009-08-20 01:44:21 +0000358 if (!InstParams) return NULL;
359
360 CXXRecordDecl *Pattern = D->getTemplatedDecl();
361 CXXRecordDecl *RecordInst
362 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), Owner,
363 Pattern->getLocation(), Pattern->getIdentifier(),
364 Pattern->getTagKeywordLoc(), /*PrevDecl=*/ NULL);
365
366 ClassTemplateDecl *Inst
367 = ClassTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
368 D->getIdentifier(), InstParams, RecordInst, 0);
369 RecordInst->setDescribedClassTemplate(Inst);
370 Inst->setAccess(D->getAccess());
371 Inst->setInstantiatedFromMemberTemplate(D);
372
373 Owner->addDecl(Inst);
374 return Inst;
375}
376
Douglas Gregord475b8d2009-03-25 21:17:03 +0000377Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
378 CXXRecordDecl *PrevDecl = 0;
379 if (D->isInjectedClassName())
380 PrevDecl = cast<CXXRecordDecl>(Owner);
381
382 CXXRecordDecl *Record
383 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000384 D->getLocation(), D->getIdentifier(),
385 D->getTagKeywordLoc(), PrevDecl);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000386 Record->setImplicit(D->isImplicit());
387 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000388 if (!D->isInjectedClassName())
389 Record->setInstantiationOfMemberClass(D);
390
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000391 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000392 return Record;
393}
394
Douglas Gregore53060f2009-06-25 22:08:12 +0000395Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000396 // Check whether there is already a function template specialization for
397 // this declaration.
398 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
399 void *InsertPos = 0;
400 if (FunctionTemplate) {
401 llvm::FoldingSetNodeID ID;
402 FunctionTemplateSpecializationInfo::Profile(ID,
403 TemplateArgs.getFlatArgumentList(),
Douglas Gregor828e2262009-07-29 16:09:57 +0000404 TemplateArgs.flat_size(),
405 SemaRef.Context);
Douglas Gregor127102b2009-06-29 20:59:39 +0000406
407 FunctionTemplateSpecializationInfo *Info
408 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
409 InsertPos);
410
411 // If we already have a function template specialization, return it.
412 if (Info)
413 return Info->Function;
414 }
Douglas Gregore53060f2009-06-25 22:08:12 +0000415
416 Sema::LocalInstantiationScope Scope(SemaRef);
417
418 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCallce3ff2b2009-08-25 22:02:44 +0000419 QualType T = SubstFunctionType(D, Params);
Douglas Gregore53060f2009-06-25 22:08:12 +0000420 if (T.isNull())
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000421 return 0;
John McCallfd810b12009-08-14 02:03:10 +0000422
Douglas Gregore53060f2009-06-25 22:08:12 +0000423 // Build the instantiated method declaration.
John McCallfd810b12009-08-14 02:03:10 +0000424 FunctionDecl *Function;
425 if (FriendFunctionDecl* FFD = dyn_cast<FriendFunctionDecl>(D)) {
426 // The new decl's semantic context. FIXME: this might need
427 // to be instantiated.
428 DeclContext *DC = D->getDeclContext();
429
430 // This assert is bogus and exists only to catch cases we don't
431 // handle yet.
432 assert(!DC->isDependentContext());
433
434 Function =
435 FriendFunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000436 D->getDeclName(), T, D->getDeclaratorInfo(),
437 D->isInline(), FFD->getFriendLoc());
John McCallfd810b12009-08-14 02:03:10 +0000438 Function->setLexicalDeclContext(Owner);
439 } else {
440 Function =
441 FunctionDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000442 D->getDeclName(), T, D->getDeclaratorInfo(),
443 D->getStorageClass(),
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +0000444 D->isInline(), D->hasWrittenPrototype());
John McCallfd810b12009-08-14 02:03:10 +0000445 }
Douglas Gregore53060f2009-06-25 22:08:12 +0000446
447 // Attach the parameters
448 for (unsigned P = 0; P < Params.size(); ++P)
449 Params[P]->setOwningFunction(Function);
450 Function->setParams(SemaRef.Context, Params.data(), Params.size());
451
452 if (InitFunctionInstantiation(Function, D))
453 Function->setInvalidDecl();
454
455 bool Redeclaration = false;
456 bool OverloadableAttrRequired = false;
457 NamedDecl *PrevDecl = 0;
458 SemaRef.CheckFunctionDeclaration(Function, PrevDecl, Redeclaration,
459 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000460
Douglas Gregor127102b2009-06-29 20:59:39 +0000461 if (FunctionTemplate) {
462 // Record this function template specialization.
463 Function->setFunctionTemplateSpecialization(SemaRef.Context,
464 FunctionTemplate,
465 &TemplateArgs,
466 InsertPos);
John McCallfd810b12009-08-14 02:03:10 +0000467 }
468
469 // If this was a friend function decl, it's a member which
470 // needs to be added.
471 if (isa<FriendFunctionDecl>(Function)) {
472 // If the new context is still dependent, this declaration
473 // needs to remain hidden.
474 if (Owner->isDependentContext())
475 Owner->addHiddenDecl(Function);
476 else
477 Owner->addDecl(Function);
478 }
Douglas Gregor127102b2009-06-29 20:59:39 +0000479
Douglas Gregore53060f2009-06-25 22:08:12 +0000480 return Function;
481}
482
483Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
Douglas Gregor6b906862009-08-21 00:16:32 +0000484 // Check whether there is already a function template specialization for
485 // this declaration.
486 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
487 void *InsertPos = 0;
488 if (FunctionTemplate) {
489 llvm::FoldingSetNodeID ID;
490 FunctionTemplateSpecializationInfo::Profile(ID,
491 TemplateArgs.getFlatArgumentList(),
492 TemplateArgs.flat_size(),
493 SemaRef.Context);
494
495 FunctionTemplateSpecializationInfo *Info
496 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
497 InsertPos);
498
499 // If we already have a function template specialization, return it.
500 if (Info)
501 return Info->Function;
502 }
503
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000504 Sema::LocalInstantiationScope Scope(SemaRef);
505
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000506 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCallce3ff2b2009-08-25 22:02:44 +0000507 QualType T = SubstFunctionType(D, Params);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000508 if (T.isNull())
509 return 0;
510
511 // Build the instantiated method declaration.
512 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
Douglas Gregordec06662009-08-21 18:42:58 +0000513 CXXMethodDecl *Method = 0;
514
515 DeclarationName Name = D->getDeclName();
Douglas Gregor17e32f32009-08-21 22:43:28 +0000516 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Douglas Gregordec06662009-08-21 18:42:58 +0000517 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
518 Name = SemaRef.Context.DeclarationNames.getCXXConstructorName(
519 SemaRef.Context.getCanonicalType(ClassTy));
520 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
Douglas Gregor17e32f32009-08-21 22:43:28 +0000521 Constructor->getLocation(),
Douglas Gregordec06662009-08-21 18:42:58 +0000522 Name, T,
Douglas Gregor17e32f32009-08-21 22:43:28 +0000523 Constructor->getDeclaratorInfo(),
524 Constructor->isExplicit(),
525 Constructor->isInline(), false);
526 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
527 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
528 Name = SemaRef.Context.DeclarationNames.getCXXDestructorName(
529 SemaRef.Context.getCanonicalType(ClassTy));
530 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
531 Destructor->getLocation(), Name,
532 T, Destructor->isInline(), false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000533 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
534 CanQualType ConvTy
535 = SemaRef.Context.getCanonicalType(
536 T->getAsFunctionType()->getResultType());
537 Name = SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(
538 ConvTy);
539 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
540 Conversion->getLocation(), Name,
541 T, Conversion->getDeclaratorInfo(),
542 Conversion->isInline(),
543 Conversion->isExplicit());
Douglas Gregordec06662009-08-21 18:42:58 +0000544 } else {
545 Method = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
546 D->getDeclName(), T, D->getDeclaratorInfo(),
547 D->isStatic(), D->isInline());
548 }
Douglas Gregor6b906862009-08-21 00:16:32 +0000549
550 if (!FunctionTemplate)
551 Method->setInstantiationOfMemberFunction(D);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000552
Douglas Gregor7caa6822009-07-24 20:34:43 +0000553 // If we are instantiating a member function defined
554 // out-of-line, the instantiation will have the same lexical
555 // context (which will be a namespace scope) as the template.
556 if (D->isOutOfLine())
557 Method->setLexicalDeclContext(D->getLexicalDeclContext());
558
Douglas Gregor5545e162009-03-24 00:38:23 +0000559 // Attach the parameters
560 for (unsigned P = 0; P < Params.size(); ++P)
561 Params[P]->setOwningFunction(Method);
Jay Foadbeaaccd2009-05-21 09:52:38 +0000562 Method->setParams(SemaRef.Context, Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +0000563
564 if (InitMethodInstantiation(Method, D))
565 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000566
Douglas Gregordec06662009-08-21 18:42:58 +0000567 NamedDecl *PrevDecl = 0;
568
569 if (!FunctionTemplate) {
570 PrevDecl = SemaRef.LookupQualifiedName(Owner, Name,
571 Sema::LookupOrdinaryName, true);
572
573 // In C++, the previous declaration we find might be a tag type
574 // (class or enum). In this case, the new declaration will hide the
575 // tag type. Note that this does does not apply if we're declaring a
576 // typedef (C++ [dcl.typedef]p4).
577 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
578 PrevDecl = 0;
579 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000580
Douglas Gregor6b906862009-08-21 00:16:32 +0000581 if (FunctionTemplate)
582 // Record this function template specialization.
583 Method->setFunctionTemplateSpecialization(SemaRef.Context,
584 FunctionTemplate,
585 &TemplateArgs,
586 InsertPos);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000587
588 bool Redeclaration = false;
589 bool OverloadableAttrRequired = false;
590 SemaRef.CheckFunctionDeclaration(Method, PrevDecl, Redeclaration,
591 /*FIXME:*/OverloadableAttrRequired);
592
593 if (!FunctionTemplate && (!Method->isInvalidDecl() || !PrevDecl))
Douglas Gregordec06662009-08-21 18:42:58 +0000594 Owner->addDecl(Method);
595
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000596 return Method;
597}
598
Douglas Gregor615c5d42009-03-24 16:43:20 +0000599Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +0000600 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +0000601}
602
Douglas Gregor03b2b072009-03-24 00:15:49 +0000603Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +0000604 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +0000605}
606
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000607Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000608 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000609}
610
Douglas Gregor6477b692009-03-25 15:04:13 +0000611ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
John McCallce3ff2b2009-08-25 22:02:44 +0000612 QualType OrigT = SemaRef.SubstType(D->getOriginalType(), TemplateArgs,
Douglas Gregor7e063902009-05-11 23:53:27 +0000613 D->getLocation(), D->getDeclName());
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000614 if (OrigT.isNull())
615 return 0;
616
617 QualType T = SemaRef.adjustParameterType(OrigT);
618
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000619 // Allocate the parameter
620 ParmVarDecl *Param = 0;
621 if (T == OrigT)
622 Param = ParmVarDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000623 D->getIdentifier(), T, D->getDeclaratorInfo(),
624 D->getStorageClass(), 0);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000625 else
626 Param = OriginalParmVarDecl::Create(SemaRef.Context, Owner,
627 D->getLocation(), D->getIdentifier(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000628 T, D->getDeclaratorInfo(), OrigT,
629 D->getStorageClass(), 0);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000630
Anders Carlsson9351c172009-08-25 03:18:48 +0000631 // Mark the default argument as being uninstantiated.
632 if (Expr *Arg = D->getDefaultArg())
633 Param->setUninstantiatedDefaultArg(Arg);
634
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000635 // Note: we don't try to instantiate function parameters until after
636 // we've instantiated the function's type. Therefore, we don't have
637 // to check for 'void' parameter types here.
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000638 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000639 return Param;
640}
641
642Decl *
643TemplateDeclInstantiator::VisitOriginalParmVarDecl(OriginalParmVarDecl *D) {
644 // Since parameter types can decay either before or after
645 // instantiation, we simply treat OriginalParmVarDecls as
646 // ParmVarDecls the same way, and create one or the other depending
647 // on what happens after template instantiation.
648 return VisitParmVarDecl(D);
649}
650
John McCalle29ba202009-08-20 01:44:21 +0000651Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
652 TemplateTypeParmDecl *D) {
653 // TODO: don't always clone when decls are refcounted.
654 const Type* T = D->getTypeForDecl();
655 assert(T->isTemplateTypeParmType());
656 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
657
658 TemplateTypeParmDecl *Inst =
659 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
660 TTPT->getDepth(), TTPT->getIndex(),
661 TTPT->getName(),
662 D->wasDeclaredWithTypename(),
663 D->isParameterPack());
664
665 if (D->hasDefaultArgument()) {
666 QualType DefaultPattern = D->getDefaultArgument();
667 QualType DefaultInst
John McCallce3ff2b2009-08-25 22:02:44 +0000668 = SemaRef.SubstType(DefaultPattern, TemplateArgs,
669 D->getDefaultArgumentLoc(),
670 D->getDeclName());
John McCalle29ba202009-08-20 01:44:21 +0000671
672 Inst->setDefaultArgument(DefaultInst,
673 D->getDefaultArgumentLoc(),
674 D->defaultArgumentWasInherited() /* preserve? */);
675 }
676
677 return Inst;
678}
679
John McCallce3ff2b2009-08-25 22:02:44 +0000680Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
681 const TemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +0000682 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000683 return Instantiator.Visit(D);
684}
685
John McCalle29ba202009-08-20 01:44:21 +0000686/// \brief Instantiates a nested template parameter list in the current
687/// instantiation context.
688///
689/// \param L The parameter list to instantiate
690///
691/// \returns NULL if there was an error
692TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +0000693TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +0000694 // Get errors for all the parameters before bailing out.
695 bool Invalid = false;
696
697 unsigned N = L->size();
698 typedef llvm::SmallVector<Decl*,8> ParamVector;
699 ParamVector Params;
700 Params.reserve(N);
701 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
702 PI != PE; ++PI) {
703 Decl *D = Visit(*PI);
704 Params.push_back(D);
705 Invalid = Invalid || !D;
706 }
707
708 // Clean up if we had an error.
709 if (Invalid) {
710 for (ParamVector::iterator PI = Params.begin(), PE = Params.end();
711 PI != PE; ++PI)
712 if (*PI)
713 (*PI)->Destroy(SemaRef.Context);
714 return NULL;
715 }
716
717 TemplateParameterList *InstL
718 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
719 L->getLAngleLoc(), &Params.front(), N,
720 L->getRAngleLoc());
721 return InstL;
722}
723
John McCallce3ff2b2009-08-25 22:02:44 +0000724/// \brief Does substitution on the type of the given function, including
725/// all of the function parameters.
Douglas Gregor5545e162009-03-24 00:38:23 +0000726///
John McCallce3ff2b2009-08-25 22:02:44 +0000727/// \param D The function whose type will be the basis of the substitution
Douglas Gregor5545e162009-03-24 00:38:23 +0000728///
729/// \param Params the instantiated parameter declarations
730
John McCallce3ff2b2009-08-25 22:02:44 +0000731/// \returns the instantiated function's type if successful, a NULL
Douglas Gregor5545e162009-03-24 00:38:23 +0000732/// type if there was an error.
733QualType
John McCallce3ff2b2009-08-25 22:02:44 +0000734TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +0000735 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
736 bool InvalidDecl = false;
737
John McCallce3ff2b2009-08-25 22:02:44 +0000738 // Substitute all of the function's formal parameter types.
Douglas Gregor7e063902009-05-11 23:53:27 +0000739 TemplateDeclInstantiator ParamInstantiator(SemaRef, 0, TemplateArgs);
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000740 llvm::SmallVector<QualType, 4> ParamTys;
Douglas Gregor5545e162009-03-24 00:38:23 +0000741 for (FunctionDecl::param_iterator P = D->param_begin(),
742 PEnd = D->param_end();
743 P != PEnd; ++P) {
Douglas Gregor6477b692009-03-25 15:04:13 +0000744 if (ParmVarDecl *PInst = ParamInstantiator.VisitParmVarDecl(*P)) {
Douglas Gregor5545e162009-03-24 00:38:23 +0000745 if (PInst->getType()->isVoidType()) {
746 SemaRef.Diag(PInst->getLocation(), diag::err_param_with_void_type);
747 PInst->setInvalidDecl();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000748 } else if (SemaRef.RequireNonAbstractType(PInst->getLocation(),
749 PInst->getType(),
750 diag::err_abstract_type_in_decl,
751 Sema::AbstractParamType))
Douglas Gregor5545e162009-03-24 00:38:23 +0000752 PInst->setInvalidDecl();
753
754 Params.push_back(PInst);
755 ParamTys.push_back(PInst->getType());
756
757 if (PInst->isInvalidDecl())
758 InvalidDecl = true;
759 } else
760 InvalidDecl = true;
761 }
762
763 // FIXME: Deallocate dead declarations.
764 if (InvalidDecl)
765 return QualType();
766
767 const FunctionProtoType *Proto = D->getType()->getAsFunctionProtoType();
768 assert(Proto && "Missing prototype?");
769 QualType ResultType
John McCallce3ff2b2009-08-25 22:02:44 +0000770 = SemaRef.SubstType(Proto->getResultType(), TemplateArgs,
771 D->getLocation(), D->getDeclName());
Douglas Gregor5545e162009-03-24 00:38:23 +0000772 if (ResultType.isNull())
773 return QualType();
774
Jay Foadbeaaccd2009-05-21 09:52:38 +0000775 return SemaRef.BuildFunctionType(ResultType, ParamTys.data(), ParamTys.size(),
Douglas Gregor5545e162009-03-24 00:38:23 +0000776 Proto->isVariadic(), Proto->getTypeQuals(),
777 D->getLocation(), D->getDeclName());
778}
779
Douglas Gregore53060f2009-06-25 22:08:12 +0000780/// \brief Initializes the common fields of an instantiation function
781/// declaration (New) from the corresponding fields of its template (Tmpl).
782///
783/// \returns true if there was an error
784bool
785TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
786 FunctionDecl *Tmpl) {
787 if (Tmpl->isDeleted())
788 New->setDeleted();
Douglas Gregorcca9e962009-07-01 22:01:06 +0000789
790 // If we are performing substituting explicitly-specified template arguments
791 // or deduced template arguments into a function template and we reach this
792 // point, we are now past the point where SFINAE applies and have committed
793 // to keeping the new function template specialization. We therefore
794 // convert the active template instantiation for the function template
795 // into a template instantiation for this specific function template
796 // specialization, which is not a SFINAE context, so that we diagnose any
797 // further errors in the declaration itself.
798 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
799 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
800 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
801 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
802 if (FunctionTemplateDecl *FunTmpl
803 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
804 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
805 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +0000806 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000807 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
808 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
809 }
810 }
811
Douglas Gregore53060f2009-06-25 22:08:12 +0000812 return false;
813}
814
Douglas Gregor5545e162009-03-24 00:38:23 +0000815/// \brief Initializes common fields of an instantiated method
816/// declaration (New) from the corresponding fields of its template
817/// (Tmpl).
818///
819/// \returns true if there was an error
820bool
821TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
822 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +0000823 if (InitFunctionInstantiation(New, Tmpl))
824 return true;
825
Douglas Gregor5545e162009-03-24 00:38:23 +0000826 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
827 New->setAccess(Tmpl->getAccess());
Anders Carlsson77b7f1d2009-05-14 22:15:41 +0000828 if (Tmpl->isVirtualAsWritten()) {
829 New->setVirtualAsWritten(true);
Douglas Gregor5545e162009-03-24 00:38:23 +0000830 Record->setAggregate(false);
831 Record->setPOD(false);
Eli Friedman1d954f62009-08-15 21:55:26 +0000832 Record->setEmpty(false);
Douglas Gregor5545e162009-03-24 00:38:23 +0000833 Record->setPolymorphic(true);
834 }
Douglas Gregor5545e162009-03-24 00:38:23 +0000835 if (Tmpl->isPure()) {
836 New->setPure();
837 Record->setAbstract(true);
838 }
839
840 // FIXME: attributes
841 // FIXME: New needs a pointer to Tmpl
842 return false;
843}
Douglas Gregora58861f2009-05-13 20:28:22 +0000844
845/// \brief Instantiate the definition of the given function from its
846/// template.
847///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000848/// \param PointOfInstantiation the point at which the instantiation was
849/// required. Note that this is not precisely a "point of instantiation"
850/// for the function, but it's close.
851///
Douglas Gregora58861f2009-05-13 20:28:22 +0000852/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000853/// function template specialization or member function of a class template
854/// specialization.
855///
856/// \param Recursive if true, recursively instantiates any functions that
857/// are required by this instantiation.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000858void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000859 FunctionDecl *Function,
860 bool Recursive) {
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000861 if (Function->isInvalidDecl())
862 return;
863
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000864 assert(!Function->getBody() && "Already instantiated!");
Douglas Gregord7f37bf2009-06-22 23:06:13 +0000865
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000866 // Find the function body that we'll be substituting.
Douglas Gregor1637be72009-06-26 00:10:03 +0000867 const FunctionDecl *PatternDecl = 0;
868 if (FunctionTemplateDecl *Primary = Function->getPrimaryTemplate())
869 PatternDecl = Primary->getTemplatedDecl();
870 else
871 PatternDecl = Function->getInstantiatedFromMemberFunction();
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000872 Stmt *Pattern = 0;
873 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000874 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000875
876 if (!Pattern)
877 return;
878
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000879 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
880 if (Inst)
881 return;
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000882
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000883 // If we're performing recursive template instantiation, create our own
884 // queue of pending implicit instantiations that we will instantiate later,
885 // while we're still within our own instantiation context.
886 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
887 if (Recursive)
888 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
889
Douglas Gregore2c31ff2009-05-15 17:59:04 +0000890 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
891
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000892 // Introduce a new scope where local variable instantiations will be
893 // recorded.
894 LocalInstantiationScope Scope(*this);
895
896 // Introduce the instantiated function parameters into the local
897 // instantiation scope.
898 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
899 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
900 Function->getParamDecl(I));
901
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000902 // Enter the scope of this instantiation. We don't use
903 // PushDeclContext because we don't have a scope.
904 DeclContext *PreviousContext = CurContext;
905 CurContext = Function;
906
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000907 // Instantiate the function body.
908 OwningStmtResult Body
John McCallce3ff2b2009-08-25 22:02:44 +0000909 = SubstStmt(Pattern, getTemplateInstantiationArgs(Function));
Douglas Gregore2c31ff2009-05-15 17:59:04 +0000910
911 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
912 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000913
914 CurContext = PreviousContext;
Douglas Gregoraba43bb2009-05-26 20:50:29 +0000915
916 DeclGroupRef DG(Function);
917 Consumer.HandleTopLevelDecl(DG);
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000918
919 if (Recursive) {
920 // Instantiate any pending implicit instantiations found during the
921 // instantiation of this template.
922 PerformPendingImplicitInstantiations();
923
924 // Restore the set of pending implicit instantiations.
925 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
926 }
Douglas Gregora58861f2009-05-13 20:28:22 +0000927}
928
929/// \brief Instantiate the definition of the given variable from its
930/// template.
931///
Douglas Gregor7caa6822009-07-24 20:34:43 +0000932/// \param PointOfInstantiation the point at which the instantiation was
933/// required. Note that this is not precisely a "point of instantiation"
934/// for the function, but it's close.
935///
936/// \param Var the already-instantiated declaration of a static member
937/// variable of a class template specialization.
938///
939/// \param Recursive if true, recursively instantiates any functions that
940/// are required by this instantiation.
941void Sema::InstantiateStaticDataMemberDefinition(
942 SourceLocation PointOfInstantiation,
943 VarDecl *Var,
944 bool Recursive) {
945 if (Var->isInvalidDecl())
946 return;
947
948 // Find the out-of-line definition of this static data member.
949 // FIXME: Do we have to look for specializations separately?
950 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
951 bool FoundOutOfLineDef = false;
952 assert(Def && "This data member was not instantiated from a template?");
953 assert(Def->isStaticDataMember() && "Not a static data member?");
954 for (VarDecl::redecl_iterator RD = Def->redecls_begin(),
955 RDEnd = Def->redecls_end();
956 RD != RDEnd; ++RD) {
957 if (RD->getLexicalDeclContext()->isFileContext()) {
958 Def = *RD;
959 FoundOutOfLineDef = true;
960 }
961 }
962
963 if (!FoundOutOfLineDef) {
964 // We did not find an out-of-line definition of this static data member,
965 // so we won't perform any instantiation. Rather, we rely on the user to
966 // instantiate this definition (or provide a specialization for it) in
967 // another translation unit.
968 return;
969 }
970
971 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
972 if (Inst)
973 return;
974
975 // If we're performing recursive template instantiation, create our own
976 // queue of pending implicit instantiations that we will instantiate later,
977 // while we're still within our own instantiation context.
978 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
979 if (Recursive)
980 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
981
982 // Enter the scope of this instantiation. We don't use
983 // PushDeclContext because we don't have a scope.
984 DeclContext *PreviousContext = CurContext;
985 CurContext = Var->getDeclContext();
986
987#if 0
988 // Instantiate the initializer of this static data member.
989 OwningExprResult Init
990 = InstantiateExpr(Def->getInit(), getTemplateInstantiationArgs(Var));
991 if (Init.isInvalid()) {
992 // If instantiation of the initializer failed, mark the declaration invalid
993 // and don't instantiate anything else that was triggered by this
994 // instantiation.
995 Var->setInvalidDecl();
996
997 // Restore the set of pending implicit instantiations.
998 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
999
1000 return;
1001 }
1002
1003 // Type-check the initializer.
1004 if (Init.get())
1005 AddInitializerToDecl(DeclPtrTy::make(Var), move(Init),
1006 Def->hasCXXDirectInitializer());
1007 else
1008 ActOnUninitializedDecl(DeclPtrTy::make(Var), false);
1009#else
John McCallce3ff2b2009-08-25 22:02:44 +00001010 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Douglas Gregor7caa6822009-07-24 20:34:43 +00001011 getTemplateInstantiationArgs(Var)));
1012#endif
1013
1014 CurContext = PreviousContext;
1015
1016 if (Var) {
1017 DeclGroupRef DG(Var);
1018 Consumer.HandleTopLevelDecl(DG);
1019 }
1020
1021 if (Recursive) {
1022 // Instantiate any pending implicit instantiations found during the
1023 // instantiation of this template.
1024 PerformPendingImplicitInstantiations();
1025
1026 // Restore the set of pending implicit instantiations.
1027 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1028 }
Douglas Gregora58861f2009-05-13 20:28:22 +00001029}
Douglas Gregor815215d2009-05-27 05:35:12 +00001030
1031static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
1032 if (D->getKind() != Other->getKind())
1033 return false;
1034
1035 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001036 return Record->getInstantiatedFromMemberClass()->getCanonicalDecl()
1037 == D->getCanonicalDecl();
Douglas Gregor815215d2009-05-27 05:35:12 +00001038
1039 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001040 return Function->getInstantiatedFromMemberFunction()->getCanonicalDecl()
1041 == D->getCanonicalDecl();
Douglas Gregor815215d2009-05-27 05:35:12 +00001042
Douglas Gregor8dbc3c62009-05-27 17:20:35 +00001043 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001044 return Enum->getInstantiatedFromMemberEnum()->getCanonicalDecl()
1045 == D->getCanonicalDecl();
Douglas Gregor815215d2009-05-27 05:35:12 +00001046
Douglas Gregor7caa6822009-07-24 20:34:43 +00001047 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
1048 if (Var->isStaticDataMember())
1049 return Var->getInstantiatedFromStaticDataMember()->getCanonicalDecl()
1050 == D->getCanonicalDecl();
1051
Douglas Gregor815215d2009-05-27 05:35:12 +00001052 // FIXME: How can we find instantiations of anonymous unions?
1053
1054 return D->getDeclName() && isa<NamedDecl>(Other) &&
1055 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
1056}
1057
1058template<typename ForwardIterator>
1059static NamedDecl *findInstantiationOf(ASTContext &Ctx,
1060 NamedDecl *D,
1061 ForwardIterator first,
1062 ForwardIterator last) {
1063 for (; first != last; ++first)
1064 if (isInstantiationOf(Ctx, D, *first))
1065 return cast<NamedDecl>(*first);
1066
1067 return 0;
1068}
1069
Douglas Gregored961e72009-05-27 17:54:46 +00001070/// \brief Find the instantiation of the given declaration within the
1071/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00001072///
1073/// This routine is intended to be used when \p D is a declaration
1074/// referenced from within a template, that needs to mapped into the
1075/// corresponding declaration within an instantiation. For example,
1076/// given:
1077///
1078/// \code
1079/// template<typename T>
1080/// struct X {
1081/// enum Kind {
1082/// KnownValue = sizeof(T)
1083/// };
1084///
1085/// bool getKind() const { return KnownValue; }
1086/// };
1087///
1088/// template struct X<int>;
1089/// \endcode
1090///
1091/// In the instantiation of X<int>::getKind(), we need to map the
1092/// EnumConstantDecl for KnownValue (which refers to
1093/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00001094/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
1095/// this mapping from within the instantiation of X<int>.
John McCallce3ff2b2009-08-25 22:02:44 +00001096NamedDecl * Sema::FindInstantiatedDecl(NamedDecl *D) {
Douglas Gregor815215d2009-05-27 05:35:12 +00001097 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor2bba76b2009-05-27 17:07:49 +00001098 if (isa<ParmVarDecl>(D) || ParentDC->isFunctionOrMethod()) {
1099 // D is a local of some kind. Look into the map of local
1100 // declarations to their instantiations.
1101 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
1102 }
Douglas Gregor815215d2009-05-27 05:35:12 +00001103
Douglas Gregor2bba76b2009-05-27 17:07:49 +00001104 if (NamedDecl *ParentDecl = dyn_cast<NamedDecl>(ParentDC)) {
John McCallce3ff2b2009-08-25 22:02:44 +00001105 ParentDecl = FindInstantiatedDecl(ParentDecl);
Douglas Gregor815215d2009-05-27 05:35:12 +00001106 if (!ParentDecl)
1107 return 0;
1108
1109 ParentDC = cast<DeclContext>(ParentDecl);
1110 }
1111
Douglas Gregor815215d2009-05-27 05:35:12 +00001112 if (ParentDC != D->getDeclContext()) {
1113 // We performed some kind of instantiation in the parent context,
1114 // so now we need to look into the instantiated parent context to
1115 // find the instantiation of the declaration D.
1116 NamedDecl *Result = 0;
1117 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001118 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00001119 Result = findInstantiationOf(Context, D, Found.first, Found.second);
1120 } else {
1121 // Since we don't have a name for the entity we're looking for,
1122 // our only option is to walk through all of the declarations to
1123 // find that name. This will occur in a few cases:
1124 //
1125 // - anonymous struct/union within a template
1126 // - unnamed class/struct/union/enum within a template
1127 //
1128 // FIXME: Find a better way to find these instantiations!
1129 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001130 ParentDC->decls_begin(),
1131 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00001132 }
1133 assert(Result && "Unable to find instantiation of declaration!");
1134 D = Result;
1135 }
1136
Douglas Gregor815215d2009-05-27 05:35:12 +00001137 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
Douglas Gregored961e72009-05-27 17:54:46 +00001138 if (ClassTemplateDecl *ClassTemplate
1139 = Record->getDescribedClassTemplate()) {
1140 // When the declaration D was parsed, it referred to the current
1141 // instantiation. Therefore, look through the current context,
1142 // which contains actual instantiations, to find the
1143 // instantiation of the "current instantiation" that D refers
1144 // to. Alternatively, we could just instantiate the
1145 // injected-class-name with the current template arguments, but
1146 // such an instantiation is far more expensive.
1147 for (DeclContext *DC = CurContext; !DC->isFileContext();
1148 DC = DC->getParent()) {
1149 if (ClassTemplateSpecializationDecl *Spec
1150 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001151 if (Spec->getSpecializedTemplate()->getCanonicalDecl()
1152 == ClassTemplate->getCanonicalDecl())
Douglas Gregored961e72009-05-27 17:54:46 +00001153 return Spec;
1154 }
1155
1156 assert(false &&
1157 "Unable to find declaration for the current instantiation");
Douglas Gregor815215d2009-05-27 05:35:12 +00001158 }
1159
1160 return D;
1161}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001162
1163/// \brief Performs template instantiation for all implicit template
1164/// instantiations we have seen until this point.
1165void Sema::PerformPendingImplicitInstantiations() {
1166 while (!PendingImplicitInstantiations.empty()) {
1167 PendingImplicitInstantiation Inst = PendingImplicitInstantiations.front();
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001168 PendingImplicitInstantiations.pop_front();
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001169
Douglas Gregor7caa6822009-07-24 20:34:43 +00001170 // Instantiate function definitions
1171 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001172 if (!Function->getBody())
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001173 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00001174 continue;
1175 }
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001176
Douglas Gregor7caa6822009-07-24 20:34:43 +00001177 // Instantiate static data member definitions.
1178 VarDecl *Var = cast<VarDecl>(Inst.first);
1179 assert(Var->isStaticDataMember() && "Not a static data member?");
1180 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001181 }
1182}