blob: a6513f167263e73711c8e76fd7d1389153a74394 [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"
18#include "llvm/Support/Compiler.h"
19
20using namespace clang;
21
22namespace {
23 class VISIBILITY_HIDDEN TemplateDeclInstantiator
Chris Lattnerb28317a2009-03-28 19:18:32 +000024 : public DeclVisitor<TemplateDeclInstantiator, Decl *> {
Douglas Gregor8dbc2692009-03-17 21:15:40 +000025 Sema &SemaRef;
26 DeclContext *Owner;
Douglas Gregor7e063902009-05-11 23:53:27 +000027 const TemplateArgumentList &TemplateArgs;
Douglas Gregor8dbc2692009-03-17 21:15:40 +000028
29 public:
30 typedef Sema::OwningExprResult OwningExprResult;
31
32 TemplateDeclInstantiator(Sema &SemaRef, DeclContext *Owner,
Douglas Gregor7e063902009-05-11 23:53:27 +000033 const TemplateArgumentList &TemplateArgs)
34 : SemaRef(SemaRef), Owner(Owner), TemplateArgs(TemplateArgs) { }
Douglas Gregor8dbc2692009-03-17 21:15:40 +000035
Mike Stump390b4cc2009-05-16 07:39:55 +000036 // FIXME: Once we get closer to completion, replace these manually-written
37 // declarations with automatically-generated ones from
38 // clang/AST/DeclNodes.def.
Douglas Gregor4f722be2009-03-25 15:45:12 +000039 Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D);
40 Decl *VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000041 Decl *VisitTypedefDecl(TypedefDecl *D);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +000042 Decl *VisitVarDecl(VarDecl *D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000043 Decl *VisitFieldDecl(FieldDecl *D);
44 Decl *VisitStaticAssertDecl(StaticAssertDecl *D);
45 Decl *VisitEnumDecl(EnumDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000046 Decl *VisitEnumConstantDecl(EnumConstantDecl *D);
Douglas Gregore53060f2009-06-25 22:08:12 +000047 Decl *VisitFunctionDecl(FunctionDecl *D);
Douglas Gregord475b8d2009-03-25 21:17:03 +000048 Decl *VisitCXXRecordDecl(CXXRecordDecl *D);
Douglas Gregor2dc0e642009-03-23 23:06:20 +000049 Decl *VisitCXXMethodDecl(CXXMethodDecl *D);
Douglas Gregor615c5d42009-03-24 16:43:20 +000050 Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
Douglas Gregor03b2b072009-03-24 00:15:49 +000051 Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +000052 Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000053 ParmVarDecl *VisitParmVarDecl(ParmVarDecl *D);
Douglas Gregor2dc0e642009-03-23 23:06:20 +000054 Decl *VisitOriginalParmVarDecl(OriginalParmVarDecl *D);
Douglas Gregor5545e162009-03-24 00:38:23 +000055
Douglas Gregor8dbc2692009-03-17 21:15:40 +000056 // Base case. FIXME: Remove once we can instantiate everything.
57 Decl *VisitDecl(Decl *) {
Douglas Gregor3d7a12a2009-03-25 23:32:15 +000058 assert(false && "Template instantiation of unknown declaration kind!");
Douglas Gregor8dbc2692009-03-17 21:15:40 +000059 return 0;
60 }
Douglas Gregor5545e162009-03-24 00:38:23 +000061
62 // Helper functions for instantiating methods.
63 QualType InstantiateFunctionType(FunctionDecl *D,
64 llvm::SmallVectorImpl<ParmVarDecl *> &Params);
Douglas Gregore53060f2009-06-25 22:08:12 +000065 bool InitFunctionInstantiation(FunctionDecl *New, FunctionDecl *Tmpl);
Douglas Gregor5545e162009-03-24 00:38:23 +000066 bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000067 };
68}
69
Douglas Gregor4f722be2009-03-25 15:45:12 +000070Decl *
71TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
72 assert(false && "Translation units cannot be instantiated");
73 return D;
74}
75
76Decl *
77TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
78 assert(false && "Namespaces cannot be instantiated");
79 return D;
80}
81
Douglas Gregor8dbc2692009-03-17 21:15:40 +000082Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
83 bool Invalid = false;
84 QualType T = D->getUnderlyingType();
85 if (T->isDependentType()) {
Douglas Gregor1eee0e72009-05-14 21:06:31 +000086 T = SemaRef.InstantiateType(T, TemplateArgs,
87 D->getLocation(), D->getDeclName());
Douglas Gregor8dbc2692009-03-17 21:15:40 +000088 if (T.isNull()) {
89 Invalid = true;
90 T = SemaRef.Context.IntTy;
91 }
92 }
93
94 // Create the new typedef
95 TypedefDecl *Typedef
96 = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(),
97 D->getIdentifier(), T);
98 if (Invalid)
99 Typedef->setInvalidDecl();
100
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000101 Owner->addDecl(Typedef);
Douglas Gregorbc221632009-05-28 16:34:51 +0000102
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000103 return Typedef;
104}
105
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000106Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
107 // Instantiate the type of the declaration
108 QualType T = SemaRef.InstantiateType(D->getType(), TemplateArgs,
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000109 D->getTypeSpecStartLoc(),
110 D->getDeclName());
111 if (T.isNull())
112 return 0;
113
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000114 // Build the instantiated declaration
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000115 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
116 D->getLocation(), D->getIdentifier(),
117 T, D->getStorageClass(),
118 D->getTypeSpecStartLoc());
119 Var->setThreadSpecified(D->isThreadSpecified());
120 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
121 Var->setDeclaredInCondition(D->isDeclaredInCondition());
122
Douglas Gregor7caa6822009-07-24 20:34:43 +0000123 // If we are instantiating a static data member defined
124 // out-of-line, the instantiation will have the same lexical
125 // context (which will be a namespace scope) as the template.
126 if (D->isOutOfLine())
127 Var->setLexicalDeclContext(D->getLexicalDeclContext());
128
Mike Stump390b4cc2009-05-16 07:39:55 +0000129 // FIXME: In theory, we could have a previous declaration for variables that
130 // are not static data members.
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000131 bool Redeclaration = false;
Chris Lattnereaaebc72009-04-25 08:06:05 +0000132 SemaRef.CheckVariableDeclaration(Var, 0, Redeclaration);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000133
134 if (D->isOutOfLine()) {
135 D->getLexicalDeclContext()->addDecl(Var);
136 Owner->makeDeclVisibleInContext(Var);
137 } else {
138 Owner->addDecl(Var);
139 }
140
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000141 if (D->getInit()) {
142 OwningExprResult Init
Douglas Gregor7e063902009-05-11 23:53:27 +0000143 = SemaRef.InstantiateExpr(D->getInit(), TemplateArgs);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000144 if (Init.isInvalid())
145 Var->setInvalidDecl();
146 else
Chris Lattnerb28317a2009-03-28 19:18:32 +0000147 SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var), move(Init),
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000148 D->hasCXXDirectInitializer());
Douglas Gregord308e622009-05-18 20:51:54 +0000149 } else {
150 // FIXME: Call ActOnUninitializedDecl? (Not always)
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000151 }
152
Douglas Gregor7caa6822009-07-24 20:34:43 +0000153 // Link instantiations of static data members back to the template from
154 // which they were instantiated.
155 if (Var->isStaticDataMember())
156 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D);
157
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000158 return Var;
159}
160
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000161Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
162 bool Invalid = false;
163 QualType T = D->getType();
164 if (T->isDependentType()) {
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000165 T = SemaRef.InstantiateType(T, TemplateArgs,
166 D->getLocation(), D->getDeclName());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000167 if (!T.isNull() && T->isFunctionType()) {
168 // C++ [temp.arg.type]p3:
169 // If a declaration acquires a function type through a type
170 // dependent on a template-parameter and this causes a
171 // declaration that does not use the syntactic form of a
172 // function declarator to have function type, the program is
173 // ill-formed.
174 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
175 << T;
176 T = QualType();
177 Invalid = true;
178 }
179 }
180
181 Expr *BitWidth = D->getBitWidth();
182 if (Invalid)
183 BitWidth = 0;
184 else if (BitWidth) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000185 // The bit-width expression is not potentially evaluated.
186 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
187
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000188 OwningExprResult InstantiatedBitWidth
Douglas Gregor7e063902009-05-11 23:53:27 +0000189 = SemaRef.InstantiateExpr(BitWidth, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000190 if (InstantiatedBitWidth.isInvalid()) {
191 Invalid = true;
192 BitWidth = 0;
193 } else
Anders Carlssone9146f22009-05-01 19:49:17 +0000194 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000195 }
196
197 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(), T,
198 cast<RecordDecl>(Owner),
199 D->getLocation(),
200 D->isMutable(),
201 BitWidth,
Steve Naroffea218b82009-07-14 14:58:18 +0000202 D->getTypeSpecStartLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000203 D->getAccess(),
204 0);
205 if (Field) {
206 if (Invalid)
207 Field->setInvalidDecl();
208
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000209 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000210 }
211
212 return Field;
213}
214
215Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
216 Expr *AssertExpr = D->getAssertExpr();
217
Douglas Gregorac7610d2009-06-22 20:57:11 +0000218 // The expression in a static assertion is not potentially evaluated.
219 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
220
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000221 OwningExprResult InstantiatedAssertExpr
Douglas Gregor7e063902009-05-11 23:53:27 +0000222 = SemaRef.InstantiateExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000223 if (InstantiatedAssertExpr.isInvalid())
224 return 0;
225
226 OwningExprResult Message = SemaRef.Clone(D->getMessage());
227 Decl *StaticAssert
Chris Lattnerb28317a2009-03-28 19:18:32 +0000228 = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
229 move(InstantiatedAssertExpr),
230 move(Message)).getAs<Decl>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000231 return StaticAssert;
232}
233
234Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
235 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
236 D->getLocation(), D->getIdentifier(),
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000237 D->getTagKeywordLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000238 /*PrevDecl=*/0);
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000239 Enum->setInstantiationOfMemberEnum(D);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000240 Enum->setAccess(D->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000241 Owner->addDecl(Enum);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000242 Enum->startDefinition();
243
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000244 llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000245
246 EnumConstantDecl *LastEnumConst = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000247 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
248 ECEnd = D->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000249 EC != ECEnd; ++EC) {
250 // The specified value for the enumerator.
251 OwningExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000252 if (Expr *UninstValue = EC->getInitExpr()) {
253 // The enumerator's value expression is not potentially evaluated.
254 EnterExpressionEvaluationContext Unevaluated(SemaRef,
255 Action::Unevaluated);
256
Douglas Gregor7e063902009-05-11 23:53:27 +0000257 Value = SemaRef.InstantiateExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000258 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000259
260 // Drop the initial value and continue.
261 bool isInvalid = false;
262 if (Value.isInvalid()) {
263 Value = SemaRef.Owned((Expr *)0);
264 isInvalid = true;
265 }
266
267 EnumConstantDecl *EnumConst
268 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
269 EC->getLocation(), EC->getIdentifier(),
270 move(Value));
271
272 if (isInvalid) {
273 if (EnumConst)
274 EnumConst->setInvalidDecl();
275 Enum->setInvalidDecl();
276 }
277
278 if (EnumConst) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000279 Enum->addDecl(EnumConst);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000280 Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst));
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000281 LastEnumConst = EnumConst;
282 }
283 }
284
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000285 // FIXME: Fixup LBraceLoc and RBraceLoc
286 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
287 Sema::DeclPtrTy::make(Enum),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000288 &Enumerators[0], Enumerators.size());
289
290 return Enum;
291}
292
Douglas Gregor6477b692009-03-25 15:04:13 +0000293Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
294 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
295 return 0;
296}
297
Douglas Gregord475b8d2009-03-25 21:17:03 +0000298Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
299 CXXRecordDecl *PrevDecl = 0;
300 if (D->isInjectedClassName())
301 PrevDecl = cast<CXXRecordDecl>(Owner);
302
303 CXXRecordDecl *Record
304 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000305 D->getLocation(), D->getIdentifier(),
306 D->getTagKeywordLoc(), PrevDecl);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000307 Record->setImplicit(D->isImplicit());
308 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000309 if (!D->isInjectedClassName())
310 Record->setInstantiationOfMemberClass(D);
311
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000312 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000313 return Record;
314}
315
Douglas Gregore53060f2009-06-25 22:08:12 +0000316Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000317 // Check whether there is already a function template specialization for
318 // this declaration.
319 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
320 void *InsertPos = 0;
321 if (FunctionTemplate) {
322 llvm::FoldingSetNodeID ID;
323 FunctionTemplateSpecializationInfo::Profile(ID,
324 TemplateArgs.getFlatArgumentList(),
325 TemplateArgs.flat_size());
326
327 FunctionTemplateSpecializationInfo *Info
328 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
329 InsertPos);
330
331 // If we already have a function template specialization, return it.
332 if (Info)
333 return Info->Function;
334 }
Douglas Gregore53060f2009-06-25 22:08:12 +0000335
336 Sema::LocalInstantiationScope Scope(SemaRef);
337
338 llvm::SmallVector<ParmVarDecl *, 4> Params;
339 QualType T = InstantiateFunctionType(D, Params);
340 if (T.isNull())
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000341 return 0;
Douglas Gregore53060f2009-06-25 22:08:12 +0000342
343 // Build the instantiated method declaration.
344 FunctionDecl *Function
345 = FunctionDecl::Create(SemaRef.Context, Owner, D->getLocation(),
346 D->getDeclName(), T, D->getStorageClass(),
347 D->isInline(), D->hasWrittenPrototype(),
348 D->getTypeSpecStartLoc());
349
350 // FIXME: friend functions
351
352 // Attach the parameters
353 for (unsigned P = 0; P < Params.size(); ++P)
354 Params[P]->setOwningFunction(Function);
355 Function->setParams(SemaRef.Context, Params.data(), Params.size());
356
357 if (InitFunctionInstantiation(Function, D))
358 Function->setInvalidDecl();
359
360 bool Redeclaration = false;
361 bool OverloadableAttrRequired = false;
362 NamedDecl *PrevDecl = 0;
363 SemaRef.CheckFunctionDeclaration(Function, PrevDecl, Redeclaration,
364 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000365
Douglas Gregor127102b2009-06-29 20:59:39 +0000366 if (FunctionTemplate) {
367 // Record this function template specialization.
368 Function->setFunctionTemplateSpecialization(SemaRef.Context,
369 FunctionTemplate,
370 &TemplateArgs,
371 InsertPos);
372 }
373
Douglas Gregore53060f2009-06-25 22:08:12 +0000374 return Function;
375}
376
377Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
378 // FIXME: Look for existing, explicit specializations.
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000379 Sema::LocalInstantiationScope Scope(SemaRef);
380
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000381 llvm::SmallVector<ParmVarDecl *, 4> Params;
Douglas Gregor5545e162009-03-24 00:38:23 +0000382 QualType T = InstantiateFunctionType(D, Params);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000383 if (T.isNull())
384 return 0;
385
386 // Build the instantiated method declaration.
387 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
388 CXXMethodDecl *Method
389 = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
390 D->getDeclName(), T, D->isStatic(),
391 D->isInline());
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000392 Method->setInstantiationOfMemberFunction(D);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000393
Douglas Gregor7caa6822009-07-24 20:34:43 +0000394 // If we are instantiating a member function defined
395 // out-of-line, the instantiation will have the same lexical
396 // context (which will be a namespace scope) as the template.
397 if (D->isOutOfLine())
398 Method->setLexicalDeclContext(D->getLexicalDeclContext());
399
Douglas Gregor5545e162009-03-24 00:38:23 +0000400 // Attach the parameters
401 for (unsigned P = 0; P < Params.size(); ++P)
402 Params[P]->setOwningFunction(Method);
Jay Foadbeaaccd2009-05-21 09:52:38 +0000403 Method->setParams(SemaRef.Context, Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +0000404
405 if (InitMethodInstantiation(Method, D))
406 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000407
408 NamedDecl *PrevDecl
409 = SemaRef.LookupQualifiedName(Owner, Method->getDeclName(),
410 Sema::LookupOrdinaryName, true);
411 // In C++, the previous declaration we find might be a tag type
412 // (class or enum). In this case, the new declaration will hide the
413 // tag type. Note that this does does not apply if we're declaring a
414 // typedef (C++ [dcl.typedef]p4).
415 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
416 PrevDecl = 0;
417 bool Redeclaration = false;
418 bool OverloadableAttrRequired = false;
Chris Lattnereaaebc72009-04-25 08:06:05 +0000419 SemaRef.CheckFunctionDeclaration(Method, PrevDecl, Redeclaration,
420 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000421
422 if (!Method->isInvalidDecl() || !PrevDecl)
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000423 Owner->addDecl(Method);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000424 return Method;
425}
426
Douglas Gregor615c5d42009-03-24 16:43:20 +0000427Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregore53060f2009-06-25 22:08:12 +0000428 // FIXME: Look for existing, explicit specializations.
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000429 Sema::LocalInstantiationScope Scope(SemaRef);
430
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000431 llvm::SmallVector<ParmVarDecl *, 4> Params;
Douglas Gregor615c5d42009-03-24 16:43:20 +0000432 QualType T = InstantiateFunctionType(D, Params);
433 if (T.isNull())
434 return 0;
435
436 // Build the instantiated method declaration.
437 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
438 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
439 DeclarationName Name
Douglas Gregor49f25ec2009-05-15 21:18:27 +0000440 = SemaRef.Context.DeclarationNames.getCXXConstructorName(
441 SemaRef.Context.getCanonicalType(ClassTy));
Douglas Gregor615c5d42009-03-24 16:43:20 +0000442 CXXConstructorDecl *Constructor
443 = CXXConstructorDecl::Create(SemaRef.Context, Record, D->getLocation(),
444 Name, T, D->isExplicit(), D->isInline(),
445 false);
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000446 Constructor->setInstantiationOfMemberFunction(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +0000447
448 // Attach the parameters
449 for (unsigned P = 0; P < Params.size(); ++P)
450 Params[P]->setOwningFunction(Constructor);
Jay Foadbeaaccd2009-05-21 09:52:38 +0000451 Constructor->setParams(SemaRef.Context, Params.data(), Params.size());
Douglas Gregor615c5d42009-03-24 16:43:20 +0000452
453 if (InitMethodInstantiation(Constructor, D))
454 Constructor->setInvalidDecl();
455
456 NamedDecl *PrevDecl
457 = SemaRef.LookupQualifiedName(Owner, Name, Sema::LookupOrdinaryName, true);
458
459 // In C++, the previous declaration we find might be a tag type
460 // (class or enum). In this case, the new declaration will hide the
461 // tag type. Note that this does does not apply if we're declaring a
462 // typedef (C++ [dcl.typedef]p4).
463 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
464 PrevDecl = 0;
465 bool Redeclaration = false;
466 bool OverloadableAttrRequired = false;
Chris Lattnereaaebc72009-04-25 08:06:05 +0000467 SemaRef.CheckFunctionDeclaration(Constructor, PrevDecl, Redeclaration,
468 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor615c5d42009-03-24 16:43:20 +0000469
Douglas Gregor49f25ec2009-05-15 21:18:27 +0000470 Record->addedConstructor(SemaRef.Context, Constructor);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000471 Owner->addDecl(Constructor);
Douglas Gregor615c5d42009-03-24 16:43:20 +0000472 return Constructor;
473}
474
Douglas Gregor03b2b072009-03-24 00:15:49 +0000475Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregore53060f2009-06-25 22:08:12 +0000476 // FIXME: Look for existing, explicit specializations.
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000477 Sema::LocalInstantiationScope Scope(SemaRef);
478
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000479 llvm::SmallVector<ParmVarDecl *, 4> Params;
Douglas Gregor5545e162009-03-24 00:38:23 +0000480 QualType T = InstantiateFunctionType(D, Params);
Douglas Gregor03b2b072009-03-24 00:15:49 +0000481 if (T.isNull())
482 return 0;
Douglas Gregor5545e162009-03-24 00:38:23 +0000483 assert(Params.size() == 0 && "Destructor with parameters?");
484
Douglas Gregor03b2b072009-03-24 00:15:49 +0000485 // Build the instantiated destructor declaration.
486 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
Douglas Gregor49f25ec2009-05-15 21:18:27 +0000487 QualType ClassTy =
488 SemaRef.Context.getCanonicalType(SemaRef.Context.getTypeDeclType(Record));
Douglas Gregor03b2b072009-03-24 00:15:49 +0000489 CXXDestructorDecl *Destructor
490 = CXXDestructorDecl::Create(SemaRef.Context, Record,
491 D->getLocation(),
492 SemaRef.Context.DeclarationNames.getCXXDestructorName(ClassTy),
493 T, D->isInline(), false);
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000494 Destructor->setInstantiationOfMemberFunction(D);
Douglas Gregor5545e162009-03-24 00:38:23 +0000495 if (InitMethodInstantiation(Destructor, D))
496 Destructor->setInvalidDecl();
Douglas Gregor03b2b072009-03-24 00:15:49 +0000497
498 bool Redeclaration = false;
499 bool OverloadableAttrRequired = false;
500 NamedDecl *PrevDecl = 0;
Chris Lattnereaaebc72009-04-25 08:06:05 +0000501 SemaRef.CheckFunctionDeclaration(Destructor, PrevDecl, Redeclaration,
502 /*FIXME:*/OverloadableAttrRequired);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000503 Owner->addDecl(Destructor);
Douglas Gregor03b2b072009-03-24 00:15:49 +0000504 return Destructor;
505}
506
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000507Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregore53060f2009-06-25 22:08:12 +0000508 // FIXME: Look for existing, explicit specializations.
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000509 Sema::LocalInstantiationScope Scope(SemaRef);
510
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000511 llvm::SmallVector<ParmVarDecl *, 4> Params;
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000512 QualType T = InstantiateFunctionType(D, Params);
513 if (T.isNull())
514 return 0;
515 assert(Params.size() == 0 && "Destructor with parameters?");
516
517 // Build the instantiated conversion declaration.
518 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
519 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
520 QualType ConvTy
521 = SemaRef.Context.getCanonicalType(T->getAsFunctionType()->getResultType());
522 CXXConversionDecl *Conversion
523 = CXXConversionDecl::Create(SemaRef.Context, Record,
524 D->getLocation(),
525 SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(ConvTy),
526 T, D->isInline(), D->isExplicit());
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000527 Conversion->setInstantiationOfMemberFunction(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000528 if (InitMethodInstantiation(Conversion, D))
529 Conversion->setInvalidDecl();
530
531 bool Redeclaration = false;
532 bool OverloadableAttrRequired = false;
533 NamedDecl *PrevDecl = 0;
Chris Lattnereaaebc72009-04-25 08:06:05 +0000534 SemaRef.CheckFunctionDeclaration(Conversion, PrevDecl, Redeclaration,
535 /*FIXME:*/OverloadableAttrRequired);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000536 Owner->addDecl(Conversion);
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000537 return Conversion;
538}
539
Douglas Gregor6477b692009-03-25 15:04:13 +0000540ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000541 QualType OrigT = SemaRef.InstantiateType(D->getOriginalType(), TemplateArgs,
Douglas Gregor7e063902009-05-11 23:53:27 +0000542 D->getLocation(), D->getDeclName());
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000543 if (OrigT.isNull())
544 return 0;
545
546 QualType T = SemaRef.adjustParameterType(OrigT);
547
548 if (D->getDefaultArg()) {
549 // FIXME: Leave a marker for "uninstantiated" default
550 // arguments. They only get instantiated on demand at the call
551 // site.
552 unsigned DiagID = SemaRef.Diags.getCustomDiagID(Diagnostic::Warning,
553 "sorry, dropping default argument during template instantiation");
554 SemaRef.Diag(D->getDefaultArg()->getSourceRange().getBegin(), DiagID)
555 << D->getDefaultArg()->getSourceRange();
556 }
557
558 // Allocate the parameter
559 ParmVarDecl *Param = 0;
560 if (T == OrigT)
561 Param = ParmVarDecl::Create(SemaRef.Context, Owner, D->getLocation(),
562 D->getIdentifier(), T, D->getStorageClass(),
563 0);
564 else
565 Param = OriginalParmVarDecl::Create(SemaRef.Context, Owner,
566 D->getLocation(), D->getIdentifier(),
567 T, OrigT, D->getStorageClass(), 0);
568
569 // Note: we don't try to instantiate function parameters until after
570 // we've instantiated the function's type. Therefore, we don't have
571 // to check for 'void' parameter types here.
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000572 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000573 return Param;
574}
575
576Decl *
577TemplateDeclInstantiator::VisitOriginalParmVarDecl(OriginalParmVarDecl *D) {
578 // Since parameter types can decay either before or after
579 // instantiation, we simply treat OriginalParmVarDecls as
580 // ParmVarDecls the same way, and create one or the other depending
581 // on what happens after template instantiation.
582 return VisitParmVarDecl(D);
583}
584
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000585Decl *Sema::InstantiateDecl(Decl *D, DeclContext *Owner,
Douglas Gregor7e063902009-05-11 23:53:27 +0000586 const TemplateArgumentList &TemplateArgs) {
587 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000588 return Instantiator.Visit(D);
589}
590
Douglas Gregor5545e162009-03-24 00:38:23 +0000591/// \brief Instantiates the type of the given function, including
592/// instantiating all of the function parameters.
593///
594/// \param D The function that we will be instantiated
595///
596/// \param Params the instantiated parameter declarations
597
598/// \returns the instantiated function's type if successfull, a NULL
599/// type if there was an error.
600QualType
601TemplateDeclInstantiator::InstantiateFunctionType(FunctionDecl *D,
602 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
603 bool InvalidDecl = false;
604
605 // Instantiate the function parameters
Douglas Gregor7e063902009-05-11 23:53:27 +0000606 TemplateDeclInstantiator ParamInstantiator(SemaRef, 0, TemplateArgs);
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000607 llvm::SmallVector<QualType, 4> ParamTys;
Douglas Gregor5545e162009-03-24 00:38:23 +0000608 for (FunctionDecl::param_iterator P = D->param_begin(),
609 PEnd = D->param_end();
610 P != PEnd; ++P) {
Douglas Gregor6477b692009-03-25 15:04:13 +0000611 if (ParmVarDecl *PInst = ParamInstantiator.VisitParmVarDecl(*P)) {
Douglas Gregor5545e162009-03-24 00:38:23 +0000612 if (PInst->getType()->isVoidType()) {
613 SemaRef.Diag(PInst->getLocation(), diag::err_param_with_void_type);
614 PInst->setInvalidDecl();
615 }
616 else if (SemaRef.RequireNonAbstractType(PInst->getLocation(),
617 PInst->getType(),
618 diag::err_abstract_type_in_decl,
Anders Carlsson8211eff2009-03-24 01:19:16 +0000619 Sema::AbstractParamType))
Douglas Gregor5545e162009-03-24 00:38:23 +0000620 PInst->setInvalidDecl();
621
622 Params.push_back(PInst);
623 ParamTys.push_back(PInst->getType());
624
625 if (PInst->isInvalidDecl())
626 InvalidDecl = true;
627 } else
628 InvalidDecl = true;
629 }
630
631 // FIXME: Deallocate dead declarations.
632 if (InvalidDecl)
633 return QualType();
634
635 const FunctionProtoType *Proto = D->getType()->getAsFunctionProtoType();
636 assert(Proto && "Missing prototype?");
637 QualType ResultType
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000638 = SemaRef.InstantiateType(Proto->getResultType(), TemplateArgs,
Douglas Gregor5545e162009-03-24 00:38:23 +0000639 D->getLocation(), D->getDeclName());
640 if (ResultType.isNull())
641 return QualType();
642
Jay Foadbeaaccd2009-05-21 09:52:38 +0000643 return SemaRef.BuildFunctionType(ResultType, ParamTys.data(), ParamTys.size(),
Douglas Gregor5545e162009-03-24 00:38:23 +0000644 Proto->isVariadic(), Proto->getTypeQuals(),
645 D->getLocation(), D->getDeclName());
646}
647
Douglas Gregore53060f2009-06-25 22:08:12 +0000648/// \brief Initializes the common fields of an instantiation function
649/// declaration (New) from the corresponding fields of its template (Tmpl).
650///
651/// \returns true if there was an error
652bool
653TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
654 FunctionDecl *Tmpl) {
655 if (Tmpl->isDeleted())
656 New->setDeleted();
Douglas Gregorcca9e962009-07-01 22:01:06 +0000657
658 // If we are performing substituting explicitly-specified template arguments
659 // or deduced template arguments into a function template and we reach this
660 // point, we are now past the point where SFINAE applies and have committed
661 // to keeping the new function template specialization. We therefore
662 // convert the active template instantiation for the function template
663 // into a template instantiation for this specific function template
664 // specialization, which is not a SFINAE context, so that we diagnose any
665 // further errors in the declaration itself.
666 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
667 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
668 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
669 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
670 if (FunctionTemplateDecl *FunTmpl
671 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
672 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
673 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +0000674 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000675 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
676 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
677 }
678 }
679
Douglas Gregore53060f2009-06-25 22:08:12 +0000680 return false;
681}
682
Douglas Gregor5545e162009-03-24 00:38:23 +0000683/// \brief Initializes common fields of an instantiated method
684/// declaration (New) from the corresponding fields of its template
685/// (Tmpl).
686///
687/// \returns true if there was an error
688bool
689TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
690 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +0000691 if (InitFunctionInstantiation(New, Tmpl))
692 return true;
693
Douglas Gregor5545e162009-03-24 00:38:23 +0000694 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
695 New->setAccess(Tmpl->getAccess());
Anders Carlsson77b7f1d2009-05-14 22:15:41 +0000696 if (Tmpl->isVirtualAsWritten()) {
697 New->setVirtualAsWritten(true);
Douglas Gregor5545e162009-03-24 00:38:23 +0000698 Record->setAggregate(false);
699 Record->setPOD(false);
700 Record->setPolymorphic(true);
701 }
Douglas Gregor5545e162009-03-24 00:38:23 +0000702 if (Tmpl->isPure()) {
703 New->setPure();
704 Record->setAbstract(true);
705 }
706
707 // FIXME: attributes
708 // FIXME: New needs a pointer to Tmpl
709 return false;
710}
Douglas Gregora58861f2009-05-13 20:28:22 +0000711
712/// \brief Instantiate the definition of the given function from its
713/// template.
714///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000715/// \param PointOfInstantiation the point at which the instantiation was
716/// required. Note that this is not precisely a "point of instantiation"
717/// for the function, but it's close.
718///
Douglas Gregora58861f2009-05-13 20:28:22 +0000719/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000720/// function template specialization or member function of a class template
721/// specialization.
722///
723/// \param Recursive if true, recursively instantiates any functions that
724/// are required by this instantiation.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000725void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000726 FunctionDecl *Function,
727 bool Recursive) {
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000728 if (Function->isInvalidDecl())
729 return;
730
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000731 assert(!Function->getBody() && "Already instantiated!");
Douglas Gregord7f37bf2009-06-22 23:06:13 +0000732
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000733 // Find the function body that we'll be substituting.
Douglas Gregor1637be72009-06-26 00:10:03 +0000734 const FunctionDecl *PatternDecl = 0;
735 if (FunctionTemplateDecl *Primary = Function->getPrimaryTemplate())
736 PatternDecl = Primary->getTemplatedDecl();
737 else
738 PatternDecl = Function->getInstantiatedFromMemberFunction();
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000739 Stmt *Pattern = 0;
740 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000741 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000742
743 if (!Pattern)
744 return;
745
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000746 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
747 if (Inst)
748 return;
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000749
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000750 // If we're performing recursive template instantiation, create our own
751 // queue of pending implicit instantiations that we will instantiate later,
752 // while we're still within our own instantiation context.
753 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
754 if (Recursive)
755 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
756
Douglas Gregore2c31ff2009-05-15 17:59:04 +0000757 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
758
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000759 // Introduce a new scope where local variable instantiations will be
760 // recorded.
761 LocalInstantiationScope Scope(*this);
762
763 // Introduce the instantiated function parameters into the local
764 // instantiation scope.
765 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
766 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
767 Function->getParamDecl(I));
768
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000769 // Enter the scope of this instantiation. We don't use
770 // PushDeclContext because we don't have a scope.
771 DeclContext *PreviousContext = CurContext;
772 CurContext = Function;
773
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000774 // Instantiate the function body.
775 OwningStmtResult Body
776 = InstantiateStmt(Pattern, getTemplateInstantiationArgs(Function));
Douglas Gregore2c31ff2009-05-15 17:59:04 +0000777
778 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
779 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000780
781 CurContext = PreviousContext;
Douglas Gregoraba43bb2009-05-26 20:50:29 +0000782
783 DeclGroupRef DG(Function);
784 Consumer.HandleTopLevelDecl(DG);
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000785
786 if (Recursive) {
787 // Instantiate any pending implicit instantiations found during the
788 // instantiation of this template.
789 PerformPendingImplicitInstantiations();
790
791 // Restore the set of pending implicit instantiations.
792 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
793 }
Douglas Gregora58861f2009-05-13 20:28:22 +0000794}
795
796/// \brief Instantiate the definition of the given variable from its
797/// template.
798///
Douglas Gregor7caa6822009-07-24 20:34:43 +0000799/// \param PointOfInstantiation the point at which the instantiation was
800/// required. Note that this is not precisely a "point of instantiation"
801/// for the function, but it's close.
802///
803/// \param Var the already-instantiated declaration of a static member
804/// variable of a class template specialization.
805///
806/// \param Recursive if true, recursively instantiates any functions that
807/// are required by this instantiation.
808void Sema::InstantiateStaticDataMemberDefinition(
809 SourceLocation PointOfInstantiation,
810 VarDecl *Var,
811 bool Recursive) {
812 if (Var->isInvalidDecl())
813 return;
814
815 // Find the out-of-line definition of this static data member.
816 // FIXME: Do we have to look for specializations separately?
817 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
818 bool FoundOutOfLineDef = false;
819 assert(Def && "This data member was not instantiated from a template?");
820 assert(Def->isStaticDataMember() && "Not a static data member?");
821 for (VarDecl::redecl_iterator RD = Def->redecls_begin(),
822 RDEnd = Def->redecls_end();
823 RD != RDEnd; ++RD) {
824 if (RD->getLexicalDeclContext()->isFileContext()) {
825 Def = *RD;
826 FoundOutOfLineDef = true;
827 }
828 }
829
830 if (!FoundOutOfLineDef) {
831 // We did not find an out-of-line definition of this static data member,
832 // so we won't perform any instantiation. Rather, we rely on the user to
833 // instantiate this definition (or provide a specialization for it) in
834 // another translation unit.
835 return;
836 }
837
838 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
839 if (Inst)
840 return;
841
842 // If we're performing recursive template instantiation, create our own
843 // queue of pending implicit instantiations that we will instantiate later,
844 // while we're still within our own instantiation context.
845 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
846 if (Recursive)
847 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
848
849 // Enter the scope of this instantiation. We don't use
850 // PushDeclContext because we don't have a scope.
851 DeclContext *PreviousContext = CurContext;
852 CurContext = Var->getDeclContext();
853
854#if 0
855 // Instantiate the initializer of this static data member.
856 OwningExprResult Init
857 = InstantiateExpr(Def->getInit(), getTemplateInstantiationArgs(Var));
858 if (Init.isInvalid()) {
859 // If instantiation of the initializer failed, mark the declaration invalid
860 // and don't instantiate anything else that was triggered by this
861 // instantiation.
862 Var->setInvalidDecl();
863
864 // Restore the set of pending implicit instantiations.
865 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
866
867 return;
868 }
869
870 // Type-check the initializer.
871 if (Init.get())
872 AddInitializerToDecl(DeclPtrTy::make(Var), move(Init),
873 Def->hasCXXDirectInitializer());
874 else
875 ActOnUninitializedDecl(DeclPtrTy::make(Var), false);
876#else
877 Var = cast_or_null<VarDecl>(InstantiateDecl(Def, Var->getDeclContext(),
878 getTemplateInstantiationArgs(Var)));
879#endif
880
881 CurContext = PreviousContext;
882
883 if (Var) {
884 DeclGroupRef DG(Var);
885 Consumer.HandleTopLevelDecl(DG);
886 }
887
888 if (Recursive) {
889 // Instantiate any pending implicit instantiations found during the
890 // instantiation of this template.
891 PerformPendingImplicitInstantiations();
892
893 // Restore the set of pending implicit instantiations.
894 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
895 }
Douglas Gregora58861f2009-05-13 20:28:22 +0000896}
Douglas Gregor815215d2009-05-27 05:35:12 +0000897
898static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
899 if (D->getKind() != Other->getKind())
900 return false;
901
902 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +0000903 return Record->getInstantiatedFromMemberClass()->getCanonicalDecl()
904 == D->getCanonicalDecl();
Douglas Gregor815215d2009-05-27 05:35:12 +0000905
906 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +0000907 return Function->getInstantiatedFromMemberFunction()->getCanonicalDecl()
908 == D->getCanonicalDecl();
Douglas Gregor815215d2009-05-27 05:35:12 +0000909
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000910 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +0000911 return Enum->getInstantiatedFromMemberEnum()->getCanonicalDecl()
912 == D->getCanonicalDecl();
Douglas Gregor815215d2009-05-27 05:35:12 +0000913
Douglas Gregor7caa6822009-07-24 20:34:43 +0000914 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
915 if (Var->isStaticDataMember())
916 return Var->getInstantiatedFromStaticDataMember()->getCanonicalDecl()
917 == D->getCanonicalDecl();
918
Douglas Gregor815215d2009-05-27 05:35:12 +0000919 // FIXME: How can we find instantiations of anonymous unions?
920
921 return D->getDeclName() && isa<NamedDecl>(Other) &&
922 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
923}
924
925template<typename ForwardIterator>
926static NamedDecl *findInstantiationOf(ASTContext &Ctx,
927 NamedDecl *D,
928 ForwardIterator first,
929 ForwardIterator last) {
930 for (; first != last; ++first)
931 if (isInstantiationOf(Ctx, D, *first))
932 return cast<NamedDecl>(*first);
933
934 return 0;
935}
936
Douglas Gregored961e72009-05-27 17:54:46 +0000937/// \brief Find the instantiation of the given declaration within the
938/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +0000939///
940/// This routine is intended to be used when \p D is a declaration
941/// referenced from within a template, that needs to mapped into the
942/// corresponding declaration within an instantiation. For example,
943/// given:
944///
945/// \code
946/// template<typename T>
947/// struct X {
948/// enum Kind {
949/// KnownValue = sizeof(T)
950/// };
951///
952/// bool getKind() const { return KnownValue; }
953/// };
954///
955/// template struct X<int>;
956/// \endcode
957///
958/// In the instantiation of X<int>::getKind(), we need to map the
959/// EnumConstantDecl for KnownValue (which refers to
960/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +0000961/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
962/// this mapping from within the instantiation of X<int>.
963NamedDecl * Sema::InstantiateCurrentDeclRef(NamedDecl *D) {
Douglas Gregor815215d2009-05-27 05:35:12 +0000964 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor2bba76b2009-05-27 17:07:49 +0000965 if (isa<ParmVarDecl>(D) || ParentDC->isFunctionOrMethod()) {
966 // D is a local of some kind. Look into the map of local
967 // declarations to their instantiations.
968 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
969 }
Douglas Gregor815215d2009-05-27 05:35:12 +0000970
Douglas Gregor2bba76b2009-05-27 17:07:49 +0000971 if (NamedDecl *ParentDecl = dyn_cast<NamedDecl>(ParentDC)) {
Douglas Gregored961e72009-05-27 17:54:46 +0000972 ParentDecl = InstantiateCurrentDeclRef(ParentDecl);
Douglas Gregor815215d2009-05-27 05:35:12 +0000973 if (!ParentDecl)
974 return 0;
975
976 ParentDC = cast<DeclContext>(ParentDecl);
977 }
978
Douglas Gregor815215d2009-05-27 05:35:12 +0000979 if (ParentDC != D->getDeclContext()) {
980 // We performed some kind of instantiation in the parent context,
981 // so now we need to look into the instantiated parent context to
982 // find the instantiation of the declaration D.
983 NamedDecl *Result = 0;
984 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000985 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +0000986 Result = findInstantiationOf(Context, D, Found.first, Found.second);
987 } else {
988 // Since we don't have a name for the entity we're looking for,
989 // our only option is to walk through all of the declarations to
990 // find that name. This will occur in a few cases:
991 //
992 // - anonymous struct/union within a template
993 // - unnamed class/struct/union/enum within a template
994 //
995 // FIXME: Find a better way to find these instantiations!
996 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000997 ParentDC->decls_begin(),
998 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +0000999 }
1000 assert(Result && "Unable to find instantiation of declaration!");
1001 D = Result;
1002 }
1003
Douglas Gregor815215d2009-05-27 05:35:12 +00001004 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
Douglas Gregored961e72009-05-27 17:54:46 +00001005 if (ClassTemplateDecl *ClassTemplate
1006 = Record->getDescribedClassTemplate()) {
1007 // When the declaration D was parsed, it referred to the current
1008 // instantiation. Therefore, look through the current context,
1009 // which contains actual instantiations, to find the
1010 // instantiation of the "current instantiation" that D refers
1011 // to. Alternatively, we could just instantiate the
1012 // injected-class-name with the current template arguments, but
1013 // such an instantiation is far more expensive.
1014 for (DeclContext *DC = CurContext; !DC->isFileContext();
1015 DC = DC->getParent()) {
1016 if (ClassTemplateSpecializationDecl *Spec
1017 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001018 if (Spec->getSpecializedTemplate()->getCanonicalDecl()
1019 == ClassTemplate->getCanonicalDecl())
Douglas Gregored961e72009-05-27 17:54:46 +00001020 return Spec;
1021 }
1022
1023 assert(false &&
1024 "Unable to find declaration for the current instantiation");
Douglas Gregor815215d2009-05-27 05:35:12 +00001025 }
1026
1027 return D;
1028}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001029
1030/// \brief Performs template instantiation for all implicit template
1031/// instantiations we have seen until this point.
1032void Sema::PerformPendingImplicitInstantiations() {
1033 while (!PendingImplicitInstantiations.empty()) {
1034 PendingImplicitInstantiation Inst = PendingImplicitInstantiations.front();
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001035 PendingImplicitInstantiations.pop_front();
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001036
Douglas Gregor7caa6822009-07-24 20:34:43 +00001037 // Instantiate function definitions
1038 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001039 if (!Function->getBody())
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001040 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00001041 continue;
1042 }
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001043
Douglas Gregor7caa6822009-07-24 20:34:43 +00001044 // Instantiate static data member definitions.
1045 VarDecl *Var = cast<VarDecl>(Inst.first);
1046 assert(Var->isStaticDataMember() && "Not a static data member?");
1047 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001048 }
1049}