blob: 30d7b6acd61d20e61cbb7ca2d2ada706545e322a [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);
Douglas Gregor5545e162009-03-24 00:38:23 +000056
Douglas Gregor8dbc2692009-03-17 21:15:40 +000057 // Base case. FIXME: Remove once we can instantiate everything.
58 Decl *VisitDecl(Decl *) {
Douglas Gregor3d7a12a2009-03-25 23:32:15 +000059 assert(false && "Template instantiation of unknown declaration kind!");
Douglas Gregor8dbc2692009-03-17 21:15:40 +000060 return 0;
61 }
Douglas Gregor5545e162009-03-24 00:38:23 +000062
John McCallfd810b12009-08-14 02:03:10 +000063 const LangOptions &getLangOptions() {
64 return SemaRef.getLangOptions();
65 }
66
Douglas Gregor5545e162009-03-24 00:38:23 +000067 // Helper functions for instantiating methods.
68 QualType InstantiateFunctionType(FunctionDecl *D,
69 llvm::SmallVectorImpl<ParmVarDecl *> &Params);
Douglas Gregore53060f2009-06-25 22:08:12 +000070 bool InitFunctionInstantiation(FunctionDecl *New, FunctionDecl *Tmpl);
Douglas Gregor5545e162009-03-24 00:38:23 +000071 bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000072 };
73}
74
Douglas Gregor4f722be2009-03-25 15:45:12 +000075Decl *
76TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
77 assert(false && "Translation units cannot be instantiated");
78 return D;
79}
80
81Decl *
82TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
83 assert(false && "Namespaces cannot be instantiated");
84 return D;
85}
86
Douglas Gregor8dbc2692009-03-17 21:15:40 +000087Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
88 bool Invalid = false;
89 QualType T = D->getUnderlyingType();
90 if (T->isDependentType()) {
Douglas Gregor1eee0e72009-05-14 21:06:31 +000091 T = SemaRef.InstantiateType(T, TemplateArgs,
92 D->getLocation(), D->getDeclName());
Douglas Gregor8dbc2692009-03-17 21:15:40 +000093 if (T.isNull()) {
94 Invalid = true;
95 T = SemaRef.Context.IntTy;
96 }
97 }
98
99 // Create the new typedef
100 TypedefDecl *Typedef
101 = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(),
102 D->getIdentifier(), T);
103 if (Invalid)
104 Typedef->setInvalidDecl();
105
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000106 Owner->addDecl(Typedef);
Douglas Gregorbc221632009-05-28 16:34:51 +0000107
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000108 return Typedef;
109}
110
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000111Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
112 // Instantiate the type of the declaration
113 QualType T = SemaRef.InstantiateType(D->getType(), TemplateArgs,
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000114 D->getTypeSpecStartLoc(),
115 D->getDeclName());
116 if (T.isNull())
117 return 0;
118
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000119 // Build the instantiated declaration
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000120 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
121 D->getLocation(), D->getIdentifier(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000122 T, D->getDeclaratorInfo(),
123 D->getStorageClass(),D->getTypeSpecStartLoc());
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000124 Var->setThreadSpecified(D->isThreadSpecified());
125 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
126 Var->setDeclaredInCondition(D->isDeclaredInCondition());
127
Douglas Gregor7caa6822009-07-24 20:34:43 +0000128 // If we are instantiating a static data member defined
129 // out-of-line, the instantiation will have the same lexical
130 // context (which will be a namespace scope) as the template.
131 if (D->isOutOfLine())
132 Var->setLexicalDeclContext(D->getLexicalDeclContext());
133
Mike Stump390b4cc2009-05-16 07:39:55 +0000134 // FIXME: In theory, we could have a previous declaration for variables that
135 // are not static data members.
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000136 bool Redeclaration = false;
Chris Lattnereaaebc72009-04-25 08:06:05 +0000137 SemaRef.CheckVariableDeclaration(Var, 0, Redeclaration);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000138
139 if (D->isOutOfLine()) {
140 D->getLexicalDeclContext()->addDecl(Var);
141 Owner->makeDeclVisibleInContext(Var);
142 } else {
143 Owner->addDecl(Var);
144 }
145
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000146 if (D->getInit()) {
147 OwningExprResult Init
Douglas Gregor7e063902009-05-11 23:53:27 +0000148 = SemaRef.InstantiateExpr(D->getInit(), TemplateArgs);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000149 if (Init.isInvalid())
150 Var->setInvalidDecl();
151 else
Chris Lattnerb28317a2009-03-28 19:18:32 +0000152 SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var), move(Init),
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000153 D->hasCXXDirectInitializer());
Douglas Gregor65b90052009-07-27 17:43:39 +0000154 } else if (!Var->isStaticDataMember() || Var->isOutOfLine())
155 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000156
Douglas Gregor7caa6822009-07-24 20:34:43 +0000157 // Link instantiations of static data members back to the template from
158 // which they were instantiated.
159 if (Var->isStaticDataMember())
160 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D);
161
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000162 return Var;
163}
164
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000165Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
166 bool Invalid = false;
167 QualType T = D->getType();
168 if (T->isDependentType()) {
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000169 T = SemaRef.InstantiateType(T, TemplateArgs,
170 D->getLocation(), D->getDeclName());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000171 if (!T.isNull() && T->isFunctionType()) {
172 // C++ [temp.arg.type]p3:
173 // If a declaration acquires a function type through a type
174 // dependent on a template-parameter and this causes a
175 // declaration that does not use the syntactic form of a
176 // function declarator to have function type, the program is
177 // ill-formed.
178 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
179 << T;
180 T = QualType();
181 Invalid = true;
182 }
183 }
184
185 Expr *BitWidth = D->getBitWidth();
186 if (Invalid)
187 BitWidth = 0;
188 else if (BitWidth) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000189 // The bit-width expression is not potentially evaluated.
190 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
191
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000192 OwningExprResult InstantiatedBitWidth
Douglas Gregor7e063902009-05-11 23:53:27 +0000193 = SemaRef.InstantiateExpr(BitWidth, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000194 if (InstantiatedBitWidth.isInvalid()) {
195 Invalid = true;
196 BitWidth = 0;
197 } else
Anders Carlssone9146f22009-05-01 19:49:17 +0000198 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000199 }
200
201 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(), T,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000202 D->getDeclaratorInfo(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000203 cast<RecordDecl>(Owner),
204 D->getLocation(),
205 D->isMutable(),
206 BitWidth,
Steve Naroffea218b82009-07-14 14:58:18 +0000207 D->getTypeSpecStartLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000208 D->getAccess(),
209 0);
210 if (Field) {
211 if (Invalid)
212 Field->setInvalidDecl();
213
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000214 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000215 }
216
217 return Field;
218}
219
John McCallfd810b12009-08-14 02:03:10 +0000220Decl *TemplateDeclInstantiator::VisitFriendClassDecl(FriendClassDecl *D) {
221 QualType T = D->getFriendType();
222 if (T->isDependentType()) {
223 T = SemaRef.InstantiateType(T, TemplateArgs, D->getLocation(),
224 DeclarationName());
225 assert(T.isNull() || getLangOptions().CPlusPlus0x || T->isRecordType());
226 }
227
228 // FIXME: the target context might be dependent.
229 DeclContext *DC = D->getDeclContext();
230 assert(DC->isFileContext());
231
232 FriendClassDecl *NewD =
233 FriendClassDecl::Create(SemaRef.Context, DC, D->getLocation(), T,
234 D->getFriendLoc());
235 Owner->addDecl(NewD);
236 return NewD;
237}
238
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000239Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
240 Expr *AssertExpr = D->getAssertExpr();
241
Douglas Gregorac7610d2009-06-22 20:57:11 +0000242 // The expression in a static assertion is not potentially evaluated.
243 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
244
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000245 OwningExprResult InstantiatedAssertExpr
Douglas Gregor7e063902009-05-11 23:53:27 +0000246 = SemaRef.InstantiateExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000247 if (InstantiatedAssertExpr.isInvalid())
248 return 0;
249
Douglas Gregor43d9d922009-08-08 01:41:12 +0000250 OwningExprResult Message(SemaRef, D->getMessage());
251 D->getMessage()->Retain();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000252 Decl *StaticAssert
Chris Lattnerb28317a2009-03-28 19:18:32 +0000253 = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
254 move(InstantiatedAssertExpr),
255 move(Message)).getAs<Decl>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000256 return StaticAssert;
257}
258
259Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
260 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
261 D->getLocation(), D->getIdentifier(),
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000262 D->getTagKeywordLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000263 /*PrevDecl=*/0);
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000264 Enum->setInstantiationOfMemberEnum(D);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000265 Enum->setAccess(D->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000266 Owner->addDecl(Enum);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000267 Enum->startDefinition();
268
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000269 llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000270
271 EnumConstantDecl *LastEnumConst = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000272 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
273 ECEnd = D->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000274 EC != ECEnd; ++EC) {
275 // The specified value for the enumerator.
276 OwningExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000277 if (Expr *UninstValue = EC->getInitExpr()) {
278 // The enumerator's value expression is not potentially evaluated.
279 EnterExpressionEvaluationContext Unevaluated(SemaRef,
280 Action::Unevaluated);
281
Douglas Gregor7e063902009-05-11 23:53:27 +0000282 Value = SemaRef.InstantiateExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000283 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000284
285 // Drop the initial value and continue.
286 bool isInvalid = false;
287 if (Value.isInvalid()) {
288 Value = SemaRef.Owned((Expr *)0);
289 isInvalid = true;
290 }
291
292 EnumConstantDecl *EnumConst
293 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
294 EC->getLocation(), EC->getIdentifier(),
295 move(Value));
296
297 if (isInvalid) {
298 if (EnumConst)
299 EnumConst->setInvalidDecl();
300 Enum->setInvalidDecl();
301 }
302
303 if (EnumConst) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000304 Enum->addDecl(EnumConst);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000305 Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst));
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000306 LastEnumConst = EnumConst;
307 }
308 }
309
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000310 // FIXME: Fixup LBraceLoc and RBraceLoc
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000311 // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000312 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
313 Sema::DeclPtrTy::make(Enum),
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000314 &Enumerators[0], Enumerators.size(),
315 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000316
317 return Enum;
318}
319
Douglas Gregor6477b692009-03-25 15:04:13 +0000320Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
321 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
322 return 0;
323}
324
Douglas Gregord475b8d2009-03-25 21:17:03 +0000325Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
326 CXXRecordDecl *PrevDecl = 0;
327 if (D->isInjectedClassName())
328 PrevDecl = cast<CXXRecordDecl>(Owner);
329
330 CXXRecordDecl *Record
331 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000332 D->getLocation(), D->getIdentifier(),
333 D->getTagKeywordLoc(), PrevDecl);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000334 Record->setImplicit(D->isImplicit());
335 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000336 if (!D->isInjectedClassName())
337 Record->setInstantiationOfMemberClass(D);
338
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000339 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000340 return Record;
341}
342
Douglas Gregore53060f2009-06-25 22:08:12 +0000343Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000344 // Check whether there is already a function template specialization for
345 // this declaration.
346 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
347 void *InsertPos = 0;
348 if (FunctionTemplate) {
349 llvm::FoldingSetNodeID ID;
350 FunctionTemplateSpecializationInfo::Profile(ID,
351 TemplateArgs.getFlatArgumentList(),
Douglas Gregor828e2262009-07-29 16:09:57 +0000352 TemplateArgs.flat_size(),
353 SemaRef.Context);
Douglas Gregor127102b2009-06-29 20:59:39 +0000354
355 FunctionTemplateSpecializationInfo *Info
356 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
357 InsertPos);
358
359 // If we already have a function template specialization, return it.
360 if (Info)
361 return Info->Function;
362 }
Douglas Gregore53060f2009-06-25 22:08:12 +0000363
364 Sema::LocalInstantiationScope Scope(SemaRef);
365
366 llvm::SmallVector<ParmVarDecl *, 4> Params;
367 QualType T = InstantiateFunctionType(D, Params);
368 if (T.isNull())
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000369 return 0;
John McCallfd810b12009-08-14 02:03:10 +0000370
Douglas Gregore53060f2009-06-25 22:08:12 +0000371 // Build the instantiated method declaration.
John McCallfd810b12009-08-14 02:03:10 +0000372 FunctionDecl *Function;
373 if (FriendFunctionDecl* FFD = dyn_cast<FriendFunctionDecl>(D)) {
374 // The new decl's semantic context. FIXME: this might need
375 // to be instantiated.
376 DeclContext *DC = D->getDeclContext();
377
378 // This assert is bogus and exists only to catch cases we don't
379 // handle yet.
380 assert(!DC->isDependentContext());
381
382 Function =
383 FriendFunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000384 D->getDeclName(), T, D->getDeclaratorInfo(),
385 D->isInline(), FFD->getFriendLoc());
John McCallfd810b12009-08-14 02:03:10 +0000386 Function->setLexicalDeclContext(Owner);
387 } else {
388 Function =
389 FunctionDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000390 D->getDeclName(), T, D->getDeclaratorInfo(),
391 D->getStorageClass(),
Douglas Gregore53060f2009-06-25 22:08:12 +0000392 D->isInline(), D->hasWrittenPrototype(),
393 D->getTypeSpecStartLoc());
John McCallfd810b12009-08-14 02:03:10 +0000394 }
Douglas Gregore53060f2009-06-25 22:08:12 +0000395
396 // Attach the parameters
397 for (unsigned P = 0; P < Params.size(); ++P)
398 Params[P]->setOwningFunction(Function);
399 Function->setParams(SemaRef.Context, Params.data(), Params.size());
400
401 if (InitFunctionInstantiation(Function, D))
402 Function->setInvalidDecl();
403
404 bool Redeclaration = false;
405 bool OverloadableAttrRequired = false;
406 NamedDecl *PrevDecl = 0;
407 SemaRef.CheckFunctionDeclaration(Function, PrevDecl, Redeclaration,
408 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000409
Douglas Gregor127102b2009-06-29 20:59:39 +0000410 if (FunctionTemplate) {
411 // Record this function template specialization.
412 Function->setFunctionTemplateSpecialization(SemaRef.Context,
413 FunctionTemplate,
414 &TemplateArgs,
415 InsertPos);
John McCallfd810b12009-08-14 02:03:10 +0000416 }
417
418 // If this was a friend function decl, it's a member which
419 // needs to be added.
420 if (isa<FriendFunctionDecl>(Function)) {
421 // If the new context is still dependent, this declaration
422 // needs to remain hidden.
423 if (Owner->isDependentContext())
424 Owner->addHiddenDecl(Function);
425 else
426 Owner->addDecl(Function);
427 }
Douglas Gregor127102b2009-06-29 20:59:39 +0000428
Douglas Gregore53060f2009-06-25 22:08:12 +0000429 return Function;
430}
431
432Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
433 // FIXME: Look for existing, explicit specializations.
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000434 Sema::LocalInstantiationScope Scope(SemaRef);
435
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000436 llvm::SmallVector<ParmVarDecl *, 4> Params;
Douglas Gregor5545e162009-03-24 00:38:23 +0000437 QualType T = InstantiateFunctionType(D, Params);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000438 if (T.isNull())
439 return 0;
440
441 // Build the instantiated method declaration.
442 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
443 CXXMethodDecl *Method
444 = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000445 D->getDeclName(), T, D->getDeclaratorInfo(),
446 D->isStatic(), D->isInline());
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000447 Method->setInstantiationOfMemberFunction(D);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000448
Douglas Gregor7caa6822009-07-24 20:34:43 +0000449 // If we are instantiating a member function defined
450 // out-of-line, the instantiation will have the same lexical
451 // context (which will be a namespace scope) as the template.
452 if (D->isOutOfLine())
453 Method->setLexicalDeclContext(D->getLexicalDeclContext());
454
Douglas Gregor5545e162009-03-24 00:38:23 +0000455 // Attach the parameters
456 for (unsigned P = 0; P < Params.size(); ++P)
457 Params[P]->setOwningFunction(Method);
Jay Foadbeaaccd2009-05-21 09:52:38 +0000458 Method->setParams(SemaRef.Context, Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +0000459
460 if (InitMethodInstantiation(Method, D))
461 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000462
463 NamedDecl *PrevDecl
464 = SemaRef.LookupQualifiedName(Owner, Method->getDeclName(),
465 Sema::LookupOrdinaryName, true);
466 // In C++, the previous declaration we find might be a tag type
467 // (class or enum). In this case, the new declaration will hide the
468 // tag type. Note that this does does not apply if we're declaring a
469 // typedef (C++ [dcl.typedef]p4).
470 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
471 PrevDecl = 0;
472 bool Redeclaration = false;
473 bool OverloadableAttrRequired = false;
Chris Lattnereaaebc72009-04-25 08:06:05 +0000474 SemaRef.CheckFunctionDeclaration(Method, PrevDecl, Redeclaration,
475 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000476
477 if (!Method->isInvalidDecl() || !PrevDecl)
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000478 Owner->addDecl(Method);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000479 return Method;
480}
481
Douglas Gregor615c5d42009-03-24 16:43:20 +0000482Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregore53060f2009-06-25 22:08:12 +0000483 // FIXME: Look for existing, explicit specializations.
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000484 Sema::LocalInstantiationScope Scope(SemaRef);
485
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000486 llvm::SmallVector<ParmVarDecl *, 4> Params;
Douglas Gregor615c5d42009-03-24 16:43:20 +0000487 QualType T = InstantiateFunctionType(D, Params);
488 if (T.isNull())
489 return 0;
490
491 // Build the instantiated method declaration.
492 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
493 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
494 DeclarationName Name
Douglas Gregor49f25ec2009-05-15 21:18:27 +0000495 = SemaRef.Context.DeclarationNames.getCXXConstructorName(
496 SemaRef.Context.getCanonicalType(ClassTy));
Douglas Gregor615c5d42009-03-24 16:43:20 +0000497 CXXConstructorDecl *Constructor
498 = CXXConstructorDecl::Create(SemaRef.Context, Record, D->getLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000499 Name, T, D->getDeclaratorInfo(),
500 D->isExplicit(), D->isInline(), false);
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000501 Constructor->setInstantiationOfMemberFunction(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +0000502
503 // Attach the parameters
504 for (unsigned P = 0; P < Params.size(); ++P)
505 Params[P]->setOwningFunction(Constructor);
Jay Foadbeaaccd2009-05-21 09:52:38 +0000506 Constructor->setParams(SemaRef.Context, Params.data(), Params.size());
Douglas Gregor615c5d42009-03-24 16:43:20 +0000507
508 if (InitMethodInstantiation(Constructor, D))
509 Constructor->setInvalidDecl();
510
511 NamedDecl *PrevDecl
512 = SemaRef.LookupQualifiedName(Owner, Name, Sema::LookupOrdinaryName, true);
513
514 // In C++, the previous declaration we find might be a tag type
515 // (class or enum). In this case, the new declaration will hide the
516 // tag type. Note that this does does not apply if we're declaring a
517 // typedef (C++ [dcl.typedef]p4).
518 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
519 PrevDecl = 0;
520 bool Redeclaration = false;
521 bool OverloadableAttrRequired = false;
Chris Lattnereaaebc72009-04-25 08:06:05 +0000522 SemaRef.CheckFunctionDeclaration(Constructor, PrevDecl, Redeclaration,
523 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor615c5d42009-03-24 16:43:20 +0000524
Douglas Gregor49f25ec2009-05-15 21:18:27 +0000525 Record->addedConstructor(SemaRef.Context, Constructor);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000526 Owner->addDecl(Constructor);
Douglas Gregor615c5d42009-03-24 16:43:20 +0000527 return Constructor;
528}
529
Douglas Gregor03b2b072009-03-24 00:15:49 +0000530Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregore53060f2009-06-25 22:08:12 +0000531 // FIXME: Look for existing, explicit specializations.
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000532 Sema::LocalInstantiationScope Scope(SemaRef);
533
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000534 llvm::SmallVector<ParmVarDecl *, 4> Params;
Douglas Gregor5545e162009-03-24 00:38:23 +0000535 QualType T = InstantiateFunctionType(D, Params);
Douglas Gregor03b2b072009-03-24 00:15:49 +0000536 if (T.isNull())
537 return 0;
Douglas Gregor5545e162009-03-24 00:38:23 +0000538 assert(Params.size() == 0 && "Destructor with parameters?");
539
Douglas Gregor03b2b072009-03-24 00:15:49 +0000540 // Build the instantiated destructor declaration.
541 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
Douglas Gregor50d62d12009-08-05 05:36:45 +0000542 CanQualType ClassTy =
Douglas Gregor49f25ec2009-05-15 21:18:27 +0000543 SemaRef.Context.getCanonicalType(SemaRef.Context.getTypeDeclType(Record));
Douglas Gregor03b2b072009-03-24 00:15:49 +0000544 CXXDestructorDecl *Destructor
545 = CXXDestructorDecl::Create(SemaRef.Context, Record,
546 D->getLocation(),
547 SemaRef.Context.DeclarationNames.getCXXDestructorName(ClassTy),
548 T, D->isInline(), false);
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000549 Destructor->setInstantiationOfMemberFunction(D);
Douglas Gregor5545e162009-03-24 00:38:23 +0000550 if (InitMethodInstantiation(Destructor, D))
551 Destructor->setInvalidDecl();
Douglas Gregor03b2b072009-03-24 00:15:49 +0000552
553 bool Redeclaration = false;
554 bool OverloadableAttrRequired = false;
555 NamedDecl *PrevDecl = 0;
Chris Lattnereaaebc72009-04-25 08:06:05 +0000556 SemaRef.CheckFunctionDeclaration(Destructor, PrevDecl, Redeclaration,
557 /*FIXME:*/OverloadableAttrRequired);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000558 Owner->addDecl(Destructor);
Douglas Gregor03b2b072009-03-24 00:15:49 +0000559 return Destructor;
560}
561
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000562Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregore53060f2009-06-25 22:08:12 +0000563 // FIXME: Look for existing, explicit specializations.
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000564 Sema::LocalInstantiationScope Scope(SemaRef);
565
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000566 llvm::SmallVector<ParmVarDecl *, 4> Params;
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000567 QualType T = InstantiateFunctionType(D, Params);
568 if (T.isNull())
569 return 0;
570 assert(Params.size() == 0 && "Destructor with parameters?");
571
572 // Build the instantiated conversion declaration.
573 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
574 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
Douglas Gregor50d62d12009-08-05 05:36:45 +0000575 CanQualType ConvTy
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000576 = SemaRef.Context.getCanonicalType(T->getAsFunctionType()->getResultType());
577 CXXConversionDecl *Conversion
578 = CXXConversionDecl::Create(SemaRef.Context, Record,
579 D->getLocation(),
580 SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(ConvTy),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000581 T, D->getDeclaratorInfo(),
582 D->isInline(), D->isExplicit());
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000583 Conversion->setInstantiationOfMemberFunction(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000584 if (InitMethodInstantiation(Conversion, D))
585 Conversion->setInvalidDecl();
586
587 bool Redeclaration = false;
588 bool OverloadableAttrRequired = false;
589 NamedDecl *PrevDecl = 0;
Chris Lattnereaaebc72009-04-25 08:06:05 +0000590 SemaRef.CheckFunctionDeclaration(Conversion, PrevDecl, Redeclaration,
591 /*FIXME:*/OverloadableAttrRequired);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000592 Owner->addDecl(Conversion);
Douglas Gregorbb969ed2009-03-25 00:34:44 +0000593 return Conversion;
594}
595
Douglas Gregor6477b692009-03-25 15:04:13 +0000596ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000597 QualType OrigT = SemaRef.InstantiateType(D->getOriginalType(), TemplateArgs,
Douglas Gregor7e063902009-05-11 23:53:27 +0000598 D->getLocation(), D->getDeclName());
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000599 if (OrigT.isNull())
600 return 0;
601
602 QualType T = SemaRef.adjustParameterType(OrigT);
603
604 if (D->getDefaultArg()) {
605 // FIXME: Leave a marker for "uninstantiated" default
606 // arguments. They only get instantiated on demand at the call
607 // site.
608 unsigned DiagID = SemaRef.Diags.getCustomDiagID(Diagnostic::Warning,
609 "sorry, dropping default argument during template instantiation");
610 SemaRef.Diag(D->getDefaultArg()->getSourceRange().getBegin(), DiagID)
611 << D->getDefaultArg()->getSourceRange();
612 }
613
614 // Allocate the parameter
615 ParmVarDecl *Param = 0;
616 if (T == OrigT)
617 Param = ParmVarDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000618 D->getIdentifier(), T, D->getDeclaratorInfo(),
619 D->getStorageClass(), 0);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000620 else
621 Param = OriginalParmVarDecl::Create(SemaRef.Context, Owner,
622 D->getLocation(), D->getIdentifier(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000623 T, D->getDeclaratorInfo(), OrigT,
624 D->getStorageClass(), 0);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000625
626 // Note: we don't try to instantiate function parameters until after
627 // we've instantiated the function's type. Therefore, we don't have
628 // to check for 'void' parameter types here.
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000629 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000630 return Param;
631}
632
633Decl *
634TemplateDeclInstantiator::VisitOriginalParmVarDecl(OriginalParmVarDecl *D) {
635 // Since parameter types can decay either before or after
636 // instantiation, we simply treat OriginalParmVarDecls as
637 // ParmVarDecls the same way, and create one or the other depending
638 // on what happens after template instantiation.
639 return VisitParmVarDecl(D);
640}
641
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000642Decl *Sema::InstantiateDecl(Decl *D, DeclContext *Owner,
Douglas Gregor7e063902009-05-11 23:53:27 +0000643 const TemplateArgumentList &TemplateArgs) {
644 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000645 return Instantiator.Visit(D);
646}
647
Douglas Gregor5545e162009-03-24 00:38:23 +0000648/// \brief Instantiates the type of the given function, including
649/// instantiating all of the function parameters.
650///
651/// \param D The function that we will be instantiated
652///
653/// \param Params the instantiated parameter declarations
654
655/// \returns the instantiated function's type if successfull, a NULL
656/// type if there was an error.
657QualType
658TemplateDeclInstantiator::InstantiateFunctionType(FunctionDecl *D,
659 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
660 bool InvalidDecl = false;
661
662 // Instantiate the function parameters
Douglas Gregor7e063902009-05-11 23:53:27 +0000663 TemplateDeclInstantiator ParamInstantiator(SemaRef, 0, TemplateArgs);
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000664 llvm::SmallVector<QualType, 4> ParamTys;
Douglas Gregor5545e162009-03-24 00:38:23 +0000665 for (FunctionDecl::param_iterator P = D->param_begin(),
666 PEnd = D->param_end();
667 P != PEnd; ++P) {
Douglas Gregor6477b692009-03-25 15:04:13 +0000668 if (ParmVarDecl *PInst = ParamInstantiator.VisitParmVarDecl(*P)) {
Douglas Gregor5545e162009-03-24 00:38:23 +0000669 if (PInst->getType()->isVoidType()) {
670 SemaRef.Diag(PInst->getLocation(), diag::err_param_with_void_type);
671 PInst->setInvalidDecl();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000672 } else if (SemaRef.RequireNonAbstractType(PInst->getLocation(),
673 PInst->getType(),
674 diag::err_abstract_type_in_decl,
675 Sema::AbstractParamType))
Douglas Gregor5545e162009-03-24 00:38:23 +0000676 PInst->setInvalidDecl();
677
678 Params.push_back(PInst);
679 ParamTys.push_back(PInst->getType());
680
681 if (PInst->isInvalidDecl())
682 InvalidDecl = true;
683 } else
684 InvalidDecl = true;
685 }
686
687 // FIXME: Deallocate dead declarations.
688 if (InvalidDecl)
689 return QualType();
690
691 const FunctionProtoType *Proto = D->getType()->getAsFunctionProtoType();
692 assert(Proto && "Missing prototype?");
693 QualType ResultType
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000694 = SemaRef.InstantiateType(Proto->getResultType(), TemplateArgs,
Douglas Gregor5545e162009-03-24 00:38:23 +0000695 D->getLocation(), D->getDeclName());
696 if (ResultType.isNull())
697 return QualType();
698
Jay Foadbeaaccd2009-05-21 09:52:38 +0000699 return SemaRef.BuildFunctionType(ResultType, ParamTys.data(), ParamTys.size(),
Douglas Gregor5545e162009-03-24 00:38:23 +0000700 Proto->isVariadic(), Proto->getTypeQuals(),
701 D->getLocation(), D->getDeclName());
702}
703
Douglas Gregore53060f2009-06-25 22:08:12 +0000704/// \brief Initializes the common fields of an instantiation function
705/// declaration (New) from the corresponding fields of its template (Tmpl).
706///
707/// \returns true if there was an error
708bool
709TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
710 FunctionDecl *Tmpl) {
711 if (Tmpl->isDeleted())
712 New->setDeleted();
Douglas Gregorcca9e962009-07-01 22:01:06 +0000713
714 // If we are performing substituting explicitly-specified template arguments
715 // or deduced template arguments into a function template and we reach this
716 // point, we are now past the point where SFINAE applies and have committed
717 // to keeping the new function template specialization. We therefore
718 // convert the active template instantiation for the function template
719 // into a template instantiation for this specific function template
720 // specialization, which is not a SFINAE context, so that we diagnose any
721 // further errors in the declaration itself.
722 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
723 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
724 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
725 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
726 if (FunctionTemplateDecl *FunTmpl
727 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
728 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
729 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +0000730 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000731 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
732 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
733 }
734 }
735
Douglas Gregore53060f2009-06-25 22:08:12 +0000736 return false;
737}
738
Douglas Gregor5545e162009-03-24 00:38:23 +0000739/// \brief Initializes common fields of an instantiated method
740/// declaration (New) from the corresponding fields of its template
741/// (Tmpl).
742///
743/// \returns true if there was an error
744bool
745TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
746 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +0000747 if (InitFunctionInstantiation(New, Tmpl))
748 return true;
749
Douglas Gregor5545e162009-03-24 00:38:23 +0000750 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
751 New->setAccess(Tmpl->getAccess());
Anders Carlsson77b7f1d2009-05-14 22:15:41 +0000752 if (Tmpl->isVirtualAsWritten()) {
753 New->setVirtualAsWritten(true);
Douglas Gregor5545e162009-03-24 00:38:23 +0000754 Record->setAggregate(false);
755 Record->setPOD(false);
Eli Friedman1d954f62009-08-15 21:55:26 +0000756 Record->setEmpty(false);
Douglas Gregor5545e162009-03-24 00:38:23 +0000757 Record->setPolymorphic(true);
758 }
Douglas Gregor5545e162009-03-24 00:38:23 +0000759 if (Tmpl->isPure()) {
760 New->setPure();
761 Record->setAbstract(true);
762 }
763
764 // FIXME: attributes
765 // FIXME: New needs a pointer to Tmpl
766 return false;
767}
Douglas Gregora58861f2009-05-13 20:28:22 +0000768
769/// \brief Instantiate the definition of the given function from its
770/// template.
771///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000772/// \param PointOfInstantiation the point at which the instantiation was
773/// required. Note that this is not precisely a "point of instantiation"
774/// for the function, but it's close.
775///
Douglas Gregora58861f2009-05-13 20:28:22 +0000776/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000777/// function template specialization or member function of a class template
778/// specialization.
779///
780/// \param Recursive if true, recursively instantiates any functions that
781/// are required by this instantiation.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000782void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000783 FunctionDecl *Function,
784 bool Recursive) {
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000785 if (Function->isInvalidDecl())
786 return;
787
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000788 assert(!Function->getBody() && "Already instantiated!");
Douglas Gregord7f37bf2009-06-22 23:06:13 +0000789
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000790 // Find the function body that we'll be substituting.
Douglas Gregor1637be72009-06-26 00:10:03 +0000791 const FunctionDecl *PatternDecl = 0;
792 if (FunctionTemplateDecl *Primary = Function->getPrimaryTemplate())
793 PatternDecl = Primary->getTemplatedDecl();
794 else
795 PatternDecl = Function->getInstantiatedFromMemberFunction();
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000796 Stmt *Pattern = 0;
797 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000798 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +0000799
800 if (!Pattern)
801 return;
802
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000803 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
804 if (Inst)
805 return;
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000806
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000807 // If we're performing recursive template instantiation, create our own
808 // queue of pending implicit instantiations that we will instantiate later,
809 // while we're still within our own instantiation context.
810 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
811 if (Recursive)
812 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
813
Douglas Gregore2c31ff2009-05-15 17:59:04 +0000814 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
815
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000816 // Introduce a new scope where local variable instantiations will be
817 // recorded.
818 LocalInstantiationScope Scope(*this);
819
820 // Introduce the instantiated function parameters into the local
821 // instantiation scope.
822 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
823 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
824 Function->getParamDecl(I));
825
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000826 // Enter the scope of this instantiation. We don't use
827 // PushDeclContext because we don't have a scope.
828 DeclContext *PreviousContext = CurContext;
829 CurContext = Function;
830
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000831 // Instantiate the function body.
832 OwningStmtResult Body
833 = InstantiateStmt(Pattern, getTemplateInstantiationArgs(Function));
Douglas Gregore2c31ff2009-05-15 17:59:04 +0000834
835 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
836 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000837
838 CurContext = PreviousContext;
Douglas Gregoraba43bb2009-05-26 20:50:29 +0000839
840 DeclGroupRef DG(Function);
841 Consumer.HandleTopLevelDecl(DG);
Douglas Gregorb33fe2f2009-06-30 17:20:14 +0000842
843 if (Recursive) {
844 // Instantiate any pending implicit instantiations found during the
845 // instantiation of this template.
846 PerformPendingImplicitInstantiations();
847
848 // Restore the set of pending implicit instantiations.
849 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
850 }
Douglas Gregora58861f2009-05-13 20:28:22 +0000851}
852
853/// \brief Instantiate the definition of the given variable from its
854/// template.
855///
Douglas Gregor7caa6822009-07-24 20:34:43 +0000856/// \param PointOfInstantiation the point at which the instantiation was
857/// required. Note that this is not precisely a "point of instantiation"
858/// for the function, but it's close.
859///
860/// \param Var the already-instantiated declaration of a static member
861/// variable of a class template specialization.
862///
863/// \param Recursive if true, recursively instantiates any functions that
864/// are required by this instantiation.
865void Sema::InstantiateStaticDataMemberDefinition(
866 SourceLocation PointOfInstantiation,
867 VarDecl *Var,
868 bool Recursive) {
869 if (Var->isInvalidDecl())
870 return;
871
872 // Find the out-of-line definition of this static data member.
873 // FIXME: Do we have to look for specializations separately?
874 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
875 bool FoundOutOfLineDef = false;
876 assert(Def && "This data member was not instantiated from a template?");
877 assert(Def->isStaticDataMember() && "Not a static data member?");
878 for (VarDecl::redecl_iterator RD = Def->redecls_begin(),
879 RDEnd = Def->redecls_end();
880 RD != RDEnd; ++RD) {
881 if (RD->getLexicalDeclContext()->isFileContext()) {
882 Def = *RD;
883 FoundOutOfLineDef = true;
884 }
885 }
886
887 if (!FoundOutOfLineDef) {
888 // We did not find an out-of-line definition of this static data member,
889 // so we won't perform any instantiation. Rather, we rely on the user to
890 // instantiate this definition (or provide a specialization for it) in
891 // another translation unit.
892 return;
893 }
894
895 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
896 if (Inst)
897 return;
898
899 // If we're performing recursive template instantiation, create our own
900 // queue of pending implicit instantiations that we will instantiate later,
901 // while we're still within our own instantiation context.
902 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
903 if (Recursive)
904 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
905
906 // Enter the scope of this instantiation. We don't use
907 // PushDeclContext because we don't have a scope.
908 DeclContext *PreviousContext = CurContext;
909 CurContext = Var->getDeclContext();
910
911#if 0
912 // Instantiate the initializer of this static data member.
913 OwningExprResult Init
914 = InstantiateExpr(Def->getInit(), getTemplateInstantiationArgs(Var));
915 if (Init.isInvalid()) {
916 // If instantiation of the initializer failed, mark the declaration invalid
917 // and don't instantiate anything else that was triggered by this
918 // instantiation.
919 Var->setInvalidDecl();
920
921 // Restore the set of pending implicit instantiations.
922 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
923
924 return;
925 }
926
927 // Type-check the initializer.
928 if (Init.get())
929 AddInitializerToDecl(DeclPtrTy::make(Var), move(Init),
930 Def->hasCXXDirectInitializer());
931 else
932 ActOnUninitializedDecl(DeclPtrTy::make(Var), false);
933#else
934 Var = cast_or_null<VarDecl>(InstantiateDecl(Def, Var->getDeclContext(),
935 getTemplateInstantiationArgs(Var)));
936#endif
937
938 CurContext = PreviousContext;
939
940 if (Var) {
941 DeclGroupRef DG(Var);
942 Consumer.HandleTopLevelDecl(DG);
943 }
944
945 if (Recursive) {
946 // Instantiate any pending implicit instantiations found during the
947 // instantiation of this template.
948 PerformPendingImplicitInstantiations();
949
950 // Restore the set of pending implicit instantiations.
951 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
952 }
Douglas Gregora58861f2009-05-13 20:28:22 +0000953}
Douglas Gregor815215d2009-05-27 05:35:12 +0000954
955static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
956 if (D->getKind() != Other->getKind())
957 return false;
958
959 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +0000960 return Record->getInstantiatedFromMemberClass()->getCanonicalDecl()
961 == D->getCanonicalDecl();
Douglas Gregor815215d2009-05-27 05:35:12 +0000962
963 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +0000964 return Function->getInstantiatedFromMemberFunction()->getCanonicalDecl()
965 == D->getCanonicalDecl();
Douglas Gregor815215d2009-05-27 05:35:12 +0000966
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000967 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +0000968 return Enum->getInstantiatedFromMemberEnum()->getCanonicalDecl()
969 == D->getCanonicalDecl();
Douglas Gregor815215d2009-05-27 05:35:12 +0000970
Douglas Gregor7caa6822009-07-24 20:34:43 +0000971 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
972 if (Var->isStaticDataMember())
973 return Var->getInstantiatedFromStaticDataMember()->getCanonicalDecl()
974 == D->getCanonicalDecl();
975
Douglas Gregor815215d2009-05-27 05:35:12 +0000976 // FIXME: How can we find instantiations of anonymous unions?
977
978 return D->getDeclName() && isa<NamedDecl>(Other) &&
979 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
980}
981
982template<typename ForwardIterator>
983static NamedDecl *findInstantiationOf(ASTContext &Ctx,
984 NamedDecl *D,
985 ForwardIterator first,
986 ForwardIterator last) {
987 for (; first != last; ++first)
988 if (isInstantiationOf(Ctx, D, *first))
989 return cast<NamedDecl>(*first);
990
991 return 0;
992}
993
Douglas Gregored961e72009-05-27 17:54:46 +0000994/// \brief Find the instantiation of the given declaration within the
995/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +0000996///
997/// This routine is intended to be used when \p D is a declaration
998/// referenced from within a template, that needs to mapped into the
999/// corresponding declaration within an instantiation. For example,
1000/// given:
1001///
1002/// \code
1003/// template<typename T>
1004/// struct X {
1005/// enum Kind {
1006/// KnownValue = sizeof(T)
1007/// };
1008///
1009/// bool getKind() const { return KnownValue; }
1010/// };
1011///
1012/// template struct X<int>;
1013/// \endcode
1014///
1015/// In the instantiation of X<int>::getKind(), we need to map the
1016/// EnumConstantDecl for KnownValue (which refers to
1017/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00001018/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
1019/// this mapping from within the instantiation of X<int>.
1020NamedDecl * Sema::InstantiateCurrentDeclRef(NamedDecl *D) {
Douglas Gregor815215d2009-05-27 05:35:12 +00001021 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor2bba76b2009-05-27 17:07:49 +00001022 if (isa<ParmVarDecl>(D) || ParentDC->isFunctionOrMethod()) {
1023 // D is a local of some kind. Look into the map of local
1024 // declarations to their instantiations.
1025 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
1026 }
Douglas Gregor815215d2009-05-27 05:35:12 +00001027
Douglas Gregor2bba76b2009-05-27 17:07:49 +00001028 if (NamedDecl *ParentDecl = dyn_cast<NamedDecl>(ParentDC)) {
Douglas Gregored961e72009-05-27 17:54:46 +00001029 ParentDecl = InstantiateCurrentDeclRef(ParentDecl);
Douglas Gregor815215d2009-05-27 05:35:12 +00001030 if (!ParentDecl)
1031 return 0;
1032
1033 ParentDC = cast<DeclContext>(ParentDecl);
1034 }
1035
Douglas Gregor815215d2009-05-27 05:35:12 +00001036 if (ParentDC != D->getDeclContext()) {
1037 // We performed some kind of instantiation in the parent context,
1038 // so now we need to look into the instantiated parent context to
1039 // find the instantiation of the declaration D.
1040 NamedDecl *Result = 0;
1041 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001042 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00001043 Result = findInstantiationOf(Context, D, Found.first, Found.second);
1044 } else {
1045 // Since we don't have a name for the entity we're looking for,
1046 // our only option is to walk through all of the declarations to
1047 // find that name. This will occur in a few cases:
1048 //
1049 // - anonymous struct/union within a template
1050 // - unnamed class/struct/union/enum within a template
1051 //
1052 // FIXME: Find a better way to find these instantiations!
1053 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001054 ParentDC->decls_begin(),
1055 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00001056 }
1057 assert(Result && "Unable to find instantiation of declaration!");
1058 D = Result;
1059 }
1060
Douglas Gregor815215d2009-05-27 05:35:12 +00001061 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
Douglas Gregored961e72009-05-27 17:54:46 +00001062 if (ClassTemplateDecl *ClassTemplate
1063 = Record->getDescribedClassTemplate()) {
1064 // When the declaration D was parsed, it referred to the current
1065 // instantiation. Therefore, look through the current context,
1066 // which contains actual instantiations, to find the
1067 // instantiation of the "current instantiation" that D refers
1068 // to. Alternatively, we could just instantiate the
1069 // injected-class-name with the current template arguments, but
1070 // such an instantiation is far more expensive.
1071 for (DeclContext *DC = CurContext; !DC->isFileContext();
1072 DC = DC->getParent()) {
1073 if (ClassTemplateSpecializationDecl *Spec
1074 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001075 if (Spec->getSpecializedTemplate()->getCanonicalDecl()
1076 == ClassTemplate->getCanonicalDecl())
Douglas Gregored961e72009-05-27 17:54:46 +00001077 return Spec;
1078 }
1079
1080 assert(false &&
1081 "Unable to find declaration for the current instantiation");
Douglas Gregor815215d2009-05-27 05:35:12 +00001082 }
1083
1084 return D;
1085}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001086
1087/// \brief Performs template instantiation for all implicit template
1088/// instantiations we have seen until this point.
1089void Sema::PerformPendingImplicitInstantiations() {
1090 while (!PendingImplicitInstantiations.empty()) {
1091 PendingImplicitInstantiation Inst = PendingImplicitInstantiations.front();
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001092 PendingImplicitInstantiations.pop_front();
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001093
Douglas Gregor7caa6822009-07-24 20:34:43 +00001094 // Instantiate function definitions
1095 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001096 if (!Function->getBody())
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001097 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00001098 continue;
1099 }
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001100
Douglas Gregor7caa6822009-07-24 20:34:43 +00001101 // Instantiate static data member definitions.
1102 VarDecl *Var = cast<VarDecl>(Inst.first);
1103 assert(Var->isStaticDataMember() && "Not a static data member?");
1104 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00001105 }
1106}