blob: bd25c8fb15791e295434275cc5a998880d6f9385 [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);
John McCallfd810b12009-08-14 02:03:10 +000047 Decl *VisitFriendClassDecl(FriendClassDecl *D);
Douglas Gregore53060f2009-06-25 22:08:12 +000048 Decl *VisitFunctionDecl(FunctionDecl *D);
Douglas Gregord475b8d2009-03-25 21:17:03 +000049 Decl *VisitCXXRecordDecl(CXXRecordDecl *D);
Douglas Gregor2dc0e642009-03-23 23:06:20 +000050 Decl *VisitCXXMethodDecl(CXXMethodDecl *D);
Douglas Gregor615c5d42009-03-24 16:43:20 +000051 Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
Douglas Gregor03b2b072009-03-24 00:15:49 +000052 Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +000053 Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000054 ParmVarDecl *VisitParmVarDecl(ParmVarDecl *D);
Douglas Gregor2dc0e642009-03-23 23:06:20 +000055 Decl *VisitOriginalParmVarDecl(OriginalParmVarDecl *D);
John McCalle29ba202009-08-20 01:44:21 +000056 Decl *VisitClassTemplateDecl(ClassTemplateDecl *D);
57 Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Douglas Gregor5545e162009-03-24 00:38:23 +000058
Douglas Gregor8dbc2692009-03-17 21:15:40 +000059 // Base case. FIXME: Remove once we can instantiate everything.
60 Decl *VisitDecl(Decl *) {
Douglas Gregor3d7a12a2009-03-25 23:32:15 +000061 assert(false && "Template instantiation of unknown declaration kind!");
Douglas Gregor8dbc2692009-03-17 21:15:40 +000062 return 0;
63 }
Douglas Gregor5545e162009-03-24 00:38:23 +000064
John McCallfd810b12009-08-14 02:03:10 +000065 const LangOptions &getLangOptions() {
66 return SemaRef.getLangOptions();
67 }
68
Douglas Gregor5545e162009-03-24 00:38:23 +000069 // Helper functions for instantiating methods.
John McCallce3ff2b2009-08-25 22:02:44 +000070 QualType SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +000071 llvm::SmallVectorImpl<ParmVarDecl *> &Params);
Douglas Gregore53060f2009-06-25 22:08:12 +000072 bool InitFunctionInstantiation(FunctionDecl *New, FunctionDecl *Tmpl);
Douglas Gregor5545e162009-03-24 00:38:23 +000073 bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl);
John McCalle29ba202009-08-20 01:44:21 +000074
75 TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +000076 SubstTemplateParams(TemplateParameterList *List);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000077 };
78}
79
Douglas Gregor4f722be2009-03-25 15:45:12 +000080Decl *
81TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
82 assert(false && "Translation units cannot be instantiated");
83 return D;
84}
85
86Decl *
87TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
88 assert(false && "Namespaces cannot be instantiated");
89 return D;
90}
91
Douglas Gregor8dbc2692009-03-17 21:15:40 +000092Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
93 bool Invalid = false;
94 QualType T = D->getUnderlyingType();
95 if (T->isDependentType()) {
John McCallce3ff2b2009-08-25 22:02:44 +000096 T = SemaRef.SubstType(T, TemplateArgs,
97 D->getLocation(), D->getDeclName());
Douglas Gregor8dbc2692009-03-17 21:15:40 +000098 if (T.isNull()) {
99 Invalid = true;
100 T = SemaRef.Context.IntTy;
101 }
102 }
103
104 // Create the new typedef
105 TypedefDecl *Typedef
106 = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(),
107 D->getIdentifier(), T);
108 if (Invalid)
109 Typedef->setInvalidDecl();
110
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000111 Owner->addDecl(Typedef);
Douglas Gregorbc221632009-05-28 16:34:51 +0000112
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000113 return Typedef;
114}
115
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000116Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
John McCallce3ff2b2009-08-25 22:02:44 +0000117 // Do substitution on the type of the declaration
118 QualType T = SemaRef.SubstType(D->getType(), TemplateArgs,
119 D->getTypeSpecStartLoc(),
120 D->getDeclName());
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000121 if (T.isNull())
122 return 0;
123
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000124 // Build the instantiated declaration
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000125 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
126 D->getLocation(), D->getIdentifier(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000127 T, D->getDeclaratorInfo(),
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +0000128 D->getStorageClass());
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000129 Var->setThreadSpecified(D->isThreadSpecified());
130 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
131 Var->setDeclaredInCondition(D->isDeclaredInCondition());
132
Douglas Gregor7caa6822009-07-24 20:34:43 +0000133 // If we are instantiating a static data member defined
134 // out-of-line, the instantiation will have the same lexical
135 // context (which will be a namespace scope) as the template.
136 if (D->isOutOfLine())
137 Var->setLexicalDeclContext(D->getLexicalDeclContext());
138
Mike Stump390b4cc2009-05-16 07:39:55 +0000139 // FIXME: In theory, we could have a previous declaration for variables that
140 // are not static data members.
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000141 bool Redeclaration = false;
Chris Lattnereaaebc72009-04-25 08:06:05 +0000142 SemaRef.CheckVariableDeclaration(Var, 0, Redeclaration);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000143
144 if (D->isOutOfLine()) {
145 D->getLexicalDeclContext()->addDecl(Var);
146 Owner->makeDeclVisibleInContext(Var);
147 } else {
148 Owner->addDecl(Var);
149 }
150
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000151 if (D->getInit()) {
152 OwningExprResult Init
John McCallce3ff2b2009-08-25 22:02:44 +0000153 = SemaRef.SubstExpr(D->getInit(), TemplateArgs);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000154 if (Init.isInvalid())
155 Var->setInvalidDecl();
156 else
Chris Lattnerb28317a2009-03-28 19:18:32 +0000157 SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var), move(Init),
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000158 D->hasCXXDirectInitializer());
Douglas Gregor65b90052009-07-27 17:43:39 +0000159 } else if (!Var->isStaticDataMember() || Var->isOutOfLine())
160 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000161
Douglas Gregor7caa6822009-07-24 20:34:43 +0000162 // Link instantiations of static data members back to the template from
163 // which they were instantiated.
164 if (Var->isStaticDataMember())
165 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D);
166
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000167 return Var;
168}
169
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000170Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
171 bool Invalid = false;
172 QualType T = D->getType();
173 if (T->isDependentType()) {
John McCallce3ff2b2009-08-25 22:02:44 +0000174 T = SemaRef.SubstType(T, TemplateArgs,
175 D->getLocation(), D->getDeclName());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000176 if (!T.isNull() && T->isFunctionType()) {
177 // C++ [temp.arg.type]p3:
178 // If a declaration acquires a function type through a type
179 // dependent on a template-parameter and this causes a
180 // declaration that does not use the syntactic form of a
181 // function declarator to have function type, the program is
182 // ill-formed.
183 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
184 << T;
185 T = QualType();
186 Invalid = true;
187 }
188 }
189
190 Expr *BitWidth = D->getBitWidth();
191 if (Invalid)
192 BitWidth = 0;
193 else if (BitWidth) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000194 // The bit-width expression is not potentially evaluated.
195 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
196
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000197 OwningExprResult InstantiatedBitWidth
John McCallce3ff2b2009-08-25 22:02:44 +0000198 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000199 if (InstantiatedBitWidth.isInvalid()) {
200 Invalid = true;
201 BitWidth = 0;
202 } else
Anders Carlssone9146f22009-05-01 19:49:17 +0000203 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000204 }
205
206 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(), T,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000207 D->getDeclaratorInfo(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000208 cast<RecordDecl>(Owner),
209 D->getLocation(),
210 D->isMutable(),
211 BitWidth,
Steve Naroffea218b82009-07-14 14:58:18 +0000212 D->getTypeSpecStartLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000213 D->getAccess(),
214 0);
215 if (Field) {
216 if (Invalid)
217 Field->setInvalidDecl();
218
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000219 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000220 }
221
222 return Field;
223}
224
John McCallfd810b12009-08-14 02:03:10 +0000225Decl *TemplateDeclInstantiator::VisitFriendClassDecl(FriendClassDecl *D) {
226 QualType T = D->getFriendType();
227 if (T->isDependentType()) {
John McCallce3ff2b2009-08-25 22:02:44 +0000228 T = SemaRef.SubstType(T, TemplateArgs, D->getLocation(),
229 DeclarationName());
John McCallfd810b12009-08-14 02:03:10 +0000230 assert(T.isNull() || getLangOptions().CPlusPlus0x || T->isRecordType());
231 }
232
233 // FIXME: the target context might be dependent.
234 DeclContext *DC = D->getDeclContext();
235 assert(DC->isFileContext());
236
237 FriendClassDecl *NewD =
238 FriendClassDecl::Create(SemaRef.Context, DC, D->getLocation(), T,
239 D->getFriendLoc());
240 Owner->addDecl(NewD);
241 return NewD;
242}
243
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000244Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
245 Expr *AssertExpr = D->getAssertExpr();
246
Douglas Gregorac7610d2009-06-22 20:57:11 +0000247 // The expression in a static assertion is not potentially evaluated.
248 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
249
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000250 OwningExprResult InstantiatedAssertExpr
John McCallce3ff2b2009-08-25 22:02:44 +0000251 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000252 if (InstantiatedAssertExpr.isInvalid())
253 return 0;
254
Douglas Gregor43d9d922009-08-08 01:41:12 +0000255 OwningExprResult Message(SemaRef, D->getMessage());
256 D->getMessage()->Retain();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000257 Decl *StaticAssert
Chris Lattnerb28317a2009-03-28 19:18:32 +0000258 = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
259 move(InstantiatedAssertExpr),
260 move(Message)).getAs<Decl>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000261 return StaticAssert;
262}
263
264Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
265 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
266 D->getLocation(), D->getIdentifier(),
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000267 D->getTagKeywordLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000268 /*PrevDecl=*/0);
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000269 Enum->setInstantiationOfMemberEnum(D);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000270 Enum->setAccess(D->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000271 Owner->addDecl(Enum);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000272 Enum->startDefinition();
273
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000274 llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000275
276 EnumConstantDecl *LastEnumConst = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000277 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
278 ECEnd = D->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000279 EC != ECEnd; ++EC) {
280 // The specified value for the enumerator.
281 OwningExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000282 if (Expr *UninstValue = EC->getInitExpr()) {
283 // The enumerator's value expression is not potentially evaluated.
284 EnterExpressionEvaluationContext Unevaluated(SemaRef,
285 Action::Unevaluated);
286
John McCallce3ff2b2009-08-25 22:02:44 +0000287 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000288 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000289
290 // Drop the initial value and continue.
291 bool isInvalid = false;
292 if (Value.isInvalid()) {
293 Value = SemaRef.Owned((Expr *)0);
294 isInvalid = true;
295 }
296
297 EnumConstantDecl *EnumConst
298 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
299 EC->getLocation(), EC->getIdentifier(),
300 move(Value));
301
302 if (isInvalid) {
303 if (EnumConst)
304 EnumConst->setInvalidDecl();
305 Enum->setInvalidDecl();
306 }
307
308 if (EnumConst) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000309 Enum->addDecl(EnumConst);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000310 Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst));
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000311 LastEnumConst = EnumConst;
312 }
313 }
314
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000315 // FIXME: Fixup LBraceLoc and RBraceLoc
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000316 // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000317 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
318 Sema::DeclPtrTy::make(Enum),
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000319 &Enumerators[0], Enumerators.size(),
320 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000321
322 return Enum;
323}
324
Douglas Gregor6477b692009-03-25 15:04:13 +0000325Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
326 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
327 return 0;
328}
329
John McCalle29ba202009-08-20 01:44:21 +0000330Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
331 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000332 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
John McCalle29ba202009-08-20 01:44:21 +0000333 if (!InstParams) return NULL;
334
335 CXXRecordDecl *Pattern = D->getTemplatedDecl();
336 CXXRecordDecl *RecordInst
337 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), Owner,
338 Pattern->getLocation(), Pattern->getIdentifier(),
339 Pattern->getTagKeywordLoc(), /*PrevDecl=*/ NULL);
340
341 ClassTemplateDecl *Inst
342 = ClassTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
343 D->getIdentifier(), InstParams, RecordInst, 0);
344 RecordInst->setDescribedClassTemplate(Inst);
345 Inst->setAccess(D->getAccess());
346 Inst->setInstantiatedFromMemberTemplate(D);
347
348 Owner->addDecl(Inst);
349 return Inst;
350}
351
Douglas Gregord475b8d2009-03-25 21:17:03 +0000352Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
353 CXXRecordDecl *PrevDecl = 0;
354 if (D->isInjectedClassName())
355 PrevDecl = cast<CXXRecordDecl>(Owner);
356
357 CXXRecordDecl *Record
358 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000359 D->getLocation(), D->getIdentifier(),
360 D->getTagKeywordLoc(), PrevDecl);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000361 Record->setImplicit(D->isImplicit());
362 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000363 if (!D->isInjectedClassName())
364 Record->setInstantiationOfMemberClass(D);
365
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000366 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000367 return Record;
368}
369
Douglas Gregore53060f2009-06-25 22:08:12 +0000370Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000371 // Check whether there is already a function template specialization for
372 // this declaration.
373 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
374 void *InsertPos = 0;
375 if (FunctionTemplate) {
376 llvm::FoldingSetNodeID ID;
377 FunctionTemplateSpecializationInfo::Profile(ID,
378 TemplateArgs.getFlatArgumentList(),
Douglas Gregor828e2262009-07-29 16:09:57 +0000379 TemplateArgs.flat_size(),
380 SemaRef.Context);
Douglas Gregor127102b2009-06-29 20:59:39 +0000381
382 FunctionTemplateSpecializationInfo *Info
383 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
384 InsertPos);
385
386 // If we already have a function template specialization, return it.
387 if (Info)
388 return Info->Function;
389 }
Douglas Gregore53060f2009-06-25 22:08:12 +0000390
391 Sema::LocalInstantiationScope Scope(SemaRef);
392
393 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCallce3ff2b2009-08-25 22:02:44 +0000394 QualType T = SubstFunctionType(D, Params);
Douglas Gregore53060f2009-06-25 22:08:12 +0000395 if (T.isNull())
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000396 return 0;
John McCallfd810b12009-08-14 02:03:10 +0000397
Douglas Gregore53060f2009-06-25 22:08:12 +0000398 // Build the instantiated method declaration.
John McCallfd810b12009-08-14 02:03:10 +0000399 FunctionDecl *Function;
400 if (FriendFunctionDecl* FFD = dyn_cast<FriendFunctionDecl>(D)) {
401 // The new decl's semantic context. FIXME: this might need
402 // to be instantiated.
403 DeclContext *DC = D->getDeclContext();
404
405 // This assert is bogus and exists only to catch cases we don't
406 // handle yet.
407 assert(!DC->isDependentContext());
408
409 Function =
410 FriendFunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000411 D->getDeclName(), T, D->getDeclaratorInfo(),
412 D->isInline(), FFD->getFriendLoc());
John McCallfd810b12009-08-14 02:03:10 +0000413 Function->setLexicalDeclContext(Owner);
414 } else {
415 Function =
416 FunctionDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000417 D->getDeclName(), T, D->getDeclaratorInfo(),
418 D->getStorageClass(),
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +0000419 D->isInline(), D->hasWrittenPrototype());
John McCallfd810b12009-08-14 02:03:10 +0000420 }
Douglas Gregore53060f2009-06-25 22:08:12 +0000421
422 // Attach the parameters
423 for (unsigned P = 0; P < Params.size(); ++P)
424 Params[P]->setOwningFunction(Function);
425 Function->setParams(SemaRef.Context, Params.data(), Params.size());
426
427 if (InitFunctionInstantiation(Function, D))
428 Function->setInvalidDecl();
429
430 bool Redeclaration = false;
431 bool OverloadableAttrRequired = false;
432 NamedDecl *PrevDecl = 0;
433 SemaRef.CheckFunctionDeclaration(Function, PrevDecl, Redeclaration,
434 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000435
Douglas Gregor127102b2009-06-29 20:59:39 +0000436 if (FunctionTemplate) {
437 // Record this function template specialization.
438 Function->setFunctionTemplateSpecialization(SemaRef.Context,
439 FunctionTemplate,
440 &TemplateArgs,
441 InsertPos);
John McCallfd810b12009-08-14 02:03:10 +0000442 }
443
444 // If this was a friend function decl, it's a member which
445 // needs to be added.
446 if (isa<FriendFunctionDecl>(Function)) {
447 // If the new context is still dependent, this declaration
448 // needs to remain hidden.
449 if (Owner->isDependentContext())
450 Owner->addHiddenDecl(Function);
451 else
452 Owner->addDecl(Function);
453 }
Douglas Gregor127102b2009-06-29 20:59:39 +0000454
Douglas Gregore53060f2009-06-25 22:08:12 +0000455 return Function;
456}
457
458Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
Douglas Gregor6b906862009-08-21 00:16:32 +0000459 // Check whether there is already a function template specialization for
460 // this declaration.
461 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
462 void *InsertPos = 0;
463 if (FunctionTemplate) {
464 llvm::FoldingSetNodeID ID;
465 FunctionTemplateSpecializationInfo::Profile(ID,
466 TemplateArgs.getFlatArgumentList(),
467 TemplateArgs.flat_size(),
468 SemaRef.Context);
469
470 FunctionTemplateSpecializationInfo *Info
471 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
472 InsertPos);
473
474 // If we already have a function template specialization, return it.
475 if (Info)
476 return Info->Function;
477 }
478
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000479 Sema::LocalInstantiationScope Scope(SemaRef);
480
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000481 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCallce3ff2b2009-08-25 22:02:44 +0000482 QualType T = SubstFunctionType(D, Params);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000483 if (T.isNull())
484 return 0;
485
486 // Build the instantiated method declaration.
487 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
Douglas Gregordec06662009-08-21 18:42:58 +0000488 CXXMethodDecl *Method = 0;
489
490 DeclarationName Name = D->getDeclName();
Douglas Gregor17e32f32009-08-21 22:43:28 +0000491 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Douglas Gregordec06662009-08-21 18:42:58 +0000492 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
493 Name = SemaRef.Context.DeclarationNames.getCXXConstructorName(
494 SemaRef.Context.getCanonicalType(ClassTy));
495 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
Douglas Gregor17e32f32009-08-21 22:43:28 +0000496 Constructor->getLocation(),
Douglas Gregordec06662009-08-21 18:42:58 +0000497 Name, T,
Douglas Gregor17e32f32009-08-21 22:43:28 +0000498 Constructor->getDeclaratorInfo(),
499 Constructor->isExplicit(),
500 Constructor->isInline(), false);
501 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
502 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
503 Name = SemaRef.Context.DeclarationNames.getCXXDestructorName(
504 SemaRef.Context.getCanonicalType(ClassTy));
505 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
506 Destructor->getLocation(), Name,
507 T, Destructor->isInline(), false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000508 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
509 CanQualType ConvTy
510 = SemaRef.Context.getCanonicalType(
511 T->getAsFunctionType()->getResultType());
512 Name = SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(
513 ConvTy);
514 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
515 Conversion->getLocation(), Name,
516 T, Conversion->getDeclaratorInfo(),
517 Conversion->isInline(),
518 Conversion->isExplicit());
Douglas Gregordec06662009-08-21 18:42:58 +0000519 } else {
520 Method = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
521 D->getDeclName(), T, D->getDeclaratorInfo(),
522 D->isStatic(), D->isInline());
523 }
Douglas Gregor6b906862009-08-21 00:16:32 +0000524
525 if (!FunctionTemplate)
526 Method->setInstantiationOfMemberFunction(D);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000527
Douglas Gregor7caa6822009-07-24 20:34:43 +0000528 // If we are instantiating a member function defined
529 // out-of-line, the instantiation will have the same lexical
530 // context (which will be a namespace scope) as the template.
531 if (D->isOutOfLine())
532 Method->setLexicalDeclContext(D->getLexicalDeclContext());
533
Douglas Gregor5545e162009-03-24 00:38:23 +0000534 // Attach the parameters
535 for (unsigned P = 0; P < Params.size(); ++P)
536 Params[P]->setOwningFunction(Method);
Jay Foadbeaaccd2009-05-21 09:52:38 +0000537 Method->setParams(SemaRef.Context, Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +0000538
539 if (InitMethodInstantiation(Method, D))
540 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000541
Douglas Gregordec06662009-08-21 18:42:58 +0000542 NamedDecl *PrevDecl = 0;
543
544 if (!FunctionTemplate) {
545 PrevDecl = SemaRef.LookupQualifiedName(Owner, Name,
546 Sema::LookupOrdinaryName, true);
547
548 // In C++, the previous declaration we find might be a tag type
549 // (class or enum). In this case, the new declaration will hide the
550 // tag type. Note that this does does not apply if we're declaring a
551 // typedef (C++ [dcl.typedef]p4).
552 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
553 PrevDecl = 0;
554 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000555
Douglas Gregor6b906862009-08-21 00:16:32 +0000556 if (FunctionTemplate)
557 // Record this function template specialization.
558 Method->setFunctionTemplateSpecialization(SemaRef.Context,
559 FunctionTemplate,
560 &TemplateArgs,
561 InsertPos);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000562
563 bool Redeclaration = false;
564 bool OverloadableAttrRequired = false;
565 SemaRef.CheckFunctionDeclaration(Method, PrevDecl, Redeclaration,
566 /*FIXME:*/OverloadableAttrRequired);
567
568 if (!FunctionTemplate && (!Method->isInvalidDecl() || !PrevDecl))
Douglas Gregordec06662009-08-21 18:42:58 +0000569 Owner->addDecl(Method);
570
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000571 return Method;
572}
573
Douglas Gregor615c5d42009-03-24 16:43:20 +0000574Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +0000575 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +0000576}
577
Douglas Gregor03b2b072009-03-24 00:15:49 +0000578Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +0000579 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +0000580}
581
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000582Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +0000583 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000584}
585
Douglas Gregor6477b692009-03-25 15:04:13 +0000586ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
John McCallce3ff2b2009-08-25 22:02:44 +0000587 QualType OrigT = SemaRef.SubstType(D->getOriginalType(), TemplateArgs,
Douglas Gregor7e063902009-05-11 23:53:27 +0000588 D->getLocation(), D->getDeclName());
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000589 if (OrigT.isNull())
590 return 0;
591
592 QualType T = SemaRef.adjustParameterType(OrigT);
593
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000594 // Allocate the parameter
595 ParmVarDecl *Param = 0;
596 if (T == OrigT)
597 Param = ParmVarDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000598 D->getIdentifier(), T, D->getDeclaratorInfo(),
599 D->getStorageClass(), 0);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000600 else
601 Param = OriginalParmVarDecl::Create(SemaRef.Context, Owner,
602 D->getLocation(), D->getIdentifier(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000603 T, D->getDeclaratorInfo(), OrigT,
604 D->getStorageClass(), 0);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000605
Anders Carlsson9351c172009-08-25 03:18:48 +0000606 // Mark the default argument as being uninstantiated.
607 if (Expr *Arg = D->getDefaultArg())
608 Param->setUninstantiatedDefaultArg(Arg);
609
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000610 // Note: we don't try to instantiate function parameters until after
611 // we've instantiated the function's type. Therefore, we don't have
612 // to check for 'void' parameter types here.
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000613 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000614 return Param;
615}
616
617Decl *
618TemplateDeclInstantiator::VisitOriginalParmVarDecl(OriginalParmVarDecl *D) {
619 // Since parameter types can decay either before or after
620 // instantiation, we simply treat OriginalParmVarDecls as
621 // ParmVarDecls the same way, and create one or the other depending
622 // on what happens after template instantiation.
623 return VisitParmVarDecl(D);
624}
625
John McCalle29ba202009-08-20 01:44:21 +0000626Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
627 TemplateTypeParmDecl *D) {
628 // TODO: don't always clone when decls are refcounted.
629 const Type* T = D->getTypeForDecl();
630 assert(T->isTemplateTypeParmType());
631 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
632
633 TemplateTypeParmDecl *Inst =
634 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
635 TTPT->getDepth(), TTPT->getIndex(),
636 TTPT->getName(),
637 D->wasDeclaredWithTypename(),
638 D->isParameterPack());
639
640 if (D->hasDefaultArgument()) {
641 QualType DefaultPattern = D->getDefaultArgument();
642 QualType DefaultInst
John McCallce3ff2b2009-08-25 22:02:44 +0000643 = SemaRef.SubstType(DefaultPattern, TemplateArgs,
644 D->getDefaultArgumentLoc(),
645 D->getDeclName());
John McCalle29ba202009-08-20 01:44:21 +0000646
647 Inst->setDefaultArgument(DefaultInst,
648 D->getDefaultArgumentLoc(),
649 D->defaultArgumentWasInherited() /* preserve? */);
650 }
651
652 return Inst;
653}
654
John McCallce3ff2b2009-08-25 22:02:44 +0000655Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
656 const TemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +0000657 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000658 return Instantiator.Visit(D);
659}
660
John McCalle29ba202009-08-20 01:44:21 +0000661/// \brief Instantiates a nested template parameter list in the current
662/// instantiation context.
663///
664/// \param L The parameter list to instantiate
665///
666/// \returns NULL if there was an error
667TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +0000668TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +0000669 // Get errors for all the parameters before bailing out.
670 bool Invalid = false;
671
672 unsigned N = L->size();
673 typedef llvm::SmallVector<Decl*,8> ParamVector;
674 ParamVector Params;
675 Params.reserve(N);
676 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
677 PI != PE; ++PI) {
678 Decl *D = Visit(*PI);
679 Params.push_back(D);
680 Invalid = Invalid || !D;
681 }
682
683 // Clean up if we had an error.
684 if (Invalid) {
685 for (ParamVector::iterator PI = Params.begin(), PE = Params.end();
686 PI != PE; ++PI)
687 if (*PI)
688 (*PI)->Destroy(SemaRef.Context);
689 return NULL;
690 }
691
692 TemplateParameterList *InstL
693 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
694 L->getLAngleLoc(), &Params.front(), N,
695 L->getRAngleLoc());
696 return InstL;
697}
698
John McCallce3ff2b2009-08-25 22:02:44 +0000699/// \brief Does substitution on the type of the given function, including
700/// all of the function parameters.
Douglas Gregor5545e162009-03-24 00:38:23 +0000701///
John McCallce3ff2b2009-08-25 22:02:44 +0000702/// \param D The function whose type will be the basis of the substitution
Douglas Gregor5545e162009-03-24 00:38:23 +0000703///
704/// \param Params the instantiated parameter declarations
705
John McCallce3ff2b2009-08-25 22:02:44 +0000706/// \returns the instantiated function's type if successful, a NULL
Douglas Gregor5545e162009-03-24 00:38:23 +0000707/// type if there was an error.
708QualType
John McCallce3ff2b2009-08-25 22:02:44 +0000709TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +0000710 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
711 bool InvalidDecl = false;
712
John McCallce3ff2b2009-08-25 22:02:44 +0000713 // Substitute all of the function's formal parameter types.
Douglas Gregor7e063902009-05-11 23:53:27 +0000714 TemplateDeclInstantiator ParamInstantiator(SemaRef, 0, TemplateArgs);
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000715 llvm::SmallVector<QualType, 4> ParamTys;
Douglas Gregor5545e162009-03-24 00:38:23 +0000716 for (FunctionDecl::param_iterator P = D->param_begin(),
717 PEnd = D->param_end();
718 P != PEnd; ++P) {
Douglas Gregor6477b692009-03-25 15:04:13 +0000719 if (ParmVarDecl *PInst = ParamInstantiator.VisitParmVarDecl(*P)) {
Douglas Gregor5545e162009-03-24 00:38:23 +0000720 if (PInst->getType()->isVoidType()) {
721 SemaRef.Diag(PInst->getLocation(), diag::err_param_with_void_type);
722 PInst->setInvalidDecl();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000723 } else if (SemaRef.RequireNonAbstractType(PInst->getLocation(),
724 PInst->getType(),
725 diag::err_abstract_type_in_decl,
726 Sema::AbstractParamType))
Douglas Gregor5545e162009-03-24 00:38:23 +0000727 PInst->setInvalidDecl();
728
729 Params.push_back(PInst);
730 ParamTys.push_back(PInst->getType());
731
732 if (PInst->isInvalidDecl())
733 InvalidDecl = true;
734 } else
735 InvalidDecl = true;
736 }
737
738 // FIXME: Deallocate dead declarations.
739 if (InvalidDecl)
740 return QualType();
741
742 const FunctionProtoType *Proto = D->getType()->getAsFunctionProtoType();
743 assert(Proto && "Missing prototype?");
744 QualType ResultType
John McCallce3ff2b2009-08-25 22:02:44 +0000745 = SemaRef.SubstType(Proto->getResultType(), TemplateArgs,
746 D->getLocation(), D->getDeclName());
Douglas Gregor5545e162009-03-24 00:38:23 +0000747 if (ResultType.isNull())
748 return QualType();
749
Jay Foadbeaaccd2009-05-21 09:52:38 +0000750 return SemaRef.BuildFunctionType(ResultType, ParamTys.data(), ParamTys.size(),
Douglas Gregor5545e162009-03-24 00:38:23 +0000751 Proto->isVariadic(), Proto->getTypeQuals(),
752 D->getLocation(), D->getDeclName());
753}
754
Douglas Gregore53060f2009-06-25 22:08:12 +0000755/// \brief Initializes the common fields of an instantiation function
756/// declaration (New) from the corresponding fields of its template (Tmpl).
757///
758/// \returns true if there was an error
759bool
760TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
761 FunctionDecl *Tmpl) {
762 if (Tmpl->isDeleted())
763 New->setDeleted();
Douglas Gregorcca9e962009-07-01 22:01:06 +0000764
765 // If we are performing substituting explicitly-specified template arguments
766 // or deduced template arguments into a function template and we reach this
767 // point, we are now past the point where SFINAE applies and have committed
768 // to keeping the new function template specialization. We therefore
769 // convert the active template instantiation for the function template
770 // into a template instantiation for this specific function template
771 // specialization, which is not a SFINAE context, so that we diagnose any
772 // further errors in the declaration itself.
773 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
774 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
775 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
776 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
777 if (FunctionTemplateDecl *FunTmpl
778 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
779 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
780 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +0000781 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000782 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
783 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
784 }
785 }
786
Douglas Gregore53060f2009-06-25 22:08:12 +0000787 return false;
788}
789
Douglas Gregor5545e162009-03-24 00:38:23 +0000790/// \brief Initializes common fields of an instantiated method
791/// declaration (New) from the corresponding fields of its template
792/// (Tmpl).
793///
794/// \returns true if there was an error
795bool
796TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
797 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +0000798 if (InitFunctionInstantiation(New, Tmpl))
799 return true;
800
Douglas Gregor5545e162009-03-24 00:38:23 +0000801 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
802 New->setAccess(Tmpl->getAccess());
Anders Carlsson77b7f1d2009-05-14 22:15:41 +0000803 if (Tmpl->isVirtualAsWritten()) {
804 New->setVirtualAsWritten(true);
Douglas Gregor5545e162009-03-24 00:38:23 +0000805 Record->setAggregate(false);
806 Record->setPOD(false);
Eli Friedman1d954f62009-08-15 21:55:26 +0000807 Record->setEmpty(false);
Douglas Gregor5545e162009-03-24 00:38:23 +0000808 Record->setPolymorphic(true);
809 }
Douglas Gregor5545e162009-03-24 00:38:23 +0000810 if (Tmpl->isPure()) {
811 New->setPure();
812 Record->setAbstract(true);
813 }
814
815 // FIXME: attributes
816 // FIXME: New needs a pointer to Tmpl
817 return false;
818}
Douglas Gregora58861f2009-05-13 20:28:22 +0000819
820/// \brief Instantiate the definition of the given function from its
821/// template.
822///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000823/// \param PointOfInstantiation the point at which the instantiation was
824/// required. Note that this is not precisely a "point of instantiation"
825/// for the function, but it's close.
826///
Douglas Gregora58861f2009-05-13 20:28:22 +0000827/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000828/// function template specialization or member function of a class template
829/// specialization.
830///
831/// \param Recursive if true, recursively instantiates any functions that
832/// are required by this instantiation.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000833void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000834 FunctionDecl *Function,
835 bool Recursive) {
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000836 if (Function->isInvalidDecl())
837 return;
838
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000839 assert(!Function->getBody() && "Already instantiated!");
Douglas Gregord7f37bf2009-06-22 23:06:13 +0000840
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000841 // Find the function body that we'll be substituting.
Douglas Gregor1637be72009-06-26 00:10:03 +0000842 const FunctionDecl *PatternDecl = 0;
843 if (FunctionTemplateDecl *Primary = Function->getPrimaryTemplate())
844 PatternDecl = Primary->getTemplatedDecl();
845 else
846 PatternDecl = Function->getInstantiatedFromMemberFunction();
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000847 Stmt *Pattern = 0;
848 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000849 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000850
851 if (!Pattern)
852 return;
853
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000854 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
855 if (Inst)
856 return;
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000857
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000858 // If we're performing recursive template instantiation, create our own
859 // queue of pending implicit instantiations that we will instantiate later,
860 // while we're still within our own instantiation context.
861 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
862 if (Recursive)
863 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
864
Douglas Gregore2c31ff2009-05-15 17:59:04 +0000865 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
866
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000867 // Introduce a new scope where local variable instantiations will be
868 // recorded.
869 LocalInstantiationScope Scope(*this);
870
871 // Introduce the instantiated function parameters into the local
872 // instantiation scope.
873 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
874 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
875 Function->getParamDecl(I));
876
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000877 // Enter the scope of this instantiation. We don't use
878 // PushDeclContext because we don't have a scope.
879 DeclContext *PreviousContext = CurContext;
880 CurContext = Function;
881
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000882 // Instantiate the function body.
883 OwningStmtResult Body
John McCallce3ff2b2009-08-25 22:02:44 +0000884 = SubstStmt(Pattern, getTemplateInstantiationArgs(Function));
Douglas Gregore2c31ff2009-05-15 17:59:04 +0000885
886 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
887 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000888
889 CurContext = PreviousContext;
Douglas Gregoraba43bb2009-05-26 20:50:29 +0000890
891 DeclGroupRef DG(Function);
892 Consumer.HandleTopLevelDecl(DG);
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000893
894 if (Recursive) {
895 // Instantiate any pending implicit instantiations found during the
896 // instantiation of this template.
897 PerformPendingImplicitInstantiations();
898
899 // Restore the set of pending implicit instantiations.
900 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
901 }
Douglas Gregora58861f2009-05-13 20:28:22 +0000902}
903
904/// \brief Instantiate the definition of the given variable from its
905/// template.
906///
Douglas Gregor7caa6822009-07-24 20:34:43 +0000907/// \param PointOfInstantiation the point at which the instantiation was
908/// required. Note that this is not precisely a "point of instantiation"
909/// for the function, but it's close.
910///
911/// \param Var the already-instantiated declaration of a static member
912/// variable of a class template specialization.
913///
914/// \param Recursive if true, recursively instantiates any functions that
915/// are required by this instantiation.
916void Sema::InstantiateStaticDataMemberDefinition(
917 SourceLocation PointOfInstantiation,
918 VarDecl *Var,
919 bool Recursive) {
920 if (Var->isInvalidDecl())
921 return;
922
923 // Find the out-of-line definition of this static data member.
924 // FIXME: Do we have to look for specializations separately?
925 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
926 bool FoundOutOfLineDef = false;
927 assert(Def && "This data member was not instantiated from a template?");
928 assert(Def->isStaticDataMember() && "Not a static data member?");
929 for (VarDecl::redecl_iterator RD = Def->redecls_begin(),
930 RDEnd = Def->redecls_end();
931 RD != RDEnd; ++RD) {
932 if (RD->getLexicalDeclContext()->isFileContext()) {
933 Def = *RD;
934 FoundOutOfLineDef = true;
935 }
936 }
937
938 if (!FoundOutOfLineDef) {
939 // We did not find an out-of-line definition of this static data member,
940 // so we won't perform any instantiation. Rather, we rely on the user to
941 // instantiate this definition (or provide a specialization for it) in
942 // another translation unit.
943 return;
944 }
945
946 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
947 if (Inst)
948 return;
949
950 // If we're performing recursive template instantiation, create our own
951 // queue of pending implicit instantiations that we will instantiate later,
952 // while we're still within our own instantiation context.
953 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
954 if (Recursive)
955 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
956
957 // Enter the scope of this instantiation. We don't use
958 // PushDeclContext because we don't have a scope.
959 DeclContext *PreviousContext = CurContext;
960 CurContext = Var->getDeclContext();
961
962#if 0
963 // Instantiate the initializer of this static data member.
964 OwningExprResult Init
965 = InstantiateExpr(Def->getInit(), getTemplateInstantiationArgs(Var));
966 if (Init.isInvalid()) {
967 // If instantiation of the initializer failed, mark the declaration invalid
968 // and don't instantiate anything else that was triggered by this
969 // instantiation.
970 Var->setInvalidDecl();
971
972 // Restore the set of pending implicit instantiations.
973 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
974
975 return;
976 }
977
978 // Type-check the initializer.
979 if (Init.get())
980 AddInitializerToDecl(DeclPtrTy::make(Var), move(Init),
981 Def->hasCXXDirectInitializer());
982 else
983 ActOnUninitializedDecl(DeclPtrTy::make(Var), false);
984#else
John McCallce3ff2b2009-08-25 22:02:44 +0000985 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Douglas Gregor7caa6822009-07-24 20:34:43 +0000986 getTemplateInstantiationArgs(Var)));
987#endif
988
989 CurContext = PreviousContext;
990
991 if (Var) {
992 DeclGroupRef DG(Var);
993 Consumer.HandleTopLevelDecl(DG);
994 }
995
996 if (Recursive) {
997 // Instantiate any pending implicit instantiations found during the
998 // instantiation of this template.
999 PerformPendingImplicitInstantiations();
1000
1001 // Restore the set of pending implicit instantiations.
1002 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1003 }
Douglas Gregora58861f2009-05-13 20:28:22 +00001004}
Douglas Gregor815215d2009-05-27 05:35:12 +00001005
1006static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
1007 if (D->getKind() != Other->getKind())
1008 return false;
1009
1010 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001011 return Record->getInstantiatedFromMemberClass()->getCanonicalDecl()
1012 == D->getCanonicalDecl();
Douglas Gregor815215d2009-05-27 05:35:12 +00001013
1014 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001015 return Function->getInstantiatedFromMemberFunction()->getCanonicalDecl()
1016 == D->getCanonicalDecl();
Douglas Gregor815215d2009-05-27 05:35:12 +00001017
Douglas Gregor8dbc3c62009-05-27 17:20:35 +00001018 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001019 return Enum->getInstantiatedFromMemberEnum()->getCanonicalDecl()
1020 == D->getCanonicalDecl();
Douglas Gregor815215d2009-05-27 05:35:12 +00001021
Douglas Gregor7caa6822009-07-24 20:34:43 +00001022 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
1023 if (Var->isStaticDataMember())
1024 return Var->getInstantiatedFromStaticDataMember()->getCanonicalDecl()
1025 == D->getCanonicalDecl();
1026
Douglas Gregor815215d2009-05-27 05:35:12 +00001027 // FIXME: How can we find instantiations of anonymous unions?
1028
1029 return D->getDeclName() && isa<NamedDecl>(Other) &&
1030 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
1031}
1032
1033template<typename ForwardIterator>
1034static NamedDecl *findInstantiationOf(ASTContext &Ctx,
1035 NamedDecl *D,
1036 ForwardIterator first,
1037 ForwardIterator last) {
1038 for (; first != last; ++first)
1039 if (isInstantiationOf(Ctx, D, *first))
1040 return cast<NamedDecl>(*first);
1041
1042 return 0;
1043}
1044
Douglas Gregored961e72009-05-27 17:54:46 +00001045/// \brief Find the instantiation of the given declaration within the
1046/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00001047///
1048/// This routine is intended to be used when \p D is a declaration
1049/// referenced from within a template, that needs to mapped into the
1050/// corresponding declaration within an instantiation. For example,
1051/// given:
1052///
1053/// \code
1054/// template<typename T>
1055/// struct X {
1056/// enum Kind {
1057/// KnownValue = sizeof(T)
1058/// };
1059///
1060/// bool getKind() const { return KnownValue; }
1061/// };
1062///
1063/// template struct X<int>;
1064/// \endcode
1065///
1066/// In the instantiation of X<int>::getKind(), we need to map the
1067/// EnumConstantDecl for KnownValue (which refers to
1068/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00001069/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
1070/// this mapping from within the instantiation of X<int>.
John McCallce3ff2b2009-08-25 22:02:44 +00001071NamedDecl * Sema::FindInstantiatedDecl(NamedDecl *D) {
Douglas Gregor815215d2009-05-27 05:35:12 +00001072 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor2bba76b2009-05-27 17:07:49 +00001073 if (isa<ParmVarDecl>(D) || ParentDC->isFunctionOrMethod()) {
1074 // D is a local of some kind. Look into the map of local
1075 // declarations to their instantiations.
1076 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
1077 }
Douglas Gregor815215d2009-05-27 05:35:12 +00001078
Douglas Gregor2bba76b2009-05-27 17:07:49 +00001079 if (NamedDecl *ParentDecl = dyn_cast<NamedDecl>(ParentDC)) {
John McCallce3ff2b2009-08-25 22:02:44 +00001080 ParentDecl = FindInstantiatedDecl(ParentDecl);
Douglas Gregor815215d2009-05-27 05:35:12 +00001081 if (!ParentDecl)
1082 return 0;
1083
1084 ParentDC = cast<DeclContext>(ParentDecl);
1085 }
1086
Douglas Gregor815215d2009-05-27 05:35:12 +00001087 if (ParentDC != D->getDeclContext()) {
1088 // We performed some kind of instantiation in the parent context,
1089 // so now we need to look into the instantiated parent context to
1090 // find the instantiation of the declaration D.
1091 NamedDecl *Result = 0;
1092 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001093 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00001094 Result = findInstantiationOf(Context, D, Found.first, Found.second);
1095 } else {
1096 // Since we don't have a name for the entity we're looking for,
1097 // our only option is to walk through all of the declarations to
1098 // find that name. This will occur in a few cases:
1099 //
1100 // - anonymous struct/union within a template
1101 // - unnamed class/struct/union/enum within a template
1102 //
1103 // FIXME: Find a better way to find these instantiations!
1104 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001105 ParentDC->decls_begin(),
1106 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00001107 }
1108 assert(Result && "Unable to find instantiation of declaration!");
1109 D = Result;
1110 }
1111
Douglas Gregor815215d2009-05-27 05:35:12 +00001112 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
Douglas Gregored961e72009-05-27 17:54:46 +00001113 if (ClassTemplateDecl *ClassTemplate
1114 = Record->getDescribedClassTemplate()) {
1115 // When the declaration D was parsed, it referred to the current
1116 // instantiation. Therefore, look through the current context,
1117 // which contains actual instantiations, to find the
1118 // instantiation of the "current instantiation" that D refers
1119 // to. Alternatively, we could just instantiate the
1120 // injected-class-name with the current template arguments, but
1121 // such an instantiation is far more expensive.
1122 for (DeclContext *DC = CurContext; !DC->isFileContext();
1123 DC = DC->getParent()) {
1124 if (ClassTemplateSpecializationDecl *Spec
1125 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001126 if (Spec->getSpecializedTemplate()->getCanonicalDecl()
1127 == ClassTemplate->getCanonicalDecl())
Douglas Gregored961e72009-05-27 17:54:46 +00001128 return Spec;
1129 }
1130
1131 assert(false &&
1132 "Unable to find declaration for the current instantiation");
Douglas Gregor815215d2009-05-27 05:35:12 +00001133 }
1134
1135 return D;
1136}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001137
1138/// \brief Performs template instantiation for all implicit template
1139/// instantiations we have seen until this point.
1140void Sema::PerformPendingImplicitInstantiations() {
1141 while (!PendingImplicitInstantiations.empty()) {
1142 PendingImplicitInstantiation Inst = PendingImplicitInstantiations.front();
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001143 PendingImplicitInstantiations.pop_front();
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001144
Douglas Gregor7caa6822009-07-24 20:34:43 +00001145 // Instantiate function definitions
1146 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001147 if (!Function->getBody())
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001148 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00001149 continue;
1150 }
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001151
Douglas Gregor7caa6822009-07-24 20:34:43 +00001152 // Instantiate static data member definitions.
1153 VarDecl *Var = cast<VarDecl>(Inst.first);
1154 assert(Var->isStaticDataMember() && "Not a static data member?");
1155 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001156 }
1157}