blob: 9785fb2653e7e506c42297feccfc969da0a57177 [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 Gregord6350ae2009-08-28 20:31:08 +000028 const MultiLevelTemplateArgumentList &TemplateArgs;
Douglas Gregor8dbc2692009-03-17 21:15:40 +000029
30 public:
31 typedef Sema::OwningExprResult OwningExprResult;
32
33 TemplateDeclInstantiator(Sema &SemaRef, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +000034 const MultiLevelTemplateArgumentList &TemplateArgs)
Douglas Gregor7e063902009-05-11 23:53:27 +000035 : 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 McCall02cace72009-08-28 07:59:38 +000048 Decl *VisitFriendDecl(FriendDecl *D);
Douglas Gregore53060f2009-06-25 22:08:12 +000049 Decl *VisitFunctionDecl(FunctionDecl *D);
Douglas Gregord475b8d2009-03-25 21:17:03 +000050 Decl *VisitCXXRecordDecl(CXXRecordDecl *D);
Douglas Gregord60e1052009-08-27 16:57:43 +000051 Decl *VisitCXXMethodDecl(CXXMethodDecl *D,
52 TemplateParameterList *TemplateParams = 0);
Douglas Gregor615c5d42009-03-24 16:43:20 +000053 Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
Douglas Gregor03b2b072009-03-24 00:15:49 +000054 Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +000055 Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000056 ParmVarDecl *VisitParmVarDecl(ParmVarDecl *D);
Douglas Gregor2dc0e642009-03-23 23:06:20 +000057 Decl *VisitOriginalParmVarDecl(OriginalParmVarDecl *D);
John McCalle29ba202009-08-20 01:44:21 +000058 Decl *VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregord60e1052009-08-27 16:57:43 +000059 Decl *VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
John McCalle29ba202009-08-20 01:44:21 +000060 Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Anders Carlsson0dde18e2009-08-28 15:18:15 +000061 Decl *VisitUnresolvedUsingDecl(UnresolvedUsingDecl *D);
62
Douglas Gregor8dbc2692009-03-17 21:15:40 +000063 // Base case. FIXME: Remove once we can instantiate everything.
64 Decl *VisitDecl(Decl *) {
Douglas Gregor3d7a12a2009-03-25 23:32:15 +000065 assert(false && "Template instantiation of unknown declaration kind!");
Douglas Gregor8dbc2692009-03-17 21:15:40 +000066 return 0;
67 }
Douglas Gregor5545e162009-03-24 00:38:23 +000068
John McCallfd810b12009-08-14 02:03:10 +000069 const LangOptions &getLangOptions() {
70 return SemaRef.getLangOptions();
71 }
72
Douglas Gregor5545e162009-03-24 00:38:23 +000073 // Helper functions for instantiating methods.
John McCallce3ff2b2009-08-25 22:02:44 +000074 QualType SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +000075 llvm::SmallVectorImpl<ParmVarDecl *> &Params);
Douglas Gregore53060f2009-06-25 22:08:12 +000076 bool InitFunctionInstantiation(FunctionDecl *New, FunctionDecl *Tmpl);
Douglas Gregor5545e162009-03-24 00:38:23 +000077 bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl);
John McCalle29ba202009-08-20 01:44:21 +000078
79 TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +000080 SubstTemplateParams(TemplateParameterList *List);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000081 };
82}
83
Douglas Gregor4f722be2009-03-25 15:45:12 +000084Decl *
85TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
86 assert(false && "Translation units cannot be instantiated");
87 return D;
88}
89
90Decl *
91TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
92 assert(false && "Namespaces cannot be instantiated");
93 return D;
94}
95
Douglas Gregor8dbc2692009-03-17 21:15:40 +000096Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
97 bool Invalid = false;
98 QualType T = D->getUnderlyingType();
99 if (T->isDependentType()) {
John McCallce3ff2b2009-08-25 22:02:44 +0000100 T = SemaRef.SubstType(T, TemplateArgs,
101 D->getLocation(), D->getDeclName());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000102 if (T.isNull()) {
103 Invalid = true;
104 T = SemaRef.Context.IntTy;
105 }
106 }
107
108 // Create the new typedef
109 TypedefDecl *Typedef
110 = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(),
111 D->getIdentifier(), T);
112 if (Invalid)
113 Typedef->setInvalidDecl();
114
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000115 Owner->addDecl(Typedef);
Douglas Gregorbc221632009-05-28 16:34:51 +0000116
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000117 return Typedef;
118}
119
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000120Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
John McCallce3ff2b2009-08-25 22:02:44 +0000121 // Do substitution on the type of the declaration
122 QualType T = SemaRef.SubstType(D->getType(), TemplateArgs,
123 D->getTypeSpecStartLoc(),
124 D->getDeclName());
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000125 if (T.isNull())
126 return 0;
127
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000128 // Build the instantiated declaration
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000129 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
130 D->getLocation(), D->getIdentifier(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000131 T, D->getDeclaratorInfo(),
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +0000132 D->getStorageClass());
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000133 Var->setThreadSpecified(D->isThreadSpecified());
134 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
135 Var->setDeclaredInCondition(D->isDeclaredInCondition());
136
Douglas Gregor7caa6822009-07-24 20:34:43 +0000137 // If we are instantiating a static data member defined
138 // out-of-line, the instantiation will have the same lexical
139 // context (which will be a namespace scope) as the template.
140 if (D->isOutOfLine())
141 Var->setLexicalDeclContext(D->getLexicalDeclContext());
142
Mike Stump390b4cc2009-05-16 07:39:55 +0000143 // FIXME: In theory, we could have a previous declaration for variables that
144 // are not static data members.
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000145 bool Redeclaration = false;
Chris Lattnereaaebc72009-04-25 08:06:05 +0000146 SemaRef.CheckVariableDeclaration(Var, 0, Redeclaration);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000147
148 if (D->isOutOfLine()) {
149 D->getLexicalDeclContext()->addDecl(Var);
150 Owner->makeDeclVisibleInContext(Var);
151 } else {
152 Owner->addDecl(Var);
153 }
154
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000155 if (D->getInit()) {
156 OwningExprResult Init
John McCallce3ff2b2009-08-25 22:02:44 +0000157 = SemaRef.SubstExpr(D->getInit(), TemplateArgs);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000158 if (Init.isInvalid())
159 Var->setInvalidDecl();
Douglas Gregor83ddad32009-08-26 21:14:46 +0000160 else if (ParenListExpr *PLE = dyn_cast<ParenListExpr>((Expr *)Init.get())) {
161 // FIXME: We're faking all of the comma locations, which is suboptimal.
162 // Do we even need these comma locations?
163 llvm::SmallVector<SourceLocation, 4> FakeCommaLocs;
164 if (PLE->getNumExprs() > 0) {
165 FakeCommaLocs.reserve(PLE->getNumExprs() - 1);
166 for (unsigned I = 0, N = PLE->getNumExprs() - 1; I != N; ++I) {
167 Expr *E = PLE->getExpr(I)->Retain();
168 FakeCommaLocs.push_back(
169 SemaRef.PP.getLocForEndOfToken(E->getLocEnd()));
170 }
Douglas Gregore9f8eb62009-08-26 23:26:04 +0000171 PLE->getExpr(PLE->getNumExprs() - 1)->Retain();
Douglas Gregor83ddad32009-08-26 21:14:46 +0000172 }
173
174 // Add the direct initializer to the declaration.
175 SemaRef.AddCXXDirectInitializerToDecl(Sema::DeclPtrTy::make(Var),
176 PLE->getLParenLoc(),
177 Sema::MultiExprArg(SemaRef,
178 (void**)PLE->getExprs(),
179 PLE->getNumExprs()),
180 FakeCommaLocs.data(),
181 PLE->getRParenLoc());
182
183 // When Init is destroyed, it will destroy the instantiated ParenListExpr;
184 // we've explicitly retained all of its subexpressions already.
185 } else
Chris Lattnerb28317a2009-03-28 19:18:32 +0000186 SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var), move(Init),
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000187 D->hasCXXDirectInitializer());
Douglas Gregor65b90052009-07-27 17:43:39 +0000188 } else if (!Var->isStaticDataMember() || Var->isOutOfLine())
189 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000190
Douglas Gregor7caa6822009-07-24 20:34:43 +0000191 // Link instantiations of static data members back to the template from
192 // which they were instantiated.
193 if (Var->isStaticDataMember())
194 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D);
195
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000196 return Var;
197}
198
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000199Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
200 bool Invalid = false;
201 QualType T = D->getType();
202 if (T->isDependentType()) {
John McCallce3ff2b2009-08-25 22:02:44 +0000203 T = SemaRef.SubstType(T, TemplateArgs,
204 D->getLocation(), D->getDeclName());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000205 if (!T.isNull() && T->isFunctionType()) {
206 // C++ [temp.arg.type]p3:
207 // If a declaration acquires a function type through a type
208 // dependent on a template-parameter and this causes a
209 // declaration that does not use the syntactic form of a
210 // function declarator to have function type, the program is
211 // ill-formed.
212 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
213 << T;
214 T = QualType();
215 Invalid = true;
216 }
217 }
218
219 Expr *BitWidth = D->getBitWidth();
220 if (Invalid)
221 BitWidth = 0;
222 else if (BitWidth) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000223 // The bit-width expression is not potentially evaluated.
224 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
225
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000226 OwningExprResult InstantiatedBitWidth
John McCallce3ff2b2009-08-25 22:02:44 +0000227 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000228 if (InstantiatedBitWidth.isInvalid()) {
229 Invalid = true;
230 BitWidth = 0;
231 } else
Anders Carlssone9146f22009-05-01 19:49:17 +0000232 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000233 }
234
235 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(), T,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000236 D->getDeclaratorInfo(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000237 cast<RecordDecl>(Owner),
238 D->getLocation(),
239 D->isMutable(),
240 BitWidth,
Steve Naroffea218b82009-07-14 14:58:18 +0000241 D->getTypeSpecStartLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000242 D->getAccess(),
243 0);
244 if (Field) {
245 if (Invalid)
246 Field->setInvalidDecl();
247
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000248 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000249 }
250
251 return Field;
252}
253
John McCall02cace72009-08-28 07:59:38 +0000254Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
255 FriendDecl::FriendUnion FU;
256
257 // Handle friend type expressions by simply substituting template
258 // parameters into the pattern type.
259 if (Type *Ty = D->getFriendType()) {
260 QualType T = SemaRef.SubstType(QualType(Ty,0), TemplateArgs,
261 D->getLocation(), DeclarationName());
262 if (T.isNull()) return 0;
263
264 assert(getLangOptions().CPlusPlus0x || T->isRecordType());
265 FU = T.getTypePtr();
266
267 // Handle everything else by appropriate substitution.
268 } else {
269 NamedDecl *ND = D->getFriendDecl();
270 assert(ND && "friend decl must be a decl or a type!");
271
272 Decl *NewND = Visit(ND);
273 if (!NewND) return 0;
274
275 FU = cast<NamedDecl>(NewND);
John McCallfd810b12009-08-14 02:03:10 +0000276 }
John McCall02cace72009-08-28 07:59:38 +0000277
278 FriendDecl *FD =
279 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(), FU,
280 D->getFriendLoc());
John McCall5fee1102009-08-29 03:50:18 +0000281 FD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +0000282 Owner->addDecl(FD);
283 return FD;
John McCallfd810b12009-08-14 02:03:10 +0000284}
285
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000286Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
287 Expr *AssertExpr = D->getAssertExpr();
288
Douglas Gregorac7610d2009-06-22 20:57:11 +0000289 // The expression in a static assertion is not potentially evaluated.
290 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
291
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000292 OwningExprResult InstantiatedAssertExpr
John McCallce3ff2b2009-08-25 22:02:44 +0000293 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000294 if (InstantiatedAssertExpr.isInvalid())
295 return 0;
296
Douglas Gregor43d9d922009-08-08 01:41:12 +0000297 OwningExprResult Message(SemaRef, D->getMessage());
298 D->getMessage()->Retain();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000299 Decl *StaticAssert
Chris Lattnerb28317a2009-03-28 19:18:32 +0000300 = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
301 move(InstantiatedAssertExpr),
302 move(Message)).getAs<Decl>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000303 return StaticAssert;
304}
305
306Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
307 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
308 D->getLocation(), D->getIdentifier(),
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000309 D->getTagKeywordLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000310 /*PrevDecl=*/0);
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000311 Enum->setInstantiationOfMemberEnum(D);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000312 Enum->setAccess(D->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000313 Owner->addDecl(Enum);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000314 Enum->startDefinition();
315
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000316 llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000317
318 EnumConstantDecl *LastEnumConst = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000319 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
320 ECEnd = D->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000321 EC != ECEnd; ++EC) {
322 // The specified value for the enumerator.
323 OwningExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000324 if (Expr *UninstValue = EC->getInitExpr()) {
325 // The enumerator's value expression is not potentially evaluated.
326 EnterExpressionEvaluationContext Unevaluated(SemaRef,
327 Action::Unevaluated);
328
John McCallce3ff2b2009-08-25 22:02:44 +0000329 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000330 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000331
332 // Drop the initial value and continue.
333 bool isInvalid = false;
334 if (Value.isInvalid()) {
335 Value = SemaRef.Owned((Expr *)0);
336 isInvalid = true;
337 }
338
339 EnumConstantDecl *EnumConst
340 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
341 EC->getLocation(), EC->getIdentifier(),
342 move(Value));
343
344 if (isInvalid) {
345 if (EnumConst)
346 EnumConst->setInvalidDecl();
347 Enum->setInvalidDecl();
348 }
349
350 if (EnumConst) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000351 Enum->addDecl(EnumConst);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000352 Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst));
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000353 LastEnumConst = EnumConst;
354 }
355 }
356
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000357 // FIXME: Fixup LBraceLoc and RBraceLoc
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000358 // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000359 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
360 Sema::DeclPtrTy::make(Enum),
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000361 &Enumerators[0], Enumerators.size(),
362 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000363
364 return Enum;
365}
366
Douglas Gregor6477b692009-03-25 15:04:13 +0000367Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
368 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
369 return 0;
370}
371
John McCalle29ba202009-08-20 01:44:21 +0000372Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
373 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000374 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Douglas Gregord60e1052009-08-27 16:57:43 +0000375 if (!InstParams)
376 return NULL;
John McCalle29ba202009-08-20 01:44:21 +0000377
378 CXXRecordDecl *Pattern = D->getTemplatedDecl();
379 CXXRecordDecl *RecordInst
380 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), Owner,
381 Pattern->getLocation(), Pattern->getIdentifier(),
382 Pattern->getTagKeywordLoc(), /*PrevDecl=*/ NULL);
383
384 ClassTemplateDecl *Inst
385 = ClassTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
386 D->getIdentifier(), InstParams, RecordInst, 0);
387 RecordInst->setDescribedClassTemplate(Inst);
388 Inst->setAccess(D->getAccess());
389 Inst->setInstantiatedFromMemberTemplate(D);
390
391 Owner->addDecl(Inst);
392 return Inst;
393}
394
Douglas Gregord60e1052009-08-27 16:57:43 +0000395Decl *
396TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
397 TemplateParameterList *TempParams = D->getTemplateParameters();
398 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
399 if (!InstParams)
400 return NULL;
401
402 // FIXME: Handle instantiation of nested function templates that aren't
403 // member function templates. This could happen inside a FriendDecl.
404 assert(isa<CXXMethodDecl>(D->getTemplatedDecl()));
405 CXXMethodDecl *InstMethod
406 = cast_or_null<CXXMethodDecl>(
407 VisitCXXMethodDecl(cast<CXXMethodDecl>(D->getTemplatedDecl()),
408 InstParams));
409 if (!InstMethod)
410 return 0;
411
412 // Link the instantiated function template declaration to the function
413 // template from which it was instantiated.
414 FunctionTemplateDecl *InstTemplate = InstMethod->getDescribedFunctionTemplate();
415 assert(InstTemplate && "VisitCXXMethodDecl didn't create a template!");
416 InstTemplate->setInstantiatedFromMemberTemplate(D);
417 Owner->addDecl(InstTemplate);
418 return InstTemplate;
419}
420
Douglas Gregord475b8d2009-03-25 21:17:03 +0000421Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
422 CXXRecordDecl *PrevDecl = 0;
423 if (D->isInjectedClassName())
424 PrevDecl = cast<CXXRecordDecl>(Owner);
425
426 CXXRecordDecl *Record
427 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000428 D->getLocation(), D->getIdentifier(),
429 D->getTagKeywordLoc(), PrevDecl);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000430 Record->setImplicit(D->isImplicit());
Eli Friedmaneaba1af2009-08-27 19:11:42 +0000431 // FIXME: Check against AS_none is an ugly hack to work around the issue that
432 // the tag decls introduced by friend class declarations don't have an access
433 // specifier. Remove once this area of the code gets sorted out.
434 if (D->getAccess() != AS_none)
435 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000436 if (!D->isInjectedClassName())
437 Record->setInstantiationOfMemberClass(D);
438
John McCall02cace72009-08-28 07:59:38 +0000439 // If the original function was part of a friend declaration,
440 // inherit its namespace state.
441 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
442 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
443
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000444 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000445 return Record;
446}
447
John McCall02cace72009-08-28 07:59:38 +0000448/// Normal class members are of more specific types and therefore
449/// don't make it here. This function serves two purposes:
450/// 1) instantiating function templates
451/// 2) substituting friend declarations
452/// FIXME: preserve function definitions in case #2
Douglas Gregore53060f2009-06-25 22:08:12 +0000453Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000454 // Check whether there is already a function template specialization for
455 // this declaration.
456 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
457 void *InsertPos = 0;
458 if (FunctionTemplate) {
459 llvm::FoldingSetNodeID ID;
460 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000461 TemplateArgs.getInnermost().getFlatArgumentList(),
462 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor828e2262009-07-29 16:09:57 +0000463 SemaRef.Context);
Douglas Gregor127102b2009-06-29 20:59:39 +0000464
465 FunctionTemplateSpecializationInfo *Info
466 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
467 InsertPos);
468
469 // If we already have a function template specialization, return it.
470 if (Info)
471 return Info->Function;
472 }
Douglas Gregore53060f2009-06-25 22:08:12 +0000473
474 Sema::LocalInstantiationScope Scope(SemaRef);
475
476 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCallce3ff2b2009-08-25 22:02:44 +0000477 QualType T = SubstFunctionType(D, Params);
Douglas Gregore53060f2009-06-25 22:08:12 +0000478 if (T.isNull())
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000479 return 0;
John McCallfd810b12009-08-14 02:03:10 +0000480
Douglas Gregore53060f2009-06-25 22:08:12 +0000481 // Build the instantiated method declaration.
John McCall02cace72009-08-28 07:59:38 +0000482 DeclContext *DC = SemaRef.FindInstantiatedContext(D->getDeclContext());
483 FunctionDecl *Function =
484 FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000485 D->getDeclName(), T, D->getDeclaratorInfo(),
486 D->getStorageClass(),
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +0000487 D->isInline(), D->hasWrittenPrototype());
John McCall02cace72009-08-28 07:59:38 +0000488 Function->setLexicalDeclContext(Owner);
489
Douglas Gregore53060f2009-06-25 22:08:12 +0000490 // Attach the parameters
491 for (unsigned P = 0; P < Params.size(); ++P)
492 Params[P]->setOwningFunction(Function);
493 Function->setParams(SemaRef.Context, Params.data(), Params.size());
John McCall02cace72009-08-28 07:59:38 +0000494
495 // If the original function was part of a friend declaration,
496 // inherit its namespace state and add it to the owner.
497 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind()) {
498 bool WasDeclared = (FOK == Decl::FOK_Declared);
499 Function->setObjectOfFriendDecl(WasDeclared);
500 if (!Owner->isDependentContext())
501 DC->makeDeclVisibleInContext(Function);
John McCallf181d8a2009-08-29 03:16:09 +0000502
503 Function->setInstantiationOfMemberFunction(D);
John McCall02cace72009-08-28 07:59:38 +0000504 }
Douglas Gregore53060f2009-06-25 22:08:12 +0000505
506 if (InitFunctionInstantiation(Function, D))
507 Function->setInvalidDecl();
508
509 bool Redeclaration = false;
510 bool OverloadableAttrRequired = false;
511 NamedDecl *PrevDecl = 0;
512 SemaRef.CheckFunctionDeclaration(Function, PrevDecl, Redeclaration,
513 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000514
Douglas Gregor127102b2009-06-29 20:59:39 +0000515 if (FunctionTemplate) {
516 // Record this function template specialization.
517 Function->setFunctionTemplateSpecialization(SemaRef.Context,
518 FunctionTemplate,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000519 &TemplateArgs.getInnermost(),
Douglas Gregor127102b2009-06-29 20:59:39 +0000520 InsertPos);
John McCallfd810b12009-08-14 02:03:10 +0000521 }
522
Douglas Gregore53060f2009-06-25 22:08:12 +0000523 return Function;
524}
525
Douglas Gregord60e1052009-08-27 16:57:43 +0000526Decl *
527TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
528 TemplateParameterList *TemplateParams) {
Douglas Gregor6b906862009-08-21 00:16:32 +0000529 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
530 void *InsertPos = 0;
Douglas Gregord60e1052009-08-27 16:57:43 +0000531 if (FunctionTemplate && !TemplateParams) {
532 // We are creating a function template specialization from a function
533 // template. Check whether there is already a function template
534 // specialization for this particular set of template arguments.
Douglas Gregor6b906862009-08-21 00:16:32 +0000535 llvm::FoldingSetNodeID ID;
536 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000537 TemplateArgs.getInnermost().getFlatArgumentList(),
538 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor6b906862009-08-21 00:16:32 +0000539 SemaRef.Context);
540
541 FunctionTemplateSpecializationInfo *Info
542 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
543 InsertPos);
544
545 // If we already have a function template specialization, return it.
546 if (Info)
547 return Info->Function;
548 }
549
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000550 Sema::LocalInstantiationScope Scope(SemaRef);
551
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000552 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCallce3ff2b2009-08-25 22:02:44 +0000553 QualType T = SubstFunctionType(D, Params);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000554 if (T.isNull())
555 return 0;
556
557 // Build the instantiated method declaration.
558 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
Douglas Gregordec06662009-08-21 18:42:58 +0000559 CXXMethodDecl *Method = 0;
560
561 DeclarationName Name = D->getDeclName();
Douglas Gregor17e32f32009-08-21 22:43:28 +0000562 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Douglas Gregordec06662009-08-21 18:42:58 +0000563 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
564 Name = SemaRef.Context.DeclarationNames.getCXXConstructorName(
565 SemaRef.Context.getCanonicalType(ClassTy));
566 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
Douglas Gregor17e32f32009-08-21 22:43:28 +0000567 Constructor->getLocation(),
Douglas Gregordec06662009-08-21 18:42:58 +0000568 Name, T,
Douglas Gregor17e32f32009-08-21 22:43:28 +0000569 Constructor->getDeclaratorInfo(),
570 Constructor->isExplicit(),
571 Constructor->isInline(), false);
572 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
573 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
574 Name = SemaRef.Context.DeclarationNames.getCXXDestructorName(
575 SemaRef.Context.getCanonicalType(ClassTy));
576 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
577 Destructor->getLocation(), Name,
578 T, Destructor->isInline(), false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000579 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
580 CanQualType ConvTy
581 = SemaRef.Context.getCanonicalType(
582 T->getAsFunctionType()->getResultType());
583 Name = SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(
584 ConvTy);
585 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
586 Conversion->getLocation(), Name,
587 T, Conversion->getDeclaratorInfo(),
588 Conversion->isInline(),
589 Conversion->isExplicit());
Douglas Gregordec06662009-08-21 18:42:58 +0000590 } else {
591 Method = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
592 D->getDeclName(), T, D->getDeclaratorInfo(),
593 D->isStatic(), D->isInline());
594 }
Douglas Gregor6b906862009-08-21 00:16:32 +0000595
Douglas Gregord60e1052009-08-27 16:57:43 +0000596 if (TemplateParams) {
597 // Our resulting instantiation is actually a function template, since we
598 // are substituting only the outer template parameters. For example, given
599 //
600 // template<typename T>
601 // struct X {
602 // template<typename U> void f(T, U);
603 // };
604 //
605 // X<int> x;
606 //
607 // We are instantiating the member template "f" within X<int>, which means
608 // substituting int for T, but leaving "f" as a member function template.
609 // Build the function template itself.
610 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
611 Method->getLocation(),
612 Method->getDeclName(),
613 TemplateParams, Method);
614 if (D->isOutOfLine())
615 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
616 Method->setDescribedFunctionTemplate(FunctionTemplate);
617 } else if (!FunctionTemplate)
Douglas Gregor6b906862009-08-21 00:16:32 +0000618 Method->setInstantiationOfMemberFunction(D);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000619
Douglas Gregor7caa6822009-07-24 20:34:43 +0000620 // If we are instantiating a member function defined
621 // out-of-line, the instantiation will have the same lexical
622 // context (which will be a namespace scope) as the template.
623 if (D->isOutOfLine())
624 Method->setLexicalDeclContext(D->getLexicalDeclContext());
625
Douglas Gregor5545e162009-03-24 00:38:23 +0000626 // Attach the parameters
627 for (unsigned P = 0; P < Params.size(); ++P)
628 Params[P]->setOwningFunction(Method);
Jay Foadbeaaccd2009-05-21 09:52:38 +0000629 Method->setParams(SemaRef.Context, Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +0000630
631 if (InitMethodInstantiation(Method, D))
632 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000633
Douglas Gregordec06662009-08-21 18:42:58 +0000634 NamedDecl *PrevDecl = 0;
635
Douglas Gregord60e1052009-08-27 16:57:43 +0000636 if (!FunctionTemplate || TemplateParams) {
Douglas Gregordec06662009-08-21 18:42:58 +0000637 PrevDecl = SemaRef.LookupQualifiedName(Owner, Name,
638 Sema::LookupOrdinaryName, true);
639
640 // In C++, the previous declaration we find might be a tag type
641 // (class or enum). In this case, the new declaration will hide the
642 // tag type. Note that this does does not apply if we're declaring a
643 // typedef (C++ [dcl.typedef]p4).
644 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
645 PrevDecl = 0;
646 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000647
Douglas Gregord60e1052009-08-27 16:57:43 +0000648 if (FunctionTemplate && !TemplateParams)
Douglas Gregor6b906862009-08-21 00:16:32 +0000649 // Record this function template specialization.
650 Method->setFunctionTemplateSpecialization(SemaRef.Context,
651 FunctionTemplate,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000652 &TemplateArgs.getInnermost(),
Douglas Gregor6b906862009-08-21 00:16:32 +0000653 InsertPos);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000654
655 bool Redeclaration = false;
656 bool OverloadableAttrRequired = false;
657 SemaRef.CheckFunctionDeclaration(Method, PrevDecl, Redeclaration,
658 /*FIXME:*/OverloadableAttrRequired);
659
660 if (!FunctionTemplate && (!Method->isInvalidDecl() || !PrevDecl))
Douglas Gregordec06662009-08-21 18:42:58 +0000661 Owner->addDecl(Method);
662
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000663 return Method;
664}
665
Douglas Gregor615c5d42009-03-24 16:43:20 +0000666Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +0000667 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +0000668}
669
Douglas Gregor03b2b072009-03-24 00:15:49 +0000670Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +0000671 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +0000672}
673
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000674Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000675 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000676}
677
Douglas Gregor6477b692009-03-25 15:04:13 +0000678ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
John McCallce3ff2b2009-08-25 22:02:44 +0000679 QualType OrigT = SemaRef.SubstType(D->getOriginalType(), TemplateArgs,
Douglas Gregor7e063902009-05-11 23:53:27 +0000680 D->getLocation(), D->getDeclName());
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000681 if (OrigT.isNull())
682 return 0;
683
684 QualType T = SemaRef.adjustParameterType(OrigT);
685
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000686 // Allocate the parameter
687 ParmVarDecl *Param = 0;
688 if (T == OrigT)
689 Param = ParmVarDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000690 D->getIdentifier(), T, D->getDeclaratorInfo(),
691 D->getStorageClass(), 0);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000692 else
693 Param = OriginalParmVarDecl::Create(SemaRef.Context, Owner,
694 D->getLocation(), D->getIdentifier(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000695 T, D->getDeclaratorInfo(), OrigT,
696 D->getStorageClass(), 0);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000697
Anders Carlsson9351c172009-08-25 03:18:48 +0000698 // Mark the default argument as being uninstantiated.
699 if (Expr *Arg = D->getDefaultArg())
700 Param->setUninstantiatedDefaultArg(Arg);
701
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000702 // Note: we don't try to instantiate function parameters until after
703 // we've instantiated the function's type. Therefore, we don't have
704 // to check for 'void' parameter types here.
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000705 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000706 return Param;
707}
708
709Decl *
710TemplateDeclInstantiator::VisitOriginalParmVarDecl(OriginalParmVarDecl *D) {
711 // Since parameter types can decay either before or after
712 // instantiation, we simply treat OriginalParmVarDecls as
713 // ParmVarDecls the same way, and create one or the other depending
714 // on what happens after template instantiation.
715 return VisitParmVarDecl(D);
716}
717
John McCalle29ba202009-08-20 01:44:21 +0000718Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
719 TemplateTypeParmDecl *D) {
720 // TODO: don't always clone when decls are refcounted.
721 const Type* T = D->getTypeForDecl();
722 assert(T->isTemplateTypeParmType());
723 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
724
725 TemplateTypeParmDecl *Inst =
726 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
727 TTPT->getDepth(), TTPT->getIndex(),
728 TTPT->getName(),
729 D->wasDeclaredWithTypename(),
730 D->isParameterPack());
731
732 if (D->hasDefaultArgument()) {
733 QualType DefaultPattern = D->getDefaultArgument();
734 QualType DefaultInst
John McCallce3ff2b2009-08-25 22:02:44 +0000735 = SemaRef.SubstType(DefaultPattern, TemplateArgs,
736 D->getDefaultArgumentLoc(),
737 D->getDeclName());
John McCalle29ba202009-08-20 01:44:21 +0000738
739 Inst->setDefaultArgument(DefaultInst,
740 D->getDefaultArgumentLoc(),
741 D->defaultArgumentWasInherited() /* preserve? */);
742 }
743
744 return Inst;
745}
746
Anders Carlsson0dde18e2009-08-28 15:18:15 +0000747Decl *
748TemplateDeclInstantiator::VisitUnresolvedUsingDecl(UnresolvedUsingDecl *D) {
749 NestedNameSpecifier *NNS =
750 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
751 D->getTargetNestedNameRange(),
752 TemplateArgs);
753 if (!NNS)
754 return 0;
755
756 CXXScopeSpec SS;
757 SS.setRange(D->getTargetNestedNameRange());
758 SS.setScopeRep(NNS);
759
Anders Carlsson0d8df782009-08-29 19:37:28 +0000760 NamedDecl *UD =
761 SemaRef.BuildUsingDeclaration(D->getLocation(), SS,
762 D->getTargetNameLocation(),
763 D->getTargetName(), 0, D->isTypeName());
764 if (UD)
765 SemaRef.Context.setInstantiatedFromUnresolvedUsingDecl(cast<UsingDecl>(UD),
766 D);
767 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +0000768}
769
John McCallce3ff2b2009-08-25 22:02:44 +0000770Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000771 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +0000772 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000773 return Instantiator.Visit(D);
774}
775
John McCalle29ba202009-08-20 01:44:21 +0000776/// \brief Instantiates a nested template parameter list in the current
777/// instantiation context.
778///
779/// \param L The parameter list to instantiate
780///
781/// \returns NULL if there was an error
782TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +0000783TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +0000784 // Get errors for all the parameters before bailing out.
785 bool Invalid = false;
786
787 unsigned N = L->size();
788 typedef llvm::SmallVector<Decl*,8> ParamVector;
789 ParamVector Params;
790 Params.reserve(N);
791 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
792 PI != PE; ++PI) {
793 Decl *D = Visit(*PI);
794 Params.push_back(D);
795 Invalid = Invalid || !D;
796 }
797
798 // Clean up if we had an error.
799 if (Invalid) {
800 for (ParamVector::iterator PI = Params.begin(), PE = Params.end();
801 PI != PE; ++PI)
802 if (*PI)
803 (*PI)->Destroy(SemaRef.Context);
804 return NULL;
805 }
806
807 TemplateParameterList *InstL
808 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
809 L->getLAngleLoc(), &Params.front(), N,
810 L->getRAngleLoc());
811 return InstL;
812}
813
John McCallce3ff2b2009-08-25 22:02:44 +0000814/// \brief Does substitution on the type of the given function, including
815/// all of the function parameters.
Douglas Gregor5545e162009-03-24 00:38:23 +0000816///
John McCallce3ff2b2009-08-25 22:02:44 +0000817/// \param D The function whose type will be the basis of the substitution
Douglas Gregor5545e162009-03-24 00:38:23 +0000818///
819/// \param Params the instantiated parameter declarations
820
John McCallce3ff2b2009-08-25 22:02:44 +0000821/// \returns the instantiated function's type if successful, a NULL
Douglas Gregor5545e162009-03-24 00:38:23 +0000822/// type if there was an error.
823QualType
John McCallce3ff2b2009-08-25 22:02:44 +0000824TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +0000825 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
826 bool InvalidDecl = false;
827
John McCallce3ff2b2009-08-25 22:02:44 +0000828 // Substitute all of the function's formal parameter types.
Douglas Gregor7e063902009-05-11 23:53:27 +0000829 TemplateDeclInstantiator ParamInstantiator(SemaRef, 0, TemplateArgs);
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000830 llvm::SmallVector<QualType, 4> ParamTys;
Douglas Gregor5545e162009-03-24 00:38:23 +0000831 for (FunctionDecl::param_iterator P = D->param_begin(),
832 PEnd = D->param_end();
833 P != PEnd; ++P) {
Douglas Gregor6477b692009-03-25 15:04:13 +0000834 if (ParmVarDecl *PInst = ParamInstantiator.VisitParmVarDecl(*P)) {
Douglas Gregor5545e162009-03-24 00:38:23 +0000835 if (PInst->getType()->isVoidType()) {
836 SemaRef.Diag(PInst->getLocation(), diag::err_param_with_void_type);
837 PInst->setInvalidDecl();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000838 } else if (SemaRef.RequireNonAbstractType(PInst->getLocation(),
839 PInst->getType(),
840 diag::err_abstract_type_in_decl,
841 Sema::AbstractParamType))
Douglas Gregor5545e162009-03-24 00:38:23 +0000842 PInst->setInvalidDecl();
843
844 Params.push_back(PInst);
845 ParamTys.push_back(PInst->getType());
846
847 if (PInst->isInvalidDecl())
848 InvalidDecl = true;
849 } else
850 InvalidDecl = true;
851 }
852
853 // FIXME: Deallocate dead declarations.
854 if (InvalidDecl)
855 return QualType();
856
857 const FunctionProtoType *Proto = D->getType()->getAsFunctionProtoType();
858 assert(Proto && "Missing prototype?");
859 QualType ResultType
John McCallce3ff2b2009-08-25 22:02:44 +0000860 = SemaRef.SubstType(Proto->getResultType(), TemplateArgs,
861 D->getLocation(), D->getDeclName());
Douglas Gregor5545e162009-03-24 00:38:23 +0000862 if (ResultType.isNull())
863 return QualType();
864
Jay Foadbeaaccd2009-05-21 09:52:38 +0000865 return SemaRef.BuildFunctionType(ResultType, ParamTys.data(), ParamTys.size(),
Douglas Gregor5545e162009-03-24 00:38:23 +0000866 Proto->isVariadic(), Proto->getTypeQuals(),
867 D->getLocation(), D->getDeclName());
868}
869
Douglas Gregore53060f2009-06-25 22:08:12 +0000870/// \brief Initializes the common fields of an instantiation function
871/// declaration (New) from the corresponding fields of its template (Tmpl).
872///
873/// \returns true if there was an error
874bool
875TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
876 FunctionDecl *Tmpl) {
877 if (Tmpl->isDeleted())
878 New->setDeleted();
Douglas Gregorcca9e962009-07-01 22:01:06 +0000879
880 // If we are performing substituting explicitly-specified template arguments
881 // or deduced template arguments into a function template and we reach this
882 // point, we are now past the point where SFINAE applies and have committed
883 // to keeping the new function template specialization. We therefore
884 // convert the active template instantiation for the function template
885 // into a template instantiation for this specific function template
886 // specialization, which is not a SFINAE context, so that we diagnose any
887 // further errors in the declaration itself.
888 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
889 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
890 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
891 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
892 if (FunctionTemplateDecl *FunTmpl
893 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
894 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
895 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +0000896 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000897 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
898 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
899 }
900 }
901
Douglas Gregore53060f2009-06-25 22:08:12 +0000902 return false;
903}
904
Douglas Gregor5545e162009-03-24 00:38:23 +0000905/// \brief Initializes common fields of an instantiated method
906/// declaration (New) from the corresponding fields of its template
907/// (Tmpl).
908///
909/// \returns true if there was an error
910bool
911TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
912 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +0000913 if (InitFunctionInstantiation(New, Tmpl))
914 return true;
915
Douglas Gregor5545e162009-03-24 00:38:23 +0000916 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
917 New->setAccess(Tmpl->getAccess());
Anders Carlsson77b7f1d2009-05-14 22:15:41 +0000918 if (Tmpl->isVirtualAsWritten()) {
919 New->setVirtualAsWritten(true);
Douglas Gregor5545e162009-03-24 00:38:23 +0000920 Record->setAggregate(false);
921 Record->setPOD(false);
Eli Friedman1d954f62009-08-15 21:55:26 +0000922 Record->setEmpty(false);
Douglas Gregor5545e162009-03-24 00:38:23 +0000923 Record->setPolymorphic(true);
924 }
Douglas Gregor5545e162009-03-24 00:38:23 +0000925 if (Tmpl->isPure()) {
926 New->setPure();
927 Record->setAbstract(true);
928 }
929
930 // FIXME: attributes
931 // FIXME: New needs a pointer to Tmpl
932 return false;
933}
Douglas Gregora58861f2009-05-13 20:28:22 +0000934
935/// \brief Instantiate the definition of the given function from its
936/// template.
937///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000938/// \param PointOfInstantiation the point at which the instantiation was
939/// required. Note that this is not precisely a "point of instantiation"
940/// for the function, but it's close.
941///
Douglas Gregora58861f2009-05-13 20:28:22 +0000942/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000943/// function template specialization or member function of a class template
944/// specialization.
945///
946/// \param Recursive if true, recursively instantiates any functions that
947/// are required by this instantiation.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000948void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000949 FunctionDecl *Function,
950 bool Recursive) {
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000951 if (Function->isInvalidDecl())
952 return;
953
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000954 assert(!Function->getBody() && "Already instantiated!");
Douglas Gregord7f37bf2009-06-22 23:06:13 +0000955
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000956 // Find the function body that we'll be substituting.
Douglas Gregor1637be72009-06-26 00:10:03 +0000957 const FunctionDecl *PatternDecl = 0;
Douglas Gregor5ec178f2009-08-28 21:09:48 +0000958 if (FunctionTemplateDecl *Primary = Function->getPrimaryTemplate()) {
959 while (Primary->getInstantiatedFromMemberTemplate())
960 Primary = Primary->getInstantiatedFromMemberTemplate();
961
Douglas Gregor1637be72009-06-26 00:10:03 +0000962 PatternDecl = Primary->getTemplatedDecl();
Douglas Gregor5ec178f2009-08-28 21:09:48 +0000963 } else
Douglas Gregor1637be72009-06-26 00:10:03 +0000964 PatternDecl = Function->getInstantiatedFromMemberFunction();
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000965 Stmt *Pattern = 0;
966 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000967 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000968
969 if (!Pattern)
970 return;
971
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000972 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
973 if (Inst)
974 return;
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000975
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000976 // 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
Douglas Gregore2c31ff2009-05-15 17:59:04 +0000983 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
984
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000985 // Introduce a new scope where local variable instantiations will be
986 // recorded.
987 LocalInstantiationScope Scope(*this);
988
989 // Introduce the instantiated function parameters into the local
990 // instantiation scope.
991 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
992 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
993 Function->getParamDecl(I));
994
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000995 // Enter the scope of this instantiation. We don't use
996 // PushDeclContext because we don't have a scope.
997 DeclContext *PreviousContext = CurContext;
998 CurContext = Function;
999
Anders Carlsson09025312009-08-29 05:16:22 +00001000 MultiLevelTemplateArgumentList TemplateArgs =
1001 getTemplateInstantiationArgs(Function);
1002
1003 // If this is a constructor, instantiate the member initializers.
1004 if (const CXXConstructorDecl *Ctor =
1005 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
1006 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
1007 TemplateArgs);
1008 }
1009
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001010 // Instantiate the function body.
Anders Carlsson09025312009-08-29 05:16:22 +00001011 OwningStmtResult Body = SubstStmt(Pattern, TemplateArgs);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001012
1013 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
1014 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001015
1016 CurContext = PreviousContext;
Douglas Gregoraba43bb2009-05-26 20:50:29 +00001017
1018 DeclGroupRef DG(Function);
1019 Consumer.HandleTopLevelDecl(DG);
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001020
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}
1030
1031/// \brief Instantiate the definition of the given variable from its
1032/// template.
1033///
Douglas Gregor7caa6822009-07-24 20:34:43 +00001034/// \param PointOfInstantiation the point at which the instantiation was
1035/// required. Note that this is not precisely a "point of instantiation"
1036/// for the function, but it's close.
1037///
1038/// \param Var the already-instantiated declaration of a static member
1039/// variable of a class template specialization.
1040///
1041/// \param Recursive if true, recursively instantiates any functions that
1042/// are required by this instantiation.
1043void Sema::InstantiateStaticDataMemberDefinition(
1044 SourceLocation PointOfInstantiation,
1045 VarDecl *Var,
1046 bool Recursive) {
1047 if (Var->isInvalidDecl())
1048 return;
1049
1050 // Find the out-of-line definition of this static data member.
1051 // FIXME: Do we have to look for specializations separately?
1052 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
1053 bool FoundOutOfLineDef = false;
1054 assert(Def && "This data member was not instantiated from a template?");
1055 assert(Def->isStaticDataMember() && "Not a static data member?");
1056 for (VarDecl::redecl_iterator RD = Def->redecls_begin(),
1057 RDEnd = Def->redecls_end();
1058 RD != RDEnd; ++RD) {
1059 if (RD->getLexicalDeclContext()->isFileContext()) {
1060 Def = *RD;
1061 FoundOutOfLineDef = true;
1062 }
1063 }
1064
1065 if (!FoundOutOfLineDef) {
1066 // We did not find an out-of-line definition of this static data member,
1067 // so we won't perform any instantiation. Rather, we rely on the user to
1068 // instantiate this definition (or provide a specialization for it) in
1069 // another translation unit.
1070 return;
1071 }
1072
1073 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
1074 if (Inst)
1075 return;
1076
1077 // If we're performing recursive template instantiation, create our own
1078 // queue of pending implicit instantiations that we will instantiate later,
1079 // while we're still within our own instantiation context.
1080 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1081 if (Recursive)
1082 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1083
1084 // Enter the scope of this instantiation. We don't use
1085 // PushDeclContext because we don't have a scope.
1086 DeclContext *PreviousContext = CurContext;
1087 CurContext = Var->getDeclContext();
1088
John McCallce3ff2b2009-08-25 22:02:44 +00001089 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Douglas Gregor7caa6822009-07-24 20:34:43 +00001090 getTemplateInstantiationArgs(Var)));
Douglas Gregor7caa6822009-07-24 20:34:43 +00001091
1092 CurContext = PreviousContext;
1093
1094 if (Var) {
1095 DeclGroupRef DG(Var);
1096 Consumer.HandleTopLevelDecl(DG);
1097 }
1098
1099 if (Recursive) {
1100 // Instantiate any pending implicit instantiations found during the
1101 // instantiation of this template.
1102 PerformPendingImplicitInstantiations();
1103
1104 // Restore the set of pending implicit instantiations.
1105 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1106 }
Douglas Gregora58861f2009-05-13 20:28:22 +00001107}
Douglas Gregor815215d2009-05-27 05:35:12 +00001108
Anders Carlsson09025312009-08-29 05:16:22 +00001109void
1110Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
1111 const CXXConstructorDecl *Tmpl,
1112 const MultiLevelTemplateArgumentList &TemplateArgs) {
1113
1114 llvm::SmallVector<MemInitTy*, 4> NewInits;
1115
1116 // Instantiate all the initializers.
1117 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
1118 InitsEnd = Tmpl->init_end(); Inits != InitsEnd; ++Inits) {
1119 CXXBaseOrMemberInitializer *Init = *Inits;
1120
1121 ASTOwningVector<&ActionBase::DeleteExpr> NewArgs(*this);
1122
1123 // Instantiate all the arguments.
1124 for (ExprIterator Args = Init->arg_begin(), ArgsEnd = Init->arg_end();
1125 Args != ArgsEnd; ++Args) {
1126 OwningExprResult NewArg = SubstExpr(*Args, TemplateArgs);
1127
1128 if (NewArg.isInvalid())
1129 New->setInvalidDecl();
1130 else
1131 NewArgs.push_back(NewArg.takeAs<Expr>());
1132 }
1133
1134 MemInitResult NewInit;
1135
1136 if (Init->isBaseInitializer()) {
Eli Friedmanc5573a82009-08-29 22:22:07 +00001137 QualType BaseType(Init->getBaseClass(), 0);
1138 BaseType = SubstType(BaseType, TemplateArgs, Init->getSourceLocation(),
1139 New->getDeclName());
Anders Carlsson09025312009-08-29 05:16:22 +00001140
1141 NewInit = BuildBaseInitializer(BaseType,
1142 (Expr **)NewArgs.data(),
1143 NewArgs.size(),
1144 Init->getSourceLocation(),
1145 Init->getRParenLoc(),
1146 New->getParent());
1147 } else if (Init->isMemberInitializer()) {
1148 FieldDecl *Member =
1149 cast<FieldDecl>(FindInstantiatedDecl(Init->getMember()));
1150
1151 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
1152 NewArgs.size(),
1153 Init->getSourceLocation(),
1154 Init->getRParenLoc());
1155 }
1156
1157 if (NewInit.isInvalid())
1158 New->setInvalidDecl();
1159 else {
1160 // FIXME: It would be nice if ASTOwningVector had a release function.
1161 NewArgs.take();
1162
1163 NewInits.push_back((MemInitTy *)NewInit.get());
1164 }
1165 }
1166
1167 // Assign all the initializers to the new constructor.
1168 ActOnMemInitializers(DeclPtrTy::make(New),
1169 /*FIXME: ColonLoc */
1170 SourceLocation(),
1171 NewInits.data(), NewInits.size());
1172}
1173
John McCall52a575a2009-08-29 08:11:13 +00001174// TODO: this could be templated if the various decl types used the
1175// same method name.
1176static bool isInstantiationOf(ClassTemplateDecl *Pattern,
1177 ClassTemplateDecl *Instance) {
1178 Pattern = Pattern->getCanonicalDecl();
1179
1180 do {
1181 Instance = Instance->getCanonicalDecl();
1182 if (Pattern == Instance) return true;
1183 Instance = Instance->getInstantiatedFromMemberTemplate();
1184 } while (Instance);
1185
1186 return false;
1187}
1188
1189static bool isInstantiationOf(CXXRecordDecl *Pattern,
1190 CXXRecordDecl *Instance) {
1191 Pattern = Pattern->getCanonicalDecl();
1192
1193 do {
1194 Instance = Instance->getCanonicalDecl();
1195 if (Pattern == Instance) return true;
1196 Instance = Instance->getInstantiatedFromMemberClass();
1197 } while (Instance);
1198
1199 return false;
1200}
1201
1202static bool isInstantiationOf(FunctionDecl *Pattern,
1203 FunctionDecl *Instance) {
1204 Pattern = Pattern->getCanonicalDecl();
1205
1206 do {
1207 Instance = Instance->getCanonicalDecl();
1208 if (Pattern == Instance) return true;
1209 Instance = Instance->getInstantiatedFromMemberFunction();
1210 } while (Instance);
1211
1212 return false;
1213}
1214
1215static bool isInstantiationOf(EnumDecl *Pattern,
1216 EnumDecl *Instance) {
1217 Pattern = Pattern->getCanonicalDecl();
1218
1219 do {
1220 Instance = Instance->getCanonicalDecl();
1221 if (Pattern == Instance) return true;
1222 Instance = Instance->getInstantiatedFromMemberEnum();
1223 } while (Instance);
1224
1225 return false;
1226}
1227
Anders Carlsson0d8df782009-08-29 19:37:28 +00001228static bool isInstantiationOf(UnresolvedUsingDecl *Pattern,
1229 UsingDecl *Instance,
1230 ASTContext &C) {
1231 return C.getInstantiatedFromUnresolvedUsingDecl(Instance) == Pattern;
1232}
1233
John McCall52a575a2009-08-29 08:11:13 +00001234static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
1235 VarDecl *Instance) {
1236 assert(Instance->isStaticDataMember());
1237
1238 Pattern = Pattern->getCanonicalDecl();
1239
1240 do {
1241 Instance = Instance->getCanonicalDecl();
1242 if (Pattern == Instance) return true;
1243 Instance = Instance->getInstantiatedFromStaticDataMember();
1244 } while (Instance);
1245
1246 return false;
1247}
1248
Douglas Gregor815215d2009-05-27 05:35:12 +00001249static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00001250 if (D->getKind() != Other->getKind()) {
1251 if (UnresolvedUsingDecl *UUD = dyn_cast<UnresolvedUsingDecl>(D)) {
1252 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
1253 return isInstantiationOf(UUD, UD, Ctx);
1254 }
1255 }
Douglas Gregor815215d2009-05-27 05:35:12 +00001256
Anders Carlsson0d8df782009-08-29 19:37:28 +00001257 return false;
1258 }
1259
John McCall52a575a2009-08-29 08:11:13 +00001260 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
1261 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00001262
John McCall52a575a2009-08-29 08:11:13 +00001263 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
1264 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00001265
John McCall52a575a2009-08-29 08:11:13 +00001266 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
1267 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00001268
Douglas Gregor7caa6822009-07-24 20:34:43 +00001269 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00001270 if (Var->isStaticDataMember())
1271 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
1272
1273 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
1274 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00001275
Douglas Gregor815215d2009-05-27 05:35:12 +00001276 // FIXME: How can we find instantiations of anonymous unions?
1277
1278 return D->getDeclName() && isa<NamedDecl>(Other) &&
1279 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
1280}
1281
1282template<typename ForwardIterator>
1283static NamedDecl *findInstantiationOf(ASTContext &Ctx,
1284 NamedDecl *D,
1285 ForwardIterator first,
1286 ForwardIterator last) {
1287 for (; first != last; ++first)
1288 if (isInstantiationOf(Ctx, D, *first))
1289 return cast<NamedDecl>(*first);
1290
1291 return 0;
1292}
1293
John McCall02cace72009-08-28 07:59:38 +00001294/// \brief Finds the instantiation of the given declaration context
1295/// within the current instantiation.
1296///
1297/// \returns NULL if there was an error
1298DeclContext *Sema::FindInstantiatedContext(DeclContext* DC) {
1299 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
1300 Decl* ID = FindInstantiatedDecl(D);
1301 return cast_or_null<DeclContext>(ID);
1302 } else return DC;
1303}
1304
Douglas Gregored961e72009-05-27 17:54:46 +00001305/// \brief Find the instantiation of the given declaration within the
1306/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00001307///
1308/// This routine is intended to be used when \p D is a declaration
1309/// referenced from within a template, that needs to mapped into the
1310/// corresponding declaration within an instantiation. For example,
1311/// given:
1312///
1313/// \code
1314/// template<typename T>
1315/// struct X {
1316/// enum Kind {
1317/// KnownValue = sizeof(T)
1318/// };
1319///
1320/// bool getKind() const { return KnownValue; }
1321/// };
1322///
1323/// template struct X<int>;
1324/// \endcode
1325///
1326/// In the instantiation of X<int>::getKind(), we need to map the
1327/// EnumConstantDecl for KnownValue (which refers to
1328/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00001329/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
1330/// this mapping from within the instantiation of X<int>.
John McCallce3ff2b2009-08-25 22:02:44 +00001331NamedDecl * Sema::FindInstantiatedDecl(NamedDecl *D) {
Douglas Gregor815215d2009-05-27 05:35:12 +00001332 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor2bba76b2009-05-27 17:07:49 +00001333 if (isa<ParmVarDecl>(D) || ParentDC->isFunctionOrMethod()) {
1334 // D is a local of some kind. Look into the map of local
1335 // declarations to their instantiations.
1336 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
1337 }
Douglas Gregor815215d2009-05-27 05:35:12 +00001338
John McCall52a575a2009-08-29 08:11:13 +00001339 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
1340 if (ClassTemplateDecl *ClassTemplate
1341 = Record->getDescribedClassTemplate()) {
1342 // When the declaration D was parsed, it referred to the current
1343 // instantiation. Therefore, look through the current context,
1344 // which contains actual instantiations, to find the
1345 // instantiation of the "current instantiation" that D refers
1346 // to. Alternatively, we could just instantiate the
1347 // injected-class-name with the current template arguments, but
1348 // such an instantiation is far more expensive.
1349 for (DeclContext *DC = CurContext; !DC->isFileContext();
1350 DC = DC->getParent()) {
1351 if (ClassTemplateSpecializationDecl *Spec
1352 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
1353 if (isInstantiationOf(ClassTemplate, Spec->getSpecializedTemplate()))
1354 return Spec;
1355 }
1356
1357 assert(false &&
1358 "Unable to find declaration for the current instantiation");
1359 }
1360
John McCall02cace72009-08-28 07:59:38 +00001361 ParentDC = FindInstantiatedContext(ParentDC);
1362 if (!ParentDC) return 0;
Douglas Gregor815215d2009-05-27 05:35:12 +00001363
Douglas Gregor815215d2009-05-27 05:35:12 +00001364 if (ParentDC != D->getDeclContext()) {
1365 // We performed some kind of instantiation in the parent context,
1366 // so now we need to look into the instantiated parent context to
1367 // find the instantiation of the declaration D.
1368 NamedDecl *Result = 0;
1369 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001370 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00001371 Result = findInstantiationOf(Context, D, Found.first, Found.second);
1372 } else {
1373 // Since we don't have a name for the entity we're looking for,
1374 // our only option is to walk through all of the declarations to
1375 // find that name. This will occur in a few cases:
1376 //
1377 // - anonymous struct/union within a template
1378 // - unnamed class/struct/union/enum within a template
1379 //
1380 // FIXME: Find a better way to find these instantiations!
1381 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001382 ParentDC->decls_begin(),
1383 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00001384 }
John McCall52a575a2009-08-29 08:11:13 +00001385
Douglas Gregor815215d2009-05-27 05:35:12 +00001386 assert(Result && "Unable to find instantiation of declaration!");
1387 D = Result;
1388 }
1389
Douglas Gregor815215d2009-05-27 05:35:12 +00001390 return D;
1391}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001392
1393/// \brief Performs template instantiation for all implicit template
1394/// instantiations we have seen until this point.
1395void Sema::PerformPendingImplicitInstantiations() {
1396 while (!PendingImplicitInstantiations.empty()) {
1397 PendingImplicitInstantiation Inst = PendingImplicitInstantiations.front();
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001398 PendingImplicitInstantiations.pop_front();
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001399
Douglas Gregor7caa6822009-07-24 20:34:43 +00001400 // Instantiate function definitions
1401 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001402 if (!Function->getBody())
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001403 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00001404 continue;
1405 }
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001406
Douglas Gregor7caa6822009-07-24 20:34:43 +00001407 // Instantiate static data member definitions.
1408 VarDecl *Var = cast<VarDecl>(Inst.first);
1409 assert(Var->isStaticDataMember() && "Not a static data member?");
1410 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001411 }
1412}